@keystrokehq/cli 1.0.30 → 1.0.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +0,0 @@
1
- {"version":3,"file":"dist-B-_WEYqH.mjs","names":["z.custom","z.union","z.string","z.number","z.looseObject","z.object","z\n .object","z.literal","z.unknown","z.array","z.enum","z.intersection","z.boolean","z.record","z.preprocess","z\n .looseObject","z\n .looseObject","z\n .object","z.optional","z.null","z.iso.datetime","z.discriminatedUnion","crypto","z\n .url","z.NEVER","z.looseObject","z.string","z.array","z.boolean","z.object","z\n .object","z.coerce.number","z.literal","z.any","z.number","Qt","z.enum","z.object","z.string","z.array","z.union","z.literal","SKIP_DIRS","Guard.IsObject","Guard.HasPropertyKey","Guard.IsArray","Settings.Get","Settings.Get","Guard.IsObject","Memory.Update","Guard.HasPropertyKey","Memory.Create","Guard.Keys","Memory.Create","Number","Memory.Create","String","Memory.Create","AllowedDigits","Type.Object","Type.String","Type.Array","Type.Optional","Type.Number","zodSchema","z.custom","z.ZodType","z.object","z.string","z.array","z.function","require","buildPgSchema","buildSqliteSchema","tableRegistry","schema","require","storage","fs","fs","path","path","cp","process","zodSchema","z.custom","z.ZodType","z.object","z.string","z.enum","z.function","WORKFLOW","cronScheduleSchema","z.string","zodSchema","z.custom","z.ZodType","workflowSchema","agentSchema","promptSchema","z.union","z.function","normalizeLegacySlugFields","slugField","optionalTextField","baseSourceShape","webhookSourceSchema","z.object","z.literal","cronSourceSchema","pollSourceSchema","z.array","triggerSourceSchema","z.preprocess","z.discriminatedUnion","workflowAttachmentSchema","agentAttachmentSchema","triggerAttachmentCoreSchema","TRIGGER_ATTACHMENT","z.toJSONSchema","z.custom","z.ZodType","z.string","z.union","z.function","z.object","z.literal","z.array","z.preprocess","z.discriminatedUnion"],"sources":["../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/compat.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js","../../../node_modules/.pnpm/pkce-challenge@5.0.1/node_modules/pkce-challenge/dist/index.node.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js","../../../node_modules/.pnpm/just-bash@3.0.1/node_modules/just-bash/dist/bundle/chunks/chunk-G5EVRAOO.js","../../../packages/manifest/dist/discovery-CWjr_liZ.mjs","../../../packages/sandbox/dist/files-BOUCjfCQ.mjs","../../../node_modules/.pnpm/typebox@1.1.38/node_modules/typebox/build/system/memory/metrics.mjs","../../../node_modules/.pnpm/typebox@1.1.38/node_modules/typebox/build/guard/guard.mjs","../../../node_modules/.pnpm/typebox@1.1.38/node_modules/typebox/build/system/memory/clone.mjs","../../../node_modules/.pnpm/typebox@1.1.38/node_modules/typebox/build/system/settings/settings.mjs","../../../node_modules/.pnpm/typebox@1.1.38/node_modules/typebox/build/system/memory/create.mjs","../../../node_modules/.pnpm/typebox@1.1.38/node_modules/typebox/build/system/memory/update.mjs","../../../node_modules/.pnpm/typebox@1.1.38/node_modules/typebox/build/type/types/schema.mjs","../../../node_modules/.pnpm/typebox@1.1.38/node_modules/typebox/build/type/types/_optional.mjs","../../../node_modules/.pnpm/typebox@1.1.38/node_modules/typebox/build/type/types/array.mjs","../../../node_modules/.pnpm/typebox@1.1.38/node_modules/typebox/build/type/types/properties.mjs","../../../node_modules/.pnpm/typebox@1.1.38/node_modules/typebox/build/type/types/object.mjs","../../../node_modules/.pnpm/typebox@1.1.38/node_modules/typebox/build/system/hashing/hash.mjs","../../../node_modules/.pnpm/typebox@1.1.38/node_modules/typebox/build/type/types/integer.mjs","../../../node_modules/.pnpm/typebox@1.1.38/node_modules/typebox/build/type/types/number.mjs","../../../node_modules/.pnpm/typebox@1.1.38/node_modules/typebox/build/type/types/string.mjs","../../../node_modules/.pnpm/typebox@1.1.38/node_modules/typebox/build/type/types/record.mjs","../../../node_modules/.pnpm/typebox@1.1.38/node_modules/typebox/build/type/script/token/internal/char.mjs","../../../node_modules/.pnpm/typebox@1.1.38/node_modules/typebox/build/type/script/token/unsigned_integer.mjs","../../../node_modules/.pnpm/typebox@1.1.38/node_modules/typebox/build/type/script/token/ident.mjs","../../../node_modules/.pnpm/typebox@1.1.38/node_modules/typebox/build/type/script/token/unsigned_number.mjs","../../../node_modules/.pnpm/typebox@1.1.38/node_modules/typebox/build/type/engine/indexed/from_object.mjs","../../../packages/sandbox/dist/create-coding-tools-d9-WzxBW.mjs","../../../node_modules/.pnpm/just-bash@3.0.1/node_modules/just-bash/dist/bundle/index.js","../../../node_modules/.pnpm/cron-schedule@6.0.0/node_modules/cron-schedule/dist/utils.js","../../../node_modules/.pnpm/cron-schedule@6.0.0/node_modules/cron-schedule/dist/cron.js","../../../node_modules/.pnpm/cron-schedule@6.0.0/node_modules/cron-schedule/dist/cron-parser.js","../../../packages/action/dist/index.mjs","../../../packages/tracing/dist/index.mjs","../../../packages/database/dist/index.mjs","../../../packages/platform-database/dist/auth-verifications-D-no86bc.mjs","../../../packages/platform-database/dist/index.mjs","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/codegen/code.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/codegen/scope.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/codegen/index.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/util.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/names.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/errors.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/boolSchema.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/rules.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/applicability.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/dataType.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/defaults.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/code.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/keyword.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/subschema.js","../../../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js","../../../node_modules/.pnpm/json-schema-traverse@1.0.0/node_modules/json-schema-traverse/index.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/resolve.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/index.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/validation_error.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/ref_error.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/index.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/data.json","../../../node_modules/.pnpm/fast-uri@3.1.2/node_modules/fast-uri/lib/utils.js","../../../node_modules/.pnpm/fast-uri@3.1.2/node_modules/fast-uri/lib/schemes.js","../../../node_modules/.pnpm/fast-uri@3.1.2/node_modules/fast-uri/index.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/uri.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/core.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/core/id.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/core/ref.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/core/index.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitNumber.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/multipleOf.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/ucs2length.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitLength.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/pattern.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitProperties.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/required.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitItems.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/equal.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/const.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/enum.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/index.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/items.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/items2020.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/contains.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/dependencies.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/properties.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/not.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/anyOf.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/oneOf.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/allOf.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/if.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/thenElse.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/index.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/format/format.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/format/index.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/metadata.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/draft7.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/discriminator/types.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/discriminator/index.js","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/json-schema-draft-07.json","../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/ajv.js","../../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.20.0/node_modules/ajv-formats/dist/formats.js","../../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.20.0/node_modules/ajv-formats/dist/limit.js","../../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.20.0/node_modules/ajv-formats/dist/index.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js","../../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/windows.js","../../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/mode.js","../../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js","../../../node_modules/.pnpm/which@2.0.2/node_modules/which/which.js","../../../node_modules/.pnpm/path-key@3.1.1/node_modules/path-key/index.js","../../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js","../../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/escape.js","../../../node_modules/.pnpm/shebang-regex@3.0.0/node_modules/shebang-regex/index.js","../../../node_modules/.pnpm/shebang-command@2.0.0/node_modules/shebang-command/index.js","../../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js","../../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js","../../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/enoent.js","../../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/index.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js","../../../packages/workflow/dist/index.mjs","../../../packages/trigger/dist/index.mjs","../../../packages/manifest/dist/index.mjs"],"sourcesContent":["// Zod 3 compat layer\nimport * as core from \"../core/index.js\";\n/** @deprecated Use the raw string literal codes instead, e.g. \"invalid_type\". */\nexport const ZodIssueCode = {\n invalid_type: \"invalid_type\",\n too_big: \"too_big\",\n too_small: \"too_small\",\n invalid_format: \"invalid_format\",\n not_multiple_of: \"not_multiple_of\",\n unrecognized_keys: \"unrecognized_keys\",\n invalid_union: \"invalid_union\",\n invalid_key: \"invalid_key\",\n invalid_element: \"invalid_element\",\n invalid_value: \"invalid_value\",\n custom: \"custom\",\n};\nexport { $brand, config } from \"../core/index.js\";\n/** @deprecated Use `z.config(params)` instead. */\nexport function setErrorMap(map) {\n core.config({\n customError: map,\n });\n}\n/** @deprecated Use `z.config()` instead. */\nexport function getErrorMap() {\n return core.config().customError;\n}\n/** @deprecated Do not use. Stub definition, only included for zod-to-json-schema compatibility. */\nexport var ZodFirstPartyTypeKind;\n(function (ZodFirstPartyTypeKind) {\n})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));\n","import * as z from 'zod/v4';\nexport const LATEST_PROTOCOL_VERSION = '2025-11-25';\nexport const DEFAULT_NEGOTIATED_PROTOCOL_VERSION = '2025-03-26';\nexport const SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, '2025-06-18', '2025-03-26', '2024-11-05', '2024-10-07'];\nexport const RELATED_TASK_META_KEY = 'io.modelcontextprotocol/related-task';\n/* JSON-RPC types */\nexport const JSONRPC_VERSION = '2.0';\n/**\n * Assert 'object' type schema.\n *\n * @internal\n */\nconst AssertObjectSchema = z.custom((v) => v !== null && (typeof v === 'object' || typeof v === 'function'));\n/**\n * A progress token, used to associate progress notifications with the original request.\n */\nexport const ProgressTokenSchema = z.union([z.string(), z.number().int()]);\n/**\n * An opaque token used to represent a cursor for pagination.\n */\nexport const CursorSchema = z.string();\n/**\n * Task creation parameters, used to ask that the server create a task to represent a request.\n */\nexport const TaskCreationParamsSchema = z.looseObject({\n /**\n * Requested duration in milliseconds to retain task from creation.\n */\n ttl: z.number().optional(),\n /**\n * Time in milliseconds to wait between task status requests.\n */\n pollInterval: z.number().optional()\n});\nexport const TaskMetadataSchema = z.object({\n ttl: z.number().optional()\n});\n/**\n * Metadata for associating messages with a task.\n * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`.\n */\nexport const RelatedTaskMetadataSchema = z.object({\n taskId: z.string()\n});\nconst RequestMetaSchema = z.looseObject({\n /**\n * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.\n */\n progressToken: ProgressTokenSchema.optional(),\n /**\n * If specified, this request is related to the provided task.\n */\n [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional()\n});\n/**\n * Common params for any request.\n */\nconst BaseRequestParamsSchema = z.object({\n /**\n * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage.\n */\n _meta: RequestMetaSchema.optional()\n});\n/**\n * Common params for any task-augmented request.\n */\nexport const TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * If specified, the caller is requesting task-augmented execution for this request.\n * The request will return a CreateTaskResult immediately, and the actual result can be\n * retrieved later via tasks/result.\n *\n * Task augmentation is subject to capability negotiation - receivers MUST declare support\n * for task augmentation of specific request types in their capabilities.\n */\n task: TaskMetadataSchema.optional()\n});\n/**\n * Checks if a value is a valid TaskAugmentedRequestParams.\n * @param value - The value to check.\n *\n * @returns True if the value is a valid TaskAugmentedRequestParams, false otherwise.\n */\nexport const isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success;\nexport const RequestSchema = z.object({\n method: z.string(),\n params: BaseRequestParamsSchema.loose().optional()\n});\nconst NotificationsParamsSchema = z.object({\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: RequestMetaSchema.optional()\n});\nexport const NotificationSchema = z.object({\n method: z.string(),\n params: NotificationsParamsSchema.loose().optional()\n});\nexport const ResultSchema = z.looseObject({\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: RequestMetaSchema.optional()\n});\n/**\n * A uniquely identifying ID for a request in JSON-RPC.\n */\nexport const RequestIdSchema = z.union([z.string(), z.number().int()]);\n/**\n * A request that expects a response.\n */\nexport const JSONRPCRequestSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n id: RequestIdSchema,\n ...RequestSchema.shape\n})\n .strict();\nexport const isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success;\n/**\n * A notification which does not expect a response.\n */\nexport const JSONRPCNotificationSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n ...NotificationSchema.shape\n})\n .strict();\nexport const isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success;\n/**\n * A successful (non-error) response to a request.\n */\nexport const JSONRPCResultResponseSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n id: RequestIdSchema,\n result: ResultSchema\n})\n .strict();\n/**\n * Checks if a value is a valid JSONRPCResultResponse.\n * @param value - The value to check.\n *\n * @returns True if the value is a valid JSONRPCResultResponse, false otherwise.\n */\nexport const isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success;\n/**\n * @deprecated Use {@link isJSONRPCResultResponse} instead.\n *\n * Please note that {@link JSONRPCResponse} is a union of {@link JSONRPCResultResponse} and {@link JSONRPCErrorResponse} as per the updated JSON-RPC specification. (was previously just {@link JSONRPCResultResponse})\n */\nexport const isJSONRPCResponse = isJSONRPCResultResponse;\n/**\n * Error codes defined by the JSON-RPC specification.\n */\nexport var ErrorCode;\n(function (ErrorCode) {\n // SDK error codes\n ErrorCode[ErrorCode[\"ConnectionClosed\"] = -32000] = \"ConnectionClosed\";\n ErrorCode[ErrorCode[\"RequestTimeout\"] = -32001] = \"RequestTimeout\";\n // Standard JSON-RPC error codes\n ErrorCode[ErrorCode[\"ParseError\"] = -32700] = \"ParseError\";\n ErrorCode[ErrorCode[\"InvalidRequest\"] = -32600] = \"InvalidRequest\";\n ErrorCode[ErrorCode[\"MethodNotFound\"] = -32601] = \"MethodNotFound\";\n ErrorCode[ErrorCode[\"InvalidParams\"] = -32602] = \"InvalidParams\";\n ErrorCode[ErrorCode[\"InternalError\"] = -32603] = \"InternalError\";\n // MCP-specific error codes\n ErrorCode[ErrorCode[\"UrlElicitationRequired\"] = -32042] = \"UrlElicitationRequired\";\n})(ErrorCode || (ErrorCode = {}));\n/**\n * A response to a request that indicates an error occurred.\n */\nexport const JSONRPCErrorResponseSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n id: RequestIdSchema.optional(),\n error: z.object({\n /**\n * The error type that occurred.\n */\n code: z.number().int(),\n /**\n * A short description of the error. The message SHOULD be limited to a concise single sentence.\n */\n message: z.string(),\n /**\n * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.).\n */\n data: z.unknown().optional()\n })\n})\n .strict();\n/**\n * @deprecated Use {@link JSONRPCErrorResponseSchema} instead.\n */\nexport const JSONRPCErrorSchema = JSONRPCErrorResponseSchema;\n/**\n * Checks if a value is a valid JSONRPCErrorResponse.\n * @param value - The value to check.\n *\n * @returns True if the value is a valid JSONRPCErrorResponse, false otherwise.\n */\nexport const isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success;\n/**\n * @deprecated Use {@link isJSONRPCErrorResponse} instead.\n */\nexport const isJSONRPCError = isJSONRPCErrorResponse;\nexport const JSONRPCMessageSchema = z.union([\n JSONRPCRequestSchema,\n JSONRPCNotificationSchema,\n JSONRPCResultResponseSchema,\n JSONRPCErrorResponseSchema\n]);\nexport const JSONRPCResponseSchema = z.union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]);\n/* Empty result */\n/**\n * A response that indicates success but carries no data.\n */\nexport const EmptyResultSchema = ResultSchema.strict();\nexport const CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The ID of the request to cancel.\n *\n * This MUST correspond to the ID of a request previously issued in the same direction.\n */\n requestId: RequestIdSchema.optional(),\n /**\n * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.\n */\n reason: z.string().optional()\n});\n/* Cancellation */\n/**\n * This notification can be sent by either side to indicate that it is cancelling a previously-issued request.\n *\n * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished.\n *\n * This notification indicates that the result will be unused, so any associated processing SHOULD cease.\n *\n * A client MUST NOT attempt to cancel its `initialize` request.\n */\nexport const CancelledNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/cancelled'),\n params: CancelledNotificationParamsSchema\n});\n/* Base Metadata */\n/**\n * Icon schema for use in tools, prompts, resources, and implementations.\n */\nexport const IconSchema = z.object({\n /**\n * URL or data URI for the icon.\n */\n src: z.string(),\n /**\n * Optional MIME type for the icon.\n */\n mimeType: z.string().optional(),\n /**\n * Optional array of strings that specify sizes at which the icon can be used.\n * Each string should be in WxH format (e.g., `\"48x48\"`, `\"96x96\"`) or `\"any\"` for scalable formats like SVG.\n *\n * If not provided, the client should assume that the icon can be used at any size.\n */\n sizes: z.array(z.string()).optional(),\n /**\n * Optional specifier for the theme this icon is designed for. `light` indicates\n * the icon is designed to be used with a light background, and `dark` indicates\n * the icon is designed to be used with a dark background.\n *\n * If not provided, the client should assume the icon can be used with any theme.\n */\n theme: z.enum(['light', 'dark']).optional()\n});\n/**\n * Base schema to add `icons` property.\n *\n */\nexport const IconsSchema = z.object({\n /**\n * Optional set of sized icons that the client can display in a user interface.\n *\n * Clients that support rendering icons MUST support at least the following MIME types:\n * - `image/png` - PNG images (safe, universal compatibility)\n * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)\n *\n * Clients that support rendering icons SHOULD also support:\n * - `image/svg+xml` - SVG images (scalable but requires security precautions)\n * - `image/webp` - WebP images (modern, efficient format)\n */\n icons: z.array(IconSchema).optional()\n});\n/**\n * Base metadata interface for common properties across resources, tools, prompts, and implementations.\n */\nexport const BaseMetadataSchema = z.object({\n /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */\n name: z.string(),\n /**\n * Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\n * even by those unfamiliar with domain-specific terminology.\n *\n * If not provided, the name should be used for display (except for Tool,\n * where `annotations.title` should be given precedence over using `name`,\n * if present).\n */\n title: z.string().optional()\n});\n/* Initialization */\n/**\n * Describes the name and version of an MCP implementation.\n */\nexport const ImplementationSchema = BaseMetadataSchema.extend({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n version: z.string(),\n /**\n * An optional URL of the website for this implementation.\n */\n websiteUrl: z.string().optional(),\n /**\n * An optional human-readable description of what this implementation does.\n *\n * This can be used by clients or servers to provide context about their purpose\n * and capabilities. For example, a server might describe the types of resources\n * or tools it provides, while a client might describe its intended use case.\n */\n description: z.string().optional()\n});\nconst FormElicitationCapabilitySchema = z.intersection(z.object({\n applyDefaults: z.boolean().optional()\n}), z.record(z.string(), z.unknown()));\nconst ElicitationCapabilitySchema = z.preprocess(value => {\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n if (Object.keys(value).length === 0) {\n return { form: {} };\n }\n }\n return value;\n}, z.intersection(z.object({\n form: FormElicitationCapabilitySchema.optional(),\n url: AssertObjectSchema.optional()\n}), z.record(z.string(), z.unknown()).optional()));\n/**\n * Task capabilities for clients, indicating which request types support task creation.\n */\nexport const ClientTasksCapabilitySchema = z.looseObject({\n /**\n * Present if the client supports listing tasks.\n */\n list: AssertObjectSchema.optional(),\n /**\n * Present if the client supports cancelling tasks.\n */\n cancel: AssertObjectSchema.optional(),\n /**\n * Capabilities for task creation on specific request types.\n */\n requests: z\n .looseObject({\n /**\n * Task support for sampling requests.\n */\n sampling: z\n .looseObject({\n createMessage: AssertObjectSchema.optional()\n })\n .optional(),\n /**\n * Task support for elicitation requests.\n */\n elicitation: z\n .looseObject({\n create: AssertObjectSchema.optional()\n })\n .optional()\n })\n .optional()\n});\n/**\n * Task capabilities for servers, indicating which request types support task creation.\n */\nexport const ServerTasksCapabilitySchema = z.looseObject({\n /**\n * Present if the server supports listing tasks.\n */\n list: AssertObjectSchema.optional(),\n /**\n * Present if the server supports cancelling tasks.\n */\n cancel: AssertObjectSchema.optional(),\n /**\n * Capabilities for task creation on specific request types.\n */\n requests: z\n .looseObject({\n /**\n * Task support for tool requests.\n */\n tools: z\n .looseObject({\n call: AssertObjectSchema.optional()\n })\n .optional()\n })\n .optional()\n});\n/**\n * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities.\n */\nexport const ClientCapabilitiesSchema = z.object({\n /**\n * Experimental, non-standard capabilities that the client supports.\n */\n experimental: z.record(z.string(), AssertObjectSchema).optional(),\n /**\n * Present if the client supports sampling from an LLM.\n */\n sampling: z\n .object({\n /**\n * Present if the client supports context inclusion via includeContext parameter.\n * If not declared, servers SHOULD only use `includeContext: \"none\"` (or omit it).\n */\n context: AssertObjectSchema.optional(),\n /**\n * Present if the client supports tool use via tools and toolChoice parameters.\n */\n tools: AssertObjectSchema.optional()\n })\n .optional(),\n /**\n * Present if the client supports eliciting user input.\n */\n elicitation: ElicitationCapabilitySchema.optional(),\n /**\n * Present if the client supports listing roots.\n */\n roots: z\n .object({\n /**\n * Whether the client supports issuing notifications for changes to the roots list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the client supports task creation.\n */\n tasks: ClientTasksCapabilitySchema.optional(),\n /**\n * Extensions that the client supports. Keys are extension identifiers (vendor-prefix/extension-name).\n */\n extensions: z.record(z.string(), AssertObjectSchema).optional()\n});\nexport const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well.\n */\n protocolVersion: z.string(),\n capabilities: ClientCapabilitiesSchema,\n clientInfo: ImplementationSchema\n});\n/**\n * This request is sent from the client to the server when it first connects, asking it to begin initialization.\n */\nexport const InitializeRequestSchema = RequestSchema.extend({\n method: z.literal('initialize'),\n params: InitializeRequestParamsSchema\n});\nexport const isInitializeRequest = (value) => InitializeRequestSchema.safeParse(value).success;\n/**\n * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities.\n */\nexport const ServerCapabilitiesSchema = z.object({\n /**\n * Experimental, non-standard capabilities that the server supports.\n */\n experimental: z.record(z.string(), AssertObjectSchema).optional(),\n /**\n * Present if the server supports sending log messages to the client.\n */\n logging: AssertObjectSchema.optional(),\n /**\n * Present if the server supports sending completions to the client.\n */\n completions: AssertObjectSchema.optional(),\n /**\n * Present if the server offers any prompt templates.\n */\n prompts: z\n .object({\n /**\n * Whether this server supports issuing notifications for changes to the prompt list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the server offers any resources to read.\n */\n resources: z\n .object({\n /**\n * Whether this server supports clients subscribing to resource updates.\n */\n subscribe: z.boolean().optional(),\n /**\n * Whether this server supports issuing notifications for changes to the resource list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the server offers any tools to call.\n */\n tools: z\n .object({\n /**\n * Whether this server supports issuing notifications for changes to the tool list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the server supports task creation.\n */\n tasks: ServerTasksCapabilitySchema.optional(),\n /**\n * Extensions that the server supports. Keys are extension identifiers (vendor-prefix/extension-name).\n */\n extensions: z.record(z.string(), AssertObjectSchema).optional()\n});\n/**\n * After receiving an initialize request from the client, the server sends this response.\n */\nexport const InitializeResultSchema = ResultSchema.extend({\n /**\n * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect.\n */\n protocolVersion: z.string(),\n capabilities: ServerCapabilitiesSchema,\n serverInfo: ImplementationSchema,\n /**\n * Instructions describing how to use the server and its features.\n *\n * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a \"hint\" to the model. For example, this information MAY be added to the system prompt.\n */\n instructions: z.string().optional()\n});\n/**\n * This notification is sent from the client to the server after initialization has finished.\n */\nexport const InitializedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/initialized'),\n params: NotificationsParamsSchema.optional()\n});\nexport const isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success;\n/* Ping */\n/**\n * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected.\n */\nexport const PingRequestSchema = RequestSchema.extend({\n method: z.literal('ping'),\n params: BaseRequestParamsSchema.optional()\n});\n/* Progress notifications */\nexport const ProgressSchema = z.object({\n /**\n * The progress thus far. This should increase every time progress is made, even if the total is unknown.\n */\n progress: z.number(),\n /**\n * Total number of items to process (or total progress required), if known.\n */\n total: z.optional(z.number()),\n /**\n * An optional message describing the current progress.\n */\n message: z.optional(z.string())\n});\nexport const ProgressNotificationParamsSchema = z.object({\n ...NotificationsParamsSchema.shape,\n ...ProgressSchema.shape,\n /**\n * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding.\n */\n progressToken: ProgressTokenSchema\n});\n/**\n * An out-of-band notification used to inform the receiver of a progress update for a long-running request.\n *\n * @category notifications/progress\n */\nexport const ProgressNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/progress'),\n params: ProgressNotificationParamsSchema\n});\nexport const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * An opaque token representing the current pagination position.\n * If provided, the server should return results starting after this cursor.\n */\n cursor: CursorSchema.optional()\n});\n/* Pagination */\nexport const PaginatedRequestSchema = RequestSchema.extend({\n params: PaginatedRequestParamsSchema.optional()\n});\nexport const PaginatedResultSchema = ResultSchema.extend({\n /**\n * An opaque token representing the pagination position after the last returned result.\n * If present, there may be more results available.\n */\n nextCursor: CursorSchema.optional()\n});\n/**\n * The status of a task.\n * */\nexport const TaskStatusSchema = z.enum(['working', 'input_required', 'completed', 'failed', 'cancelled']);\n/* Tasks */\n/**\n * A pollable state object associated with a request.\n */\nexport const TaskSchema = z.object({\n taskId: z.string(),\n status: TaskStatusSchema,\n /**\n * Time in milliseconds to keep task results available after completion.\n * If null, the task has unlimited lifetime until manually cleaned up.\n */\n ttl: z.union([z.number(), z.null()]),\n /**\n * ISO 8601 timestamp when the task was created.\n */\n createdAt: z.string(),\n /**\n * ISO 8601 timestamp when the task was last updated.\n */\n lastUpdatedAt: z.string(),\n pollInterval: z.optional(z.number()),\n /**\n * Optional diagnostic message for failed tasks or other status information.\n */\n statusMessage: z.optional(z.string())\n});\n/**\n * Result returned when a task is created, containing the task data wrapped in a task field.\n */\nexport const CreateTaskResultSchema = ResultSchema.extend({\n task: TaskSchema\n});\n/**\n * Parameters for task status notification.\n */\nexport const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema);\n/**\n * A notification sent when a task's status changes.\n */\nexport const TaskStatusNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/tasks/status'),\n params: TaskStatusNotificationParamsSchema\n});\n/**\n * A request to get the state of a specific task.\n */\nexport const GetTaskRequestSchema = RequestSchema.extend({\n method: z.literal('tasks/get'),\n params: BaseRequestParamsSchema.extend({\n taskId: z.string()\n })\n});\n/**\n * The response to a tasks/get request.\n */\nexport const GetTaskResultSchema = ResultSchema.merge(TaskSchema);\n/**\n * A request to get the result of a specific task.\n */\nexport const GetTaskPayloadRequestSchema = RequestSchema.extend({\n method: z.literal('tasks/result'),\n params: BaseRequestParamsSchema.extend({\n taskId: z.string()\n })\n});\n/**\n * The response to a tasks/result request.\n * The structure matches the result type of the original request.\n * For example, a tools/call task would return the CallToolResult structure.\n *\n */\nexport const GetTaskPayloadResultSchema = ResultSchema.loose();\n/**\n * A request to list tasks.\n */\nexport const ListTasksRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('tasks/list')\n});\n/**\n * The response to a tasks/list request.\n */\nexport const ListTasksResultSchema = PaginatedResultSchema.extend({\n tasks: z.array(TaskSchema)\n});\n/**\n * A request to cancel a specific task.\n */\nexport const CancelTaskRequestSchema = RequestSchema.extend({\n method: z.literal('tasks/cancel'),\n params: BaseRequestParamsSchema.extend({\n taskId: z.string()\n })\n});\n/**\n * The response to a tasks/cancel request.\n */\nexport const CancelTaskResultSchema = ResultSchema.merge(TaskSchema);\n/* Resources */\n/**\n * The contents of a specific resource or sub-resource.\n */\nexport const ResourceContentsSchema = z.object({\n /**\n * The URI of this resource.\n */\n uri: z.string(),\n /**\n * The MIME type of this resource, if known.\n */\n mimeType: z.optional(z.string()),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\nexport const TextResourceContentsSchema = ResourceContentsSchema.extend({\n /**\n * The text of the item. This must only be set if the item can actually be represented as text (not binary data).\n */\n text: z.string()\n});\n/**\n * A Zod schema for validating Base64 strings that is more performant and\n * robust for very large inputs than the default regex-based check. It avoids\n * stack overflows by using the native `atob` function for validation.\n */\nconst Base64Schema = z.string().refine(val => {\n try {\n // atob throws a DOMException if the string contains characters\n // that are not part of the Base64 character set.\n atob(val);\n return true;\n }\n catch {\n return false;\n }\n}, { message: 'Invalid Base64 string' });\nexport const BlobResourceContentsSchema = ResourceContentsSchema.extend({\n /**\n * A base64-encoded string representing the binary data of the item.\n */\n blob: Base64Schema\n});\n/**\n * The sender or recipient of messages and data in a conversation.\n */\nexport const RoleSchema = z.enum(['user', 'assistant']);\n/**\n * Optional annotations providing clients additional context about a resource.\n */\nexport const AnnotationsSchema = z.object({\n /**\n * Intended audience(s) for the resource.\n */\n audience: z.array(RoleSchema).optional(),\n /**\n * Importance hint for the resource, from 0 (least) to 1 (most).\n */\n priority: z.number().min(0).max(1).optional(),\n /**\n * ISO 8601 timestamp for the most recent modification.\n */\n lastModified: z.iso.datetime({ offset: true }).optional()\n});\n/**\n * A known resource that the server is capable of reading.\n */\nexport const ResourceSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * The URI of this resource.\n */\n uri: z.string(),\n /**\n * A description of what this resource represents.\n *\n * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.\n */\n description: z.optional(z.string()),\n /**\n * The MIME type of this resource, if known.\n */\n mimeType: z.optional(z.string()),\n /**\n * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known.\n *\n * This can be used by Hosts to display file sizes and estimate context window usage.\n */\n size: z.optional(z.number()),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.optional(z.looseObject({}))\n});\n/**\n * A template description for resources available on the server.\n */\nexport const ResourceTemplateSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * A URI template (according to RFC 6570) that can be used to construct resource URIs.\n */\n uriTemplate: z.string(),\n /**\n * A description of what this template is for.\n *\n * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.\n */\n description: z.optional(z.string()),\n /**\n * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type.\n */\n mimeType: z.optional(z.string()),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.optional(z.looseObject({}))\n});\n/**\n * Sent from the client to request a list of resources the server has.\n */\nexport const ListResourcesRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('resources/list')\n});\n/**\n * The server's response to a resources/list request from the client.\n */\nexport const ListResourcesResultSchema = PaginatedResultSchema.extend({\n resources: z.array(ResourceSchema)\n});\n/**\n * Sent from the client to request a list of resource templates the server has.\n */\nexport const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('resources/templates/list')\n});\n/**\n * The server's response to a resources/templates/list request from the client.\n */\nexport const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({\n resourceTemplates: z.array(ResourceTemplateSchema)\n});\nexport const ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.\n *\n * @format uri\n */\n uri: z.string()\n});\n/**\n * Parameters for a `resources/read` request.\n */\nexport const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema;\n/**\n * Sent from the client to the server, to read a specific resource URI.\n */\nexport const ReadResourceRequestSchema = RequestSchema.extend({\n method: z.literal('resources/read'),\n params: ReadResourceRequestParamsSchema\n});\n/**\n * The server's response to a resources/read request from the client.\n */\nexport const ReadResourceResultSchema = ResultSchema.extend({\n contents: z.array(z.union([TextResourceContentsSchema, BlobResourceContentsSchema]))\n});\n/**\n * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client.\n */\nexport const ResourceListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/resources/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\nexport const SubscribeRequestParamsSchema = ResourceRequestParamsSchema;\n/**\n * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes.\n */\nexport const SubscribeRequestSchema = RequestSchema.extend({\n method: z.literal('resources/subscribe'),\n params: SubscribeRequestParamsSchema\n});\nexport const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema;\n/**\n * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request.\n */\nexport const UnsubscribeRequestSchema = RequestSchema.extend({\n method: z.literal('resources/unsubscribe'),\n params: UnsubscribeRequestParamsSchema\n});\n/**\n * Parameters for a `notifications/resources/updated` notification.\n */\nexport const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.\n */\n uri: z.string()\n});\n/**\n * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request.\n */\nexport const ResourceUpdatedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/resources/updated'),\n params: ResourceUpdatedNotificationParamsSchema\n});\n/* Prompts */\n/**\n * Describes an argument that a prompt can accept.\n */\nexport const PromptArgumentSchema = z.object({\n /**\n * The name of the argument.\n */\n name: z.string(),\n /**\n * A human-readable description of the argument.\n */\n description: z.optional(z.string()),\n /**\n * Whether this argument must be provided.\n */\n required: z.optional(z.boolean())\n});\n/**\n * A prompt or prompt template that the server offers.\n */\nexport const PromptSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * An optional description of what this prompt provides\n */\n description: z.optional(z.string()),\n /**\n * A list of arguments to use for templating the prompt.\n */\n arguments: z.optional(z.array(PromptArgumentSchema)),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.optional(z.looseObject({}))\n});\n/**\n * Sent from the client to request a list of prompts and prompt templates the server has.\n */\nexport const ListPromptsRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('prompts/list')\n});\n/**\n * The server's response to a prompts/list request from the client.\n */\nexport const ListPromptsResultSchema = PaginatedResultSchema.extend({\n prompts: z.array(PromptSchema)\n});\n/**\n * Parameters for a `prompts/get` request.\n */\nexport const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * The name of the prompt or prompt template.\n */\n name: z.string(),\n /**\n * Arguments to use for templating the prompt.\n */\n arguments: z.record(z.string(), z.string()).optional()\n});\n/**\n * Used by the client to get a prompt provided by the server.\n */\nexport const GetPromptRequestSchema = RequestSchema.extend({\n method: z.literal('prompts/get'),\n params: GetPromptRequestParamsSchema\n});\n/**\n * Text provided to or from an LLM.\n */\nexport const TextContentSchema = z.object({\n type: z.literal('text'),\n /**\n * The text content of the message.\n */\n text: z.string(),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * An image provided to or from an LLM.\n */\nexport const ImageContentSchema = z.object({\n type: z.literal('image'),\n /**\n * The base64-encoded image data.\n */\n data: Base64Schema,\n /**\n * The MIME type of the image. Different providers may support different image types.\n */\n mimeType: z.string(),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * An Audio provided to or from an LLM.\n */\nexport const AudioContentSchema = z.object({\n type: z.literal('audio'),\n /**\n * The base64-encoded audio data.\n */\n data: Base64Schema,\n /**\n * The MIME type of the audio. Different providers may support different audio types.\n */\n mimeType: z.string(),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * A tool call request from an assistant (LLM).\n * Represents the assistant's request to use a tool.\n */\nexport const ToolUseContentSchema = z.object({\n type: z.literal('tool_use'),\n /**\n * The name of the tool to invoke.\n * Must match a tool name from the request's tools array.\n */\n name: z.string(),\n /**\n * Unique identifier for this tool call.\n * Used to correlate with ToolResultContent in subsequent messages.\n */\n id: z.string(),\n /**\n * Arguments to pass to the tool.\n * Must conform to the tool's inputSchema.\n */\n input: z.record(z.string(), z.unknown()),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * The contents of a resource, embedded into a prompt or tool call result.\n */\nexport const EmbeddedResourceSchema = z.object({\n type: z.literal('resource'),\n resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema]),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * A resource that the server is capable of reading, included in a prompt or tool call result.\n *\n * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests.\n */\nexport const ResourceLinkSchema = ResourceSchema.extend({\n type: z.literal('resource_link')\n});\n/**\n * A content block that can be used in prompts and tool results.\n */\nexport const ContentBlockSchema = z.union([\n TextContentSchema,\n ImageContentSchema,\n AudioContentSchema,\n ResourceLinkSchema,\n EmbeddedResourceSchema\n]);\n/**\n * Describes a message returned as part of a prompt.\n */\nexport const PromptMessageSchema = z.object({\n role: RoleSchema,\n content: ContentBlockSchema\n});\n/**\n * The server's response to a prompts/get request from the client.\n */\nexport const GetPromptResultSchema = ResultSchema.extend({\n /**\n * An optional description for the prompt.\n */\n description: z.string().optional(),\n messages: z.array(PromptMessageSchema)\n});\n/**\n * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client.\n */\nexport const PromptListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/prompts/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\n/* Tools */\n/**\n * Additional properties describing a Tool to clients.\n *\n * NOTE: all properties in ToolAnnotations are **hints**.\n * They are not guaranteed to provide a faithful description of\n * tool behavior (including descriptive properties like `title`).\n *\n * Clients should never make tool use decisions based on ToolAnnotations\n * received from untrusted servers.\n */\nexport const ToolAnnotationsSchema = z.object({\n /**\n * A human-readable title for the tool.\n */\n title: z.string().optional(),\n /**\n * If true, the tool does not modify its environment.\n *\n * Default: false\n */\n readOnlyHint: z.boolean().optional(),\n /**\n * If true, the tool may perform destructive updates to its environment.\n * If false, the tool performs only additive updates.\n *\n * (This property is meaningful only when `readOnlyHint == false`)\n *\n * Default: true\n */\n destructiveHint: z.boolean().optional(),\n /**\n * If true, calling the tool repeatedly with the same arguments\n * will have no additional effect on the its environment.\n *\n * (This property is meaningful only when `readOnlyHint == false`)\n *\n * Default: false\n */\n idempotentHint: z.boolean().optional(),\n /**\n * If true, this tool may interact with an \"open world\" of external\n * entities. If false, the tool's domain of interaction is closed.\n * For example, the world of a web search tool is open, whereas that\n * of a memory tool is not.\n *\n * Default: true\n */\n openWorldHint: z.boolean().optional()\n});\n/**\n * Execution-related properties for a tool.\n */\nexport const ToolExecutionSchema = z.object({\n /**\n * Indicates the tool's preference for task-augmented execution.\n * - \"required\": Clients MUST invoke the tool as a task\n * - \"optional\": Clients MAY invoke the tool as a task or normal request\n * - \"forbidden\": Clients MUST NOT attempt to invoke the tool as a task\n *\n * If not present, defaults to \"forbidden\".\n */\n taskSupport: z.enum(['required', 'optional', 'forbidden']).optional()\n});\n/**\n * Definition for a tool the client can call.\n */\nexport const ToolSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * A human-readable description of the tool.\n */\n description: z.string().optional(),\n /**\n * A JSON Schema 2020-12 object defining the expected parameters for the tool.\n * Must have type: 'object' at the root level per MCP spec.\n */\n inputSchema: z\n .object({\n type: z.literal('object'),\n properties: z.record(z.string(), AssertObjectSchema).optional(),\n required: z.array(z.string()).optional()\n })\n .catchall(z.unknown()),\n /**\n * An optional JSON Schema 2020-12 object defining the structure of the tool's output\n * returned in the structuredContent field of a CallToolResult.\n * Must have type: 'object' at the root level per MCP spec.\n */\n outputSchema: z\n .object({\n type: z.literal('object'),\n properties: z.record(z.string(), AssertObjectSchema).optional(),\n required: z.array(z.string()).optional()\n })\n .catchall(z.unknown())\n .optional(),\n /**\n * Optional additional tool information.\n */\n annotations: ToolAnnotationsSchema.optional(),\n /**\n * Execution-related properties for this tool.\n */\n execution: ToolExecutionSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Sent from the client to request a list of tools the server has.\n */\nexport const ListToolsRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('tools/list')\n});\n/**\n * The server's response to a tools/list request from the client.\n */\nexport const ListToolsResultSchema = PaginatedResultSchema.extend({\n tools: z.array(ToolSchema)\n});\n/**\n * The server's response to a tool call.\n */\nexport const CallToolResultSchema = ResultSchema.extend({\n /**\n * A list of content objects that represent the result of the tool call.\n *\n * If the Tool does not define an outputSchema, this field MUST be present in the result.\n * For backwards compatibility, this field is always present, but it may be empty.\n */\n content: z.array(ContentBlockSchema).default([]),\n /**\n * An object containing structured tool output.\n *\n * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema.\n */\n structuredContent: z.record(z.string(), z.unknown()).optional(),\n /**\n * Whether the tool call ended in an error.\n *\n * If not set, this is assumed to be false (the call was successful).\n *\n * Any errors that originate from the tool SHOULD be reported inside the result\n * object, with `isError` set to true, _not_ as an MCP protocol-level error\n * response. Otherwise, the LLM would not be able to see that an error occurred\n * and self-correct.\n *\n * However, any errors in _finding_ the tool, an error indicating that the\n * server does not support tool calls, or any other exceptional conditions,\n * should be reported as an MCP error response.\n */\n isError: z.boolean().optional()\n});\n/**\n * CallToolResultSchema extended with backwards compatibility to protocol version 2024-10-07.\n */\nexport const CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({\n toolResult: z.unknown()\n}));\n/**\n * Parameters for a `tools/call` request.\n */\nexport const CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n /**\n * The name of the tool to call.\n */\n name: z.string(),\n /**\n * Arguments to pass to the tool.\n */\n arguments: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Used by the client to invoke a tool provided by the server.\n */\nexport const CallToolRequestSchema = RequestSchema.extend({\n method: z.literal('tools/call'),\n params: CallToolRequestParamsSchema\n});\n/**\n * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client.\n */\nexport const ToolListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/tools/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\n/**\n * Base schema for list changed subscription options (without callback).\n * Used internally for Zod validation of autoRefresh and debounceMs.\n */\nexport const ListChangedOptionsBaseSchema = z.object({\n /**\n * If true, the list will be refreshed automatically when a list changed notification is received.\n * The callback will be called with the updated list.\n *\n * If false, the callback will be called with null items, allowing manual refresh.\n *\n * @default true\n */\n autoRefresh: z.boolean().default(true),\n /**\n * Debounce time in milliseconds for list changed notification processing.\n *\n * Multiple notifications received within this timeframe will only trigger one refresh.\n * Set to 0 to disable debouncing.\n *\n * @default 300\n */\n debounceMs: z.number().int().nonnegative().default(300)\n});\n/* Logging */\n/**\n * The severity of a log message.\n */\nexport const LoggingLevelSchema = z.enum(['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency']);\n/**\n * Parameters for a `logging/setLevel` request.\n */\nexport const SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message.\n */\n level: LoggingLevelSchema\n});\n/**\n * A request from the client to the server, to enable or adjust logging.\n */\nexport const SetLevelRequestSchema = RequestSchema.extend({\n method: z.literal('logging/setLevel'),\n params: SetLevelRequestParamsSchema\n});\n/**\n * Parameters for a `notifications/message` notification.\n */\nexport const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The severity of this log message.\n */\n level: LoggingLevelSchema,\n /**\n * An optional name of the logger issuing this message.\n */\n logger: z.string().optional(),\n /**\n * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here.\n */\n data: z.unknown()\n});\n/**\n * Notification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically.\n */\nexport const LoggingMessageNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/message'),\n params: LoggingMessageNotificationParamsSchema\n});\n/* Sampling */\n/**\n * Hints to use for model selection.\n */\nexport const ModelHintSchema = z.object({\n /**\n * A hint for a model name.\n */\n name: z.string().optional()\n});\n/**\n * The server's preferences for model selection, requested of the client during sampling.\n */\nexport const ModelPreferencesSchema = z.object({\n /**\n * Optional hints to use for model selection.\n */\n hints: z.array(ModelHintSchema).optional(),\n /**\n * How much to prioritize cost when selecting a model.\n */\n costPriority: z.number().min(0).max(1).optional(),\n /**\n * How much to prioritize sampling speed (latency) when selecting a model.\n */\n speedPriority: z.number().min(0).max(1).optional(),\n /**\n * How much to prioritize intelligence and capabilities when selecting a model.\n */\n intelligencePriority: z.number().min(0).max(1).optional()\n});\n/**\n * Controls tool usage behavior in sampling requests.\n */\nexport const ToolChoiceSchema = z.object({\n /**\n * Controls when tools are used:\n * - \"auto\": Model decides whether to use tools (default)\n * - \"required\": Model MUST use at least one tool before completing\n * - \"none\": Model MUST NOT use any tools\n */\n mode: z.enum(['auto', 'required', 'none']).optional()\n});\n/**\n * The result of a tool execution, provided by the user (server).\n * Represents the outcome of invoking a tool requested via ToolUseContent.\n */\nexport const ToolResultContentSchema = z.object({\n type: z.literal('tool_result'),\n toolUseId: z.string().describe('The unique identifier for the corresponding tool call.'),\n content: z.array(ContentBlockSchema).default([]),\n structuredContent: z.object({}).loose().optional(),\n isError: z.boolean().optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Basic content types for sampling responses (without tool use).\n * Used for backwards-compatible CreateMessageResult when tools are not used.\n */\nexport const SamplingContentSchema = z.discriminatedUnion('type', [TextContentSchema, ImageContentSchema, AudioContentSchema]);\n/**\n * Content block types allowed in sampling messages.\n * This includes text, image, audio, tool use requests, and tool results.\n */\nexport const SamplingMessageContentBlockSchema = z.discriminatedUnion('type', [\n TextContentSchema,\n ImageContentSchema,\n AudioContentSchema,\n ToolUseContentSchema,\n ToolResultContentSchema\n]);\n/**\n * Describes a message issued to or received from an LLM API.\n */\nexport const SamplingMessageSchema = z.object({\n role: RoleSchema,\n content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)]),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Parameters for a `sampling/createMessage` request.\n */\nexport const CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n messages: z.array(SamplingMessageSchema),\n /**\n * The server's preferences for which model to select. The client MAY modify or omit this request.\n */\n modelPreferences: ModelPreferencesSchema.optional(),\n /**\n * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.\n */\n systemPrompt: z.string().optional(),\n /**\n * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt.\n * The client MAY ignore this request.\n *\n * Default is \"none\". Values \"thisServer\" and \"allServers\" are soft-deprecated. Servers SHOULD only use these values if the client\n * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases.\n */\n includeContext: z.enum(['none', 'thisServer', 'allServers']).optional(),\n temperature: z.number().optional(),\n /**\n * The requested maximum number of tokens to sample (to prevent runaway completions).\n *\n * The client MAY choose to sample fewer tokens than the requested maximum.\n */\n maxTokens: z.number().int(),\n stopSequences: z.array(z.string()).optional(),\n /**\n * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.\n */\n metadata: AssertObjectSchema.optional(),\n /**\n * Tools that the model may use during generation.\n * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.\n */\n tools: z.array(ToolSchema).optional(),\n /**\n * Controls how the model uses tools.\n * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.\n * Default is `{ mode: \"auto\" }`.\n */\n toolChoice: ToolChoiceSchema.optional()\n});\n/**\n * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it.\n */\nexport const CreateMessageRequestSchema = RequestSchema.extend({\n method: z.literal('sampling/createMessage'),\n params: CreateMessageRequestParamsSchema\n});\n/**\n * The client's response to a sampling/create_message request from the server.\n * This is the backwards-compatible version that returns single content (no arrays).\n * Used when the request does not include tools.\n */\nexport const CreateMessageResultSchema = ResultSchema.extend({\n /**\n * The name of the model that generated the message.\n */\n model: z.string(),\n /**\n * The reason why sampling stopped, if known.\n *\n * Standard values:\n * - \"endTurn\": Natural end of the assistant's turn\n * - \"stopSequence\": A stop sequence was encountered\n * - \"maxTokens\": Maximum token limit was reached\n *\n * This field is an open string to allow for provider-specific stop reasons.\n */\n stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens']).or(z.string())),\n role: RoleSchema,\n /**\n * Response content. Single content block (text, image, or audio).\n */\n content: SamplingContentSchema\n});\n/**\n * The client's response to a sampling/create_message request when tools were provided.\n * This version supports array content for tool use flows.\n */\nexport const CreateMessageResultWithToolsSchema = ResultSchema.extend({\n /**\n * The name of the model that generated the message.\n */\n model: z.string(),\n /**\n * The reason why sampling stopped, if known.\n *\n * Standard values:\n * - \"endTurn\": Natural end of the assistant's turn\n * - \"stopSequence\": A stop sequence was encountered\n * - \"maxTokens\": Maximum token limit was reached\n * - \"toolUse\": The model wants to use one or more tools\n *\n * This field is an open string to allow for provider-specific stop reasons.\n */\n stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens', 'toolUse']).or(z.string())),\n role: RoleSchema,\n /**\n * Response content. May be a single block or array. May include ToolUseContent if stopReason is \"toolUse\".\n */\n content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)])\n});\n/* Elicitation */\n/**\n * Primitive schema definition for boolean fields.\n */\nexport const BooleanSchemaSchema = z.object({\n type: z.literal('boolean'),\n title: z.string().optional(),\n description: z.string().optional(),\n default: z.boolean().optional()\n});\n/**\n * Primitive schema definition for string fields.\n */\nexport const StringSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n minLength: z.number().optional(),\n maxLength: z.number().optional(),\n format: z.enum(['email', 'uri', 'date', 'date-time']).optional(),\n default: z.string().optional()\n});\n/**\n * Primitive schema definition for number fields.\n */\nexport const NumberSchemaSchema = z.object({\n type: z.enum(['number', 'integer']),\n title: z.string().optional(),\n description: z.string().optional(),\n minimum: z.number().optional(),\n maximum: z.number().optional(),\n default: z.number().optional()\n});\n/**\n * Schema for single-selection enumeration without display titles for options.\n */\nexport const UntitledSingleSelectEnumSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n enum: z.array(z.string()),\n default: z.string().optional()\n});\n/**\n * Schema for single-selection enumeration with display titles for each option.\n */\nexport const TitledSingleSelectEnumSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n oneOf: z.array(z.object({\n const: z.string(),\n title: z.string()\n })),\n default: z.string().optional()\n});\n/**\n * Use TitledSingleSelectEnumSchema instead.\n * This interface will be removed in a future version.\n */\nexport const LegacyTitledEnumSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n enum: z.array(z.string()),\n enumNames: z.array(z.string()).optional(),\n default: z.string().optional()\n});\n// Combined single selection enumeration\nexport const SingleSelectEnumSchemaSchema = z.union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]);\n/**\n * Schema for multiple-selection enumeration without display titles for options.\n */\nexport const UntitledMultiSelectEnumSchemaSchema = z.object({\n type: z.literal('array'),\n title: z.string().optional(),\n description: z.string().optional(),\n minItems: z.number().optional(),\n maxItems: z.number().optional(),\n items: z.object({\n type: z.literal('string'),\n enum: z.array(z.string())\n }),\n default: z.array(z.string()).optional()\n});\n/**\n * Schema for multiple-selection enumeration with display titles for each option.\n */\nexport const TitledMultiSelectEnumSchemaSchema = z.object({\n type: z.literal('array'),\n title: z.string().optional(),\n description: z.string().optional(),\n minItems: z.number().optional(),\n maxItems: z.number().optional(),\n items: z.object({\n anyOf: z.array(z.object({\n const: z.string(),\n title: z.string()\n }))\n }),\n default: z.array(z.string()).optional()\n});\n/**\n * Combined schema for multiple-selection enumeration\n */\nexport const MultiSelectEnumSchemaSchema = z.union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);\n/**\n * Primitive schema definition for enum fields.\n */\nexport const EnumSchemaSchema = z.union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]);\n/**\n * Union of all primitive schema definitions.\n */\nexport const PrimitiveSchemaDefinitionSchema = z.union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]);\n/**\n * Parameters for an `elicitation/create` request for form-based elicitation.\n */\nexport const ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n /**\n * The elicitation mode.\n *\n * Optional for backward compatibility. Clients MUST treat missing mode as \"form\".\n */\n mode: z.literal('form').optional(),\n /**\n * The message to present to the user describing what information is being requested.\n */\n message: z.string(),\n /**\n * A restricted subset of JSON Schema.\n * Only top-level properties are allowed, without nesting.\n */\n requestedSchema: z.object({\n type: z.literal('object'),\n properties: z.record(z.string(), PrimitiveSchemaDefinitionSchema),\n required: z.array(z.string()).optional()\n })\n});\n/**\n * Parameters for an `elicitation/create` request for URL-based elicitation.\n */\nexport const ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n /**\n * The elicitation mode.\n */\n mode: z.literal('url'),\n /**\n * The message to present to the user explaining why the interaction is needed.\n */\n message: z.string(),\n /**\n * The ID of the elicitation, which must be unique within the context of the server.\n * The client MUST treat this ID as an opaque value.\n */\n elicitationId: z.string(),\n /**\n * The URL that the user should navigate to.\n */\n url: z.string().url()\n});\n/**\n * The parameters for a request to elicit additional information from the user via the client.\n */\nexport const ElicitRequestParamsSchema = z.union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]);\n/**\n * A request from the server to elicit user input via the client.\n * The client should present the message and form fields to the user (form mode)\n * or navigate to a URL (URL mode).\n */\nexport const ElicitRequestSchema = RequestSchema.extend({\n method: z.literal('elicitation/create'),\n params: ElicitRequestParamsSchema\n});\n/**\n * Parameters for a `notifications/elicitation/complete` notification.\n *\n * @category notifications/elicitation/complete\n */\nexport const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The ID of the elicitation that completed.\n */\n elicitationId: z.string()\n});\n/**\n * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request.\n *\n * @category notifications/elicitation/complete\n */\nexport const ElicitationCompleteNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/elicitation/complete'),\n params: ElicitationCompleteNotificationParamsSchema\n});\n/**\n * The client's response to an elicitation/create request from the server.\n */\nexport const ElicitResultSchema = ResultSchema.extend({\n /**\n * The user action in response to the elicitation.\n * - \"accept\": User submitted the form/confirmed the action\n * - \"decline\": User explicitly decline the action\n * - \"cancel\": User dismissed without making an explicit choice\n */\n action: z.enum(['accept', 'decline', 'cancel']),\n /**\n * The submitted form data, only present when action is \"accept\".\n * Contains values matching the requested schema.\n * Per MCP spec, content is \"typically omitted\" for decline/cancel actions.\n * We normalize null to undefined for leniency while maintaining type compatibility.\n */\n content: z.preprocess(val => (val === null ? undefined : val), z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.string())])).optional())\n});\n/* Autocomplete */\n/**\n * A reference to a resource or resource template definition.\n */\nexport const ResourceTemplateReferenceSchema = z.object({\n type: z.literal('ref/resource'),\n /**\n * The URI or URI template of the resource.\n */\n uri: z.string()\n});\n/**\n * @deprecated Use ResourceTemplateReferenceSchema instead\n */\nexport const ResourceReferenceSchema = ResourceTemplateReferenceSchema;\n/**\n * Identifies a prompt.\n */\nexport const PromptReferenceSchema = z.object({\n type: z.literal('ref/prompt'),\n /**\n * The name of the prompt or prompt template\n */\n name: z.string()\n});\n/**\n * Parameters for a `completion/complete` request.\n */\nexport const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({\n ref: z.union([PromptReferenceSchema, ResourceTemplateReferenceSchema]),\n /**\n * The argument's information\n */\n argument: z.object({\n /**\n * The name of the argument\n */\n name: z.string(),\n /**\n * The value of the argument to use for completion matching.\n */\n value: z.string()\n }),\n context: z\n .object({\n /**\n * Previously-resolved variables in a URI template or prompt.\n */\n arguments: z.record(z.string(), z.string()).optional()\n })\n .optional()\n});\n/**\n * A request from the client to the server, to ask for completion options.\n */\nexport const CompleteRequestSchema = RequestSchema.extend({\n method: z.literal('completion/complete'),\n params: CompleteRequestParamsSchema\n});\nexport function assertCompleteRequestPrompt(request) {\n if (request.params.ref.type !== 'ref/prompt') {\n throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`);\n }\n void request;\n}\nexport function assertCompleteRequestResourceTemplate(request) {\n if (request.params.ref.type !== 'ref/resource') {\n throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`);\n }\n void request;\n}\n/**\n * The server's response to a completion/complete request\n */\nexport const CompleteResultSchema = ResultSchema.extend({\n completion: z.looseObject({\n /**\n * An array of completion values. Must not exceed 100 items.\n */\n values: z.array(z.string()).max(100),\n /**\n * The total number of completion options available. This can exceed the number of values actually sent in the response.\n */\n total: z.optional(z.number().int()),\n /**\n * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.\n */\n hasMore: z.optional(z.boolean())\n })\n});\n/* Roots */\n/**\n * Represents a root directory or file that the server can operate on.\n */\nexport const RootSchema = z.object({\n /**\n * The URI identifying the root. This *must* start with file:// for now.\n */\n uri: z.string().startsWith('file://'),\n /**\n * An optional name for the root.\n */\n name: z.string().optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Sent from the server to request a list of root URIs from the client.\n */\nexport const ListRootsRequestSchema = RequestSchema.extend({\n method: z.literal('roots/list'),\n params: BaseRequestParamsSchema.optional()\n});\n/**\n * The client's response to a roots/list request from the server.\n */\nexport const ListRootsResultSchema = ResultSchema.extend({\n roots: z.array(RootSchema)\n});\n/**\n * A notification from the client to the server, informing it that the list of roots has changed.\n */\nexport const RootsListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/roots/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\n/* Client messages */\nexport const ClientRequestSchema = z.union([\n PingRequestSchema,\n InitializeRequestSchema,\n CompleteRequestSchema,\n SetLevelRequestSchema,\n GetPromptRequestSchema,\n ListPromptsRequestSchema,\n ListResourcesRequestSchema,\n ListResourceTemplatesRequestSchema,\n ReadResourceRequestSchema,\n SubscribeRequestSchema,\n UnsubscribeRequestSchema,\n CallToolRequestSchema,\n ListToolsRequestSchema,\n GetTaskRequestSchema,\n GetTaskPayloadRequestSchema,\n ListTasksRequestSchema,\n CancelTaskRequestSchema\n]);\nexport const ClientNotificationSchema = z.union([\n CancelledNotificationSchema,\n ProgressNotificationSchema,\n InitializedNotificationSchema,\n RootsListChangedNotificationSchema,\n TaskStatusNotificationSchema\n]);\nexport const ClientResultSchema = z.union([\n EmptyResultSchema,\n CreateMessageResultSchema,\n CreateMessageResultWithToolsSchema,\n ElicitResultSchema,\n ListRootsResultSchema,\n GetTaskResultSchema,\n ListTasksResultSchema,\n CreateTaskResultSchema\n]);\n/* Server messages */\nexport const ServerRequestSchema = z.union([\n PingRequestSchema,\n CreateMessageRequestSchema,\n ElicitRequestSchema,\n ListRootsRequestSchema,\n GetTaskRequestSchema,\n GetTaskPayloadRequestSchema,\n ListTasksRequestSchema,\n CancelTaskRequestSchema\n]);\nexport const ServerNotificationSchema = z.union([\n CancelledNotificationSchema,\n ProgressNotificationSchema,\n LoggingMessageNotificationSchema,\n ResourceUpdatedNotificationSchema,\n ResourceListChangedNotificationSchema,\n ToolListChangedNotificationSchema,\n PromptListChangedNotificationSchema,\n TaskStatusNotificationSchema,\n ElicitationCompleteNotificationSchema\n]);\nexport const ServerResultSchema = z.union([\n EmptyResultSchema,\n InitializeResultSchema,\n CompleteResultSchema,\n GetPromptResultSchema,\n ListPromptsResultSchema,\n ListResourcesResultSchema,\n ListResourceTemplatesResultSchema,\n ReadResourceResultSchema,\n CallToolResultSchema,\n ListToolsResultSchema,\n GetTaskResultSchema,\n ListTasksResultSchema,\n CreateTaskResultSchema\n]);\nexport class McpError extends Error {\n constructor(code, message, data) {\n super(`MCP error ${code}: ${message}`);\n this.code = code;\n this.data = data;\n this.name = 'McpError';\n }\n /**\n * Factory method to create the appropriate error type based on the error code and data\n */\n static fromError(code, message, data) {\n // Check for specific error types\n if (code === ErrorCode.UrlElicitationRequired && data) {\n const errorData = data;\n if (errorData.elicitations) {\n return new UrlElicitationRequiredError(errorData.elicitations, message);\n }\n }\n // Default to generic McpError\n return new McpError(code, message, data);\n }\n}\n/**\n * Specialized error type when a tool requires a URL mode elicitation.\n * This makes it nicer for the client to handle since there is specific data to work with instead of just a code to check against.\n */\nexport class UrlElicitationRequiredError extends McpError {\n constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? 's' : ''} required`) {\n super(ErrorCode.UrlElicitationRequired, message, {\n elicitations: elicitations\n });\n }\n get elicitations() {\n return this.data?.elicitations ?? [];\n }\n}\n//# sourceMappingURL=types.js.map","let crypto;\ncrypto =\n globalThis.crypto?.webcrypto ?? // Node.js [18-16] REPL\n globalThis.crypto ?? // Node.js >18\n import(\"node:crypto\").then(m => m.webcrypto); // Node.js <18 Non-REPL\n/**\n * Creates an array of length `size` of random bytes\n * @param size\n * @returns Array of random ints (0 to 255)\n */\nasync function getRandomValues(size) {\n return (await crypto).getRandomValues(new Uint8Array(size));\n}\n/** Generate cryptographically strong random string\n * @param size The desired length of the string\n * @returns The random string\n */\nasync function random(size) {\n const mask = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~\";\n const evenDistCutoff = Math.pow(2, 8) - Math.pow(2, 8) % mask.length;\n let result = \"\";\n while (result.length < size) {\n const randomBytes = await getRandomValues(size - result.length);\n for (const randomByte of randomBytes) {\n if (randomByte < evenDistCutoff) {\n result += mask[randomByte % mask.length];\n }\n }\n }\n return result;\n}\n/** Generate a PKCE challenge verifier\n * @param length Length of the verifier\n * @returns A random verifier `length` characters long\n */\nasync function generateVerifier(length) {\n return await random(length);\n}\n/** Generate a PKCE code challenge from a code verifier\n * @param code_verifier\n * @returns The base64 url encoded code challenge\n */\nexport async function generateChallenge(code_verifier) {\n const buffer = await (await crypto).subtle.digest(\"SHA-256\", new TextEncoder().encode(code_verifier));\n // Generate base64url string\n // btoa is deprecated in Node.js but is used here for web browser compatibility\n // (which has no good replacement yet, see also https://github.com/whatwg/html/issues/6811)\n return btoa(String.fromCharCode(...new Uint8Array(buffer)))\n .replace(/\\//g, '_')\n .replace(/\\+/g, '-')\n .replace(/=/g, '');\n}\n/** Generate a PKCE challenge pair\n * @param length Length of the verifer (between 43-128). Defaults to 43.\n * @returns PKCE challenge pair\n */\nexport default async function pkceChallenge(length) {\n if (!length)\n length = 43;\n if (length < 43 || length > 128) {\n throw `Expected a length between 43 and 128. Received ${length}.`;\n }\n const verifier = await generateVerifier(length);\n const challenge = await generateChallenge(verifier);\n return {\n code_verifier: verifier,\n code_challenge: challenge,\n };\n}\n/** Verify that a code_verifier produces the expected code challenge\n * @param code_verifier\n * @param expectedChallenge The code challenge to verify\n * @returns True if challenges are equal. False otherwise.\n */\nexport async function verifyChallenge(code_verifier, expectedChallenge) {\n const actualChallenge = await generateChallenge(code_verifier);\n return actualChallenge === expectedChallenge;\n}\n","import * as z from 'zod/v4';\n/**\n * Reusable URL validation that disallows javascript: scheme\n */\nexport const SafeUrlSchema = z\n .url()\n .superRefine((val, ctx) => {\n if (!URL.canParse(val)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'URL must be parseable',\n fatal: true\n });\n return z.NEVER;\n }\n})\n .refine(url => {\n const u = new URL(url);\n return u.protocol !== 'javascript:' && u.protocol !== 'data:' && u.protocol !== 'vbscript:';\n}, { message: 'URL cannot use javascript:, data:, or vbscript: scheme' });\n/**\n * RFC 9728 OAuth Protected Resource Metadata\n */\nexport const OAuthProtectedResourceMetadataSchema = z.looseObject({\n resource: z.string().url(),\n authorization_servers: z.array(SafeUrlSchema).optional(),\n jwks_uri: z.string().url().optional(),\n scopes_supported: z.array(z.string()).optional(),\n bearer_methods_supported: z.array(z.string()).optional(),\n resource_signing_alg_values_supported: z.array(z.string()).optional(),\n resource_name: z.string().optional(),\n resource_documentation: z.string().optional(),\n resource_policy_uri: z.string().url().optional(),\n resource_tos_uri: z.string().url().optional(),\n tls_client_certificate_bound_access_tokens: z.boolean().optional(),\n authorization_details_types_supported: z.array(z.string()).optional(),\n dpop_signing_alg_values_supported: z.array(z.string()).optional(),\n dpop_bound_access_tokens_required: z.boolean().optional()\n});\n/**\n * RFC 8414 OAuth 2.0 Authorization Server Metadata\n */\nexport const OAuthMetadataSchema = z.looseObject({\n issuer: z.string(),\n authorization_endpoint: SafeUrlSchema,\n token_endpoint: SafeUrlSchema,\n registration_endpoint: SafeUrlSchema.optional(),\n scopes_supported: z.array(z.string()).optional(),\n response_types_supported: z.array(z.string()),\n response_modes_supported: z.array(z.string()).optional(),\n grant_types_supported: z.array(z.string()).optional(),\n token_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),\n service_documentation: SafeUrlSchema.optional(),\n revocation_endpoint: SafeUrlSchema.optional(),\n revocation_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n revocation_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),\n introspection_endpoint: z.string().optional(),\n introspection_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n introspection_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),\n code_challenge_methods_supported: z.array(z.string()).optional(),\n client_id_metadata_document_supported: z.boolean().optional()\n});\n/**\n * OpenID Connect Discovery 1.0 Provider Metadata\n * see: https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata\n */\nexport const OpenIdProviderMetadataSchema = z.looseObject({\n issuer: z.string(),\n authorization_endpoint: SafeUrlSchema,\n token_endpoint: SafeUrlSchema,\n userinfo_endpoint: SafeUrlSchema.optional(),\n jwks_uri: SafeUrlSchema,\n registration_endpoint: SafeUrlSchema.optional(),\n scopes_supported: z.array(z.string()).optional(),\n response_types_supported: z.array(z.string()),\n response_modes_supported: z.array(z.string()).optional(),\n grant_types_supported: z.array(z.string()).optional(),\n acr_values_supported: z.array(z.string()).optional(),\n subject_types_supported: z.array(z.string()),\n id_token_signing_alg_values_supported: z.array(z.string()),\n id_token_encryption_alg_values_supported: z.array(z.string()).optional(),\n id_token_encryption_enc_values_supported: z.array(z.string()).optional(),\n userinfo_signing_alg_values_supported: z.array(z.string()).optional(),\n userinfo_encryption_alg_values_supported: z.array(z.string()).optional(),\n userinfo_encryption_enc_values_supported: z.array(z.string()).optional(),\n request_object_signing_alg_values_supported: z.array(z.string()).optional(),\n request_object_encryption_alg_values_supported: z.array(z.string()).optional(),\n request_object_encryption_enc_values_supported: z.array(z.string()).optional(),\n token_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),\n display_values_supported: z.array(z.string()).optional(),\n claim_types_supported: z.array(z.string()).optional(),\n claims_supported: z.array(z.string()).optional(),\n service_documentation: z.string().optional(),\n claims_locales_supported: z.array(z.string()).optional(),\n ui_locales_supported: z.array(z.string()).optional(),\n claims_parameter_supported: z.boolean().optional(),\n request_parameter_supported: z.boolean().optional(),\n request_uri_parameter_supported: z.boolean().optional(),\n require_request_uri_registration: z.boolean().optional(),\n op_policy_uri: SafeUrlSchema.optional(),\n op_tos_uri: SafeUrlSchema.optional(),\n client_id_metadata_document_supported: z.boolean().optional()\n});\n/**\n * OpenID Connect Discovery metadata that may include OAuth 2.0 fields\n * This schema represents the real-world scenario where OIDC providers\n * return a mix of OpenID Connect and OAuth 2.0 metadata fields\n */\nexport const OpenIdProviderDiscoveryMetadataSchema = z.object({\n ...OpenIdProviderMetadataSchema.shape,\n ...OAuthMetadataSchema.pick({\n code_challenge_methods_supported: true\n }).shape\n});\n/**\n * OAuth 2.1 token response\n */\nexport const OAuthTokensSchema = z\n .object({\n access_token: z.string(),\n id_token: z.string().optional(), // Optional for OAuth 2.1, but necessary in OpenID Connect\n token_type: z.string(),\n expires_in: z.coerce.number().optional(),\n scope: z.string().optional(),\n refresh_token: z.string().optional()\n})\n .strip();\n/**\n * OAuth 2.1 error response\n */\nexport const OAuthErrorResponseSchema = z.object({\n error: z.string(),\n error_description: z.string().optional(),\n error_uri: z.string().optional()\n});\n/**\n * Optional version of SafeUrlSchema that allows empty string for retrocompatibility on tos_uri and logo_uri\n */\nexport const OptionalSafeUrlSchema = SafeUrlSchema.optional().or(z.literal('').transform(() => undefined));\n/**\n * RFC 7591 OAuth 2.0 Dynamic Client Registration metadata\n */\nexport const OAuthClientMetadataSchema = z\n .object({\n redirect_uris: z.array(SafeUrlSchema),\n token_endpoint_auth_method: z.string().optional(),\n grant_types: z.array(z.string()).optional(),\n response_types: z.array(z.string()).optional(),\n client_name: z.string().optional(),\n client_uri: SafeUrlSchema.optional(),\n logo_uri: OptionalSafeUrlSchema,\n scope: z.string().optional(),\n contacts: z.array(z.string()).optional(),\n tos_uri: OptionalSafeUrlSchema,\n policy_uri: z.string().optional(),\n jwks_uri: SafeUrlSchema.optional(),\n jwks: z.any().optional(),\n software_id: z.string().optional(),\n software_version: z.string().optional(),\n software_statement: z.string().optional()\n})\n .strip();\n/**\n * RFC 7591 OAuth 2.0 Dynamic Client Registration client information\n */\nexport const OAuthClientInformationSchema = z\n .object({\n client_id: z.string(),\n client_secret: z.string().optional(),\n client_id_issued_at: z.number().optional(),\n client_secret_expires_at: z.number().optional()\n})\n .strip();\n/**\n * RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata)\n */\nexport const OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema);\n/**\n * RFC 7591 OAuth 2.0 Dynamic Client Registration error response\n */\nexport const OAuthClientRegistrationErrorSchema = z\n .object({\n error: z.string(),\n error_description: z.string().optional()\n})\n .strip();\n/**\n * RFC 7009 OAuth 2.0 Token Revocation request\n */\nexport const OAuthTokenRevocationRequestSchema = z\n .object({\n token: z.string(),\n token_type_hint: z.string().optional()\n})\n .strip();\n//# sourceMappingURL=auth.js.map","/**\n * Base class for all OAuth errors\n */\nexport class OAuthError extends Error {\n constructor(message, errorUri) {\n super(message);\n this.errorUri = errorUri;\n this.name = this.constructor.name;\n }\n /**\n * Converts the error to a standard OAuth error response object\n */\n toResponseObject() {\n const response = {\n error: this.errorCode,\n error_description: this.message\n };\n if (this.errorUri) {\n response.error_uri = this.errorUri;\n }\n return response;\n }\n get errorCode() {\n return this.constructor.errorCode;\n }\n}\n/**\n * Invalid request error - The request is missing a required parameter,\n * includes an invalid parameter value, includes a parameter more than once,\n * or is otherwise malformed.\n */\nexport class InvalidRequestError extends OAuthError {\n}\nInvalidRequestError.errorCode = 'invalid_request';\n/**\n * Invalid client error - Client authentication failed (e.g., unknown client, no client\n * authentication included, or unsupported authentication method).\n */\nexport class InvalidClientError extends OAuthError {\n}\nInvalidClientError.errorCode = 'invalid_client';\n/**\n * Invalid grant error - The provided authorization grant or refresh token is\n * invalid, expired, revoked, does not match the redirection URI used in the\n * authorization request, or was issued to another client.\n */\nexport class InvalidGrantError extends OAuthError {\n}\nInvalidGrantError.errorCode = 'invalid_grant';\n/**\n * Unauthorized client error - The authenticated client is not authorized to use\n * this authorization grant type.\n */\nexport class UnauthorizedClientError extends OAuthError {\n}\nUnauthorizedClientError.errorCode = 'unauthorized_client';\n/**\n * Unsupported grant type error - The authorization grant type is not supported\n * by the authorization server.\n */\nexport class UnsupportedGrantTypeError extends OAuthError {\n}\nUnsupportedGrantTypeError.errorCode = 'unsupported_grant_type';\n/**\n * Invalid scope error - The requested scope is invalid, unknown, malformed, or\n * exceeds the scope granted by the resource owner.\n */\nexport class InvalidScopeError extends OAuthError {\n}\nInvalidScopeError.errorCode = 'invalid_scope';\n/**\n * Access denied error - The resource owner or authorization server denied the request.\n */\nexport class AccessDeniedError extends OAuthError {\n}\nAccessDeniedError.errorCode = 'access_denied';\n/**\n * Server error - The authorization server encountered an unexpected condition\n * that prevented it from fulfilling the request.\n */\nexport class ServerError extends OAuthError {\n}\nServerError.errorCode = 'server_error';\n/**\n * Temporarily unavailable error - The authorization server is currently unable to\n * handle the request due to a temporary overloading or maintenance of the server.\n */\nexport class TemporarilyUnavailableError extends OAuthError {\n}\nTemporarilyUnavailableError.errorCode = 'temporarily_unavailable';\n/**\n * Unsupported response type error - The authorization server does not support\n * obtaining an authorization code using this method.\n */\nexport class UnsupportedResponseTypeError extends OAuthError {\n}\nUnsupportedResponseTypeError.errorCode = 'unsupported_response_type';\n/**\n * Unsupported token type error - The authorization server does not support\n * the requested token type.\n */\nexport class UnsupportedTokenTypeError extends OAuthError {\n}\nUnsupportedTokenTypeError.errorCode = 'unsupported_token_type';\n/**\n * Invalid token error - The access token provided is expired, revoked, malformed,\n * or invalid for other reasons.\n */\nexport class InvalidTokenError extends OAuthError {\n}\nInvalidTokenError.errorCode = 'invalid_token';\n/**\n * Method not allowed error - The HTTP method used is not allowed for this endpoint.\n * (Custom, non-standard error)\n */\nexport class MethodNotAllowedError extends OAuthError {\n}\nMethodNotAllowedError.errorCode = 'method_not_allowed';\n/**\n * Too many requests error - Rate limit exceeded.\n * (Custom, non-standard error based on RFC 6585)\n */\nexport class TooManyRequestsError extends OAuthError {\n}\nTooManyRequestsError.errorCode = 'too_many_requests';\n/**\n * Invalid client metadata error - The client metadata is invalid.\n * (Custom error for dynamic client registration - RFC 7591)\n */\nexport class InvalidClientMetadataError extends OAuthError {\n}\nInvalidClientMetadataError.errorCode = 'invalid_client_metadata';\n/**\n * Insufficient scope error - The request requires higher privileges than provided by the access token.\n */\nexport class InsufficientScopeError extends OAuthError {\n}\nInsufficientScopeError.errorCode = 'insufficient_scope';\n/**\n * Invalid target error - The requested resource is invalid, missing, unknown, or malformed.\n * (Custom error for resource indicators - RFC 8707)\n */\nexport class InvalidTargetError extends OAuthError {\n}\nInvalidTargetError.errorCode = 'invalid_target';\n/**\n * A utility class for defining one-off error codes\n */\nexport class CustomOAuthError extends OAuthError {\n constructor(customErrorCode, message, errorUri) {\n super(message, errorUri);\n this.customErrorCode = customErrorCode;\n }\n get errorCode() {\n return this.customErrorCode;\n }\n}\n/**\n * A full list of all OAuthErrors, enabling parsing from error responses\n */\nexport const OAUTH_ERRORS = {\n [InvalidRequestError.errorCode]: InvalidRequestError,\n [InvalidClientError.errorCode]: InvalidClientError,\n [InvalidGrantError.errorCode]: InvalidGrantError,\n [UnauthorizedClientError.errorCode]: UnauthorizedClientError,\n [UnsupportedGrantTypeError.errorCode]: UnsupportedGrantTypeError,\n [InvalidScopeError.errorCode]: InvalidScopeError,\n [AccessDeniedError.errorCode]: AccessDeniedError,\n [ServerError.errorCode]: ServerError,\n [TemporarilyUnavailableError.errorCode]: TemporarilyUnavailableError,\n [UnsupportedResponseTypeError.errorCode]: UnsupportedResponseTypeError,\n [UnsupportedTokenTypeError.errorCode]: UnsupportedTokenTypeError,\n [InvalidTokenError.errorCode]: InvalidTokenError,\n [MethodNotAllowedError.errorCode]: MethodNotAllowedError,\n [TooManyRequestsError.errorCode]: TooManyRequestsError,\n [InvalidClientMetadataError.errorCode]: InvalidClientMetadataError,\n [InsufficientScopeError.errorCode]: InsufficientScopeError,\n [InvalidTargetError.errorCode]: InvalidTargetError\n};\n//# sourceMappingURL=errors.js.map","import{createRequire} from\"node:module\";const require=createRequire(import.meta.url);\nimport{a as O}from\"./chunk-4RUAZWKT.js\";import{e as j,f as K,g as C,h as re,i as Pe,j as It,k as L}from\"./chunk-SAI2SPQQ.js\";function $(e,t){for(;t<e.length;){if(e[t]===\"\\\\\"&&e[t+1]===`\n`){t+=2;continue}if(/\\s/.test(e[t])){t++;continue}break}return t}var Re=[\"=\",\"+=\",\"-=\",\"*=\",\"/=\",\"%=\",\"<<=\",\">>=\",\"&=\",\"|=\",\"^=\"];function ge(e){if(e.includes(\"#\")){let[r,s]=e.split(\"#\"),n=Number.parseInt(r,10);if(n<2||n>64)return Number.NaN;if(n<=36){let i=Number.parseInt(s,n);return i>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:i}let a=0;for(let i of s){let l;if(/[0-9]/.test(i))l=i.charCodeAt(0)-48;else if(/[a-z]/.test(i))l=i.charCodeAt(0)-97+10;else if(/[A-Z]/.test(i))l=i.charCodeAt(0)-65+36;else if(i===\"@\")l=62;else if(i===\"_\")l=63;else return Number.NaN;if(l>=n)return Number.NaN;if(a=a*n+l,a>Number.MAX_SAFE_INTEGER)return Number.MAX_SAFE_INTEGER}return a}if(e.startsWith(\"0x\")||e.startsWith(\"0X\")){let r=Number.parseInt(e.slice(2),16);return r>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:r}if(e.startsWith(\"0\")&&e.length>1&&/^[0-9]+$/.test(e)){if(/[89]/.test(e))return Number.NaN;let r=Number.parseInt(e,8);return r>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:r}let t=Number.parseInt(e,10);return t>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:t}function vt(e,t,r,s){if(r.slice(s,s+3)!==\"$((\")return null;let n=s+3,a=1,i=n;for(;n<r.length-1&&a>0;)r[n]===\"(\"&&r[n+1]===\"(\"?(a++,n+=2):r[n]===\")\"&&r[n+1]===\")\"?(a--,a>0&&(n+=2)):n++;let l=r.slice(i,n),{expr:o}=e(t,l,0);return n+=2,{expr:{type:\"ArithNested\",expression:o},pos:n}}function Dt(e,t){if(e.slice(t,t+2)!==\"$'\")return null;let r=t+2,s=\"\";for(;r<e.length&&e[r]!==\"'\";)if(e[r]===\"\\\\\"&&r+1<e.length){let a=e[r+1];switch(a){case\"n\":s+=`\n`;break;case\"t\":s+=\"\t\";break;case\"r\":s+=\"\\r\";break;case\"\\\\\":s+=\"\\\\\";break;case\"'\":s+=\"'\";break;default:s+=a}r+=2}else s+=e[r],r++;e[r]===\"'\"&&r++;let n=Number.parseInt(s,10);return{expr:{type:\"ArithNumber\",value:Number.isNaN(n)?0:n},pos:r}}function xt(e,t){if(e.slice(t,t+2)!=='$\"')return null;let r=t+2,s=\"\";for(;r<e.length&&e[r]!=='\"';)e[r]===\"\\\\\"&&r+1<e.length?(s+=e[r+1],r+=2):(s+=e[r],r++);e[r]==='\"'&&r++;let n=Number.parseInt(s,10);return{expr:{type:\"ArithNumber\",value:Number.isNaN(n)?0:n},pos:r}}function kr(e){let t=\"\",r=0;for(;r<e.length;)if(e[r]==='\"'){for(r++;r<e.length&&e[r]!=='\"';)e[r]===\"\\\\\"&&r+1<e.length?(t+=e[r+1],r+=2):(t+=e[r],r++);r<e.length&&r++}else t+=e[r],r++;return t}function M(e,t){let r=kr(t),{expr:s,pos:n}=Z(e,r,0),a=$(r,n);if(a<r.length){let i=t.slice(a).trim();if(i)return{type:\"ArithmeticExpression\",originalText:t,expression:{type:\"ArithSyntaxError\",errorToken:i,message:`${i}: syntax error: invalid arithmetic operator (error token is \"${i}\")`}}}return{type:\"ArithmeticExpression\",expression:s,originalText:t}}function F(e,t){return{expr:{type:\"ArithSyntaxError\",errorToken:e,message:`syntax error: operand expected (error token is \"${e}\")`},pos:t}}function z(e,t){return $(e,t)>=e.length}function Z(e,t,r){return Pr(e,t,r)}function Pr(e,t,r){let{expr:s,pos:n}=ye(e,t,r);for(n=$(t,n);t[n]===\",\";){if(n++,z(t,n))return F(\",\",n);let{expr:i,pos:l}=ye(e,t,n);s={type:\"ArithBinary\",operator:\",\",left:s,right:i},n=$(t,l)}return{expr:s,pos:n}}function ye(e,t,r){let{expr:s,pos:n}=Rr(e,t,r);if(n=$(t,n),t[n]===\"?\"){n++;let{expr:a,pos:i}=Z(e,t,n);if(n=$(t,i),t[n]===\":\"){n++;let{expr:l,pos:o}=Z(e,t,n);return{expr:{type:\"ArithTernary\",condition:s,consequent:a,alternate:l},pos:o}}}return{expr:s,pos:n}}function Rr(e,t,r){let{expr:s,pos:n}=_t(e,t,r);for(;n=$(t,n),t.slice(n,n+2)===\"||\";){if(n+=2,z(t,n))return F(\"||\",n);let{expr:i,pos:l}=_t(e,t,n);s={type:\"ArithBinary\",operator:\"||\",left:s,right:i},n=l}return{expr:s,pos:n}}function _t(e,t,r){let{expr:s,pos:n}=$t(e,t,r);for(;n=$(t,n),t.slice(n,n+2)===\"&&\";){if(n+=2,z(t,n))return F(\"&&\",n);let{expr:i,pos:l}=$t(e,t,n);s={type:\"ArithBinary\",operator:\"&&\",left:s,right:i},n=l}return{expr:s,pos:n}}function $t(e,t,r){let{expr:s,pos:n}=Ct(e,t,r);for(;n=$(t,n),t[n]===\"|\"&&t[n+1]!==\"|\";){if(n++,z(t,n))return F(\"|\",n);let{expr:i,pos:l}=Ct(e,t,n);s={type:\"ArithBinary\",operator:\"|\",left:s,right:i},n=l}return{expr:s,pos:n}}function Ct(e,t,r){let{expr:s,pos:n}=Ot(e,t,r);for(;n=$(t,n),t[n]===\"^\";){if(n++,z(t,n))return F(\"^\",n);let{expr:i,pos:l}=Ot(e,t,n);s={type:\"ArithBinary\",operator:\"^\",left:s,right:i},n=l}return{expr:s,pos:n}}function Ot(e,t,r){let{expr:s,pos:n}=Lt(e,t,r);for(;n=$(t,n),t[n]===\"&\"&&t[n+1]!==\"&\";){if(n++,z(t,n))return F(\"&\",n);let{expr:i,pos:l}=Lt(e,t,n);s={type:\"ArithBinary\",operator:\"&\",left:s,right:i},n=l}return{expr:s,pos:n}}function Lt(e,t,r){let{expr:s,pos:n}=Wt(e,t,r);for(;n=$(t,n),t.slice(n,n+2)===\"==\"||t.slice(n,n+2)===\"!=\";){let a=t.slice(n,n+2);if(n+=2,z(t,n))return F(a,n);let{expr:i,pos:l}=Wt(e,t,n);s={type:\"ArithBinary\",operator:a,left:s,right:i},n=l}return{expr:s,pos:n}}function Wt(e,t,r){let{expr:s,pos:n}=ze(e,t,r);for(;;)if(n=$(t,n),t.slice(n,n+2)===\"<=\"||t.slice(n,n+2)===\">=\"){let a=t.slice(n,n+2);if(n+=2,z(t,n))return F(a,n);let{expr:i,pos:l}=ze(e,t,n);s={type:\"ArithBinary\",operator:a,left:s,right:i},n=l}else if(t[n]===\"<\"||t[n]===\">\"){let a=t[n];if(n++,z(t,n))return F(a,n);let{expr:i,pos:l}=ze(e,t,n);s={type:\"ArithBinary\",operator:a,left:s,right:i},n=l}else break;return{expr:s,pos:n}}function ze(e,t,r){let{expr:s,pos:n}=Tt(e,t,r);for(;n=$(t,n),t.slice(n,n+2)===\"<<\"||t.slice(n,n+2)===\">>\";){let a=t.slice(n,n+2);if(n+=2,z(t,n))return F(a,n);let{expr:i,pos:l}=Tt(e,t,n);s={type:\"ArithBinary\",operator:a,left:s,right:i},n=l}return{expr:s,pos:n}}function Tt(e,t,r){let{expr:s,pos:n}=Mt(e,t,r);for(;n=$(t,n),(t[n]===\"+\"||t[n]===\"-\")&&t[n+1]!==t[n];){let a=t[n];if(n++,z(t,n))return F(a,n);let{expr:i,pos:l}=Mt(e,t,n);s={type:\"ArithBinary\",operator:a,left:s,right:i},n=l}return{expr:s,pos:n}}function Mt(e,t,r){let{expr:s,pos:n}=Ie(e,t,r);for(;;)if(n=$(t,n),t[n]===\"*\"&&t[n+1]!==\"*\"){if(n++,z(t,n))return F(\"*\",n);let{expr:i,pos:l}=Ie(e,t,n);s={type:\"ArithBinary\",operator:\"*\",left:s,right:i},n=l}else if(t[n]===\"/\"||t[n]===\"%\"){let a=t[n];if(n++,z(t,n))return F(a,n);let{expr:i,pos:l}=Ie(e,t,n);s={type:\"ArithBinary\",operator:a,left:s,right:i},n=l}else break;return{expr:s,pos:n}}function Ie(e,t,r){let{expr:s,pos:n}=Ge(e,t,r),a=$(t,n);if(t.slice(a,a+2)===\"**\"){if(a+=2,z(t,a))return F(\"**\",a);let{expr:l,pos:o}=Ie(e,t,a);return{expr:{type:\"ArithBinary\",operator:\"**\",left:s,right:l},pos:o}}return{expr:s,pos:n}}function Ge(e,t,r){let s=$(t,r);if(t.slice(s,s+2)===\"++\"||t.slice(s,s+2)===\"--\"){let n=t.slice(s,s+2);s+=2;let{expr:a,pos:i}=Ge(e,t,s);return{expr:{type:\"ArithUnary\",operator:n,operand:a,prefix:!0},pos:i}}if(t[s]===\"+\"||t[s]===\"-\"||t[s]===\"!\"||t[s]===\"~\"){let n=t[s];s++;let{expr:a,pos:i}=Ge(e,t,s);return{expr:{type:\"ArithUnary\",operator:n,operand:a,prefix:!0},pos:i}}return vr(e,t,s)}function Ir(e,t){let r=e[t];return r===\"$\"||r===\"`\"}function vr(e,t,r){let{expr:s,pos:n}=Vt(e,t,r,!1),a=[s];for(;Ir(t,n);){let{expr:l,pos:o}=Vt(e,t,n,!0);a.push(l),n=o}a.length>1&&(s={type:\"ArithConcat\",parts:a});let i;if(t[n]===\"[\"&&s.type===\"ArithConcat\"){n++;let{expr:l,pos:o}=Z(e,t,n);i=l,n=o,t[n]===\"]\"&&n++}if(i&&s.type===\"ArithConcat\"&&(s={type:\"ArithDynamicElement\",nameExpr:s,subscript:i},i=void 0),n=$(t,n),s.type===\"ArithConcat\"||s.type===\"ArithVariable\"||s.type===\"ArithDynamicElement\"){for(let l of Re)if(t.slice(n,n+l.length)===l&&t.slice(n,n+l.length+1)!==\"==\"){n+=l.length;let{expr:o,pos:c}=ye(e,t,n);return s.type===\"ArithDynamicElement\"?{expr:{type:\"ArithDynamicAssignment\",operator:l,target:s.nameExpr,subscript:s.subscript,value:o},pos:c}:s.type===\"ArithConcat\"?{expr:{type:\"ArithDynamicAssignment\",operator:l,target:s,value:o},pos:c}:{expr:{type:\"ArithAssignment\",operator:l,variable:s.name,value:o},pos:c}}}if(t.slice(n,n+2)===\"++\"||t.slice(n,n+2)===\"--\"){let l=t.slice(n,n+2);return n+=2,{expr:{type:\"ArithUnary\",operator:l,operand:s,prefix:!1},pos:n}}return{expr:s,pos:n}}function Vt(e,t,r,s=!1){let n=$(t,r),a=vt(Z,e,t,n);if(a)return a;let i=Dt(t,n);if(i)return i;let l=xt(t,n);if(l)return l;if(t.slice(n,n+2)===\"$(\"&&t[n+2]!==\"(\"){n+=2;let c=1,u=n;for(;n<t.length&&c>0;)t[n]===\"(\"?c++:t[n]===\")\"&&c--,c>0&&n++;let f=t.slice(u,n);return n++,{expr:{type:\"ArithCommandSubst\",command:f},pos:n}}if(t[n]===\"`\"){n++;let c=n;for(;n<t.length&&t[n]!==\"`\";)n++;let u=t.slice(c,n);return t[n]===\"`\"&&n++,{expr:{type:\"ArithCommandSubst\",command:u},pos:n}}if(t[n]===\"(\"){n++;let{expr:c,pos:u}=Z(e,t,n);return n=$(t,u),t[n]===\")\"&&n++,{expr:{type:\"ArithGroup\",expression:c},pos:n}}if(t[n]===\"'\"){n++;let c=\"\";for(;n<t.length&&t[n]!==\"'\";)c+=t[n],n++;t[n]===\"'\"&&n++;let u=Number.parseInt(c,10);return{expr:{type:\"ArithSingleQuote\",content:c,value:Number.isNaN(u)?0:u},pos:n}}if(t[n]==='\"'){n++;let c=\"\";for(;n<t.length&&t[n]!=='\"';)t[n]===\"\\\\\"&&n+1<t.length?(c+=t[n+1],n+=2):(c+=t[n],n++);t[n]==='\"'&&n++;let u=c.trim();if(!u)return{expr:{type:\"ArithNumber\",value:0},pos:n};let{expr:f}=Z(e,u,0);return{expr:f,pos:n}}if(/[0-9]/.test(t[n])){let c=\"\",u=!1,f=!1;for(;n<t.length;){let d=t[n];if(u)if(/[0-9a-zA-Z@_]/.test(d))c+=d,n++;else break;else if(d===\"#\")u=!0,c+=d,n++;else if(c===\"0\"&&(d===\"x\"||d===\"X\")&&n+1<t.length&&/[0-9a-fA-F]/.test(t[n+1]))f=!0,c+=d,n++;else if(f&&/[0-9a-fA-F]/.test(d))c+=d,n++;else if(!f&&/[0-9]/.test(d))c+=d,n++;else break}if(n<t.length&&/[a-zA-Z_]/.test(t[n])){let d=c;for(;n<t.length&&/[a-zA-Z0-9_]/.test(t[n]);)d+=t[n],n++;return{expr:{type:\"ArithSyntaxError\",errorToken:d,message:`${d}: value too great for base (error token is \"${d}\")`},pos:n}}if(t[n]===\".\"&&/[0-9]/.test(t[n+1]))throw new C(`${c}.${t[n+1]}...: syntax error: invalid arithmetic operator`);if(t[n]===\"[\"){let d=t.slice(n).trim();return{expr:{type:\"ArithNumberSubscript\",number:c,errorToken:d},pos:t.length}}return{expr:{type:\"ArithNumber\",value:ge(c)},pos:n}}if(t[n]===\"$\"&&t[n+1]===\"{\"){let c=n+2,u=1,f=c;for(;f<t.length&&u>0;)t[f]===\"{\"?u++:t[f]===\"}\"&&u--,u>0&&f++;let h=t.slice(c,f),d=f+1;if(t[d]===\"#\"){let m=d+1;for(;m<t.length&&/[0-9a-zA-Z@_]/.test(t[m]);)m++;let g=t.slice(d+1,m);return{expr:{type:\"ArithDynamicBase\",baseExpr:h,value:g},pos:m}}if(/[0-9]/.test(t[d])||t[d]===\"x\"||t[d]===\"X\"){let m=d;if(t[d]===\"x\"||t[d]===\"X\")for(m++;m<t.length&&/[0-9a-fA-F]/.test(t[m]);)m++;else for(;m<t.length&&/[0-9]/.test(t[m]);)m++;let g=t.slice(d,m);return{expr:{type:\"ArithDynamicNumber\",prefix:h,suffix:g},pos:m}}return n=d,{expr:{type:\"ArithBracedExpansion\",content:h},pos:n}}if(t[n]===\"$\"&&n+1<t.length&&/[0-9]/.test(t[n+1])){n++;let c=\"\";for(;n<t.length&&/[0-9]/.test(t[n]);)c+=t[n],n++;return{expr:{type:\"ArithVariable\",name:c,hasDollarPrefix:!0},pos:n}}if(t[n]===\"$\"&&n+1<t.length&&/[*@#?\\-!$]/.test(t[n+1])){let c=t[n+1];return n+=2,{expr:{type:\"ArithSpecialVar\",name:c},pos:n}}let o=!1;if(t[n]===\"$\"&&n+1<t.length&&/[a-zA-Z_]/.test(t[n+1])&&(o=!0,n++),n<t.length&&/[a-zA-Z_]/.test(t[n])){let c=\"\";for(;n<t.length&&/[a-zA-Z0-9_]/.test(t[n]);)c+=t[n],n++;if(t[n]===\"[\"&&!s){n++;let u;if(t[n]===\"'\"||t[n]==='\"'){let h=t[n];for(n++,u=\"\";n<t.length&&t[n]!==h;)u+=t[n],n++;t[n]===h&&n++,n=$(t,n),t[n]===\"]\"&&n++}let f;if(u===void 0){let{expr:h,pos:d}=Z(e,t,n);f=h,n=d,t[n]===\"]\"&&n++}if(n=$(t,n),t[n]===\"[\"&&f)return{expr:{type:\"ArithDoubleSubscript\",array:c,index:f},pos:n};if(!s){for(let h of Re)if(t.slice(n,n+h.length)===h&&t.slice(n,n+h.length+1)!==\"==\"){n+=h.length;let{expr:d,pos:m}=ye(e,t,n);return{expr:{type:\"ArithAssignment\",operator:h,variable:c,subscript:f,stringKey:u,value:d},pos:m}}}return{expr:{type:\"ArithArrayElement\",array:c,index:f,stringKey:u},pos:n}}if(n=$(t,n),!s){for(let u of Re)if(t.slice(n,n+u.length)===u&&t.slice(n,n+u.length+1)!==\"==\"){n+=u.length;let{expr:f,pos:h}=ye(e,t,n);return{expr:{type:\"ArithAssignment\",operator:u,variable:c,value:f},pos:h}}}return{expr:{type:\"ArithVariable\",name:c,hasDollarPrefix:o},pos:n}}if(t[n]===\"#\"){let c=n+1;for(;c<t.length&&t[c]!==`\n`;)c++;let u=t.slice(n,c).trim()||\"#\";return{expr:{type:\"ArithSyntaxError\",errorToken:u,message:`${u}: syntax error: invalid arithmetic operator (error token is \"${u}\")`},pos:t.length}}return{expr:{type:\"ArithNumber\",value:0},pos:n}}var w={script(e){return{type:\"Script\",statements:e}},statement(e,t=[],r=!1,s,n){let a={type:\"Statement\",pipelines:e,operators:t,background:r};return s&&(a.deferredError=s),n!==void 0&&(a.sourceText=n),a},pipeline(e,t=!1,r=!1,s=!1,n){return{type:\"Pipeline\",commands:e,negated:t,timed:r,timePosix:s,pipeStderr:n}},simpleCommand(e,t=[],r=[],s=[]){return{type:\"SimpleCommand\",name:e,args:t,assignments:r,redirections:s}},word(e){return{type:\"Word\",parts:e}},literal(e){return{type:\"Literal\",value:e}},singleQuoted(e){return{type:\"SingleQuoted\",value:e}},doubleQuoted(e){return{type:\"DoubleQuoted\",parts:e}},escaped(e){return{type:\"Escaped\",value:e}},parameterExpansion(e,t=null){return{type:\"ParameterExpansion\",parameter:e,operation:t}},commandSubstitution(e,t=!1){return{type:\"CommandSubstitution\",body:e,legacy:t}},arithmeticExpansion(e){return{type:\"ArithmeticExpansion\",expression:e}},assignment(e,t,r=!1,s=null){return{type:\"Assignment\",name:e,value:t,append:r,array:s}},redirection(e,t,r=null,s){let n={type:\"Redirection\",fd:r,operator:e,target:t};return s&&(n.fdVariable=s),n},hereDoc(e,t,r=!1,s=!1){return{type:\"HereDoc\",delimiter:e,content:t,stripTabs:r,quoted:s}},ifNode(e,t=null,r=[]){return{type:\"If\",clauses:e,elseBody:t,redirections:r}},forNode(e,t,r,s=[]){return{type:\"For\",variable:e,words:t,body:r,redirections:s}},whileNode(e,t,r=[]){return{type:\"While\",condition:e,body:t,redirections:r}},untilNode(e,t,r=[]){return{type:\"Until\",condition:e,body:t,redirections:r}},caseNode(e,t,r=[]){return{type:\"Case\",word:e,items:t,redirections:r}},caseItem(e,t,r=\";;\"){return{type:\"CaseItem\",patterns:e,body:t,terminator:r}},subshell(e,t=[]){return{type:\"Subshell\",body:e,redirections:t}},group(e,t=[]){return{type:\"Group\",body:e,redirections:t}},functionDef(e,t,r=[],s){return{type:\"FunctionDef\",name:e,body:t,redirections:r,sourceFile:s}},conditionalCommand(e,t=[],r){return{type:\"ConditionalCommand\",expression:e,redirections:t,line:r}},arithmeticCommand(e,t=[],r){return{type:\"ArithmeticCommand\",expression:e,redirections:t,line:r}}};var p;(function(e){e.EOF=\"EOF\",e.NEWLINE=\"NEWLINE\",e.SEMICOLON=\"SEMICOLON\",e.AMP=\"AMP\",e.PIPE=\"PIPE\",e.PIPE_AMP=\"PIPE_AMP\",e.AND_AND=\"AND_AND\",e.OR_OR=\"OR_OR\",e.BANG=\"BANG\",e.LESS=\"LESS\",e.GREAT=\"GREAT\",e.DLESS=\"DLESS\",e.DGREAT=\"DGREAT\",e.LESSAND=\"LESSAND\",e.GREATAND=\"GREATAND\",e.LESSGREAT=\"LESSGREAT\",e.DLESSDASH=\"DLESSDASH\",e.CLOBBER=\"CLOBBER\",e.TLESS=\"TLESS\",e.AND_GREAT=\"AND_GREAT\",e.AND_DGREAT=\"AND_DGREAT\",e.LPAREN=\"LPAREN\",e.RPAREN=\"RPAREN\",e.LBRACE=\"LBRACE\",e.RBRACE=\"RBRACE\",e.DSEMI=\"DSEMI\",e.SEMI_AND=\"SEMI_AND\",e.SEMI_SEMI_AND=\"SEMI_SEMI_AND\",e.DBRACK_START=\"DBRACK_START\",e.DBRACK_END=\"DBRACK_END\",e.DPAREN_START=\"DPAREN_START\",e.DPAREN_END=\"DPAREN_END\",e.IF=\"IF\",e.THEN=\"THEN\",e.ELSE=\"ELSE\",e.ELIF=\"ELIF\",e.FI=\"FI\",e.FOR=\"FOR\",e.WHILE=\"WHILE\",e.UNTIL=\"UNTIL\",e.DO=\"DO\",e.DONE=\"DONE\",e.CASE=\"CASE\",e.ESAC=\"ESAC\",e.IN=\"IN\",e.FUNCTION=\"FUNCTION\",e.SELECT=\"SELECT\",e.TIME=\"TIME\",e.COPROC=\"COPROC\",e.WORD=\"WORD\",e.NAME=\"NAME\",e.NUMBER=\"NUMBER\",e.ASSIGNMENT_WORD=\"ASSIGNMENT_WORD\",e.FD_VARIABLE=\"FD_VARIABLE\",e.COMMENT=\"COMMENT\",e.HEREDOC_CONTENT=\"HEREDOC_CONTENT\"})(p||(p={}));var pe=class extends Error{line;column;constructor(t,r,s){super(`line ${r}: ${t}`),this.line=r,this.column=s,this.name=\"LexerError\"}},Bt=new Map([[\"if\",p.IF],[\"then\",p.THEN],[\"else\",p.ELSE],[\"elif\",p.ELIF],[\"fi\",p.FI],[\"for\",p.FOR],[\"while\",p.WHILE],[\"until\",p.UNTIL],[\"do\",p.DO],[\"done\",p.DONE],[\"case\",p.CASE],[\"esac\",p.ESAC],[\"in\",p.IN],[\"function\",p.FUNCTION],[\"select\",p.SELECT],[\"time\",p.TIME],[\"coproc\",p.COPROC]]);function Ft(e){let t=e.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);if(!t)return!1;let r=e.slice(t[0].length);if(r===\"\"||r===\"+\")return!0;if(r[0]===\"[\"){let s=0,n=0;for(;n<r.length;n++)if(r[n]===\"[\")s++;else if(r[n]===\"]\"&&(s--,s===0))break;if(s!==0||n>=r.length)return!1;let a=r.slice(n+1);return a===\"\"||a===\"+\"}return!1}function zt(e){let t=0;for(let r=0;r<e.length;r++){let s=e[r];if(s===\"[\")t++;else if(s===\"]\")t--;else{if(t===0&&s===\"=\")return r;if(t===0&&s===\"+\"&&e[r+1]===\"=\")return r+1}}return-1}var Dr=[[\";\",\";\",\"&\",p.SEMI_SEMI_AND],[\"<\",\"<\",\"<\",p.TLESS],[\"&\",\">\",\">\",p.AND_DGREAT]],xr=[[\"[\",\"[\",p.DBRACK_START],[\"]\",\"]\",p.DBRACK_END],[\"(\",\"(\",p.DPAREN_START],[\")\",\")\",p.DPAREN_END],[\"&\",\"&\",p.AND_AND],[\"|\",\"|\",p.OR_OR],[\";\",\";\",p.DSEMI],[\";\",\"&\",p.SEMI_AND],[\"|\",\"&\",p.PIPE_AMP],[\">\",\">\",p.DGREAT],[\"<\",\"&\",p.LESSAND],[\">\",\"&\",p.GREATAND],[\"<\",\">\",p.LESSGREAT],[\">\",\"|\",p.CLOBBER],[\"&\",\">\",p.AND_GREAT]],_r=new Map([[\"|\",p.PIPE],[\"&\",p.AMP],[\";\",p.SEMICOLON],[\"(\",p.LPAREN],[\")\",p.RPAREN],[\"<\",p.LESS],[\">\",p.GREAT]]);function $r(e){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}function Gt(e){return e===\" \"||e===\"\t\"||e===`\n`||e===\";\"||e===\"&\"||e===\"|\"||e===\"(\"||e===\")\"||e===\"<\"||e===\">\"}var ve=class{input;pos=0;line=1;column=1;tokens=[];pendingHeredocs=[];dparenDepth=0;maxHeredocSize;constructor(t,r){this.input=t,this.maxHeredocSize=r?.maxHeredocSize??10485760}tokenize(){let r=this.input.length,s=this.tokens,n=this.pendingHeredocs;for(;this.pos<r;){if(n.length>0&&s.length>0&&s[s.length-1].type===p.NEWLINE){this.readHeredocContent();continue}if(this.skipWhitespace(),this.pos>=r)break;let a=this.nextToken();a&&s.push(a)}return s.push({type:p.EOF,value:\"\",start:this.pos,end:this.pos,line:this.line,column:this.column}),s}skipWhitespace(){let t=this.input,r=t.length,s=this.pos,n=this.column,a=this.line;for(;s<r;){let i=t[s];if(i===\" \"||i===\"\t\")s++,n++;else if(i===\"\\\\\"&&t[s+1]===`\n`)s+=2,a++,n=1;else break}this.pos=s,this.column=n,this.line=a}nextToken(){let t=this.input,r=this.pos,s=this.line,n=this.column,a=t[r],i=t[r+1],l=t[r+2];if(a===\"#\"&&this.dparenDepth===0)return this.readComment(r,s,n);if(a===`\n`)return this.pos=r+1,this.line++,this.column=1,{type:p.NEWLINE,value:`\n`,start:r,end:r+1,line:s,column:n};if(a===\"<\"&&i===\"<\"&&l===\"-\")return this.pos=r+3,this.column=n+3,this.registerHeredocFromLookahead(!0),this.makeToken(p.DLESSDASH,\"<<-\",r,s,n);for(let[c,u,f,h]of Dr)if(a===c&&i===u&&l===f)return this.pos=r+3,this.column=n+3,this.makeToken(h,c+u+f,r,s,n);if(a===\"<\"&&i===\"<\")return this.pos=r+2,this.column=n+2,this.registerHeredocFromLookahead(!1),this.makeToken(p.DLESS,\"<<\",r,s,n);if(a===\"(\"&&i===\"(\")return this.dparenDepth>0?(this.pos=r+1,this.column=n+1,this.dparenDepth++,this.makeToken(p.LPAREN,\"(\",r,s,n)):this.looksLikeNestedSubshells(r+2)||this.dparenClosesWithSpacedParens(r+2)?(this.pos=r+1,this.column=n+1,this.makeToken(p.LPAREN,\"(\",r,s,n)):(this.pos=r+2,this.column=n+2,this.dparenDepth=1,this.makeToken(p.DPAREN_START,\"((\",r,s,n));if(a===\")\"&&i===\")\")return this.dparenDepth===1?(this.pos=r+2,this.column=n+2,this.dparenDepth=0,this.makeToken(p.DPAREN_END,\"))\",r,s,n)):this.dparenDepth>1?(this.pos=r+1,this.column=n+1,this.dparenDepth--,this.makeToken(p.RPAREN,\")\",r,s,n)):(this.pos=r+1,this.column=n+1,this.makeToken(p.RPAREN,\")\",r,s,n));for(let[c,u,f]of xr)if(!(c===\"(\"&&u===\"(\"||c===\")\"&&u===\")\")&&!(this.dparenDepth>0&&c===\";\"&&(f===p.DSEMI||f===p.SEMI_AND||f===p.SEMI_SEMI_AND))&&a===c&&i===u){if(f===p.DBRACK_START||f===p.DBRACK_END){let h=t[r+2];if(h!==void 0&&h!==\" \"&&h!==\"\t\"&&h!==`\n`&&h!==\";\"&&h!==\"&\"&&h!==\"|\"&&h!==\"(\"&&h!==\")\"&&h!==\"<\"&&h!==\">\")break}return this.pos=r+2,this.column=n+2,this.makeToken(f,c+u,r,s,n)}if(a===\"(\"&&this.dparenDepth>0)return this.pos=r+1,this.column=n+1,this.dparenDepth++,this.makeToken(p.LPAREN,\"(\",r,s,n);if(a===\")\"&&this.dparenDepth>1)return this.pos=r+1,this.column=n+1,this.dparenDepth--,this.makeToken(p.RPAREN,\")\",r,s,n);let o=_r.get(a);if(o!==void 0)return this.pos=r+1,this.column=n+1,this.makeToken(o,a,r,s,n);if(a===\"{\"){let c=this.scanFdVariable(r);return c!==null?(this.pos=c.end,this.column=n+(c.end-r),{type:p.FD_VARIABLE,value:c.varname,start:r,end:c.end,line:s,column:n}):i===\"}\"?(this.pos=r+2,this.column=n+2,{type:p.WORD,value:\"{}\",start:r,end:r+2,line:s,column:n,quoted:!1,singleQuoted:!1}):this.scanBraceExpansion(r)!==null?this.readWordWithBraceExpansion(r,s,n):this.scanLiteralBraceWord(r)!==null?this.readWordWithBraceExpansion(r,s,n):i!==void 0&&i!==\" \"&&i!==\"\t\"&&i!==`\n`?this.readWord(r,s,n):(this.pos=r+1,this.column=n+1,this.makeToken(p.LBRACE,\"{\",r,s,n))}return a===\"}\"?this.isWordCharFollowing(r+1)?this.readWord(r,s,n):(this.pos=r+1,this.column=n+1,this.makeToken(p.RBRACE,\"}\",r,s,n)):a===\"!\"?i===\"=\"?(this.pos=r+2,this.column=n+2,this.makeToken(p.WORD,\"!=\",r,s,n)):(this.pos=r+1,this.column=n+1,this.makeToken(p.BANG,\"!\",r,s,n)):this.readWord(r,s,n)}looksLikeNestedSubshells(t){let r=this.input,s=r.length,n=t;for(;n<s&&(r[n]===\" \"||r[n]===\"\t\");)n++;if(n>=s)return!1;let a=r[n];if(a===\"(\")return this.looksLikeNestedSubshells(n+1);let i=/[a-zA-Z_]/.test(a),l=a===\"!\"||a===\"[\";if(!i&&!l)return!1;let o=n;for(;o<s&&/[a-zA-Z0-9_\\-.]/.test(r[o]);)o++;if(o===n)return l;let c=o;for(;c<s&&(r[c]===\" \"||r[c]===\"\t\");)c++;if(c>=s)return!1;let u=r[c];if(u===\"=\"&&r[c+1]!==\"=\"||u===`\n`||o===c&&/[+\\-*/%<>&|^!~?:]/.test(u)&&u!==\"-\"||u===\")\"&&r[c+1]===\")\")return!1;if(c>o&&(u===\"-\"||u==='\"'||u===\"'\"||u===\"$\"||/[a-zA-Z_/.]/.test(u))){let f=c;for(;f<s&&r[f]!==`\n`;){if(r[f]===\")\")return!0;f++}return!1}if(u===\")\"){let f=c+1;for(;f<s&&(r[f]===\" \"||r[f]===\"\t\");)f++;if(r[f]===\"|\"&&r[f+1]===\"|\"||r[f]===\"&\"&&r[f+1]===\"&\"||r[f]===\";\"||r[f]===\"|\"&&r[f+1]!==\"|\")return!0}return!1}makeToken(t,r,s,n,a){return{type:t,value:r,start:s,end:this.pos,line:n,column:a}}readComment(t,r,s){let n=this.input,a=n.length,i=this.pos;for(;i<a&&n[i]!==`\n`;)i++;let l=n.slice(t,i);return this.pos=i,this.column=s+(i-t),{type:p.COMMENT,value:l,start:t,end:i,line:r,column:s}}readWord(t,r,s){let n=this.input,a=n.length,i=this.pos,l=i;for(;i<a;){let y=n[i];if(y===\" \"||y===\"\t\"||y===`\n`||y===\";\"||y===\"&\"||y===\"|\"||y===\"(\"||y===\")\"||y===\"<\"||y===\">\"||y===\"'\"||y==='\"'||y===\"\\\\\"||y===\"$\"||y===\"`\"||y===\"{\"||y===\"}\"||y===\"~\"||y===\"*\"||y===\"?\"||y===\"[\")break;i++}if(i>l){let y=n[i];if(!(y===\"(\"&&i>l&&\"@*+?!\".includes(n[i-1]))){if(i>=a||y===\" \"||y===\"\t\"||y===`\n`||y===\";\"||y===\"&\"||y===\"|\"||y===\"(\"||y===\")\"||y===\"<\"||y===\">\"){let b=n.slice(l,i);this.pos=i,this.column=s+(i-l);let D=Bt.get(b);if(D!==void 0)return{type:D,value:b,start:t,end:i,line:r,column:s};let Q=zt(b);return Q>0&&Ft(b.slice(0,Q))?{type:p.ASSIGNMENT_WORD,value:b,start:t,end:i,line:r,column:s}:/^[0-9]+$/.test(b)?{type:p.NUMBER,value:b,start:t,end:i,line:r,column:s}:/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(b)?{type:p.NAME,value:b,start:t,end:i,line:r,column:s,quoted:!1,singleQuoted:!1}:{type:p.WORD,value:b,start:t,end:i,line:r,column:s,quoted:!1,singleQuoted:!1}}}}i=this.pos;let o=this.column,c=this.line,u=\"\",f=!1,h=!1,d=!1,m=!1,g=n[i]==='\"'||n[i]===\"'\",E=!1,A=0;for(;i<a;){let y=n[i];if(!d&&!m){if(y===\"(\"&&u.length>0&&\"@*+?!\".includes(u[u.length-1])){let b=this.scanExtglobPattern(i);if(b!==null){u+=b.content,i=b.end,o+=b.content.length;continue}}if(y===\"[\"&&A===0){if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(u)){let b=i+1<a?n[i+1]:\"\";if(b===\"^\"||b===\"!\"){u+=y,i++,o++;continue}A=1,u+=y,i++,o++;continue}}else if(y===\"[\"&&A>0){u.length>0&&u[u.length-1]!==\"\\\\\"&&A++,u+=y,i++,o++;continue}else if(y===\"]\"&&A>0){u.length>0&&u[u.length-1]!==\"\\\\\"&&A--,u+=y,i++,o++;continue}if(A>0){if(y===`\n`)break;u+=y,i++,o++;continue}if(y===\" \"||y===\"\t\"||y===`\n`||y===\";\"||y===\"&\"||y===\"|\"||y===\"(\"||y===\")\"||y===\"<\"||y===\">\")break}if(y===\"$\"&&i+1<a&&n[i+1]===\"'\"&&!d&&!m){for(u+=\"$'\",i+=2,o+=2;i<a&&n[i]!==\"'\";)n[i]===\"\\\\\"&&i+1<a?(u+=n[i]+n[i+1],i+=2,o+=2):(u+=n[i],i++,o++);i<a&&(u+=\"'\",i++,o++);continue}if(y===\"$\"&&i+1<a&&n[i+1]==='\"'&&!d&&!m){i++,o++,m=!0,f=!0,u===\"\"&&(g=!0),i++,o++;continue}if(y===\"'\"&&!m){if(d)if(d=!1,!g||E)u+=y;else{let b=i+1<a?n[i+1]:\"\";b&&!Gt(b)&&b!==\"'\"&&(b==='\"'?(E=!0,u+=y,h=!1,f=!1):(E=!0,u+=y))}else d=!0,g&&!E?(h=!0,f=!0):u+=y;i++,o++;continue}if(y==='\"'&&!d){if(m)if(m=!1,!g||E)u+=y;else{let b=i+1<a?n[i+1]:\"\";b&&!Gt(b)&&b!=='\"'&&(b===\"'\"?(E=!0,u+=y,h=!1,f=!1):(E=!0,u+=y))}else m=!0,g&&!E?f=!0:u+=y;i++,o++;continue}if(y===\"\\\\\"&&!d&&i+1<a){let b=n[i+1];if(b===`\n`){i+=2,c++,o=1;continue}if(m){if(b==='\"'||b===\"\\\\\"||b===\"$\"||b===\"`\"||b===`\n`){if(b===`\n`){i+=2,o=1,c++;continue}u+=y+b,i+=2,o+=2;continue}}else{b===\"\\\\\"||b==='\"'||b===\"'\"||b===\"`\"||b===\"*\"||b===\"?\"||b===\"[\"||b===\"]\"||b===\"(\"||b===\")\"||b===\"$\"||b===\"-\"||b===\".\"||b===\"^\"||b===\"+\"||b===\"{\"||b===\"}\"?u+=y+b:u+=b,i+=2,o+=2;continue}}if(y===\"$\"&&i+1<a&&n[i+1]===\"(\"&&!d){u+=y,i++,o++,u+=n[i],i++,o++;let b=1,D=!1,Q=!1,ie=0,H=!1,B=\"\",Ne=n[i]===\"(\"&&!this.dollarDparenIsSubshell(i);for(;b>0&&i<a;){let _=n[i];if(u+=_,D)_===\"'\"&&(D=!1);else if(Q)_===\"\\\\\"&&i+1<a?(u+=n[i+1],i++,o++):_==='\"'&&(Q=!1);else if(_===\"'\")D=!0,B=\"\";else if(_==='\"')Q=!0,B=\"\";else if(_===\"\\\\\"&&i+1<a)u+=n[i+1],i++,o++,B=\"\";else if(_===\"$\"&&i+1<a&&n[i+1]===\"{\"){i++,o++,u+=n[i],i++,o++;let Be=1,ke=!1,Fe=!1;for(;Be>0&&i<a;){let Y=n[i];if(Y===\"\\\\\"&&i+1<a&&!ke){u+=Y,i++,o++,u+=n[i],i++,o++;continue}u+=Y,ke?Y===\"'\"&&(ke=!1):Fe?Y==='\"'&&(Fe=!1):Y===\"'\"?ke=!0:Y==='\"'?Fe=!0:Y===\"{\"?Be++:Y===\"}\"&&Be--,Y===`\n`?(c++,o=0):o++,i++}B=\"\";continue}else if(_===\"#\"&&!Ne&&(B===\"\"||/\\s/.test(n[i-1]||\"\"))){for(;i+1<a&&n[i+1]!==`\n`;)i++,o++,u+=n[i];B=\"\"}else/[a-zA-Z_]/.test(_)?B+=_:(B===\"case\"?(ie++,H=!1):B===\"in\"&&ie>0?H=!0:B===\"esac\"&&ie>0&&(ie--,H=!1),B=\"\",_===\"(\"?i>0&&n[i-1]===\"$\"?b++:H||b++:_===\")\"?H?H=!1:b--:_===\";\"&&ie>0&&(i+1<a&&n[i+1]===\";\"||i+1<a&&n[i+1]===\"&\")&&(H=!0));_===`\n`&&(c++,o=0,B=\"\"),i++,o++}continue}if(y===\"$\"&&i+1<a&&n[i+1]===\"[\"&&!d){u+=y,i++,o++,u+=n[i],i++,o++;let b=1;for(;b>0&&i<a;){let D=n[i];u+=D,D===\"[\"?b++:D===\"]\"?b--:D===`\n`&&(c++,o=0),i++,o++}continue}if(y===\"$\"&&i+1<a&&n[i+1]===\"{\"&&!d){u+=y,i++,o++,u+=n[i],i++,o++;let b=1,D=!1,Q=!1,ie=c,H=o,B=c,Ne=o;for(;b>0&&i<a;){let _=n[i];if(_===\"\\\\\"&&i+1<a&&n[i+1]===`\n`){i+=2,c++,o=1;continue}if(_===\"\\\\\"&&i+1<a&&!D){u+=_,i++,o++,u+=n[i],i++,o++;continue}u+=_,D?_===\"'\"&&(D=!1):Q?_==='\"'&&(Q=!1):_===\"'\"?(D=!0,ie=c,H=o):_==='\"'?(Q=!0,B=c,Ne=o):_===\"{\"?b++:_===\"}\"&&b--,_===`\n`&&(c++,o=0),i++,o++}if(D)throw new pe(\"unexpected EOF while looking for matching `''\",ie,H);if(Q)throw new pe(\"unexpected EOF while looking for matching `\\\"'\",B,Ne);continue}if(y===\"$\"&&i+1<a&&!d){let b=n[i+1];if(b===\"#\"||b===\"?\"||b===\"$\"||b===\"!\"||b===\"@\"||b===\"*\"||b===\"-\"||b>=\"0\"&&b<=\"9\"){u+=y+b,i+=2,o+=2;continue}}if(y===\"`\"&&!d){for(u+=y,i++,o++;i<a&&n[i]!==\"`\";){let b=n[i];u+=b,b===\"\\\\\"&&i+1<a&&(u+=n[i+1],i++,o++),b===`\n`&&(c++,o=0),i++,o++}i<a&&(u+=n[i],i++,o++);continue}u+=y,i++,y===`\n`?(c++,o=1):o++}if(this.pos=i,this.column=o,this.line=c,E&&g&&(u=n[t]+u,f=!1,h=!1),d||m){let y=d?\"'\":'\"';throw new pe(`unexpected EOF while looking for matching \\`${y}'`,r,s)}if(!g&&u.length>=2){if(u[0]===\"'\"&&u[u.length-1]===\"'\"){let y=u.slice(1,-1);!y.includes(\"'\")&&!y.includes('\"')&&(u=y,f=!0,h=!0)}else if(u[0]==='\"'&&u[u.length-1]==='\"'){let y=u.slice(1,-1),b=!1;for(let D=0;D<y.length;D++){if(y[D]==='\"'){b=!0;break}y[D]===\"\\\\\"&&D+1<y.length&&D++}b||(u=y,f=!0,h=!1)}}if(u===\"\")return{type:p.WORD,value:\"\",start:t,end:i,line:r,column:s,quoted:f,singleQuoted:h};let S=Bt.get(u);if(!f&&S!==void 0)return{type:S,value:u,start:t,end:i,line:r,column:s};if(!g){let y=zt(u);if(y>0&&Ft(u.slice(0,y)))return{type:p.ASSIGNMENT_WORD,value:u,start:t,end:i,line:r,column:s,quoted:f,singleQuoted:h}}return/^[0-9]+$/.test(u)?{type:p.NUMBER,value:u,start:t,end:i,line:r,column:s}:$r(u)?{type:p.NAME,value:u,start:t,end:i,line:r,column:s,quoted:f,singleQuoted:h}:{type:p.WORD,value:u,start:t,end:i,line:r,column:s,quoted:f,singleQuoted:h}}readHeredocContent(){for(;this.pendingHeredocs.length>0;){let t=this.pendingHeredocs.shift();if(!t)break;let r=this.pos,s=this.line,n=this.column,a=\"\";for(;this.pos<this.input.length;){let i=\"\";for(;this.pos<this.input.length&&this.input[this.pos]!==`\n`;)i+=this.input[this.pos],this.pos++,this.column++;if((t.stripTabs?i.replace(/^\\t+/,\"\"):i)===t.delimiter){this.pos<this.input.length&&this.input[this.pos]===`\n`&&(this.pos++,this.line++,this.column=1);break}if(a+=i,a.length>this.maxHeredocSize)throw new pe(`Heredoc size limit exceeded (${this.maxHeredocSize} bytes)`,s,n);this.pos<this.input.length&&this.input[this.pos]===`\n`&&(a+=`\n`,this.pos++,this.line++,this.column=1)}this.tokens.push({type:p.HEREDOC_CONTENT,value:a,start:r,end:this.pos,line:s,column:n})}}addPendingHeredoc(t,r,s){this.pendingHeredocs.push({delimiter:t,stripTabs:r,quoted:s})}registerHeredocFromLookahead(t){let r=this.pos,s=this.column;for(;this.pos<this.input.length&&(this.input[this.pos]===\" \"||this.input[this.pos]===\"\t\");)this.pos++,this.column++;let n=\"\",a=!1;for(;this.pos<this.input.length;){let i=this.input[this.pos];if(/[\\s;<>&|()]/.test(i))break;if(i===\"'\"||i==='\"'){a=!0;let l=i;for(this.pos++,this.column++;this.pos<this.input.length&&this.input[this.pos]!==l;)n+=this.input[this.pos],this.pos++,this.column++;this.pos<this.input.length&&this.input[this.pos]===l&&(this.pos++,this.column++)}else i===\"\\\\\"?(a=!0,this.pos++,this.column++,this.pos<this.input.length&&(n+=this.input[this.pos],this.pos++,this.column++)):(n+=i,this.pos++,this.column++)}this.pos=r,this.column=s,n&&this.pendingHeredocs.push({delimiter:n,stripTabs:t,quoted:a})}isWordCharFollowing(t){if(t>=this.input.length)return!1;let r=this.input[t];return!(r===\" \"||r===\"\t\"||r===`\n`||r===\";\"||r===\"&\"||r===\"|\"||r===\"(\"||r===\")\"||r===\"<\"||r===\">\")}readWordWithBraceExpansion(t,r,s){let n=this.input,a=n.length,i=t,l=s;for(;i<a;){let c=n[i];if(c===\" \"||c===\"\t\"||c===`\n`||c===\";\"||c===\"&\"||c===\"|\"||c===\"(\"||c===\")\"||c===\"<\"||c===\">\")break;if(c===\"{\"){if(this.scanBraceExpansion(i)!==null){let f=1;for(i++,l++;i<a&&f>0;)n[i]===\"{\"?f++:n[i]===\"}\"&&f--,i++,l++;continue}i++,l++;continue}if(c===\"}\"){i++,l++;continue}if(c===\"$\"&&i+1<a&&n[i+1]===\"(\"){i++,l++,i++,l++;let u=1;for(;u>0&&i<a;)n[i]===\"(\"?u++:n[i]===\")\"&&u--,i++,l++;continue}if(c===\"$\"&&i+1<a&&n[i+1]===\"{\"){i++,l++,i++,l++;let u=1;for(;u>0&&i<a;)n[i]===\"{\"?u++:n[i]===\"}\"&&u--,i++,l++;continue}if(c===\"`\"){for(i++,l++;i<a&&n[i]!==\"`\";)n[i]===\"\\\\\"&&i+1<a?(i+=2,l+=2):(i++,l++);i<a&&(i++,l++);continue}i++,l++}let o=n.slice(t,i);return this.pos=i,this.column=l,{type:p.WORD,value:o,start:t,end:i,line:r,column:s,quoted:!1,singleQuoted:!1}}scanBraceExpansion(t){let r=this.input,s=r.length,n=t+1,a=1,i=!1,l=!1;for(;n<s&&a>0;){let o=r[n];if(o===\"{\")a++,n++;else if(o===\"}\")a--,n++;else if(o===\",\"&&a===1)i=!0,n++;else if(o===\".\"&&n+1<s&&r[n+1]===\".\")l=!0,n+=2;else{if(o===\" \"||o===\"\t\"||o===`\n`||o===\";\"||o===\"&\"||o===\"|\")return null;n++}}return a===0&&(i||l)?r.slice(t,n):null}scanLiteralBraceWord(t){let r=this.input,s=r.length,n=t+1,a=1;for(;n<s&&a>0;){let i=r[n];if(i===\"{\")a++,n++;else if(i===\"}\"){if(a--,a===0)return r.slice(t,n+1);n++}else{if(i===\" \"||i===\"\t\"||i===`\n`||i===\";\"||i===\"&\"||i===\"|\")return null;n++}}return null}scanExtglobPattern(t){let r=this.input,s=r.length,n=t+1,a=1;for(;n<s&&a>0;){let i=r[n];if(i===\"\\\\\"&&n+1<s){n+=2;continue}if(\"@*+?!\".includes(i)&&n+1<s&&r[n+1]===\"(\"){n++,a++,n++;continue}if(i===\"(\")a++,n++;else if(i===\")\")a--,n++;else{if(i===`\n`)return null;n++}}return a===0?{content:r.slice(t,n),end:n}:null}scanFdVariable(t){let r=this.input,s=r.length,n=t+1,a=n;for(;n<s;){let u=r[n];if(n===a){if(!(u>=\"a\"&&u<=\"z\"||u>=\"A\"&&u<=\"Z\"||u===\"_\"))return null}else if(!(u>=\"a\"&&u<=\"z\"||u>=\"A\"&&u<=\"Z\"||u>=\"0\"&&u<=\"9\"||u===\"_\"))break;n++}if(n===a)return null;let i=r.slice(a,n);if(n>=s||r[n]!==\"}\"||(n++,n>=s))return null;let l=r[n],o=n+1<s?r[n+1]:\"\";return l===\">\"||l===\"<\"||l===\"&\"&&(o===\">\"||o===\"<\")?{varname:i,end:n}:null}dollarDparenIsSubshell(t){let r=this.input,s=r.length,n=t+1,a=2,i=!1,l=!1,o=!1;for(;n<s&&a>0;){let c=r[n];if(i){c===\"'\"&&(i=!1),c===`\n`&&(o=!0),n++;continue}if(l){if(c===\"\\\\\"){n+=2;continue}c==='\"'&&(l=!1),c===`\n`&&(o=!0),n++;continue}if(c===\"'\"){i=!0,n++;continue}if(c==='\"'){l=!0,n++;continue}if(c===\"\\\\\"){n+=2;continue}if(c===`\n`&&(o=!0),c===\"(\"){a++,n++;continue}if(c===\")\"){if(a--,a===1){let u=n+1;if(u<s&&r[u]===\")\")return!1;let f=u,h=!1;for(;f<s&&(r[f]===\" \"||r[f]===\"\t\"||r[f]===`\n`);)h=!0,f++;if(h&&f<s&&r[f]===\")\"||o)return!0}if(a===0)return!1;n++;continue}n++}return!1}dparenClosesWithSpacedParens(t){let r=this.input,s=r.length,n=t,a=2,i=!1,l=!1;for(;n<s&&a>0;){let o=r[n];if(i){o===\"'\"&&(i=!1),n++;continue}if(l){if(o===\"\\\\\"){n+=2;continue}o==='\"'&&(l=!1),n++;continue}if(o===\"'\"){i=!0,n++;continue}if(o==='\"'){l=!0,n++;continue}if(o===\"\\\\\"){n+=2;continue}if(o===\"(\"){a++,n++;continue}if(o===\")\"){if(a--,a===1){let c=n+1;if(c<s&&r[c]===\")\")return!1;let u=c,f=!1;for(;u<s&&(r[u]===\" \"||r[u]===\"\t\"||r[u]===`\n`);)f=!0,u++;if(f&&u<s&&r[u]===\")\")return!0}if(a===0)return!1;n++;continue}if(a===1&&(o===\"|\"&&n+1<s&&r[n+1]===\"|\"||o===\"&\"&&n+1<s&&r[n+1]===\"&\"||o===\"|\"&&n+1<s&&r[n+1]!==\"|\"))return!0;n++}return!1}};var Qe=1e6,Ze=1e5,Qt=1e6,Ue=200,Zt=new Set([p.LESS,p.GREAT,p.DLESS,p.DGREAT,p.LESSAND,p.GREATAND,p.LESSGREAT,p.DLESSDASH,p.CLOBBER,p.TLESS,p.AND_GREAT,p.AND_DGREAT]),Ut=new Set([p.LESS,p.GREAT,p.DLESS,p.DGREAT,p.LESSAND,p.GREATAND,p.LESSGREAT,p.DLESSDASH,p.CLOBBER,p.TLESS]),Ht=new Set([p.LESS,p.GREAT,p.DLESS,p.DGREAT,p.LESSAND,p.GREATAND,p.LESSGREAT,p.DLESSDASH,p.CLOBBER,p.TLESS,p.AND_GREAT,p.AND_DGREAT]),G=class extends Error{line;column;token;constructor(t,r,s,n=void 0){super(`Parse error at ${r}:${s}: ${t}`),this.line=r,this.column=s,this.token=n,this.name=\"ParseException\"}};function Cr(e){let t=\"\",r=0;for(;r<e.length;){let s=e[r];if(s<128){t+=String.fromCharCode(s),r++;continue}if((s&224)===192){if(r+1<e.length&&(e[r+1]&192)===128&&s>=194){let n=(s&31)<<6|e[r+1]&63;t+=String.fromCharCode(n),r+=2;continue}t+=String.fromCharCode(s),r++;continue}if((s&240)===224){if(r+2<e.length&&(e[r+1]&192)===128&&(e[r+2]&192)===128){if(s===224&&e[r+1]<160){t+=String.fromCharCode(s),r++;continue}let n=(s&15)<<12|(e[r+1]&63)<<6|e[r+2]&63;if(n>=55296&&n<=57343){t+=String.fromCharCode(s),r++;continue}t+=String.fromCharCode(n),r+=3;continue}t+=String.fromCharCode(s),r++;continue}if((s&248)===240&&s<=244){if(r+3<e.length&&(e[r+1]&192)===128&&(e[r+2]&192)===128&&(e[r+3]&192)===128){if(s===240&&e[r+1]<144){t+=String.fromCharCode(s),r++;continue}let n=(s&7)<<18|(e[r+1]&63)<<12|(e[r+2]&63)<<6|e[r+3]&63;if(n>1114111){t+=String.fromCharCode(s),r++;continue}t+=String.fromCodePoint(n),r+=4;continue}t+=String.fromCharCode(s),r++;continue}t+=String.fromCharCode(s),r++}return t}function Kt(e,t,r){let s=r+1;for(;s<t.length&&/[a-zA-Z0-9_-]/.test(t[s]);)s++;return s}function He(e,t,r,s,n){let a=1,i=r+1;for(;i<t.length&&a>0;)t[i]===s?a++:t[i]===n&&a--,a>0&&i++;return a===0?i:-1}function fe(e,t,r){let s=r,n=1;for(;s<t.length&&n>0;){let a=t[s];if(a===\"\\\\\"&&s+1<t.length){s+=2;continue}if(a===\"'\"){let i=t.indexOf(\"'\",s+1);if(i!==-1){s=i+1;continue}}if(a==='\"'){for(s++;s<t.length&&t[s]!=='\"';)t[s]===\"\\\\\"&&s+1<t.length?s+=2:s++;s<t.length&&s++;continue}a===\"{\"?n++:a===\"}\"&&n--,n>0&&s++}return s}function Xt(e,t,r){let s=r,n=!1;for(;s<t.length;){let a=t[s];if(a===\"/\"&&n||a===\"}\")break;if(a===\"'\"){let i=t.indexOf(\"'\",s+1);if(i!==-1){s=i+1,n=!0;continue}}if(a==='\"'){for(s++;s<t.length&&t[s]!=='\"';)t[s]===\"\\\\\"&&s+1<t.length?s+=2:s++;s<t.length&&s++,n=!0;continue}a===\"\\\\\"?(s+=2,n=!0):(s++,n=!0)}return s}function Jt(e,t,r){let s=r,n=\"\";for(;s<t.length;){let a=t[s];if(a===\"*\"||a===\"?\")n+=a,s++;else if(a===\"[\"){let i=Or(t,s);i===-1?(n+=a,s++):(n+=t.slice(s,i+1),s=i+1)}else break}return{pattern:n,endIndex:s}}function Or(e,t){let r=t+1;for(r<e.length&&e[r]===\"^\"&&r++,r<e.length&&e[r]===\"]\"&&r++;r<e.length;){let s=e[r];if(s===\"\\\\\"&&r+1<e.length){let n=e[r+1];if(n==='\"'||n===\"'\")return-1;r+=2;continue}if(s===\"]\")return r;if(s==='\"'||s===\"$\"||s===\"`\")return-1;if(s===\"'\"){let n=e.indexOf(\"'\",r+1);if(n!==-1){r=n+1;continue}}if(s===\"[\"&&r+1<e.length&&e[r+1]===\":\"){let n=e.indexOf(\":]\",r+2);if(n!==-1){r=n+2;continue}}if(s===\"[\"&&r+1<e.length&&(e[r+1]===\".\"||e[r+1]===\"=\")){let a=`${e[r+1]}]`,i=e.indexOf(a,r+2);if(i!==-1){r=i+2;continue}}r++}return-1}function Yt(e,t,r){let s=\"\",n=r;for(;n<t.length&&t[n]!==\"'\";){let a=t[n];if(a===\"\\\\\"&&n+1<t.length)switch(t[n+1]){case\"n\":s+=`\n`,n+=2;break;case\"t\":s+=\"\t\",n+=2;break;case\"r\":s+=\"\\r\",n+=2;break;case\"\\\\\":s+=\"\\\\\",n+=2;break;case\"'\":s+=\"'\",n+=2;break;case'\"':s+='\"',n+=2;break;case\"a\":s+=\"\\x07\",n+=2;break;case\"b\":s+=\"\\b\",n+=2;break;case\"e\":case\"E\":s+=\"\\x1B\",n+=2;break;case\"f\":s+=\"\\f\",n+=2;break;case\"v\":s+=\"\\v\",n+=2;break;case\"x\":{let l=[],o=n;for(;o+1<t.length&&t[o]===\"\\\\\"&&t[o+1]===\"x\";){let c=t.slice(o+2,o+4),u=parseInt(c,16);if(!Number.isNaN(u)&&c.length>0)l.push(u),o+=2+c.length;else break}l.length>0?(s+=Cr(l),n=o):(s+=\"\\\\x\",n+=2);break}case\"u\":{let l=t.slice(n+2,n+6),o=parseInt(l,16);Number.isNaN(o)?(s+=\"\\\\u\",n+=2):(s+=String.fromCharCode(o),n+=6);break}case\"c\":{if(n+2<t.length){let o=t[n+2].charCodeAt(0)&31;s+=String.fromCharCode(o),n+=3}else s+=\"\\\\c\",n+=2;break}case\"0\":case\"1\":case\"2\":case\"3\":case\"4\":case\"5\":case\"6\":case\"7\":{let l=\"\",o=n+1;for(;o<t.length&&o<n+4&&/[0-7]/.test(t[o]);)l+=t[o],o++;let c=parseInt(l,8);s+=String.fromCharCode(c),n=o;break}default:s+=a,n++}else s+=a,n++}return n<t.length&&t[n]===\"'\"&&n++,{part:w.literal(s),endIndex:n}}function je(e,t){let r=t.trim();return r===\"\"?{type:\"ArithmeticExpression\",expression:{type:\"ArithNumber\",value:0}}:M(e,r)}function jt(e){let t=[],r=\"\",s=0;for(let n=0;n<e.length;n++){let a=e[n];a===\"{\"?(s++,r+=a):a===\"}\"?(s--,r+=a):a===\",\"&&s===0?(t.push(r),r=\"\"):r+=a}return t.push(r),t}function en(e,t,r,s){let n=He(e,t,r,\"{\",\"}\");if(n===-1)return null;let a=t.slice(r+1,n),i=a.match(/^(-?\\d+)\\.\\.(-?\\d+)(?:\\.\\.(-?\\d+))?$/);if(i)return{part:{type:\"BraceExpansion\",items:[{type:\"Range\",start:Number.parseInt(i[1],10),end:Number.parseInt(i[2],10),step:i[3]?Number.parseInt(i[3],10):void 0,startStr:i[1],endStr:i[2]}]},endIndex:n+1};let l=a.match(/^([a-zA-Z])\\.\\.([a-zA-Z])(?:\\.\\.(-?\\d+))?$/);return l?{part:{type:\"BraceExpansion\",items:[{type:\"Range\",start:l[1],end:l[2],step:l[3]?Number.parseInt(l[3],10):void 0}]},endIndex:n+1}:a.includes(\",\")&&s?{part:{type:\"BraceExpansion\",items:jt(a).map(u=>({type:\"Word\",word:w.word(s(e,u,!1,!1,!1))}))},endIndex:n+1}:a.includes(\",\")?{part:{type:\"BraceExpansion\",items:jt(a).map(u=>({type:\"Word\",word:w.word([w.literal(u)])}))},endIndex:n+1}:null}function Ke(e,t){let r=\"\";for(let s of t.parts)switch(s.type){case\"Literal\":r+=s.value;break;case\"SingleQuoted\":r+=`'${s.value}'`;break;case\"Escaped\":r+=s.value;break;case\"DoubleQuoted\":r+='\"';for(let n of s.parts)n.type===\"Literal\"||n.type===\"Escaped\"?r+=n.value:n.type===\"ParameterExpansion\"&&(r+=`\\${${n.parameter}}`);r+='\"';break;case\"ParameterExpansion\":r+=`\\${${s.parameter}}`;break;case\"Glob\":r+=s.pattern;break;case\"TildeExpansion\":r+=\"~\",s.user&&(r+=s.user);break;case\"BraceExpansion\":{r+=\"{\";let n=[];for(let a of s.items)if(a.type===\"Range\"){let i=a.startStr??String(a.start),l=a.endStr??String(a.end);a.step!==void 0?n.push(`${i}..${l}..${a.step}`):n.push(`${i}..${l}`)}else n.push(Ke(e,a.word));n.length===1&&s.items[0].type===\"Range\"?r+=n[0]:r+=n.join(\",\"),r+=\"}\";break}default:r+=s.type}return r}function tn(e,t){return{[p.LESS]:\"<\",[p.GREAT]:\">\",[p.DGREAT]:\">>\",[p.LESSAND]:\"<&\",[p.GREATAND]:\">&\",[p.LESSGREAT]:\"<>\",[p.CLOBBER]:\">|\",[p.TLESS]:\"<<<\",[p.AND_GREAT]:\"&>\",[p.AND_DGREAT]:\"&>>\",[p.DLESS]:\"<\",[p.DLESSDASH]:\"<\"}[t]||\">\"}function De(e){let t=e.current(),r=t.type;if(r===p.NUMBER){let s=e.peek(1);return t.end!==s.start?!1:Ut.has(s.type)}if(r===p.FD_VARIABLE){let s=e.peek(1);return Ht.has(s.type)}return Zt.has(r)}function xe(e){let t=null,r;e.check(p.NUMBER)?t=Number.parseInt(e.advance().value,10):e.check(p.FD_VARIABLE)&&(r=e.advance().value);let s=e.advance(),n=tn(e,s.type);if(s.type===p.DLESS||s.type===p.DLESSDASH)return Lr(e,n,t,s.type===p.DLESSDASH);e.isWord()||e.error(\"Expected redirection target\");let a=e.parseWord();return w.redirection(n,a,t,r)}function Lr(e,t,r,s){e.isWord()||e.error(\"Expected here-document delimiter\");let n=e.advance(),a=n.value,i=n.quoted||!1;(a.startsWith(\"'\")&&a.endsWith(\"'\")||a.startsWith('\"')&&a.endsWith('\"'))&&(a=a.slice(1,-1));let l=w.redirection(s?\"<<-\":\"<<\",w.hereDoc(a,w.word([]),s,i),r);return e.addPendingHeredoc(l,a,s,i),l}function rn(e){let t=e.current().line,r=[],s=null,n=[],a=[];for(;e.check(p.ASSIGNMENT_WORD)||De(e);)e.checkIterationLimit(),e.check(p.ASSIGNMENT_WORD)?r.push(Wr(e)):a.push(xe(e));if(e.isWord())s=e.parseWord();else if(r.length>0&&(e.check(p.DBRACK_START)||e.check(p.DPAREN_START))){let l=e.advance();s=w.word([w.literal(l.value)])}for(;(!e.isStatementEnd()||e.check(p.RBRACE))&&!e.check(p.PIPE,p.PIPE_AMP);)if(e.checkIterationLimit(),De(e))a.push(xe(e));else if(e.check(p.RBRACE)){let l=e.advance();n.push(e.parseWordFromString(l.value,!1,!1))}else if(e.check(p.LBRACE)){let l=e.advance();n.push(e.parseWordFromString(l.value,!1,!1))}else if(e.check(p.DBRACK_END)){let l=e.advance();n.push(e.parseWordFromString(l.value,!1,!1))}else if(e.isWord())n.push(e.parseWord());else if(e.check(p.ASSIGNMENT_WORD)){let l=e.advance(),o=l.value,c=o.endsWith(\"=\"),u=o.endsWith(\"=(\");if((c||u)&&(u||e.check(p.LPAREN))){let f=u?o.slice(0,-2):o.slice(0,-1);u||e.expect(p.LPAREN);let h=Xe(e);e.expect(p.RPAREN);let d=h.map(g=>Ke(e,g)),m=`${f}=(${d.join(\" \")})`;n.push(e.parseWordFromString(m,!1,!1))}else n.push(e.parseWordFromString(o,l.quoted,l.singleQuoted))}else if(e.check(p.LPAREN))e.error(\"syntax error near unexpected token `('\");else break;let i=w.simpleCommand(s,n,r,a);return i.line=t,i}function Wr(e){let t=e.expect(p.ASSIGNMENT_WORD),r=t.value,s=r.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);s||e.error(`Invalid assignment: ${r}`);let n=s[0],a,i=n.length;if(r[i]===\"[\"){let f=0,h=i+1;for(;i<r.length;i++)if(r[i]===\"[\")f++;else if(r[i]===\"]\"&&(f--,f===0))break;f!==0&&e.error(`Invalid assignment: ${r}`),a=r.slice(h,i),i++}let l=r[i]===\"+\";l&&i++,r[i]!==\"=\"&&e.error(`Invalid assignment: ${r}`),i++;let o=r.slice(i);if(o===\"(\"){let f=Xe(e);e.expect(p.RPAREN);let h=a!==void 0?`${n}[${a}]`:n;return w.assignment(h,null,l,f)}if(o===\"\"&&e.check(p.LPAREN)){let f=e.current();if(t.end===f.start){e.advance();let h=Xe(e);e.expect(p.RPAREN);let d=a!==void 0?`${n}[${a}]`:n;return w.assignment(d,null,l,h)}}let c=o?e.parseWordFromString(o,t.quoted,t.singleQuoted,!0):null,u=a!==void 0?`${n}[${a}]`:n;return w.assignment(u,c,l,null)}var Tr=new Set([p.AMP,p.PIPE,p.PIPE_AMP,p.SEMICOLON,p.AND_AND,p.OR_OR,p.DSEMI,p.SEMI_AND,p.SEMI_SEMI_AND]);function Xe(e){let t=[];for(e.skipNewlines();!e.check(p.RPAREN,p.EOF);)e.checkIterationLimit(),e.isWord()?t.push(e.parseWord()):Tr.has(e.current().type)?e.error(`syntax error near unexpected token \\`${e.current().value}'`):e.advance(),e.skipNewlines();return t}function Je(e,t){e.expect(p.IF);let r=[],s=e.parseCompoundList();e.expect(p.THEN);let n=e.parseCompoundList();if(n.length===0){let l=e.check(p.FI)?\"fi\":e.check(p.ELSE)?\"else\":e.check(p.ELIF)?\"elif\":\"fi\";e.error(`syntax error near unexpected token \\`${l}'`)}for(r.push({condition:s,body:n});e.check(p.ELIF);){e.advance();let l=e.parseCompoundList();e.expect(p.THEN);let o=e.parseCompoundList();if(o.length===0){let c=e.check(p.FI)?\"fi\":e.check(p.ELSE)?\"else\":e.check(p.ELIF)?\"elif\":\"fi\";e.error(`syntax error near unexpected token \\`${c}'`)}r.push({condition:l,body:o})}let a=null;e.check(p.ELSE)&&(e.advance(),a=e.parseCompoundList(),a.length===0&&e.error(\"syntax error near unexpected token `fi'\")),e.expect(p.FI);let i=t?.skipRedirections?[]:e.parseOptionalRedirections();return w.ifNode(r,a,i)}function Ye(e,t){let r=e.expect(p.FOR);if(e.check(p.DPAREN_START))return Vr(e,t,r.line);e.isWord()||e.error(\"Expected variable name in for loop\");let n=e.advance().value,a=null;if(e.skipNewlines(),e.check(p.IN))for(e.advance(),a=[];!e.check(p.SEMICOLON,p.NEWLINE,p.DO,p.EOF)&&e.isWord();)a.push(e.parseWord());e.check(p.SEMICOLON)&&e.advance(),e.skipNewlines(),e.expect(p.DO);let i=e.parseCompoundList();e.expect(p.DONE);let l=t?.skipRedirections?[]:e.parseOptionalRedirections();return w.forNode(n,a,i,l)}function Vr(e,t,r){e.expect(p.DPAREN_START);let s=null,n=null,a=null,i=[\"\",\"\",\"\"],l=0,o=0;for(;!e.check(p.DPAREN_END,p.EOF);){let f=e.advance();if(f.type===p.SEMICOLON&&o===0){if(l++,l>2)break}else f.value===\"(\"&&o++,f.value===\")\"&&o--,i[l]+=f.value}e.expect(p.DPAREN_END),i[0].trim()&&(s=M(e,i[0].trim())),i[1].trim()&&(n=M(e,i[1].trim())),i[2].trim()&&(a=M(e,i[2].trim())),e.skipNewlines(),e.check(p.SEMICOLON)&&e.advance(),e.skipNewlines();let c;e.check(p.LBRACE)?(e.advance(),c=e.parseCompoundList(),e.expect(p.RBRACE)):(e.expect(p.DO),c=e.parseCompoundList(),e.expect(p.DONE));let u=t?.skipRedirections?[]:e.parseOptionalRedirections();return{type:\"CStyleFor\",init:s,condition:n,update:a,body:c,redirections:u,line:r}}function et(e,t){e.expect(p.WHILE);let r=e.parseCompoundList();e.expect(p.DO);let s=e.parseCompoundList();s.length===0&&e.error(\"syntax error near unexpected token `done'\"),e.expect(p.DONE);let n=t?.skipRedirections?[]:e.parseOptionalRedirections();return w.whileNode(r,s,n)}function tt(e,t){e.expect(p.UNTIL);let r=e.parseCompoundList();e.expect(p.DO);let s=e.parseCompoundList();s.length===0&&e.error(\"syntax error near unexpected token `done'\"),e.expect(p.DONE);let n=t?.skipRedirections?[]:e.parseOptionalRedirections();return w.untilNode(r,s,n)}function nt(e,t){e.expect(p.CASE),e.isWord()||e.error(\"Expected word after 'case'\");let r=e.parseWord();e.skipNewlines(),e.expect(p.IN),e.skipNewlines();let s=[];for(;!e.check(p.ESAC,p.EOF);){e.checkIterationLimit();let a=e.getPos(),i=qr(e);if(i&&s.push(i),e.skipNewlines(),e.getPos()===a&&!i)break}e.expect(p.ESAC);let n=t?.skipRedirections?[]:e.parseOptionalRedirections();return w.caseNode(r,s,n)}function qr(e){e.check(p.LPAREN)&&e.advance();let t=[];for(;e.isWord()&&(t.push(e.parseWord()),e.check(p.PIPE));)e.advance();if(t.length===0)return null;e.expect(p.RPAREN),e.skipNewlines();let r=[];for(;!e.check(p.DSEMI,p.SEMI_AND,p.SEMI_SEMI_AND,p.ESAC,p.EOF);){e.checkIterationLimit(),e.isWord()&&e.peek(1).type===p.RPAREN&&e.error(\"syntax error near unexpected token `)'\"),e.check(p.LPAREN)&&e.peek(1).type===p.WORD&&e.error(`syntax error near unexpected token \\`${e.peek(1).value}'`);let n=e.getPos(),a=e.parseStatement();if(a&&r.push(a),e.skipSeparators(!1),e.getPos()===n&&!a)break}let s=\";;\";return e.check(p.DSEMI)?(e.advance(),s=\";;\"):e.check(p.SEMI_AND)?(e.advance(),s=\";&\"):e.check(p.SEMI_SEMI_AND)&&(e.advance(),s=\";;&\"),w.caseItem(t,r,s)}function rt(e,t){e.expect(p.LPAREN);let r=e.parseCompoundList();e.expect(p.RPAREN);let s=t?.skipRedirections?[]:e.parseOptionalRedirections();return w.subshell(r,s)}function st(e,t){e.expect(p.LBRACE);let r=e.parseCompoundList();e.expect(p.RBRACE);let s=t?.skipRedirections?[]:e.parseOptionalRedirections();return w.group(r,s)}var Fr=[\"-a\",\"-b\",\"-c\",\"-d\",\"-e\",\"-f\",\"-g\",\"-h\",\"-k\",\"-p\",\"-r\",\"-s\",\"-t\",\"-u\",\"-w\",\"-x\",\"-G\",\"-L\",\"-N\",\"-O\",\"-S\",\"-z\",\"-n\",\"-o\",\"-v\",\"-R\"],zr=[\"==\",\"!=\",\"=~\",\"<\",\">\",\"-eq\",\"-ne\",\"-lt\",\"-le\",\"-gt\",\"-ge\",\"-nt\",\"-ot\",\"-ef\"];function sn(e){return e.isWord()||e.check(p.LBRACE)||e.check(p.RBRACE)||e.check(p.ASSIGNMENT_WORD)}function an(e){if(e.check(p.BANG)&&e.peek(1).type===p.LPAREN){e.advance(),e.advance();let t=1,r=\"!(\";for(;t>0&&!e.check(p.EOF);)if(e.check(p.LPAREN))t++,r+=\"(\",e.advance();else if(e.check(p.RPAREN))t--,t>0&&(r+=\")\"),e.advance();else if(e.isWord())r+=e.advance().value;else if(e.check(p.PIPE))r+=\"|\",e.advance();else break;return r+=\")\",e.parseWordFromString(r,!1,!1,!1,!1,!0)}return e.parseWordNoBraceExpansion()}function at(e){return e.skipNewlines(),Gr(e)}function Gr(e){let t=on(e);for(e.skipNewlines();e.check(p.OR_OR);){e.advance(),e.skipNewlines();let r=on(e);t={type:\"CondOr\",left:t,right:r},e.skipNewlines()}return t}function on(e){let t=it(e);for(e.skipNewlines();e.check(p.AND_AND);){e.advance(),e.skipNewlines();let r=it(e);t={type:\"CondAnd\",left:t,right:r},e.skipNewlines()}return t}function it(e){return e.skipNewlines(),e.check(p.BANG)?(e.advance(),e.skipNewlines(),{type:\"CondNot\",operand:it(e)}):Qr(e)}function Qr(e){if(e.check(p.LPAREN)){e.advance();let t=at(e);return e.expect(p.RPAREN),{type:\"CondGroup\",expression:t}}if(sn(e)){let t=e.current(),r=t.value;if(Fr.includes(r)&&!t.quoted){if(e.advance(),e.check(p.DBRACK_END)&&e.error(`Expected operand after ${r}`),sn(e)){let a=e.parseWordNoBraceExpansion();return{type:\"CondUnary\",operator:r,operand:a}}let n=e.current();e.error(`unexpected argument \\`${n.value}' to conditional unary operator`)}let s=e.parseWordNoBraceExpansion();if(e.isWord()&&zr.includes(e.current().value)){let n=e.advance().value,a;return n===\"=~\"?a=Zr(e):n===\"==\"||n===\"!=\"?a=an(e):a=e.parseWordNoBraceExpansion(),{type:\"CondBinary\",operator:n,left:s,right:a}}if(e.check(p.LESS)){e.advance();let n=e.parseWordNoBraceExpansion();return{type:\"CondBinary\",operator:\"<\",left:s,right:n}}if(e.check(p.GREAT)){e.advance();let n=e.parseWordNoBraceExpansion();return{type:\"CondBinary\",operator:\">\",left:s,right:n}}if(e.isWord()&&e.current().value===\"=\"){e.advance();let n=an(e);return{type:\"CondBinary\",operator:\"==\",left:s,right:n}}return{type:\"CondWord\",word:s}}e.error(\"Expected conditional expression\")}function Zr(e){let t=[],r=0,s=-1,n=e.getInput(),a=()=>e.check(p.DBRACK_END)||e.check(p.AND_AND)||e.check(p.OR_OR)||e.check(p.NEWLINE)||e.check(p.EOF);for(;!a();){let i=e.current(),l=s>=0&&i.start>s;if(r===0&&l)break;if(r>0&&l){let o=n.slice(s,i.start);t.push({type:\"Literal\",value:o})}if(e.isWord()||e.check(p.ASSIGNMENT_WORD)){let o=e.parseWordForRegex();t.push(...o.parts),s=e.peek(-1).end}else if(e.check(p.LPAREN)){let o=e.advance();t.push({type:\"Literal\",value:\"(\"}),r++,s=o.end}else if(e.check(p.DPAREN_START)){let o=e.advance();t.push({type:\"Literal\",value:\"((\"}),r+=2,s=o.end}else if(e.check(p.DPAREN_END))if(r>=2){let o=e.advance();t.push({type:\"Literal\",value:\"))\"}),r-=2,s=o.end}else{if(r===1)break;break}else if(e.check(p.RPAREN))if(r>0){let o=e.advance();t.push({type:\"Literal\",value:\")\"}),r--,s=o.end}else break;else if(e.check(p.PIPE)){let o=e.advance();t.push({type:\"Literal\",value:\"|\"}),s=o.end}else if(e.check(p.SEMICOLON))if(r>0){let o=e.advance();t.push({type:\"Literal\",value:\";\"}),s=o.end}else break;else if(r>0&&e.check(p.LESS)){let o=e.advance();t.push({type:\"Literal\",value:\"<\"}),s=o.end}else if(r>0&&e.check(p.GREAT)){let o=e.advance();t.push({type:\"Literal\",value:\">\"}),s=o.end}else if(r>0&&e.check(p.DGREAT)){let o=e.advance();t.push({type:\"Literal\",value:\">>\"}),s=o.end}else if(r>0&&e.check(p.DLESS)){let o=e.advance();t.push({type:\"Literal\",value:\"<<\"}),s=o.end}else if(r>0&&e.check(p.LESSAND)){let o=e.advance();t.push({type:\"Literal\",value:\"<&\"}),s=o.end}else if(r>0&&e.check(p.GREATAND)){let o=e.advance();t.push({type:\"Literal\",value:\">&\"}),s=o.end}else if(r>0&&e.check(p.LESSGREAT)){let o=e.advance();t.push({type:\"Literal\",value:\"<>\"}),s=o.end}else if(r>0&&e.check(p.CLOBBER)){let o=e.advance();t.push({type:\"Literal\",value:\">|\"}),s=o.end}else if(r>0&&e.check(p.TLESS)){let o=e.advance();t.push({type:\"Literal\",value:\"<<<\"}),s=o.end}else if(r>0&&e.check(p.AMP)){let o=e.advance();t.push({type:\"Literal\",value:\"&\"}),s=o.end}else if(r>0&&e.check(p.LBRACE)){let o=e.advance();t.push({type:\"Literal\",value:\"{\"}),s=o.end}else if(r>0&&e.check(p.RBRACE)){let o=e.advance();t.push({type:\"Literal\",value:\"}\"}),s=o.end}else break}return t.length===0&&e.error(\"Expected regex pattern after =~\"),{type:\"Word\",parts:t}}function Ee(e){return e.length>0?e:[w.literal(\"\")]}function Hr(e,t){let r=1,s=t+1;for(;s<e.length&&r>0;){let n=e[s];if(n===\"\\\\\"){s+=2;continue}if(\"@*+?!\".includes(n)&&s+1<e.length&&e[s+1]===\"(\"){s++,r++,s++;continue}if(n===\"(\")r++;else if(n===\")\"&&(r--,r===0))return s;s++}return-1}function jr(e,t,r){let s=r+1,n=t[s];if(\"@*#?$!-0123456789\".includes(n))return{part:w.parameterExpansion(n),endIndex:s+1};let a=\"\";for(;s<t.length&&/[a-zA-Z0-9_]/.test(t[s]);)a+=t[s],s++;return{part:w.parameterExpansion(a),endIndex:s}}function Kr(e,t,r,s=!1){let n=r+2,a=!1;t[n]===\"!\"&&(a=!0,n++);let i=!1;t[n]===\"#\"&&!/[}:#%/^,]/.test(t[n+1]||\"}\")&&(i=!0,n++);let l=\"\",o=t[n];if(/[@*#?$!-]/.test(o)&&!/[a-zA-Z0-9_]/.test(t[n+1]||\"\"))l=o,n++;else for(;n<t.length&&/[a-zA-Z0-9_]/.test(t[n]);)l+=t[n],n++;if(t[n]===\"[\"){let u=He(e,t,n,\"[\",\"]\");if(l+=t.slice(n,u+1),n=u+1,t[n]===\"[\"){let f=1,h=n;for(;h<t.length&&f>0;)t[h]===\"{\"?f++:t[h]===\"}\"&&f--,f>0&&h++;let d=t.slice(r+2,h);return{part:w.parameterExpansion(\"\",{type:\"BadSubstitution\",text:d}),endIndex:h+1}}}if(l===\"\"&&!a&&!i&&t[n]!==\"}\"){let u=1,f=n;for(;f<t.length&&u>0;)t[f]===\"{\"?u++:t[f]===\"}\"&&u--,u>0&&f++;if(u>0)throw new G(\"unexpected EOF while looking for matching '}'\",0,0);let h=t.slice(r+2,f);return{part:w.parameterExpansion(\"\",{type:\"BadSubstitution\",text:h}),endIndex:f+1}}let c=null;if(a){let u=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[([@*])\\]$/);if(u)if(n<t.length&&t[n]!==\"}\"&&/[:=\\-+?#%/^,@]/.test(t[n])){let f=ot(e,t,n,l,s);f.operation?(c={type:\"Indirection\",innerOp:f.operation},n=f.endIndex):(c={type:\"ArrayKeys\",array:u[1],star:u[2]===\"*\"},l=\"\")}else c={type:\"ArrayKeys\",array:u[1],star:u[2]===\"*\"},l=\"\";else if(t[n]===\"*\"||t[n]===\"@\"&&!/[QPaAEKkuUL]/.test(t[n+1]||\"\")){let f=t[n];n++,c={type:\"VarNamePrefix\",prefix:l,star:f===\"*\"},l=\"\"}else if(n<t.length&&t[n]!==\"}\"&&/[:=\\-+?#%/^,@]/.test(t[n])){let f=ot(e,t,n,l,s);f.operation?(c={type:\"Indirection\",innerOp:f.operation},n=f.endIndex):c={type:\"Indirection\"}}else c={type:\"Indirection\"}}else if(i)if(t[n]===\":\")for(c={type:\"LengthSliceError\"};n<t.length&&t[n]!==\"}\";)n++;else t[n]!==\"}\"&&/[-+=?]/.test(t[n])?e.error(`\\${#${l}${t.slice(n,t.indexOf(\"}\",n))}}: bad substitution`):t[n]===\"/\"?e.error(`\\${#${l}${t.slice(n,t.indexOf(\"}\",n))}}: bad substitution`):c={type:\"Length\"};if(!c&&n<t.length&&t[n]!==\"}\"){let u=ot(e,t,n,l,s);c=u.operation,n=u.endIndex}if(n<t.length&&t[n]!==\"}\"){let u=t[n];if(!/[:\\-+=?#%/^,@[]/.test(u)){let f=n;for(;f<t.length&&t[f]!==\"}\";)f++;let h=t.slice(r,f+1);e.error(`\\${${h.slice(2,-1)}}: bad substitution`)}}for(;n<t.length&&t[n]!==\"}\";)n++;if(n>=t.length)throw new G(\"unexpected EOF while looking for matching '}'\",0,0);return{part:w.parameterExpansion(l,c),endIndex:n+1}}function ot(e,t,r,s,n=!1){let a=r,i=t[a],l=t[a+1]||\"\";if(i===\":\"){let o=l;if(\"-=?+\".includes(o)){a+=2;let A=fe(e,t,a),S=t.slice(a,A),y=ae(e,S,!1,!1,!0,!1,n,!1,!1,!0),b=w.word(Ee(y));if(o===\"-\")return{operation:{type:\"DefaultValue\",word:b,checkEmpty:!0},endIndex:A};if(o===\"=\")return{operation:{type:\"AssignDefault\",word:b,checkEmpty:!0},endIndex:A};if(o===\"?\")return{operation:{type:\"ErrorIfUnset\",word:b,checkEmpty:!0},endIndex:A};if(o===\"+\")return{operation:{type:\"UseAlternative\",word:b,checkEmpty:!0},endIndex:A}}a++;let c=fe(e,t,a),u=t.slice(a,c),f=-1,h=0,d=0;for(let E=0;E<u.length;E++){let A=u[E];if(A===\"(\"||A===\"[\")h++;else if(A===\")\"||A===\"]\")h--;else if(A===\"?\"&&h===0)d++;else if(A===\":\"&&h===0)if(d>0)d--;else{f=E;break}}let m=f>=0?u.slice(0,f):u,g=f>=0?u.slice(f+1):null;return{operation:{type:\"Substring\",offset:je(e,m),length:g!==null?je(e,g):null},endIndex:c}}if(\"-=?+\".includes(i)){a++;let o=fe(e,t,a),c=t.slice(a,o),u=ae(e,c,!1,!1,!0,!1,n,!1,!1,!0),f=w.word(Ee(u));if(i===\"-\")return{operation:{type:\"DefaultValue\",word:f,checkEmpty:!1},endIndex:o};if(i===\"=\")return{operation:{type:\"AssignDefault\",word:f,checkEmpty:!1},endIndex:o};if(i===\"?\")return{operation:{type:\"ErrorIfUnset\",word:c?f:null,checkEmpty:!1},endIndex:o};if(i===\"+\")return{operation:{type:\"UseAlternative\",word:f,checkEmpty:!1},endIndex:o}}if(i===\"#\"||i===\"%\"){let o=l===i,c=i===\"#\"?\"prefix\":\"suffix\";a+=o?2:1;let u=fe(e,t,a),f=t.slice(a,u),h=ae(e,f,!1,!1,!1);return{operation:{type:\"PatternRemoval\",pattern:w.word(Ee(h)),side:c,greedy:o},endIndex:u}}if(i===\"/\"){let o=l===\"/\";a+=o?2:1;let c=null;t[a]===\"#\"?(c=\"start\",a++):t[a]===\"%\"&&(c=\"end\",a++);let u;c!==null&&(t[a]===\"/\"||t[a]===\"}\")?u=a:u=Xt(e,t,a);let f=t.slice(a,u),h=ae(e,f,!1,!1,!1),d=w.word(Ee(h)),m=null,g=u;if(t[u]===\"/\"){let E=u+1,A=fe(e,t,E),S=t.slice(E,A),y=ae(e,S,!1,!1,!1);m=w.word(Ee(y)),g=A}return{operation:{type:\"PatternReplacement\",pattern:d,replacement:m,all:o,anchor:c},endIndex:g}}if(i===\"^\"||i===\",\"){let o=l===i,c=i===\"^\"?\"upper\":\"lower\";a+=o?2:1;let u=fe(e,t,a),f=t.slice(a,u),h=f?w.word([w.literal(f)]):null;return{operation:{type:\"CaseModification\",direction:c,all:o,pattern:h},endIndex:u}}return i===\"@\"&&/[QPaAEKkuUL]/.test(l)?{operation:{type:\"Transform\",operator:l},endIndex:a+2}:{operation:null,endIndex:a}}function lt(e,t,r,s=!1){let n=r+1;if(n>=t.length)return{part:w.literal(\"$\"),endIndex:n};let a=t[n];if(a===\"(\"&&t[n+1]===\"(\")return e.isDollarDparenSubshell(t,r)?e.parseCommandSubstitution(t,r):e.parseArithmeticExpansion(t,r);if(a===\"[\"){let i=1,l=n+1;for(;l<t.length&&i>0;)t[l]===\"[\"?i++:t[l]===\"]\"&&i--,i>0&&l++;if(i===0){let o=t.slice(n+1,l),c=M(e,o);return{part:w.arithmeticExpansion(c),endIndex:l+1}}}return a===\"(\"?e.parseCommandSubstitution(t,r):a===\"{\"?Kr(e,t,r,s):/[a-zA-Z_0-9@*#?$!-]/.test(a)?jr(e,t,r):{part:w.literal(\"$\"),endIndex:n}}function ln(e,t){let r=[],s=0,n=\"\",a=()=>{n&&(r.push(w.literal(n)),n=\"\")};for(;s<t.length;){let i=t[s];if(i===\"\\\\\"&&s+1<t.length){let l=t[s+1];if(l===\"$\"||l===\"`\"||l==='\"'||l===\"\\\\\"){n+=l,s+=2;continue}n+=i,s++;continue}if(i===\"$\"){a();let{part:l,endIndex:o}=lt(e,t,s,!0);l&&r.push(l),s=o;continue}if(i===\"`\"){a();let{part:l,endIndex:o}=e.parseBacktickSubstitution(t,s,!0);r.push(l),s=o;continue}n+=i,s++}return a(),r}function Xr(e,t,r){let s=[],n=r,a=\"\",i=()=>{a&&(s.push(w.literal(a)),a=\"\")};for(;n<t.length&&t[n]!=='\"';){let l=t[n];if(l===\"\\\\\"&&n+1<t.length){let o=t[n+1];if('\"\\\\$`\\n'.includes(o)){a+=o,n+=2;continue}a+=l,n++;continue}if(l===\"$\"){i();let{part:o,endIndex:c}=lt(e,t,n,!0);o&&s.push(o),n=c;continue}if(l===\"`\"){i();let{part:o,endIndex:c}=e.parseBacktickSubstitution(t,n,!0);s.push(o),n=c;continue}a+=l,n++}return i(),{part:w.doubleQuoted(s),endIndex:n}}function ae(e,t,r=!1,s=!1,n=!1,a=!1,i=!1,l=!1,o=!1,c=!1){if(s)return[w.singleQuoted(t)];if(r){let m=ln(e,t);return[w.doubleQuoted(m)]}if(t.length>=2&&t[0]==='\"'&&t[t.length-1]==='\"'){let m=t.slice(1,-1),g=!1;for(let E=0;E<m.length;E++){if(m[E]==='\"'){g=!0;break}m[E]===\"\\\\\"&&E+1<m.length&&E++}if(!g){let E=ln(e,m);return[w.doubleQuoted(E)]}}let u=[],f=0,h=\"\",d=()=>{h&&(u.push(w.literal(h)),h=\"\")};for(;f<t.length;){let m=t[f];if(m===\"\\\\\"&&f+1<t.length){let g=t[f+1];if(o){d(),u.push(w.escaped(g)),f+=2;continue}let E=a?g===\"$\"||g===\"`\"||g===`\n`:g===\"$\"||g===\"`\"||g==='\"'||g===\"'\"||g===`\n`||c&&g===\"}\",A=i?\"*?[]\\\\\".includes(g):\"*?[]\\\\(){}.^+\".includes(g);E?h+=g:A?(d(),u.push(w.escaped(g))):h+=`\\\\${g}`,f+=2;continue}if(m===\"'\"&&!i&&!a){d();let g=t.indexOf(\"'\",f+1);if(g===-1){h+=t.slice(f);break}u.push(w.singleQuoted(t.slice(f+1,g))),f=g+1;continue}if(m==='\"'&&!a){d();let{part:g,endIndex:E}=Xr(e,t,f+1);u.push(g),f=E+1;continue}if(m===\"$\"&&t[f+1]===\"'\"){d();let{part:g,endIndex:E}=Yt(e,t,f+2);u.push(g),f=E;continue}if(m===\"$\"){d();let{part:g,endIndex:E}=lt(e,t,f);g&&u.push(g),f=E;continue}if(m===\"`\"){d();let{part:g,endIndex:E}=e.parseBacktickSubstitution(t,f);u.push(g),f=E;continue}if(m===\"~\"){let g=f>0?t[f-1]:\"\";if(f===0||g===\"=\"||n&&g===\":\"){let A=Kt(e,t,f),S=t[A];if(S===void 0||S===\"/\"||S===\":\"){d();let y=t.slice(f+1,A)||null;u.push({type:\"TildeExpansion\",user:y}),f=A;continue}}}if(\"@*+?!\".includes(m)&&f+1<t.length&&t[f+1]===\"(\"){let g=Hr(t,f+1);if(g!==-1){d();let E=t.slice(f,g+1);u.push({type:\"Glob\",pattern:E}),f=g+1;continue}}if(m===\"*\"||m===\"?\"||m===\"[\"){d();let{pattern:g,endIndex:E}=Jt(e,t,f);u.push({type:\"Glob\",pattern:g}),f=E;continue}if(m===\"{\"&&!n&&!l&&!a){let g=en(e,t,f,ae);if(g){d(),u.push(g.part),f=g.endIndex;continue}}h+=m,f++}return d(),u}function un(e,t){let r=e.length,s=t+3,n=2,a=!1,i=!1;for(;s<r&&n>0;){let l=e[s];if(a){l===\"'\"&&(a=!1),s++;continue}if(i){if(l===\"\\\\\"){s+=2;continue}l==='\"'&&(i=!1),s++;continue}if(l===\"'\"){a=!0,s++;continue}if(l==='\"'){i=!0,s++;continue}if(l===\"\\\\\"){s+=2;continue}if(l===\"(\"){n++,s++;continue}if(l===\")\"){if(n--,n===1){let o=s+1;return!(o<r&&e[o]===\")\")}if(n===0)return!1;s++;continue}if(n===1&&(l===\"|\"&&s+1<r&&e[s+1]===\"|\"||l===\"&\"&&s+1<r&&e[s+1]===\"&\"||l===\"|\"&&s+1<r&&e[s+1]!==\"|\"))return!0;s++}return!1}function cn(e,t,r,s){let n=t+2,a=1,i=n,l=!1,o=!1,c=0,u=!1,f=\"\";for(;i<e.length&&a>0;){let g=e[i];l?g===\"'\"&&(l=!1):o?g===\"\\\\\"&&i+1<e.length?i++:g==='\"'&&(o=!1):g===\"'\"?(l=!0,f=\"\"):g==='\"'?(o=!0,f=\"\"):g===\"\\\\\"&&i+1<e.length?(i++,f=\"\"):/[a-zA-Z_]/.test(g)?f+=g:(f===\"case\"?(c++,u=!1):f===\"in\"&&c>0?u=!0:f===\"esac\"&&c>0&&(c--,u=!1),f=\"\",g===\"(\"?i>0&&e[i-1]===\"$\"?a++:u||a++:g===\")\"?u?u=!1:a--:g===\";\"&&c>0&&i+1<e.length&&e[i+1]===\";\"&&(u=!0)),a>0&&i++}a>0&&s(\"unexpected EOF while looking for matching `)'\");let h=e.slice(n,i),m=r().parse(h);return{part:w.commandSubstitution(m,!1),endIndex:i+1}}function fn(e,t,r,s,n){let i=t+1,l=\"\";for(;i<e.length&&e[i]!==\"`\";)if(e[i]===\"\\\\\"){let u=e[i+1];u===\"$\"||u===\"`\"||u===\"\\\\\"||u===`\n`||r&&u==='\"'?(u!==`\n`&&(l+=u),i+=2):(l+=e[i],i++)}else l+=e[i],i++;i>=e.length&&n(\"unexpected EOF while looking for matching ``'\");let c=s().parse(l);return{part:w.commandSubstitution(c,!0),endIndex:i+1}}var V=class e{tokens=[];pos=0;pendingHeredocs=[];parseIterations=0;parseDepth=0;_input=\"\";getInput(){return this._input}checkIterationLimit(){if(this.parseIterations++,this.parseIterations>Qt)throw new G(\"Maximum parse iterations exceeded (possible infinite loop)\",this.current().line,this.current().column)}enterDepth(){if(this.parseDepth++,this.parseDepth>Ue)throw new G(`Maximum parser nesting depth exceeded (${Ue})`,this.current().line,this.current().column);return()=>{this.parseDepth--}}parse(t,r){if(t.length>Qe)throw new G(`Input too large: ${t.length} bytes exceeds limit of ${Qe}`,1,1);this._input=t;let s=new ve(t,r);if(this.tokens=s.tokenize(),this.tokens.length>Ze)throw new G(`Too many tokens: ${this.tokens.length} exceeds limit of ${Ze}`,1,1);return this.pos=0,this.pendingHeredocs=[],this.parseIterations=0,this.parseDepth=0,this.parseScript()}parseTokens(t){return this.tokens=t,this.pos=0,this.pendingHeredocs=[],this.parseIterations=0,this.parseDepth=0,this.parseScript()}current(){return this.tokens[this.pos]||this.tokens[this.tokens.length-1]}peek(t=0){return this.tokens[this.pos+t]||this.tokens[this.tokens.length-1]}advance(){let t=this.current();return this.pos<this.tokens.length-1&&this.pos++,t}getPos(){return this.pos}check(t,r,s,n,...a){let i=this.tokens[this.pos]?.type;return i===t||r!==void 0&&i===r||s!==void 0&&i===s||n!==void 0&&i===n?!0:a.length>0?a.includes(i):!1}expect(t,r){if(this.check(t))return this.advance();let s=this.current();throw new G(r||`Expected ${t}, got ${s.type}`,s.line,s.column,s)}error(t){let r=this.current();throw new G(t,r.line,r.column,r)}skipNewlines(){for(;this.check(p.NEWLINE,p.COMMENT);)this.check(p.NEWLINE)?(this.advance(),this.processHeredocs()):this.advance()}skipSeparators(t=!0){for(;;){if(this.check(p.NEWLINE)){this.advance(),this.processHeredocs();continue}if(this.check(p.SEMICOLON,p.COMMENT)){this.advance();continue}if(t&&this.check(p.DSEMI,p.SEMI_AND,p.SEMI_SEMI_AND)){this.advance();continue}break}}addPendingHeredoc(t,r,s,n){this.pendingHeredocs.push({redirect:t,delimiter:r,stripTabs:s,quoted:n})}processHeredocs(){for(let t of this.pendingHeredocs)if(this.check(p.HEREDOC_CONTENT)){let r=this.advance(),s;t.quoted?s=w.word([w.literal(r.value)]):s=this.parseWordFromString(r.value,!1,!1,!1,!0),t.redirect.target=w.hereDoc(t.delimiter,s,t.stripTabs,t.quoted)}this.pendingHeredocs=[]}isStatementEnd(){return this.check(p.EOF,p.NEWLINE,p.SEMICOLON,p.AMP,p.AND_AND,p.OR_OR,p.RPAREN,p.RBRACE,p.DSEMI,p.SEMI_AND,p.SEMI_SEMI_AND)}isCommandStart(){let t=this.current().type;return t===p.WORD||t===p.NAME||t===p.NUMBER||t===p.ASSIGNMENT_WORD||t===p.IF||t===p.FOR||t===p.WHILE||t===p.UNTIL||t===p.CASE||t===p.LPAREN||t===p.LBRACE||t===p.DPAREN_START||t===p.DBRACK_START||t===p.FUNCTION||t===p.BANG||t===p.TIME||t===p.IN||t===p.LESS||t===p.GREAT||t===p.DLESS||t===p.DGREAT||t===p.LESSAND||t===p.GREATAND||t===p.LESSGREAT||t===p.DLESSDASH||t===p.CLOBBER||t===p.TLESS||t===p.AND_GREAT||t===p.AND_DGREAT}parseScript(){let t=[],s=0;for(this.skipNewlines();!this.check(p.EOF);){s++,s>1e4&&this.error(\"Parser stuck: too many iterations (>10000)\");let n=this.checkUnexpectedToken();if(n){t.push(n),this.skipSeparators(!1);continue}let a=this.pos,i=this.parseStatement();i&&t.push(i),this.skipSeparators(!1),this.check(p.DSEMI,p.SEMI_AND,p.SEMI_SEMI_AND)&&this.error(`syntax error near unexpected token \\`${this.current().value}'`),this.pos===a&&!this.check(p.EOF)&&this.advance()}return w.script(t)}checkUnexpectedToken(){let t=this.current().type,r=this.current().value;if((t===p.DO||t===p.DONE||t===p.THEN||t===p.ELSE||t===p.ELIF||t===p.FI||t===p.ESAC)&&this.error(`syntax error near unexpected token \\`${r}'`),t===p.RBRACE||t===p.RPAREN){let s=`syntax error near unexpected token \\`${r}'`;return this.advance(),w.statement([w.pipeline([w.simpleCommand(null,[],[],[])])],[],!1,{message:s,token:r})}return(t===p.DSEMI||t===p.SEMI_AND||t===p.SEMI_SEMI_AND)&&this.error(`syntax error near unexpected token \\`${r}'`),t===p.SEMICOLON&&this.error(`syntax error near unexpected token \\`${r}'`),(t===p.PIPE||t===p.PIPE_AMP)&&this.error(`syntax error near unexpected token \\`${r}'`),null}parseStatement(){if(this.skipNewlines(),!this.isCommandStart())return null;let t=this.current().start,r=[],s=[],n=!1,a=this.parsePipeline();for(r.push(a);this.check(p.AND_AND,p.OR_OR);){let o=this.advance();s.push(o.type===p.AND_AND?\"&&\":\"||\"),this.skipNewlines();let c=this.parsePipeline();r.push(c)}this.check(p.AMP)&&(this.advance(),n=!0);let i=this.pos>0?this.tokens[this.pos-1].end:t,l=this._input.slice(t,i);return w.statement(r,s,n,void 0,l)}parsePipeline(){let t=!1,r=!1;this.check(p.TIME)&&(this.advance(),t=!0,this.check(p.WORD,p.NAME)&&this.current().value===\"-p\"&&(this.advance(),r=!0));let s=0;for(;this.check(p.BANG);)this.advance(),s++;let n=s%2===1,a=[],i=[],l=this.parseCommand();for(a.push(l);this.check(p.PIPE,p.PIPE_AMP);){let o=this.advance();this.skipNewlines(),i.push(o.type===p.PIPE_AMP);let c=this.parseCommand();a.push(c)}return w.pipeline(a,n,t,r,i.length>0?i:void 0)}parseCommand(){return this.check(p.IF)?Je(this):this.check(p.FOR)?Ye(this):this.check(p.WHILE)?et(this):this.check(p.UNTIL)?tt(this):this.check(p.CASE)?nt(this):this.check(p.LPAREN)?rt(this):this.check(p.LBRACE)?st(this):this.check(p.DPAREN_START)?this.dparenClosesWithSpacedParens()?this.parseNestedSubshellsFromDparen():this.parseArithmeticCommand():this.check(p.DBRACK_START)?this.parseConditionalCommand():this.check(p.FUNCTION)?this.parseFunctionDef():this.check(p.NAME,p.WORD)&&this.peek(1).type===p.LPAREN&&this.peek(2).type===p.RPAREN?this.parseFunctionDef():rn(this)}dparenClosesWithSpacedParens(){let t=1,r=1;for(;r<this.tokens.length-this.pos;){let s=this.peek(r);if(s.type===p.EOF)return!1;if(s.type===p.DPAREN_START||s.type===p.LPAREN)t++;else if(s.type===p.DPAREN_END){if(t-=2,t<=0)return!1}else if(s.type===p.RPAREN&&(t--,t===0&&this.peek(r+1).type===p.RPAREN))return!0;r++}return!1}parseNestedSubshellsFromDparen(){this.advance();let t=this.parseCompoundList();this.expect(p.RPAREN),this.expect(p.RPAREN);let r=this.parseOptionalRedirections(),s=w.subshell(t,[]);return w.subshell([w.statement([w.pipeline([s],!1,!1,!1)])],r)}isWord(){let t=this.current().type;return t===p.WORD||t===p.NAME||t===p.NUMBER||t===p.IF||t===p.FOR||t===p.WHILE||t===p.UNTIL||t===p.CASE||t===p.FUNCTION||t===p.ELSE||t===p.ELIF||t===p.FI||t===p.THEN||t===p.DO||t===p.DONE||t===p.ESAC||t===p.IN||t===p.SELECT||t===p.TIME||t===p.COPROC||t===p.BANG}parseWord(){let t=this.advance();return this.parseWordFromString(t.value,t.quoted,t.singleQuoted)}parseWordNoBraceExpansion(){let t=this.advance();return this.parseWordFromString(t.value,t.quoted,t.singleQuoted,!1,!1,!0)}parseWordForRegex(){let t=this.advance();return this.parseWordFromString(t.value,t.quoted,t.singleQuoted,!1,!1,!0,!0)}parseWordFromString(t,r=!1,s=!1,n=!1,a=!1,i=!1,l=!1){let o=ae(this,t,r,s,n,a,!1,i,l);return w.word(o)}parseCommandSubstitution(t,r){return cn(t,r,()=>new e,s=>this.error(s))}parseBacktickSubstitution(t,r,s=!1){return fn(t,r,s,()=>new e,n=>this.error(n))}isDollarDparenSubshell(t,r){return un(t,r)}parseArithmeticExpansion(t,r){let s=r+3,n=1,a=0,i=s;for(;i<t.length-1&&n>0;)t[i]===\"$\"&&t[i+1]===\"(\"?t[i+2]===\"(\"?(n++,i+=3):(a++,i+=2):t[i]===\"(\"&&t[i+1]===\"(\"?(n++,i+=2):t[i]===\")\"&&t[i+1]===\")\"?a>0?(a--,i++):(n--,n>0&&(i+=2)):t[i]===\"(\"?(a++,i++):(t[i]===\")\"&&a>0&&a--,i++);let l=t.slice(s,i),o=this.parseArithmeticExpression(l);return{part:w.arithmeticExpansion(o),endIndex:i+2}}parseArithmeticCommand(){let t=this.expect(p.DPAREN_START),r=\"\",s=1,n=0,a=!1,i=!1;for(;s>0&&!this.check(p.EOF);){if(a){if(a=!1,n>0){n--,r+=\")\";continue}if(this.check(p.RPAREN)){s--,i=!0,this.advance();continue}if(this.check(p.DPAREN_END)){s--,i=!0;continue}r+=\")\";continue}if(this.check(p.DPAREN_START))s++,r+=\"((\",this.advance();else if(this.check(p.DPAREN_END))n>=2?(n-=2,r+=\"))\",this.advance()):n===1?(n--,r+=\")\",a=!0,this.advance()):(s--,i=!0,s>0&&(r+=\"))\"),this.advance());else if(this.check(p.LPAREN))n++,r+=\"(\",this.advance();else if(this.check(p.RPAREN))n>0&&n--,r+=\")\",this.advance();else{let c=this.current().value,u=r.length>0?r[r.length-1]:\"\";r.length>0&&!r.endsWith(\" \")&&!(c===\"=\"&&/[|&^+\\-*/%<>]$/.test(r))&&!(c===\"<\"&&u===\"<\")&&!(c===\">\"&&u===\">\")&&(r+=\" \"),r+=c,this.advance()}}i||this.expect(p.DPAREN_END);let l=this.parseArithmeticExpression(r.trim()),o=this.parseOptionalRedirections();return w.arithmeticCommand(l,o,t.line)}parseConditionalCommand(){let t=this.expect(p.DBRACK_START),r=at(this);this.expect(p.DBRACK_END);let s=this.parseOptionalRedirections();return w.conditionalCommand(r,s,t.line)}parseFunctionDef(){let t;if(this.check(p.FUNCTION)){if(this.advance(),this.check(p.NAME)||this.check(p.WORD))t=this.advance().value;else{let n=this.current();throw new G(\"Expected function name\",n.line,n.column,n)}this.check(p.LPAREN)&&(this.advance(),this.expect(p.RPAREN))}else t=this.advance().value,t.includes(\"$\")&&this.error(`\\`${t}': not a valid identifier`),this.expect(p.LPAREN),this.expect(p.RPAREN);this.skipNewlines();let r=this.parseCompoundCommandBody({forFunctionBody:!0}),s=this.parseOptionalRedirections();return w.functionDef(t,r,s)}parseCompoundCommandBody(t){let r=t?.forFunctionBody;if(this.check(p.LBRACE))return st(this,{skipRedirections:r});if(this.check(p.LPAREN))return rt(this,{skipRedirections:r});if(this.check(p.IF))return Je(this,{skipRedirections:r});if(this.check(p.FOR))return Ye(this,{skipRedirections:r});if(this.check(p.WHILE))return et(this,{skipRedirections:r});if(this.check(p.UNTIL))return tt(this,{skipRedirections:r});if(this.check(p.CASE))return nt(this,{skipRedirections:r});this.error(\"Expected compound command for function body\")}parseCompoundList(){let t=this.enterDepth(),r=[];for(this.skipNewlines();!this.check(p.EOF,p.FI,p.ELSE,p.ELIF,p.THEN,p.DO,p.DONE,p.ESAC,p.RPAREN,p.RBRACE,p.DSEMI,p.SEMI_AND,p.SEMI_SEMI_AND)&&this.isCommandStart();){this.checkIterationLimit();let s=this.pos,n=this.parseStatement();if(n&&r.push(n),this.skipSeparators(),this.pos===s&&!n)break}return t(),r}parseOptionalRedirections(){let t=[];for(;De(this);){this.checkIterationLimit();let r=this.pos;if(t.push(xe(this)),this.pos===r)break}return t}parseArithmeticExpression(t){return M(this,t)}};function di(e,t){return new V().parse(e,t)}var Yr=new Map([[\"alnum\",\"a-zA-Z0-9\"],[\"alpha\",\"a-zA-Z\"],[\"ascii\",\"\\\\x00-\\\\x7F\"],[\"blank\",\" \\\\t\"],[\"cntrl\",\"\\\\x00-\\\\x1F\\\\x7F\"],[\"digit\",\"0-9\"],[\"graph\",\"!-~\"],[\"lower\",\"a-z\"],[\"print\",\" -~\"],[\"punct\",\"!-/:-@\\\\[-`{-~\"],[\"space\",\" \\\\t\\\\n\\\\r\\\\f\\\\v\"],[\"upper\",\"A-Z\"],[\"word\",\"a-zA-Z0-9_\"],[\"xdigit\",\"0-9a-fA-F\"]]);function ut(e){return Yr.get(e)??\"\"}function hn(e){let t=[],r=\"\",s=0;for(;s<e.length;){let n=e[s];if(n===\"[\"){for(r+=n,s++,s<e.length&&(e[s]===\"!\"||e[s]===\"^\")&&(r+=e[s],s++),s<e.length&&e[s]===\"]\"&&(r+=e[s],s++);s<e.length&&e[s]!==\"]\";){if(e[s]===\"[\"&&s+1<e.length&&e[s+1]===\":\"){let a=e.indexOf(\":]\",s+2);if(a!==-1){r+=e.slice(s,a+2),s=a+2;continue}}if(e[s]===\"\\\\\"&&s+1<e.length){r+=e[s]+e[s+1],s+=2;continue}r+=e[s],s++}s<e.length&&e[s]===\"]\"&&(r+=e[s],s++)}else n===\":\"?(r!==\"\"&&t.push(r),r=\"\",s++):n===\"\\\\\"&&s+1<e.length?(r+=n+e[s+1],s+=2):(r+=n,s++)}return r!==\"\"&&t.push(r),t}function pn(e){let t=\"^\";for(let r=0;r<e.length;r++){let s=e[r];if(s===\"*\")t+=\"[^/]*\";else if(s===\"?\")t+=\"[^/]\";else if(s===\"[\"){let n=r+1,a=\"[\";n<e.length&&(e[n]===\"^\"||e[n]===\"!\")&&(a+=\"^\",n++),n<e.length&&e[n]===\"]\"&&(a+=\"\\\\]\",n++);let i=n;for(;i<e.length;){if(e[i]===\"\\\\\"&&i+1<e.length){i+=2;continue}if(e[i]===\"[\"&&i+1<e.length&&e[i+1]===\":\"){let o=e.indexOf(\":]\",i+2);if(o!==-1){i=o+2;continue}}if(e[i]===\"]\")break;i++}let l=n;for(;n<e.length&&e[n]!==\"]\";){if(e[n]===\"[\"&&n+1<e.length&&e[n+1]===\":\"){let o=e.indexOf(\":]\",n+2);if(o!==-1){let c=e.slice(n+2,o),u=ut(c);a+=u,n=o+2;continue}}if(e[n]===\"\\\\\"&&n+1<e.length){a+=`\\\\${e[n+1]}`,n+=2;continue}if(e[n]===\"-\"){let o=n===l,c=n+1===i;o||c?a+=\"\\\\-\":a+=\"-\"}else a+=e[n];n++}a+=\"]\",t+=a,r=n}else if(s===\"\\\\\"&&r+1<e.length){let n=e[r+1];/[.+^${}()|\\\\*?[\\]]/.test(n)?t+=`\\\\${n}`:t+=n,r++}else/[.+^${}()|]/.test(s)?t+=`\\\\${s}`:t+=s}return t+=\"$\",O(t)}function ct(e,t){let r=1,s=t+1;for(;s<e.length&&r>0;){let n=e[s];if(n===\"\\\\\"){s+=2;continue}if(n===\"(\")r++;else if(n===\")\"&&(r--,r===0))return s;s++}return-1}function ft(e){let t=[],r=\"\",s=0,n=!1,a=0;for(;a<e.length;){let i=e[a];if(i===\"'\"&&!n){n=!0,r+=\"\\0QUOTE_START\\0\",a++;continue}if(i===\"'\"&&n){n=!1,r+=\"\\0QUOTE_END\\0\",a++;continue}if(n){r+=i,a++;continue}if(i===\"\\\\\"){r+=i,a+1<e.length?(r+=e[a+1],a+=2):a++;continue}i===\"(\"?(s++,r+=i):i===\")\"?(s--,r+=i):i===\"|\"&&s===0?(t.push(r),r=\"\"):r+=i,a++}return t.push(r),t}var dn=5,oe=class{fs;cwd;globignorePatterns=[];hasGlobignore=!1;globstar=!1;nullglob=!1;failglob=!1;dotglob=!1;extglob=!1;globskipdots=!0;ops={count:0};maxOps;constructor(t,r,s,n){this.fs=t,this.cwd=r,typeof n==\"boolean\"?(this.globstar=n,this.maxOps=1e5):n?(this.globstar=n.globstar??!1,this.nullglob=n.nullglob??!1,this.failglob=n.failglob??!1,this.dotglob=n.dotglob??!1,this.extglob=n.extglob??!1,this.globskipdots=n.globskipdots??!0,this.maxOps=n.maxGlobOperations??1e5):this.maxOps=1e5;let a=s?.get(\"GLOBIGNORE\");a!==void 0&&a!==\"\"&&(this.hasGlobignore=!0,this.globignorePatterns=hn(a))}checkOpsLimit(){if(++this.ops.count>this.maxOps)throw new L(`Glob operation limit exceeded (${this.maxOps})`,\"glob_operations\")}hasNullglob(){return this.nullglob}hasFailglob(){return this.failglob}filterGlobignore(t){return!this.hasGlobignore&&!this.globskipdots?t:t.filter(r=>{let s=r.split(\"/\").pop()||r;if((this.hasGlobignore||this.globskipdots)&&(s===\".\"||s===\"..\"))return!1;if(this.hasGlobignore){for(let n of this.globignorePatterns)if(this.matchGlobignorePattern(r,n))return!1}return!0})}matchGlobignorePattern(t,r){return pn(r).test(t)}isGlobPattern(t){return!!(t.includes(\"*\")||t.includes(\"?\")||/\\[.*\\]/.test(t)||this.extglob&&/[@*+?!]\\(/.test(t))}async expandArgs(t,r){let s=t.map((i,l)=>(r?.[l]??!1)||!this.isGlobPattern(i)?null:this.expand(i)),n=await Promise.all(s.map(i=>i||Promise.resolve(null))),a=[];for(let i=0;i<t.length;i++){let l=n[i];l===null?a.push(t[i]):l.length>0?a.push(...l):a.push(t[i])}return a}async expand(t){if(this.globstar){let s=t.split(\"/\"),n=0;for(let a of s)if(a===\"**\"&&(n++,n>dn))throw new L(`Glob pattern has too many ** segments (max ${dn})`,\"glob_operations\")}let r;if(t.includes(\"**\")&&this.globstar&&this.isGlobstarValid(t))r=await this.expandRecursive(t);else{let s=t.replace(/\\*\\*+/g,\"*\");r=await this.expandSimple(s)}return this.filterGlobignore(r)}isGlobstarValid(t){let r=t.split(\"/\");for(let s of r)if(s.includes(\"**\")&&s!==\"**\")return!1;return!0}hasGlobChars(t){return!!(t.includes(\"*\")||t.includes(\"?\")||/\\[.*\\]/.test(t)||this.extglob&&/[@*+?!]\\(/.test(t))}async expandSimple(t){let r=t.startsWith(\"/\"),s=t.split(\"/\").filter(c=>c!==\"\"),n=-1;for(let c=0;c<s.length;c++)if(this.hasGlobChars(s[c])){n=c;break}if(n===-1)return[t];let a,i;if(n===0)r?(a=\"/\",i=\"/\"):(a=this.cwd,i=\"\");else{let c=s.slice(0,n);r?(a=`/${c.join(\"/\")}`,i=`/${c.join(\"/\")}`):(a=this.fs.resolvePath(this.cwd,c.join(\"/\")),i=c.join(\"/\"))}let l=s.slice(n);return(await this.expandSegments(a,i,l)).sort()}async expandSegments(t,r,s){if(this.checkOpsLimit(),s.length===0)return[r];let[n,...a]=s,i=[];try{if(this.fs.readdirWithFileTypes){this.checkOpsLimit();let l=await this.fs.readdirWithFileTypes(t),o=[],c=[...l],u=this.dotglob||this.hasGlobignore;if(n.startsWith(\".\")||this.dotglob){let h=l.some(m=>m.name===\".\"),d=l.some(m=>m.name===\"..\");h||c.push({name:\".\",isFile:!1,isDirectory:!0,isSymbolicLink:!1}),d||c.push({name:\"..\",isFile:!1,isDirectory:!0,isSymbolicLink:!1})}for(let h of c)if(!(h.name.startsWith(\".\")&&!n.startsWith(\".\")&&!u)&&this.matchPattern(h.name,n)){let d=t===\"/\"?`/${h.name}`:`${t}/${h.name}`,m;r===\"\"?m=h.name:r===\"/\"?m=`/${h.name}`:m=`${r}/${h.name}`,a.length===0?o.push(Promise.resolve([m])):h.isDirectory&&o.push(this.expandSegments(d,m,a))}let f=await Promise.all(o);for(let h of f)i.push(...h)}else{this.checkOpsLimit();let l=await this.fs.readdir(t),o=[],c=[...l],u=this.dotglob||this.hasGlobignore;(n.startsWith(\".\")||this.dotglob)&&(l.includes(\".\")||c.push(\".\"),l.includes(\"..\")||c.push(\"..\"));for(let h of c)if(!(h.startsWith(\".\")&&!n.startsWith(\".\")&&!u)&&this.matchPattern(h,n)){let d=t===\"/\"?`/${h}`:`${t}/${h}`,m;r===\"\"?m=h:r===\"/\"?m=`/${h}`:m=`${r}/${h}`,a.length===0?o.push(Promise.resolve([m])):o.push((async()=>{try{if(this.checkOpsLimit(),(await this.fs.stat(d)).isDirectory)return this.expandSegments(d,m,a)}catch(g){if(g instanceof L)throw g}return[]})())}let f=await Promise.all(o);for(let h of f)i.push(...h)}}catch(l){if(l instanceof L)throw l}return i}async expandRecursive(t){let r=[],s=t.indexOf(\"**\"),n=t.slice(0,s).replace(/\\/$/,\"\")||\".\",i=t.slice(s+2).replace(/^\\//,\"\");return i.includes(\"**\")&&this.isGlobstarValid(i)?(await this.walkDirectoryMultiGlobstar(n,i,r),[...new Set(r)].sort()):(await this.walkDirectory(n,i,r),r.sort())}async walkDirectoryMultiGlobstar(t,r,s){this.checkOpsLimit();let n=this.fs.resolvePath(this.cwd,t);try{this.checkOpsLimit();let a=this.fs.readdirWithFileTypes?await this.fs.readdirWithFileTypes(n):null;if(a){let i=[];for(let c of a){let u=t===\".\"?c.name:`${t}/${c.name}`;c.isDirectory&&i.push(u)}let l=t===\".\"?r:`${t}/${r}`,o=await this.expandRecursive(l);s.push(...o);for(let c=0;c<i.length;c+=100){let u=i.slice(c,c+100);await Promise.all(u.map(f=>this.walkDirectoryMultiGlobstar(f,r,s)))}}else{this.checkOpsLimit();let i=await this.fs.readdir(n),l=[];for(let u of i){let f=t===\".\"?u:`${t}/${u}`,h=this.fs.resolvePath(this.cwd,f);try{this.checkOpsLimit(),(await this.fs.stat(h)).isDirectory&&l.push(f)}catch(d){if(d instanceof L)throw d}}let o=t===\".\"?r:`${t}/${r}`,c=await this.expandRecursive(o);s.push(...c);for(let u=0;u<l.length;u+=100){let f=l.slice(u,u+100);await Promise.all(f.map(h=>this.walkDirectoryMultiGlobstar(h,r,s)))}}}catch(a){if(a instanceof L)throw a}}async walkDirectory(t,r,s){this.checkOpsLimit();let n=this.fs.resolvePath(this.cwd,t);try{if(this.fs.readdirWithFileTypes){this.checkOpsLimit();let a=await this.fs.readdirWithFileTypes(n),i=[],l=[];for(let o of a){let c=t===\".\"?o.name:`${t}/${o.name}`;o.isDirectory?l.push(c):r&&this.matchPattern(o.name,r)&&i.push(c)}s.push(...i);for(let o=0;o<l.length;o+=100){let c=l.slice(o,o+100);await Promise.all(c.map(u=>this.walkDirectory(u,r,s)))}}else{this.checkOpsLimit();let a=await this.fs.readdir(n),i=[];for(let o=0;o<a.length;o+=100){let c=a.slice(o,o+100),u=await Promise.all(c.map(async f=>{let h=t===\".\"?f:`${t}/${f}`,d=this.fs.resolvePath(this.cwd,h);try{this.checkOpsLimit();let m=await this.fs.stat(d);return{name:f,path:h,isDirectory:m.isDirectory}}catch(m){if(m instanceof L)throw m;return null}}));i.push(...u.filter(f=>f!==null))}for(let o of i)!o.isDirectory&&r&&this.matchPattern(o.name,r)&&s.push(o.path);let l=i.filter(o=>o.isDirectory);for(let o=0;o<l.length;o+=100){let c=l.slice(o,o+100);await Promise.all(c.map(u=>this.walkDirectory(u.path,r,s)))}}}catch(a){if(a instanceof L)throw a}}matchPattern(t,r){return this.patternToRegex(r).test(t)}patternToRegex(t){let r=this.patternToRegexStr(t);return O(`^${r}$`)}patternToRegexStr(t){let r=\"\",s=!1;for(let n=0;n<t.length;n++){if(t.slice(n,n+13)===\"\\0QUOTE_START\\0\"){s=!0,n+=12;continue}if(t.slice(n,n+11)===\"\\0QUOTE_END\\0\"){s=!1,n+=10;continue}let a=t[n];if(s){/[.+^${}()|\\\\*?[\\]]/.test(a)?r+=`\\\\${a}`:r+=a;continue}if(this.extglob&&(a===\"@\"||a===\"*\"||a===\"+\"||a===\"?\"||a===\"!\")&&n+1<t.length&&t[n+1]===\"(\"){let i=ct(t,n+1);if(i!==-1){let l=t.slice(n+2,i),o=ft(l),c=o.map(f=>this.patternToRegexStr(f)),u=c.length>0?c.join(\"|\"):\"(?:)\";if(a===\"@\")r+=`(?:${u})`;else if(a===\"*\")r+=`(?:${u})*`;else if(a===\"+\")r+=`(?:${u})+`;else if(a===\"?\")r+=`(?:${u})?`;else if(a===\"!\")if(i<t.length-1){let h=o.map(m=>this.computePatternLength(m));if(h.every(m=>m!==null)&&h.every(m=>m===h[0])&&h[0]!==null){let m=h[0];if(m===0)r+=\"(?:.+)\";else{let g=[];m>0&&g.push(`.{0,${m-1}}`),g.push(`.{${m+1},}`),g.push(`(?!(?:${u})).{${m}}`),r+=`(?:${g.join(\"|\")})`}}else r+=`(?:(?!(?:${u})).)*?`}else r+=`(?!(?:${u})$).*`;n=i;continue}}if(a===\"*\")r+=\".*\";else if(a===\"?\")r+=\".\";else if(a===\"[\"){let i=n+1,l=\"[\";i<t.length&&(t[i]===\"^\"||t[i]===\"!\")&&(l+=\"^\",i++),i<t.length&&t[i]===\"]\"&&(l+=\"\\\\]\",i++);let o=i;for(;o<t.length;){if(t[o]===\"\\\\\"&&o+1<t.length){o+=2;continue}if(t[o]===\"[\"&&o+1<t.length&&t[o+1]===\":\"){let u=t.indexOf(\":]\",o+2);if(u!==-1){o=u+2;continue}}if(t[o]===\"]\")break;o++}let c=i;for(;i<t.length&&t[i]!==\"]\";){if(t[i]===\"[\"&&i+1<t.length&&t[i+1]===\":\"){let u=t.indexOf(\":]\",i+2);if(u!==-1){let f=t.slice(i+2,u),h=ut(f);l+=h,i=u+2;continue}}if(t[i]===\"\\\\\"&&i+1<t.length){l+=`\\\\${t[i+1]}`,i+=2;continue}if(t[i]===\"-\"){let u=i===c,f=i+1===o;u||f?l+=\"\\\\-\":l+=\"-\"}else l+=t[i];i++}l+=\"]\",r+=l,n=i}else if(a===\"\\\\\"&&n+1<t.length){let i=t[n+1];/[.+^${}()|\\\\*?[\\]]/.test(i)?r+=`\\\\${i}`:r+=i,n++}else/[.+^${}()|]/.test(a)?r+=`\\\\${a}`:r+=a}return r}computePatternLength(t){let r=0,s=0,n=!1;for(;s<t.length;){if(t.slice(s,s+13)===\"\\0QUOTE_START\\0\"){n=!0,s+=13;continue}if(t.slice(s,s+11)===\"\\0QUOTE_END\\0\"){n=!1,s+=11;continue}let a=t[s];if(n){r+=1,s++;continue}if((a===\"@\"||a===\"*\"||a===\"+\"||a===\"?\"||a===\"!\")&&s+1<t.length&&t[s+1]===\"(\"){let i=ct(t,s+1);if(i!==-1){if(a===\"@\"){let l=t.slice(s+2,i),c=ft(l).map(u=>this.computePatternLength(u));if(c.every(u=>u!==null)&&c.every(u=>u===c[0])){r+=c[0],s=i+1;continue}return null}return null}}if(a===\"*\")return null;if(a===\"?\"){r+=1,s++;continue}if(a===\"[\"){let i=t.indexOf(\"]\",s+1);if(i!==-1){r+=1,s=i+1;continue}r+=1,s++;continue}if(a===\"\\\\\"){r+=1,s+=2;continue}r+=1,s++}return r}};function es(e,t,r){switch(r){case\"+\":return e+t;case\"-\":return e-t;case\"*\":return e*t;case\"/\":if(t===0)throw new C(\"division by 0\");return Math.trunc(e/t);case\"%\":if(t===0)throw new C(\"division by 0\");return e%t;case\"**\":if(t<0)throw new C(\"exponent less than 0\");return e**t;case\"<<\":return e<<t;case\">>\":return e>>t;case\"<\":return e<t?1:0;case\"<=\":return e<=t?1:0;case\">\":return e>t?1:0;case\">=\":return e>=t?1:0;case\"==\":return e===t?1:0;case\"!=\":return e!==t?1:0;case\"&\":return e&t;case\"|\":return e|t;case\"^\":return e^t;case\",\":return t;default:return 0}}function mn(e,t,r){switch(r){case\"=\":return t;case\"+=\":return e+t;case\"-=\":return e-t;case\"*=\":return e*t;case\"/=\":return t!==0?Math.trunc(e/t):0;case\"%=\":return t!==0?e%t:0;case\"<<=\":return e<<t;case\">>=\":return e>>t;case\"&=\":return e&t;case\"|=\":return e|t;case\"^=\":return e^t;default:return t}}function ts(e,t){switch(t){case\"-\":return-e;case\"+\":return+e;case\"!\":return e===0?1:0;case\"~\":return~e;default:return e}}async function ns(e,t){let r=e.state.env.get(t);if(r!==void 0)return r;let s=e.state.env.get(`${t}_0`);return s!==void 0?s:await v(e,t)}function rs(e){if(!e)return 0;let t=Number.parseInt(e,10);if(!Number.isNaN(t)&&/^-?\\d+$/.test(e.trim()))return t;let r=e.trim();if(!r)return 0;try{let s=new V,{expr:n,pos:a}=Z(s,r,0);if(a<r.length){let i=r.slice(a).trim().split(/\\s+/)[0];throw new C(`${r}: syntax error in expression (error token is \"${i}\")`)}return n.type===\"ArithNumber\"?n.value:t||0}catch(s){if(s instanceof C)throw s;let n=r.split(/\\s+/).slice(1)[0]||r;throw new C(`${r}: syntax error in expression (error token is \"${n}\")`)}}async function ht(e,t){if(!t)return 0;let r=Number.parseInt(t,10);if(!Number.isNaN(r)&&/^-?\\d+$/.test(t.trim()))return r;let s=t.trim();if(!s)return 0;let n=new V,{expr:a,pos:i}=Z(n,s,0);if(i<s.length){let l=s.slice(i).trim(),o=l.split(/\\s+/)[0]||l;throw new C(`syntax error in expression (error token is \"${o}\")`,\"\",\"\")}return await R(e,a)}async function pt(e,t,r=new Set,s=0){if(s>100)throw new C(\"maximum variable indirection depth exceeded\");if(r.has(t))return 0;r.add(t);let n=await ns(e,t);if(!n)return 0;let a=Number.parseInt(n,10);if(!Number.isNaN(a)&&/^-?\\d+$/.test(n.trim()))return a;let i=n.trim();if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i))return await pt(e,i,r,s+1);let l=new V,{expr:o,pos:c}=Z(l,i,0);if(c<i.length){let u=i.slice(c).trim(),f=u.split(/\\s+/)[0]||u;throw new C(`${i}: syntax error in expression (error token is \"${f}\")`)}return await R(e,o)}async function _e(e,t){if(t.startsWith(\"#\")){let f=t.slice(1),h=f.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[[@*]\\]$/);if(h){let m=h[1],g=P(e,m);return String(g.length)}let d=e.state.env.get(f)||\"\";return String(d.length)}if(t.startsWith(\"!\")){let f=t.slice(1),h=e.state.env.get(f)||\"\";return e.state.env.get(h)||\"\"}let r=[\":-\",\":=\",\":?\",\":+\",\"-\",\"=\",\"?\",\"+\"],s=-1,n=\"\";for(let f of r){let h=t.indexOf(f);h>0&&(s===-1||h<s)&&(s=h,n=f)}if(s===-1)return await v(e,t);let a=t.slice(0,s),i=t.slice(s+n.length),l=e.state.env.get(a),o=l===void 0,c=l===\"\",u=n.startsWith(\":\");switch(n){case\":-\":case\"-\":return o||u&&c?i:l||\"\";case\":=\":case\"=\":return o||u&&c?(e.state.env.set(a,i),i):l||\"\";case\":+\":case\"+\":return!(o||u&&c)?i:\"\";case\":?\":case\"?\":{if(o||u&&c)throw new Error(i||`${a}: parameter null or not set`);return l||\"\"}default:return l||\"\"}}async function R(e,t,r=!1){switch(t.type){case\"ArithNumber\":if(Number.isNaN(t.value))throw new C(\"value too great for base\");return t.value;case\"ArithVariable\":return await pt(e,t.name);case\"ArithSpecialVar\":{let n=(await v(e,t.name)).trim();if(!n)return 0;let a=Number.parseInt(n,10);if(!Number.isNaN(a)&&/^-?\\d+$/.test(n))return a;let i=new V,{expr:l}=Z(i,n,0);return await R(e,l)}case\"ArithNested\":return await R(e,t.expression);case\"ArithCommandSubst\":{if(e.execFn){let s=await e.execFn(t.command,{signal:e.state.signal});s.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||\"\")+s.stderr);let n=s.stdout.trim();return Number.parseInt(n,10)||0}return 0}case\"ArithBracedExpansion\":{let s=await _e(e,t.content);return Number.parseInt(s,10)||0}case\"ArithDynamicBase\":{let s=await _e(e,t.baseExpr),n=Number.parseInt(s,10);if(n<2||n>64)return 0;let a=`${n}#${t.value}`;return ge(a)}case\"ArithDynamicNumber\":{let n=await _e(e,t.prefix)+t.suffix;return ge(n)}case\"ArithArrayElement\":{let s=e.state.associativeArrays?.has(t.array),n=async a=>{let i=e.state.env.get(a);return i!==void 0?await ht(e,i):0};if(t.stringKey!==void 0)return await n(`${t.array}_${t.stringKey}`);if(s&&t.index?.type===\"ArithVariable\"&&!t.index.hasDollarPrefix)return await n(`${t.array}_${t.index.name}`);if(s&&t.index?.type===\"ArithVariable\"&&t.index.hasDollarPrefix){let a=await v(e,t.index.name);return await n(`${t.array}_${a}`)}if(t.index){let a=await R(e,t.index,r);if(a<0){let o=P(e,t.array),c=e.state.currentLine;if(o.length===0)return e.state.expansionStderr=(e.state.expansionStderr||\"\")+`bash: line ${c}: ${t.array}: bad array subscript\n`,0;let f=Math.max(...o.map(([h])=>typeof h==\"number\"?h:0))+1+a;if(f<0)return e.state.expansionStderr=(e.state.expansionStderr||\"\")+`bash: line ${c}: ${t.array}: bad array subscript\n`,0;a=f}let i=`${t.array}_${a}`,l=e.state.env.get(i);if(l!==void 0)return ht(e,l);if(a===0){let o=e.state.env.get(t.array);if(o!==void 0)return ht(e,o)}if(e.state.options.nounset&&!Array.from(e.state.env.keys()).some(c=>c===t.array||c.startsWith(`${t.array}_`)))throw new j(`${t.array}[${a}]`);return 0}return 0}case\"ArithDoubleSubscript\":throw new C(\"double subscript\",\"\",\"\");case\"ArithNumberSubscript\":throw new C(`${t.number}${t.errorToken}: syntax error: invalid arithmetic operator (error token is \"${t.errorToken}\")`);case\"ArithSyntaxError\":throw new C(t.message,\"\",\"\",!0);case\"ArithSingleQuote\":{if(r)throw new C(`syntax error: operand expected (error token is \"'${t.content}'\")`);return t.value}case\"ArithBinary\":{if(t.operator===\"||\")return await R(e,t.left,r)||await R(e,t.right,r)?1:0;if(t.operator===\"&&\")return await R(e,t.left,r)&&await R(e,t.right,r)?1:0;let s=await R(e,t.left,r),n=await R(e,t.right,r);return es(s,n,t.operator)}case\"ArithUnary\":{let s=await R(e,t.operand,r);if(t.operator===\"++\"||t.operator===\"--\"){if(t.operand.type===\"ArithVariable\"){let n=t.operand.name,a=Number.parseInt(await v(e,n),10)||0,i=t.operator===\"++\"?a+1:a-1;return e.state.env.set(n,String(i)),t.prefix?i:a}if(t.operand.type===\"ArithArrayElement\"){let n=t.operand.array,a=e.state.associativeArrays?.has(n),i;if(t.operand.stringKey!==void 0)i=`${n}_${t.operand.stringKey}`;else if(a&&t.operand.index?.type===\"ArithVariable\"&&!t.operand.index.hasDollarPrefix)i=`${n}_${t.operand.index.name}`;else if(a&&t.operand.index?.type===\"ArithVariable\"&&t.operand.index.hasDollarPrefix){let c=await v(e,t.operand.index.name);i=`${n}_${c}`}else if(t.operand.index){let c=await R(e,t.operand.index,r);i=`${n}_${c}`}else return s;let l=Number.parseInt(e.state.env.get(i)||\"0\",10)||0,o=t.operator===\"++\"?l+1:l-1;return e.state.env.set(i,String(o)),t.prefix?o:l}if(t.operand.type===\"ArithConcat\"){let n=\"\";for(let a of t.operand.parts)n+=await de(e,a,r);if(n&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n)){let a=Number.parseInt(e.state.env.get(n)||\"0\",10)||0,i=t.operator===\"++\"?a+1:a-1;return e.state.env.set(n,String(i)),t.prefix?i:a}}if(t.operand.type===\"ArithDynamicElement\"){let n=\"\";if(t.operand.nameExpr.type===\"ArithConcat\")for(let a of t.operand.nameExpr.parts)n+=await de(e,a,r);else t.operand.nameExpr.type===\"ArithVariable\"&&(n=t.operand.nameExpr.hasDollarPrefix?await v(e,t.operand.nameExpr.name):t.operand.nameExpr.name);if(n&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n)){let a=await R(e,t.operand.subscript,r),i=`${n}_${a}`,l=Number.parseInt(e.state.env.get(i)||\"0\",10)||0,o=t.operator===\"++\"?l+1:l-1;return e.state.env.set(i,String(o)),t.prefix?o:l}}return s}return ts(s,t.operator)}case\"ArithTernary\":return await R(e,t.condition,r)?await R(e,t.consequent,r):await R(e,t.alternate,r);case\"ArithAssignment\":{let s=t.variable,n=s;if(t.stringKey!==void 0)n=`${s}_${t.stringKey}`;else if(t.subscript){let o=e.state.associativeArrays?.has(s);if(o&&t.subscript.type===\"ArithVariable\"&&!t.subscript.hasDollarPrefix)n=`${s}_${t.subscript.name}`;else if(o&&t.subscript.type===\"ArithVariable\"&&t.subscript.hasDollarPrefix){let c=await v(e,t.subscript.name);n=`${s}_${c||\"\\\\\"}`}else if(o){let c=await R(e,t.subscript,r);n=`${s}_${c}`}else{let c=await R(e,t.subscript,r);if(c<0){let u=P(e,s);u.length>0&&(c=Math.max(...u.map(([h])=>typeof h==\"number\"?h:0))+1+c)}n=`${s}_${c}`}}let a=Number.parseInt(e.state.env.get(n)||\"0\",10)||0,i=await R(e,t.value,r),l=mn(a,i,t.operator);return e.state.env.set(n,String(l)),l}case\"ArithGroup\":return await R(e,t.expression,r);case\"ArithConcat\":{let s=\"\";for(let n of t.parts)s+=await de(e,n,r);return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(s)?await pt(e,s):Number.parseInt(s,10)||0}case\"ArithDynamicAssignment\":{let s=\"\";if(t.target.type===\"ArithConcat\")for(let o of t.target.parts)s+=await de(e,o,r);else t.target.type===\"ArithVariable\"&&(s=t.target.hasDollarPrefix?await v(e,t.target.name):t.target.name);if(!s||!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(s))return 0;let n=s;if(t.subscript){let o=await R(e,t.subscript,r);n=`${s}_${o}`}let a=Number.parseInt(e.state.env.get(n)||\"0\",10)||0,i=await R(e,t.value,r),l=mn(a,i,t.operator);return e.state.env.set(n,String(l)),l}case\"ArithDynamicElement\":{let s=\"\";if(t.nameExpr.type===\"ArithConcat\")for(let l of t.nameExpr.parts)s+=await de(e,l,r);else t.nameExpr.type===\"ArithVariable\"&&(s=t.nameExpr.hasDollarPrefix?await v(e,t.nameExpr.name):t.nameExpr.name);if(!s||!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(s))return 0;let n=await R(e,t.subscript,r),a=`${s}_${n}`,i=e.state.env.get(a);return i!==void 0?rs(i):0}default:return 0}}async function de(e,t,r=!1){switch(t.type){case\"ArithNumber\":return String(t.value);case\"ArithSingleQuote\":return String(await R(e,t,r));case\"ArithVariable\":return t.hasDollarPrefix?await v(e,t.name):t.name;case\"ArithSpecialVar\":return await v(e,t.name);case\"ArithBracedExpansion\":return await _e(e,t.content);case\"ArithCommandSubst\":return e.execFn?(await e.execFn(t.command,{signal:e.state.signal})).stdout.trim():\"0\";case\"ArithConcat\":{let s=\"\";for(let n of t.parts)s+=await de(e,n,r);return s}default:return String(await R(e,t,r))}}function dt(e){for(let t=0;t<e.length;t++){if(e[t]===\"\\\\\"){t++;continue}if(e[t]===\"$\"){let r=e[t+1];if(r===\"{\"||r&&/[a-zA-Z_]/.test(r))return!0}}return!1}function ss(e){if(!e.operation)return!1;let t=e.operation,r;if((t.type===\"DefaultValue\"||t.type===\"AssignDefault\"||t.type===\"UseAlternative\"||t.type===\"ErrorIfUnset\")&&(r=t.word?.parts),!r)return!1;for(let s of r)if(s.type===\"DoubleQuoted\"||s.type===\"SingleQuoted\")return!0;return!1}function gn(e){if(!e.operation)return!1;let t=e.operation,r;if((t.type===\"DefaultValue\"||t.type===\"AssignDefault\"||t.type===\"UseAlternative\"||t.type===\"ErrorIfUnset\")&&(r=t.word?.parts),!r||r.length===0)return!1;for(let s of r)if(s.type!==\"DoubleQuoted\"&&s.type!==\"SingleQuoted\")return!1;return!0}function Ae(e){let t=!1,r=!1,s=!1,n=!1,a=!1,i=!1,l=!1;for(let o of e){if((o.type===\"SingleQuoted\"||o.type===\"DoubleQuoted\")&&(t=!0,o.type===\"DoubleQuoted\"))for(let c of o.parts)c.type===\"ParameterExpansion\"&&(c.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[[@*]\\]$/)&&(!c.operation||c.operation.type===\"PatternRemoval\"||c.operation.type===\"PatternReplacement\")&&(n=!0),(c.operation?.type===\"VarNamePrefix\"||c.operation?.type===\"ArrayKeys\")&&(i=!0),c.operation?.type===\"Indirection\"&&(l=!0));o.type===\"CommandSubstitution\"&&(r=!0),o.type===\"ParameterExpansion\"&&(a=!0,(o.parameter===\"@\"||o.parameter===\"*\")&&(s=!0),ss(o)&&(t=!0),(o.operation?.type===\"VarNamePrefix\"||o.operation?.type===\"ArrayKeys\")&&(i=!0),o.operation?.type===\"Indirection\"&&(l=!0)),o.type===\"Glob\"&&dt(o.pattern)&&(a=!0)}return{hasQuoted:t,hasCommandSub:r,hasArrayVar:s,hasArrayAtExpansion:n,hasParamExpansion:a,hasVarNamePrefixExpansion:i,hasIndirection:l}}var yn=\"5.1.0(1)-release\",xi=\"Linux version 5.15.0-generic (just-bash) #1 SMP PREEMPT\";function _i(e){let{pid:t,ppid:r,uid:s,gid:n}=e;return`Name:\tbash\nState:\tR (running)\nPid:\t${t}\nPPid:\t${r}\nUid:\t${s}\t${s}\t${s}\t${s}\nGid:\t${n}\t${n}\t${n}\t${n}\n`}function mt(e,t){let r=`${t}_`,s=[];for(let n of e.state.env.keys())if(n.startsWith(r)){let a=n.slice(r.length),i=Number.parseInt(a,10);!Number.isNaN(i)&&String(i)===a&&s.push(i)}return s.sort((n,a)=>n-a)}function Ci(e,t){let r=`${t}_`;for(let s of e.state.env.keys())s.startsWith(r)&&e.state.env.delete(s)}function gt(e,t){let r=`${t}_`,s=`${t}__length`,n=[];for(let a of e.state.env.keys())if(a!==s&&a.startsWith(r)){let i=a.slice(r.length);if(i.startsWith(\"_length\"))continue;n.push(i)}return n.sort()}function $e(e){return e.startsWith(\"'\")&&e.endsWith(\"'\")||e.startsWith('\"')&&e.endsWith('\"')?e.slice(1,-1):e}function Oi(e){if(e.parts.length<2)return null;let t=e.parts[0],r=e.parts[1];if(t.type!==\"Glob\"||!t.pattern.startsWith(\"[\"))return null;let s,n=r,a=1;if(r.type===\"Literal\"&&r.value.startsWith(\"]\")){let f=r.value.slice(1);if(f.startsWith(\"+=\")||f.startsWith(\"=\"))s=t.pattern.slice(1);else if(f===\"\"){if(e.parts.length<3)return null;let h=e.parts[2];if(h.type!==\"Literal\"||!h.value.startsWith(\"=\")&&!h.value.startsWith(\"+=\"))return null;s=t.pattern.slice(1),n=h,a=2}else return null}else if(t.pattern===\"[\"&&(r.type===\"DoubleQuoted\"||r.type===\"SingleQuoted\")){if(e.parts.length<3)return null;let f=e.parts[2];if(f.type!==\"Literal\"||!f.value.startsWith(\"]=\")&&!f.value.startsWith(\"]+=\"))return null;if(r.type===\"SingleQuoted\")s=r.value;else{s=\"\";for(let h of r.parts)(h.type===\"Literal\"||h.type===\"Escaped\")&&(s+=h.value)}n=f,a=2}else if(t.pattern.endsWith(\"]\")){if(r.type!==\"Literal\"||!r.value.startsWith(\"=\")&&!r.value.startsWith(\"+=\"))return null;s=t.pattern.slice(1,-1)}else return null;s=$e(s);let i;if(n.type!==\"Literal\")return null;n.value.startsWith(\"]=\")||n.value.startsWith(\"]+=\")?i=n.value.slice(1):i=n.value;let l=i.startsWith(\"+=\");if(!l&&!i.startsWith(\"=\"))return null;let o=[],c=l?2:1,u=i.slice(c);u&&o.push({type:\"Literal\",value:u});for(let f=a+1;f<e.parts.length;f++){let h=e.parts[f];h.type===\"BraceExpansion\"?o.push({type:\"Literal\",value:is(h)}):o.push(h)}return{key:s,valueParts:o,append:l}}function is(e){return`{${e.items.map(r=>{if(r.type===\"Range\"){let s=r.startStr??String(r.start),n=r.endStr??String(r.end),a=`${s}..${n}`;return r.step&&(a+=`..${r.step}`),a}return En(r.word)}).join(\",\")}}`}function En(e){let t=\"\";for(let r of e.parts)switch(r.type){case\"Literal\":t+=r.value;break;case\"Glob\":t+=r.pattern;break;case\"SingleQuoted\":t+=r.value;break;case\"DoubleQuoted\":for(let s of r.parts)(s.type===\"Literal\"||s.type===\"Escaped\")&&(t+=s.value);break;case\"Escaped\":t+=r.value;break;case\"BraceExpansion\":t+=\"{\",t+=r.items.map(s=>s.type===\"Range\"?`${s.startStr}..${s.endStr}${s.step?`..${s.step}`:\"\"}`:En(s.word)).join(\",\"),t+=\"}\";break;case\"TildeExpansion\":t+=\"~\",r.user&&(t+=r.user);break}return t}function T(e){return e.get(\"IFS\")??` \t\n`}function q(e){return e.get(\"IFS\")===\"\"}function Ce(e){let t=T(e);if(t===\"\")return!0;for(let r of t)if(r!==\" \"&&r!==\"\t\"&&r!==`\n`)return!1;return!0}function An(e){let t=!1,r=[];for(let s of e.split(\"\"))s===\"-\"?t=!0:/[\\\\^$.*+?()[\\]{}|]/.test(s)?r.push(`\\\\${s}`):s===\"\t\"?r.push(\"\\\\t\"):s===`\n`?r.push(\"\\\\n\"):r.push(s);return t&&r.push(\"\\\\-\"),r.join(\"\")}function N(e){let t=e.get(\"IFS\");return t===void 0?\" \":t[0]||\"\"}var as=` \t\n`;function os(e){return as.includes(e)}function yt(e){let t=new Set,r=new Set;for(let s of e)os(s)?t.add(s):r.add(s);return{whitespace:t,nonWhitespace:r}}function Wi(e,t,r,s){if(t===\"\")return e===\"\"?{words:[],wordStarts:[]}:{words:[e],wordStarts:[0]};let{whitespace:n,nonWhitespace:a}=yt(t),i=[],l=[],o=0;for(;o<e.length&&n.has(e[o]);)o++;if(o>=e.length)return{words:[],wordStarts:[]};if(a.has(e[o]))for(i.push(\"\"),l.push(o),o++;o<e.length&&n.has(e[o]);)o++;for(;o<e.length&&!(r!==void 0&&i.length>=r);){let c=o;for(l.push(c);o<e.length;){let u=e[o];if(!s&&u===\"\\\\\"){o++,o<e.length&&o++;continue}if(n.has(u)||a.has(u))break;o++}if(i.push(e.substring(c,o)),o>=e.length)break;for(;o<e.length&&n.has(e[o]);)o++;if(o<e.length&&a.has(e[o])){for(o++;o<e.length&&n.has(e[o]);)o++;for(;o<e.length&&a.has(e[o])&&!(r!==void 0&&i.length>=r);)for(i.push(\"\"),l.push(o),o++;o<e.length&&n.has(e[o]);)o++}}return{words:i,wordStarts:l}}function Oe(e,t){if(t===\"\")return{words:e?[e]:[],hadLeadingDelimiter:!1,hadTrailingDelimiter:!1};if(e===\"\")return{words:[],hadLeadingDelimiter:!1,hadTrailingDelimiter:!1};let{whitespace:r,nonWhitespace:s}=yt(t),n=[],a=0,i=!1,l=!1,o=a;for(;a<e.length&&r.has(e[a]);)a++;if(a>o&&(i=!0),a>=e.length)return{words:[],hadLeadingDelimiter:!0,hadTrailingDelimiter:!0};if(s.has(e[a]))for(n.push(\"\"),a++;a<e.length&&r.has(e[a]);)a++;for(;a<e.length;){let c=a;for(;a<e.length;){let f=e[a];if(r.has(f)||s.has(f))break;a++}if(n.push(e.substring(c,a)),a>=e.length){l=!1;break}let u=a;for(;a<e.length&&r.has(e[a]);)a++;if(a<e.length&&s.has(e[a])){for(a++;a<e.length&&r.has(e[a]);)a++;for(;a<e.length&&s.has(e[a]);)for(n.push(\"\"),a++;a<e.length&&r.has(e[a]);)a++}a>=e.length&&a>u&&(l=!0)}return{words:n,hadLeadingDelimiter:i,hadTrailingDelimiter:l}}function x(e,t){return Oe(e,t).words}function ls(e,t){for(let r of e)if(t.has(r))return!0;return!1}function Ti(e,t,r){if(t===\"\")return e;let{whitespace:s,nonWhitespace:n}=yt(t),a=e.length;for(;a>0&&s.has(e[a-1]);){if(!r&&a>=2){let l=0,o=a-2;for(;o>=0&&e[o]===\"\\\\\";)l++,o--;if(l%2===1)break}a--}let i=e.substring(0,a);if(i.length>=1&&n.has(i[i.length-1])){if(!r&&i.length>=2){let o=0,c=i.length-2;for(;c>=0&&i[c]===\"\\\\\";)o++,c--;if(o%2===1)return i}let l=i.substring(0,i.length-1);if(!ls(l,n))return l}return i}function W(e,t){return e.state.namerefs?.has(t)??!1}function Vi(e,t){e.state.namerefs??=new Set,e.state.namerefs.add(t)}function qi(e,t){e.state.namerefs?.delete(t),e.state.boundNamerefs?.delete(t),e.state.invalidNamerefs?.delete(t)}function Bi(e,t){e.state.invalidNamerefs??=new Set,e.state.invalidNamerefs.add(t)}function Sn(e,t){return e.state.invalidNamerefs?.has(t)??!1}function Fi(e,t){e.state.boundNamerefs??=new Set,e.state.boundNamerefs.add(t)}function us(e,t){let r=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[(.+)\\]$/);if(r){let n=r[1],a=Array.from(e.state.env.keys()).some(l=>l.startsWith(`${n}_`)&&!l.includes(\"__\")),i=e.state.associativeArrays?.has(n)??!1;return a||i}return Array.from(e.state.env.keys()).some(n=>n.startsWith(`${t}_`)&&!n.includes(\"__\"))?!0:e.state.env.has(t)}function he(e,t,r=100){if(!W(e,t)||Sn(e,t))return t;let s=new Set,n=t;for(;r-- >0;){if(s.has(n))return;if(s.add(n),!W(e,n))return n;let a=e.state.env.get(n);if(a===void 0||a===\"\"||!/^[a-zA-Z_][a-zA-Z0-9_]*(\\[.+\\])?$/.test(a))return n;n=a}}function Se(e,t){if(W(e,t))return e.state.env.get(t)}function zi(e,t,r,s=100){if(!W(e,t)||Sn(e,t))return t;let n=new Set,a=t;for(;s-- >0;){if(n.has(a))return;if(n.add(a),!W(e,a))return a;let i=e.state.env.get(a);if(i===void 0||i===\"\")return r!==void 0?/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r)&&us(e,r)?a:null:a;if(!/^[a-zA-Z_][a-zA-Z0-9_]*(\\[.+\\])?$/.test(i))return a;a=i}}function cs(e,t){let r=t.replace(/\\$\\{([a-zA-Z_][a-zA-Z0-9_]*)\\}/g,(s,n)=>e.state.env.get(n)??\"\");return r=r.replace(/\\$([a-zA-Z_][a-zA-Z0-9_]*)/g,(s,n)=>e.state.env.get(n)??\"\"),r}function P(e,t){return t===\"FUNCNAME\"?(e.state.funcNameStack??[]).map((a,i)=>[i,a]):t===\"BASH_LINENO\"?(e.state.callLineStack??[]).map((a,i)=>[i,String(a)]):t===\"BASH_SOURCE\"?(e.state.sourceStack??[]).map((a,i)=>[i,a]):e.state.associativeArrays?.has(t)?gt(e,t).map(a=>[a,e.state.env.get(`${t}_${a}`)??\"\"]):mt(e,t).map(n=>[n,e.state.env.get(`${t}_${n}`)??\"\"])}function be(e,t){return t===\"FUNCNAME\"?(e.state.funcNameStack?.length??0)>0:t===\"BASH_LINENO\"?(e.state.callLineStack?.length??0)>0:t===\"BASH_SOURCE\"?(e.state.sourceStack?.length??0)>0:e.state.associativeArrays?.has(t)?gt(e,t).length>0:mt(e,t).length>0}async function v(e,t,r=!0,s=!1){switch(t){case\"?\":return String(e.state.lastExitCode);case\"$\":return String(e.state.virtualPid);case\"#\":return e.state.env.get(\"#\")||\"0\";case\"@\":return e.state.env.get(\"@\")||\"\";case\"_\":return e.state.lastArg;case\"-\":{let i=\"\";return i+=\"h\",e.state.options.errexit&&(i+=\"e\"),e.state.options.noglob&&(i+=\"f\"),e.state.options.nounset&&(i+=\"u\"),e.state.options.verbose&&(i+=\"v\"),e.state.options.xtrace&&(i+=\"x\"),i+=\"B\",e.state.options.noclobber&&(i+=\"C\"),i+=\"s\",i}case\"*\":{let i=Number.parseInt(e.state.env.get(\"#\")||\"0\",10);if(i===0)return\"\";let l=[];for(let o=1;o<=i;o++)l.push(e.state.env.get(String(o))||\"\");return l.join(N(e.state.env))}case\"0\":return e.state.env.get(\"0\")||\"bash\";case\"PWD\":return e.state.env.get(\"PWD\")??\"\";case\"OLDPWD\":return e.state.env.get(\"OLDPWD\")??\"\";case\"PPID\":return String(e.state.virtualPpid);case\"UID\":return String(e.state.virtualUid);case\"EUID\":return String(e.state.virtualUid);case\"RANDOM\":return String(Math.floor(Math.random()*32768));case\"SECONDS\":return String(Math.floor((Date.now()-e.state.startTime)/1e3));case\"BASH_VERSION\":return yn;case\"!\":return String(e.state.lastBackgroundPid);case\"BASHPID\":return String(e.state.bashPid);case\"LINENO\":return String(e.state.currentLine);case\"FUNCNAME\":{let i=e.state.funcNameStack?.[0];if(i!==void 0)return i;if(r&&e.state.options.nounset)throw new j(\"FUNCNAME\");return\"\"}case\"BASH_LINENO\":{let i=e.state.callLineStack?.[0];if(i!==void 0)return String(i);if(r&&e.state.options.nounset)throw new j(\"BASH_LINENO\");return\"\"}case\"BASH_SOURCE\":{let i=e.state.sourceStack?.[0];if(i!==void 0)return i;if(r&&e.state.options.nounset)throw new j(\"BASH_SOURCE\");return\"\"}}if(/^[a-zA-Z_][a-zA-Z0-9_]*\\[\\]$/.test(t))throw new re(`\\${${t}}`);let n=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[(.+)\\]$/);if(n){let i=n[1],l=n[2];if(W(e,i)){let f=he(e,i);if(f&&f!==i){if(f.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[(.+)\\]$/))return\"\";i=f}}if(l===\"@\"||l===\"*\"){let f=P(e,i);if(f.length>0)return f.map(([,d])=>d).join(\" \");let h=e.state.env.get(i);return h!==void 0?h:\"\"}if(i===\"FUNCNAME\"){let f=Number.parseInt(l,10);return!Number.isNaN(f)&&f>=0?e.state.funcNameStack?.[f]??\"\":\"\"}if(i===\"BASH_LINENO\"){let f=Number.parseInt(l,10);if(!Number.isNaN(f)&&f>=0){let h=e.state.callLineStack?.[f];return h!==void 0?String(h):\"\"}return\"\"}if(i===\"BASH_SOURCE\"){let f=Number.parseInt(l,10);return!Number.isNaN(f)&&f>=0?e.state.sourceStack?.[f]??\"\":\"\"}if(e.state.associativeArrays?.has(i)){let f=$e(l);f=cs(e,f);let h=e.state.env.get(`${i}_${f}`);if(h===void 0&&r&&e.state.options.nounset)throw new j(`${i}[${l}]`);return h||\"\"}let c;if(/^-?\\d+$/.test(l))c=Number.parseInt(l,10);else try{let f=new V,h=M(f,l);c=await R(e,h.expression)}catch{let f=e.state.env.get(l);c=f?Number.parseInt(f,10):0,Number.isNaN(c)&&(c=0)}if(c<0){let f=P(e,i),h=e.state.currentLine;if(f.length===0)return e.state.expansionStderr=(e.state.expansionStderr||\"\")+`bash: line ${h}: ${i}: bad array subscript\n`,\"\";let m=Math.max(...f.map(([E])=>typeof E==\"number\"?E:0))+1+c;return m<0?(e.state.expansionStderr=(e.state.expansionStderr||\"\")+`bash: line ${h}: ${i}: bad array subscript\n`,\"\"):e.state.env.get(`${i}_${m}`)||\"\"}let u=e.state.env.get(`${i}_${c}`);if(u!==void 0)return u;if(c===0){let f=e.state.env.get(i);if(f!==void 0)return f}if(r&&e.state.options.nounset)throw new j(`${i}[${c}]`);return\"\"}if(/^[1-9][0-9]*$/.test(t)){let i=e.state.env.get(t);if(i===void 0&&r&&e.state.options.nounset)throw new j(t);return i||\"\"}if(W(e,t)){let i=he(e,t);if(i===void 0)return\"\";if(i!==t)return await v(e,i,r,s);let l=e.state.env.get(t);if((l===void 0||l===\"\")&&r&&e.state.options.nounset)throw new j(t);return l||\"\"}let a=e.state.env.get(t);if(a!==void 0)return e.state.tempEnvBindings?.some(i=>i.has(t))&&(e.state.accessedTempEnvVars=e.state.accessedTempEnvVars||new Set,e.state.accessedTempEnvVars.add(t)),a;if(be(e,t)){let i=e.state.env.get(`${t}_0`);return i!==void 0?i:\"\"}if(r&&e.state.options.nounset)throw new j(t);return\"\"}async function te(e,t){if(new Set([\"?\",\"$\",\"#\",\"_\",\"-\",\"0\",\"PPID\",\"UID\",\"EUID\",\"RANDOM\",\"SECONDS\",\"BASH_VERSION\",\"!\",\"BASHPID\",\"LINENO\"]).has(t))return!0;if(t===\"@\"||t===\"*\")return Number.parseInt(e.state.env.get(\"#\")||\"0\",10)>0;if(t===\"PWD\"||t===\"OLDPWD\")return e.state.env.has(t);let s=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[(.+)\\]$/);if(s){let n=s[1],a=s[2];if(W(e,n)){let o=he(e,n);if(o&&o!==n){if(o.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[(.+)\\]$/))return!1;n=o}}if(a===\"@\"||a===\"*\")return P(e,n).length>0?!0:e.state.env.has(n);if(e.state.associativeArrays?.has(n)){let o=$e(a);return e.state.env.has(`${n}_${o}`)}let l;if(/^-?\\d+$/.test(a))l=Number.parseInt(a,10);else try{let o=new V,c=M(o,a);l=await R(e,c.expression)}catch{let o=e.state.env.get(a);l=o?Number.parseInt(o,10):0,Number.isNaN(l)&&(l=0)}if(l<0){let o=P(e,n);if(o.length===0)return!1;let u=Math.max(...o.map(([f])=>typeof f==\"number\"?f:0))+1+l;return u<0?!1:e.state.env.has(`${n}_${u}`)}return e.state.env.has(`${n}_${l}`)}if(W(e,t)){let n=he(e,t);return n===void 0||n===t?e.state.env.has(t):te(e,n)}return!!(e.state.env.has(t)||be(e,t))}async function bn(e,t){let r=\"\",s=0;for(;s<t.length;){if(t[s]===\"$\"){if(t[s+1]===\"{\"){let n=1,a=s+2;for(;a<t.length&&n>0;)t[a]===\"{\"?n++:t[a]===\"}\"&&n--,a++;r+=t.slice(s,a),s=a;continue}if(t[s+1]===\"(\"){let n=1,a=s+2;for(;a<t.length&&n>0;)t[a]===\"(\"?n++:t[a]===\")\"&&n--,a++;r+=t.slice(s,a),s=a;continue}if(/[a-zA-Z_]/.test(t[s+1]||\"\")){let n=s+1;for(;n<t.length&&/[a-zA-Z0-9_]/.test(t[n]);)n++;let a=t.slice(s+1,n),i=await v(e,a);r+=i,s=n;continue}if(/[0-9]/.test(t[s+1]||\"\")){let n=s+1;for(;n<t.length&&/[0-9]/.test(t[n]);)n++;let a=t.slice(s+1,n),i=await v(e,a);r+=i,s=n;continue}if(/[*@#?\\-!$]/.test(t[s+1]||\"\")){let n=t[s+1],a=await v(e,n);r+=a,s+=2;continue}}if(t[s]==='\"'){for(r+='\"',s++;s<t.length&&t[s]!=='\"';)if(t[s]===\"$\"&&/[a-zA-Z_]/.test(t[s+1]||\"\")){let n=s+1;for(;n<t.length&&/[a-zA-Z0-9_]/.test(t[n]);)n++;let a=t.slice(s+1,n),i=await v(e,a);r+=i,s=n}else t[s]===\"\\\\\"?(r+=t[s],s++,s<t.length&&(r+=t[s],s++)):(r+=t[s],s++);s<t.length&&(r+='\"',s++);continue}r+=t[s],s++}return r}async function Et(e,t){let r=t,s=t.startsWith('\"')&&t.endsWith('\"'),n=t.startsWith(\"'\")&&t.endsWith(\"'\");if((s||n)&&(r=t.slice(1,-1)),n)return r;let a=\"\",i=0;for(;i<r.length;)if(r[i]===\"$\")if(r[i+1]===\"(\"){let l=1,o=i+2;for(;o<r.length&&l>0;)r[o]===\"(\"&&r[o-1]===\"$\"||r[o]===\"(\"?l++:r[o]===\")\"&&l--,o++;let c=r.slice(i+2,o-1);if(e.execFn){let u=await e.execFn(c,{signal:e.state.signal});a+=u.stdout.replace(/\\n+$/,\"\"),u.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||\"\")+u.stderr)}i=o}else if(r[i+1]===\"{\"){let l=1,o=i+2;for(;o<r.length&&l>0;)r[o]===\"{\"?l++:r[o]===\"}\"&&l--,o++;let c=r.slice(i+2,o-1),u=await v(e,c);a+=u,i=o}else if(/[a-zA-Z_]/.test(r[i+1]||\"\")){let l=i+1;for(;l<r.length&&/[a-zA-Z0-9_]/.test(r[l]);)l++;let o=r.slice(i+1,l),c=await v(e,o);a+=c,i=l}else a+=r[i],i++;else if(r[i]===\"`\"){let l=i+1;for(;l<r.length&&r[l]!==\"`\";)l++;let o=r.slice(i+1,l);if(e.execFn){let c=await e.execFn(o,{signal:e.state.signal});a+=c.stdout.replace(/\\n+$/,\"\"),c.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||\"\")+c.stderr)}i=l+1}else a+=r[i],i++;return a}var Le=1e4;function fs(e,t,r,s,n){let a=r??1;a===0&&(a=1);let i=Math.abs(a),l=[],o=0;s?.match(/^-?0\\d/)&&(o=Math.max(o,s.replace(/^-/,\"\").length)),n?.match(/^-?0\\d/)&&(o=Math.max(o,n.replace(/^-/,\"\").length));let c=u=>{if(o>0){let f=u<0,h=String(Math.abs(u)).padStart(o,\"0\");return f?`-${h}`:h}return String(u)};if(e<=t)for(let u=e,f=0;u<=t&&f<Le;u+=i,f++)l.push(c(u));else for(let u=e,f=0;u>=t&&f<Le;u-=i,f++)l.push(c(u));return l}function hs(e,t,r){let s=r??1;s===0&&(s=1);let n=e.charCodeAt(0),a=t.charCodeAt(0),i=Math.abs(s),l=e>=\"A\"&&e<=\"Z\",o=e>=\"a\"&&e<=\"z\",c=t>=\"A\"&&t<=\"Z\",u=t>=\"a\"&&t<=\"z\";if(l&&u||o&&c){let h=r!==void 0?`..${r}`:\"\";throw new It(`{${e}..${t}${h}}: invalid sequence`)}let f=[];if(n<=a)for(let h=n,d=0;h<=a&&d<Le;h+=i,d++)f.push(String.fromCharCode(h));else for(let h=n,d=0;h>=a&&d<Le;h-=i,d++)f.push(String.fromCharCode(h));return f}function At(e,t,r,s,n){let a=r!==void 0?`..${r}`:\"\";return typeof e==\"number\"&&typeof t==\"number\"?{expanded:fs(e,t,r,s,n),literal:`{${e}..${t}${a}}`}:typeof e==\"string\"&&typeof t==\"string\"?{expanded:hs(e,t,r),literal:`{${e}..${t}${a}}`}:{expanded:null,literal:`{${e}..${t}${a}}`}}function wn(e){if(e.statements.length!==1)return null;let t=e.statements[0];if(t.operators.length!==0||t.pipelines.length!==1)return null;let r=t.pipelines[0];if(r.negated||r.commands.length!==1)return null;let s=r.commands[0];if(s.type!==\"SimpleCommand\")return null;let n=s;if(n.name!==null||n.args.length!==0||n.assignments.length!==0||n.redirections.length!==1)return null;let a=n.redirections[0];return a.operator!==\"<\"||a.target.type!==\"Word\"?null:{target:a.target}}function ne(e,t){return!!(/[*?[]/.test(e)||t&&/[@*+?!]\\(/.test(e))}function St(e){let t=\"\",r=0;for(;r<e.length;)e[r]===\"\\\\\"&&r+1<e.length?(t+=e[r+1],r+=2):(t+=e[r],r++);return t}function X(e){return e.replace(/([*?[\\]\\\\()|])/g,\"\\\\$1\")}function bt(e){return e.replace(/[\\\\^$.*+?()[\\]{}|]/g,\"\\\\$&\")}function I(e){return e.replace(/[.*+?^${}()|[\\]\\\\]/g,\"\\\\$&\")}function k(e,t,r=!1){let s=\"\",n=0;for(;n<e.length;){let a=e[n];if(r&&(a===\"@\"||a===\"*\"||a===\"+\"||a===\"?\"||a===\"!\")&&n+1<e.length&&e[n+1]===\"(\"){let i=ps(e,n+1);if(i!==-1){let l=e.slice(n+2,i),c=ds(l).map(f=>k(f,t,r)),u=c.length>0?c.join(\"|\"):\"(?:)\";a===\"@\"?s+=`(?:${u})`:a===\"*\"?s+=`(?:${u})*`:a===\"+\"?s+=`(?:${u})+`:a===\"?\"?s+=`(?:${u})?`:a===\"!\"&&(s+=`(?!(?:${u})$).*`),n=i+1;continue}}if(a===\"\\\\\")if(n+1<e.length){let i=e[n+1];/[\\\\^$.|+(){}[\\]*?]/.test(i)?s+=`\\\\${i}`:s+=i,n+=2}else s+=\"\\\\\\\\\",n++;else if(a===\"*\")s+=t?\".*\":\".*?\",n++;else if(a===\"?\")s+=\".\",n++;else if(a===\"[\"){let i=ms(e,n);if(i===-1)s+=\"\\\\[\",n++;else{let l=e.slice(n+1,i);s+=gs(l),n=i+1}}else/[\\^$.|+(){}]/.test(a)?(s+=`\\\\${a}`,n++):(s+=a,n++)}return s}function ps(e,t){let r=1,s=t+1;for(;s<e.length&&r>0;){let n=e[s];if(n===\"\\\\\"){s+=2;continue}if(n===\"(\")r++;else if(n===\")\"&&(r--,r===0))return s;s++}return-1}function ds(e){let t=[],r=\"\",s=0,n=0;for(;n<e.length;){let a=e[n];if(a===\"\\\\\"){r+=a,n+1<e.length?(r+=e[n+1],n+=2):n++;continue}a===\"(\"?(s++,r+=a):a===\")\"?(s--,r+=a):a===\"|\"&&s===0?(t.push(r),r=\"\"):r+=a,n++}return t.push(r),t}function ms(e,t){let r=t+1;for(r<e.length&&e[r]===\"^\"&&r++,r<e.length&&e[r]===\"]\"&&r++;r<e.length;){if(e[r]===\"\\\\\"&&r+1<e.length){r+=2;continue}if(e[r]===\"]\")return r;if(e[r]===\"'\"){let s=e.indexOf(\"'\",r+1);if(s!==-1){r=s+1;continue}}if(e[r]===\"[\"&&r+1<e.length&&e[r+1]===\":\"){let s=e.indexOf(\":]\",r+2);if(s!==-1){r=s+2;continue}}r++}return-1}function gs(e){let t=\"[\",r=0;for((e[0]===\"^\"||e[0]===\"!\")&&(t+=\"^\",r++);r<e.length;){if(e[r]===\"'\"){let n=e.indexOf(\"'\",r+1);if(n!==-1){let a=e.slice(r+1,n);for(let i of a)i===\"\\\\\"?t+=\"\\\\\\\\\":i===\"]\"?t+=\"\\\\]\":i===\"^\"&&t===\"[\"?t+=\"\\\\^\":t+=i;r=n+1;continue}}if(e[r]===\"[\"&&r+1<e.length&&e[r+1]===\":\"){let n=e.indexOf(\":]\",r+2);if(n!==-1){let a=e.slice(r+2,n);t+=Es(a),r=n+2;continue}}let s=e[r];s===\"\\\\\"?r+1<e.length?(t+=`\\\\${e[r+1]}`,r+=2):(t+=\"\\\\\\\\\",r++):s===\"-\"&&r>0&&r<e.length-1?(t+=\"-\",r++):s===\"^\"&&r===0?(t+=\"^\",r++):(s===\"]\"&&r===0?t+=\"\\\\]\":t+=s,r++)}return t+=\"]\",t}var ys=new Map([[\"alnum\",\"a-zA-Z0-9\"],[\"alpha\",\"a-zA-Z\"],[\"ascii\",\"\\\\x00-\\\\x7F\"],[\"blank\",\" \\\\t\"],[\"cntrl\",\"\\\\x00-\\\\x1F\\\\x7F\"],[\"digit\",\"0-9\"],[\"graph\",\"!-~\"],[\"lower\",\"a-z\"],[\"print\",\" -~\"],[\"punct\",\"!-/:-@\\\\[-`{-~\"],[\"space\",\" \\\\t\\\\n\\\\r\\\\f\\\\v\"],[\"upper\",\"A-Z\"],[\"word\",\"a-zA-Z0-9_\"],[\"xdigit\",\"0-9A-Fa-f\"]]);function Es(e){return ys.get(e)??\"\"}function se(e,t,r,s){if(r===\"prefix\")return O(`^${t}`,\"s\").replace(e,\"\");let n=O(`${t}$`,\"s\");if(s)return n.replace(e,\"\");for(let a=e.length;a>=0;a--){let i=e.slice(a);if(n.test(i))return e.slice(0,a)}return e}function me(e,t){let r=Array.from(e.state.env.keys()),s=new Set,n=e.state.associativeArrays??new Set,a=new Set;for(let l of r){let o=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)_\\d+$/);o&&a.add(o[1]);let c=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)__length$/);c&&a.add(c[1])}let i=l=>{for(let o of n){let c=`${o}_`;if(l.startsWith(c)&&l!==o)return!0}return!1};for(let l of r)if(l.startsWith(t))if(l.includes(\"__\")){let o=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)__length$/);o?.[1].startsWith(t)&&s.add(o[1])}else if(/_\\d+$/.test(l)){let o=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)_\\d+$/);o?.[1].startsWith(t)&&s.add(o[1])}else i(l)||s.add(l);return[...s].sort()}function As(e,t){let r=(a,i=2)=>String(a).padStart(i,\"0\");if(e===\"\"){let a=r(t.getHours()),i=r(t.getMinutes()),l=r(t.getSeconds());return`${a}:${i}:${l}`}let s=\"\",n=0;for(;n<e.length;)if(e[n]===\"%\"){if(n+1>=e.length){s+=\"%\",n++;continue}let a=e[n+1];switch(a){case\"H\":s+=r(t.getHours());break;case\"M\":s+=r(t.getMinutes());break;case\"S\":s+=r(t.getSeconds());break;case\"d\":s+=r(t.getDate());break;case\"m\":s+=r(t.getMonth()+1);break;case\"Y\":s+=t.getFullYear();break;case\"y\":s+=r(t.getFullYear()%100);break;case\"I\":{let i=t.getHours()%12;i===0&&(i=12),s+=r(i);break}case\"p\":s+=t.getHours()<12?\"AM\":\"PM\";break;case\"P\":s+=t.getHours()<12?\"am\":\"pm\";break;case\"%\":s+=\"%\";break;case\"a\":{s+=[\"Sun\",\"Mon\",\"Tue\",\"Wed\",\"Thu\",\"Fri\",\"Sat\"][t.getDay()];break}case\"b\":{s+=[\"Jan\",\"Feb\",\"Mar\",\"Apr\",\"May\",\"Jun\",\"Jul\",\"Aug\",\"Sep\",\"Oct\",\"Nov\",\"Dec\"][t.getMonth()];break}default:s+=`%${a}`}n+=2}else s+=e[n],n++;return s}function we(e,t){let r=\"\",s=0,n=e.state.env.get(\"USER\")||e.state.env.get(\"LOGNAME\")||\"user\",a=e.state.env.get(\"HOSTNAME\")||\"localhost\",i=a.split(\".\")[0],l=e.state.env.get(\"PWD\")||\"/\",o=e.state.env.get(\"HOME\")||\"/\",c=l.startsWith(o)?`~${l.slice(o.length)}`:l,u=l.split(\"/\").pop()||l,f=new Date,h=[\"Sun\",\"Mon\",\"Tue\",\"Wed\",\"Thu\",\"Fri\",\"Sat\"],d=[\"Jan\",\"Feb\",\"Mar\",\"Apr\",\"May\",\"Jun\",\"Jul\",\"Aug\",\"Sep\",\"Oct\",\"Nov\",\"Dec\"],m=e.state.env.get(\"__COMMAND_NUMBER\")||\"1\";for(;s<t.length;){let g=t[s];if(g===\"\\\\\"){if(s+1>=t.length){r+=\"\\\\\",s++;continue}let E=t[s+1];if(E>=\"0\"&&E<=\"7\"){let A=\"\",S=s+1;for(;S<t.length&&S<s+4&&t[S]>=\"0\"&&t[S]<=\"7\";)A+=t[S],S++;let y=Number.parseInt(A,8)%256;r+=String.fromCharCode(y),s=S;continue}switch(E){case\"\\\\\":r+=\"\\\\\",s+=2;break;case\"a\":r+=\"\\x07\",s+=2;break;case\"e\":r+=\"\\x1B\",s+=2;break;case\"n\":r+=`\n`,s+=2;break;case\"r\":r+=\"\\r\",s+=2;break;case\"$\":r+=\"$\",s+=2;break;case\"[\":case\"]\":s+=2;break;case\"u\":r+=n,s+=2;break;case\"h\":r+=i,s+=2;break;case\"H\":r+=a,s+=2;break;case\"w\":r+=c,s+=2;break;case\"W\":r+=u,s+=2;break;case\"d\":{let A=String(f.getDate()).padStart(2,\" \");r+=`${h[f.getDay()]} ${d[f.getMonth()]} ${A}`,s+=2;break}case\"t\":{let A=String(f.getHours()).padStart(2,\"0\"),S=String(f.getMinutes()).padStart(2,\"0\"),y=String(f.getSeconds()).padStart(2,\"0\");r+=`${A}:${S}:${y}`,s+=2;break}case\"T\":{let A=f.getHours()%12;A===0&&(A=12);let S=String(A).padStart(2,\"0\"),y=String(f.getMinutes()).padStart(2,\"0\"),b=String(f.getSeconds()).padStart(2,\"0\");r+=`${S}:${y}:${b}`,s+=2;break}case\"@\":{let A=f.getHours()%12;A===0&&(A=12);let S=String(A).padStart(2,\"0\"),y=String(f.getMinutes()).padStart(2,\"0\"),b=f.getHours()<12?\"AM\":\"PM\";r+=`${S}:${y} ${b}`,s+=2;break}case\"A\":{let A=String(f.getHours()).padStart(2,\"0\"),S=String(f.getMinutes()).padStart(2,\"0\");r+=`${A}:${S}`,s+=2;break}case\"D\":if(s+2<t.length&&t[s+2]===\"{\"){let A=t.indexOf(\"}\",s+3);if(A!==-1){let S=t.slice(s+3,A);r+=As(S,f),s=A+1}else r+=\"\\\\D\",s+=2}else r+=\"\\\\D\",s+=2;break;case\"s\":r+=\"bash\",s+=2;break;case\"v\":r+=\"5.0\",s+=2;break;case\"V\":r+=\"5.0.0\",s+=2;break;case\"j\":r+=\"0\",s+=2;break;case\"l\":r+=\"tty\",s+=2;break;case\"#\":r+=m,s+=2;break;case\"!\":r+=m,s+=2;break;case\"x\":r+=\"\\\\x\",s+=2;break;default:r+=`\\\\${E}`,s+=2}}else r+=g,s++}return r}function le(e){if(e===\"\")return\"''\";if(/[\\n\\r\\t\\x00-\\x1f\\x7f']/.test(e)){let r=\"$'\";for(let s of e)switch(s){case\"'\":r+=\"\\\\'\";break;case\"\\\\\":r+=\"\\\\\\\\\";break;case`\n`:r+=\"\\\\n\";break;case\"\\r\":r+=\"\\\\r\";break;case\"\t\":r+=\"\\\\t\";break;default:{let n=s.charCodeAt(0);n<32||n===127?r+=`\\\\${n.toString(8).padStart(3,\"0\")}`:r+=s}}return`${r}'`}return`'${e}'`}function pa(e,t){e.state.readonlyVars=e.state.readonlyVars||new Set,e.state.readonlyVars.add(t)}function wt(e,t){return e.state.readonlyVars?.has(t)??!1}function da(e,t,r=\"bash\"){if(wt(e,t)){let s=`${r}: ${t}: readonly variable\n`;throw new K(1,\"\",s)}return null}function ma(e,t){let r=e.state.exportedVars?.has(t)??!1;if(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(t),e.state.localScopes.length>0&&e.state.localScopes[e.state.localScopes.length-1].has(t)&&!r){for(e.state.localExportedVars||(e.state.localExportedVars=[]);e.state.localExportedVars.length<e.state.localScopes.length;)e.state.localExportedVars.push(new Set);e.state.localExportedVars[e.state.localExportedVars.length-1].add(t)}}function ga(e,t){e.state.exportedVars?.delete(t)}function ue(e,t){if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t))return\"\";let r=\"\",s=e.state.env.has(`${t}__length`)||Array.from(e.state.env.keys()).some(a=>a.startsWith(`${t}_`)&&/^[0-9]+$/.test(a.slice(t.length+1))),n=e.state.associativeArrays?.has(t)??!1;return s&&!n&&(r+=\"a\"),n&&(r+=\"A\"),e.state.integerVars?.has(t)&&(r+=\"i\"),W(e,t)&&(r+=\"n\"),wt(e,t)&&(r+=\"r\"),e.state.exportedVars?.has(t)&&(r+=\"x\"),r}async function Nn(e,t,r,s){return e.coverage?.hit(\"bash:expansion:default_value\"),(r.isUnset||t.checkEmpty&&r.isEmpty)&&t.word?s(e,t.word.parts,r.inDoubleQuotes):r.effectiveValue}async function kn(e,t,r,s,n){if(e.coverage?.hit(\"bash:expansion:assign_default\"),(s.isUnset||r.checkEmpty&&s.isEmpty)&&r.word){let i=await n(e,r.word.parts,s.inDoubleQuotes),l=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[(.+)\\]$/);if(l){let[,o,c]=l,u;if(/^\\d+$/.test(c))u=Number.parseInt(c,10);else{try{let h=new V,d=M(h,c);u=await R(e,d.expression)}catch{let h=e.state.env.get(c);u=h?Number.parseInt(h,10):0}Number.isNaN(u)&&(u=0)}e.state.env.set(`${o}_${u}`,i);let f=Number.parseInt(e.state.env.get(`${o}__length`)||\"0\",10);u>=f&&e.state.env.set(`${o}__length`,String(u+1))}else e.state.env.set(t,i);return i}return s.effectiveValue}async function Pn(e,t,r,s,n){if(e.coverage?.hit(\"bash:expansion:error_if_unset\"),s.isUnset||r.checkEmpty&&s.isEmpty){let i=r.word?await n(e,r.word.parts,s.inDoubleQuotes):`${t}: parameter null or not set`;throw new K(1,\"\",`bash: ${i}\n`)}return s.effectiveValue}async function Rn(e,t,r,s){return e.coverage?.hit(\"bash:expansion:use_alternative\"),!(r.isUnset||t.checkEmpty&&r.isEmpty)&&t.word?s(e,t.word.parts,r.inDoubleQuotes):\"\"}async function In(e,t,r,s,n){e.coverage?.hit(\"bash:expansion:pattern_removal\");let a=\"\",i=e.state.shoptOptions.extglob;if(r.pattern)for(let o of r.pattern.parts)if(o.type===\"Glob\")a+=k(o.pattern,r.greedy,i);else if(o.type===\"Literal\")a+=k(o.value,r.greedy,i);else if(o.type===\"SingleQuoted\"||o.type===\"Escaped\")a+=I(o.value);else if(o.type===\"DoubleQuoted\"){let c=await s(e,o.parts);a+=I(c)}else if(o.type===\"ParameterExpansion\"){let c=await n(e,o);a+=k(c,r.greedy,i)}else{let c=await n(e,o);a+=I(c)}if(r.side===\"prefix\")return O(`^${a}`,\"s\").replace(t,\"\");let l=O(`${a}$`,\"s\");if(r.greedy)return l.replace(t,\"\");for(let o=t.length;o>=0;o--){let c=t.slice(o);if(l.test(c))return t.slice(0,o)}return t}async function vn(e,t,r,s,n){e.coverage?.hit(\"bash:expansion:pattern_replacement\");let a=\"\",i=e.state.shoptOptions.extglob;if(r.pattern)for(let c of r.pattern.parts)if(c.type===\"Glob\")a+=k(c.pattern,!0,i);else if(c.type===\"Literal\")a+=k(c.value,!0,i);else if(c.type===\"SingleQuoted\"||c.type===\"Escaped\")a+=I(c.value);else if(c.type===\"DoubleQuoted\"){let u=await s(e,c.parts);a+=I(u)}else if(c.type===\"ParameterExpansion\"){let u=await n(e,c);a+=k(u,!0,i)}else{let u=await n(e,c);a+=I(u)}let l=r.replacement?await s(e,r.replacement.parts):\"\";if(r.anchor===\"start\"?a=`^${a}`:r.anchor===\"end\"&&(a=`${a}$`),a===\"\")return t;let o=r.all?\"gs\":\"s\";try{let c=O(a,o);if(r.all){let u=\"\",f=0,h=0,d=e.limits.maxStringLength,m=c.exec(t);for(;m!==null&&!(m[0].length===0&&m.index===t.length);){if(u+=t.slice(f,m.index)+l,f=m.index+m[0].length,m[0].length===0&&f++,h++,h%100===0&&u.length>d)throw new L(`pattern replacement: string length limit exceeded (${d} bytes)`,\"string_length\");m=c.exec(t)}return u+=t.slice(f),u}return c.replace(t,l)}catch(c){if(c instanceof L)throw c;return t}}function Dn(e,t,r){e.coverage?.hit(\"bash:expansion:length\");let s=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[[@*]\\]$/);if(s){let n=s[1],a=P(e,n);return a.length>0?String(a.length):e.state.env.get(n)!==void 0?\"1\":\"0\"}if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)&&be(e,t)){if(t===\"FUNCNAME\"){let a=e.state.funcNameStack?.[0]||\"\";return String([...a].length)}if(t===\"BASH_LINENO\"){let a=e.state.callLineStack?.[0];return String(a!==void 0?[...String(a)].length:0)}let n=e.state.env.get(`${t}_0`)||\"\";return String([...n].length)}return String([...r].length)}async function xn(e,t,r,s){e.coverage?.hit(\"bash:expansion:substring\");let n=await R(e,s.offset.expression),a=s.length?await R(e,s.length.expression):void 0;if(t===\"@\"||t===\"*\"){let c=Number.parseInt(e.state.env.get(\"#\")||\"0\",10),u=[];for(let m=1;m<=c;m++)u.push(e.state.env.get(String(m))||\"\");let f=e.state.env.get(\"0\")||\"bash\",h,d;if(n<=0)if(h=[f,...u],n<0){if(d=h.length+n,d<0)return\"\"}else d=0;else h=u,d=n-1;if(d<0||d>=h.length)return\"\";if(a!==void 0){let m=a<0?h.length+a:d+a;return h.slice(d,Math.max(d,m)).join(\" \")}return h.slice(d).join(\" \")}let i=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[[@*]\\]$/);if(i){let c=i[1];if(e.state.associativeArrays?.has(c))throw new K(1,\"\",`bash: \\${${c}[@]: 0: 3}: bad substitution\n`);let u=P(e,c),f=0;if(n<0){if(u.length>0){let h=u[u.length-1][0],m=(typeof h==\"number\"?h:0)+1+n;if(m<0||(f=u.findIndex(([g])=>typeof g==\"number\"&&g>=m),f<0))return\"\"}}else if(f=u.findIndex(([h])=>typeof h==\"number\"&&h>=n),f<0)return\"\";if(a!==void 0){if(a<0)throw new C(`${i[1]}[@]: substring expression < 0`);return u.slice(f,f+a).map(([,h])=>h).join(\" \")}return u.slice(f).map(([,h])=>h).join(\" \")}let l=[...r],o=n;if(o<0&&(o=Math.max(0,l.length+o)),a!==void 0){if(a<0){let c=l.length+a;return l.slice(o,Math.max(o,c)).join(\"\")}return l.slice(o,o+a).join(\"\")}return l.slice(o).join(\"\")}async function _n(e,t,r,s,n){if(e.coverage?.hit(\"bash:expansion:case_modification\"),r.pattern){let a=e.state.shoptOptions.extglob,i=\"\";for(let f of r.pattern.parts)if(f.type===\"Glob\")i+=k(f.pattern,!0,a);else if(f.type===\"Literal\")i+=k(f.value,!0,a);else if(f.type===\"SingleQuoted\"||f.type===\"Escaped\")i+=I(f.value);else if(f.type===\"DoubleQuoted\"){let h=await s(e,f.parts);i+=I(h)}else if(f.type===\"ParameterExpansion\"){let h=await n(e,f);i+=k(h,!0,a)}let l=O(`^(?:${i})$`),o=r.direction===\"upper\"?f=>f.toUpperCase():f=>f.toLowerCase(),c=\"\",u=!1;for(let f of t)!r.all&&u?c+=f:l.test(f)?(c+=o(f),u=!0):c+=f;return c}return r.direction===\"upper\"?r.all?t.toUpperCase():t.charAt(0).toUpperCase()+t.slice(1):r.all?t.toLowerCase():t.charAt(0).toLowerCase()+t.slice(1)}function $n(e,t,r,s,n){e.coverage?.hit(\"bash:expansion:transform\");let a=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[[@*]\\]$/);if(a&&n.operator===\"Q\")return P(e,a[1]).map(([,c])=>le(c)).join(\" \");if(a&&n.operator===\"a\")return ue(e,a[1]);let i=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[.+\\]$/);if(i&&n.operator===\"a\")return ue(e,i[1]);switch(n.operator){case\"Q\":return s?\"\":le(r);case\"P\":return we(e,r);case\"a\":return ue(e,t);case\"A\":return s?\"\":`${t}=${le(r)}`;case\"E\":return r.replace(/\\\\([\\\\abefnrtv'\"?])/g,(l,o)=>{switch(o){case\"\\\\\":return\"\\\\\";case\"a\":return\"\\x07\";case\"b\":return\"\\b\";case\"e\":return\"\\x1B\";case\"f\":return\"\\f\";case\"n\":return`\n`;case\"r\":return\"\\r\";case\"t\":return\"\t\";case\"v\":return\"\\v\";case\"'\":return\"'\";case'\"':return'\"';case\"?\":return\"?\";default:return o}});case\"K\":case\"k\":return s?\"\":le(r);case\"u\":return r.charAt(0).toUpperCase()+r.slice(1);case\"U\":return r.toUpperCase();case\"L\":return r.toLowerCase();default:return r}}async function Cn(e,t,r,s,n,a,i=!1){if(e.coverage?.hit(\"bash:expansion:indirection\"),W(e,t))return Se(e,t)||\"\";let l=/^[a-zA-Z_][a-zA-Z0-9_]*\\[([@*])\\]$/.test(t);if(s){if(n.innerOp?.type===\"UseAlternative\")return\"\";throw new re(`\\${!${t}}`)}let o=r;if(l&&(o===\"\"||o.includes(\" \")))throw new re(`\\${!${t}}`);let c=o.match(/^[a-zA-Z_][a-zA-Z0-9_]*\\[(.+)\\]$/);if(c&&c[1].includes(\"~\"))throw new re(`\\${!${t}}`);if(n.innerOp){let u={type:\"ParameterExpansion\",parameter:o,operation:n.innerOp};return a(e,u,i)}return await v(e,o)}function On(e,t){e.coverage?.hit(\"bash:expansion:array_keys\");let s=P(e,t.array).map(([n])=>String(n));return t.star?s.join(N(e.state.env)):s.join(\" \")}function Ln(e,t){e.coverage?.hit(\"bash:expansion:var_name_prefix\");let r=me(e,t.prefix);return t.star?r.join(N(e.state.env)):r.join(\" \")}function Wn(e,t,r,s){let n=Number.parseInt(e.state.env.get(\"#\")||\"0\",10),a=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[([@*])\\]$/);if(t===\"*\")return{isEmpty:n===0,effectiveValue:r};if(t===\"@\")return{isEmpty:n===0||n===1&&e.state.env.get(\"1\")===\"\",effectiveValue:r};if(a){let[,i,l]=a,o=P(e,i);if(o.length===0)return{isEmpty:!0,effectiveValue:\"\"};if(l===\"*\"){let c=N(e.state.env),u=o.map(([,f])=>f).join(c);return{isEmpty:s?u===\"\":!1,effectiveValue:u}}return{isEmpty:o.length===1&&o.every(([,c])=>c===\"\"),effectiveValue:o.map(([,c])=>c).join(\" \")}}return{isEmpty:r===\"\",effectiveValue:r}}function Tn(e){let t=0;for(;t<e.length;){let r=e[t];if(r===\"\\\\\"&&t+1<e.length){t+=2;continue}if(r===\"'\"){let s=e.indexOf(\"'\",t+1);if(s!==-1){t=s+1;continue}}if(r===\"$\"&&t+1<e.length&&e[t+1]===\"(\"||r===\"`\")return!0;t++}return!1}function Mn(e,t){let r=1,s=t,n=!1,a=!1;for(;s<e.length&&r>0;){let i=e[s];if(i===\"\\\\\"&&!n&&s+1<e.length){s+=2;continue}if(i===\"'\"&&!a){n=!n,s++;continue}if(i==='\"'&&!n){a=!a,s++;continue}if(!n&&!a){if(i===\"(\")r++;else if(i===\")\"&&(r--,r===0))return s}s++}return-1}async function We(e,t){let r=new V,s;try{s=r.parse(t)}catch{return\"\"}let n=e.state.bashPid;e.state.bashPid=e.state.nextVirtualPid++;let a=new Map(e.state.env),i=e.state.cwd,l=e.state.suppressVerbose;e.state.suppressVerbose=!0;try{let o=await e.executeScript(s),c=o.exitCode;return e.state.env=a,e.state.cwd=i,e.state.suppressVerbose=l,e.state.lastExitCode=c,e.state.env.set(\"?\",String(c)),o.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||\"\")+o.stderr),e.state.bashPid=n,o.stdout.replace(/\\n+$/,\"\")}catch(o){if(e.state.env=a,e.state.cwd=i,e.state.bashPid=n,e.state.suppressVerbose=l,o instanceof L)throw o;return o instanceof K?(e.state.lastExitCode=o.exitCode,e.state.env.set(\"?\",String(o.exitCode)),o.stdout?.replace(/\\n+$/,\"\")??\"\"):\"\"}}function Nt(e,t){let r=\"\",s=0;for(;s<t.length;){let n=t[s];if(n===\"'\"){let a=t.indexOf(\"'\",s+1);if(a!==-1){let i=t.slice(s+1,a);r+=X(i),s=a+1;continue}}if(n==='\"'){let a=-1,i=s+1;for(;i<t.length;){if(t[i]===\"\\\\\"){i+=2;continue}if(t[i]==='\"'){a=i;break}i++}if(a!==-1){let l=t.slice(s+1,a),o=Ss(e,l);r+=X(o),s=a+1;continue}}if(n===\"$\"&&s+1<t.length){let a=t[s+1];if(a===\"{\"){let i=t.indexOf(\"}\",s+2);if(i!==-1){let l=t.slice(s+2,i);r+=e.state.env.get(l)??\"\",s=i+1;continue}}else if(/[a-zA-Z_]/.test(a)){let i=s+1;for(;i<t.length&&/[a-zA-Z0-9_]/.test(t[i]);)i++;let l=t.slice(s+1,i);r+=e.state.env.get(l)??\"\",s=i;continue}}if(n===\"\\\\\"&&s+1<t.length){r+=n+t[s+1],s+=2;continue}r+=n,s++}return r}function Ss(e,t){let r=\"\",s=0;for(;s<t.length;){let n=t[s];if(n===\"\\\\\"&&s+1<t.length){let a=t[s+1];if(a===\"$\"||a===\"`\"||a===\"\\\\\"||a==='\"'){r+=a,s+=2;continue}r+=n,s++;continue}if(n===\"$\"&&s+1<t.length){let a=t[s+1];if(a===\"{\"){let i=t.indexOf(\"}\",s+2);if(i!==-1){let l=t.slice(s+2,i);r+=e.state.env.get(l)??\"\",s=i+1;continue}}else if(/[a-zA-Z_]/.test(a)){let i=s+1;for(;i<t.length&&/[a-zA-Z0-9_]/.test(t[i]);)i++;let l=t.slice(s+1,i);r+=e.state.env.get(l)??\"\",s=i;continue}}r+=n,s++}return r}async function Vn(e,t){let r=\"\",s=0;for(;s<t.length;){let n=t[s];if(n===\"'\"){let a=t.indexOf(\"'\",s+1);if(a!==-1){let i=t.slice(s+1,a);r+=X(i),s=a+1;continue}}if(n==='\"'){let a=-1,i=s+1;for(;i<t.length;){if(t[i]===\"\\\\\"){i+=2;continue}if(t[i]==='\"'){a=i;break}i++}if(a!==-1){let l=t.slice(s+1,a),o=await bs(e,l);r+=X(o),s=a+1;continue}}if(n===\"$\"&&s+1<t.length&&t[s+1]===\"(\"){let a=Mn(t,s+2);if(a!==-1){let i=t.slice(s+2,a),l=await We(e,i);r+=l,s=a+1;continue}}if(n===\"`\"){let a=t.indexOf(\"`\",s+1);if(a!==-1){let i=t.slice(s+1,a),l=await We(e,i);r+=l,s=a+1;continue}}if(n===\"$\"&&s+1<t.length){let a=t[s+1];if(a===\"{\"){let i=t.indexOf(\"}\",s+2);if(i!==-1){let l=t.slice(s+2,i);r+=e.state.env.get(l)??\"\",s=i+1;continue}}else if(/[a-zA-Z_]/.test(a)){let i=s+1;for(;i<t.length&&/[a-zA-Z0-9_]/.test(t[i]);)i++;let l=t.slice(s+1,i);r+=e.state.env.get(l)??\"\",s=i;continue}}if(n===\"\\\\\"&&s+1<t.length){r+=n+t[s+1],s+=2;continue}r+=n,s++}return r}async function bs(e,t){let r=\"\",s=0;for(;s<t.length;){let n=t[s];if(n===\"\\\\\"&&s+1<t.length){let a=t[s+1];if(a===\"$\"||a===\"`\"||a===\"\\\\\"||a==='\"'){r+=a,s+=2;continue}r+=n,s++;continue}if(n===\"$\"&&s+1<t.length&&t[s+1]===\"(\"){let a=Mn(t,s+2);if(a!==-1){let i=t.slice(s+2,a),l=await We(e,i);r+=l,s=a+1;continue}}if(n===\"`\"){let a=t.indexOf(\"`\",s+1);if(a!==-1){let i=t.slice(s+1,a),l=await We(e,i);r+=l,s=a+1;continue}}if(n===\"$\"&&s+1<t.length){let a=t[s+1];if(a===\"{\"){let i=t.indexOf(\"}\",s+2);if(i!==-1){let l=t.slice(s+2,i);r+=e.state.env.get(l)??\"\",s=i+1;continue}}else if(/[a-zA-Z_]/.test(a)){let i=s+1;for(;i<t.length&&/[a-zA-Z0-9_]/.test(t[i]);)i++;let l=t.slice(s+1,i);r+=e.state.env.get(l)??\"\",s=i;continue}}r+=n,s++}return r}function qn(e,t){if(!t.startsWith(\"~\"))return t;e.coverage?.hit(\"bash:expansion:tilde\");let r=e.state.env.get(\"HOME\")!==void 0?e.state.env.get(\"HOME\"):\"/home/user\";if(t===\"~\"||t.startsWith(\"~/\"))return r+t.slice(1);let s=1;for(;s<t.length&&/[a-zA-Z0-9_-]/.test(t[s]);)s++;let n=t.slice(1,s),a=t.slice(s);return a!==\"\"&&!a.startsWith(\"/\")?t:n===\"root\"?`/root${a}`:t}async function ws(e,t,r,s){let n=\"\";for(let a of t.parts)if(a.type===\"Glob\")n+=k(a.pattern,!0,e.state.shoptOptions.extglob);else if(a.type===\"Literal\")n+=k(a.value,!0,e.state.shoptOptions.extglob);else if(a.type===\"SingleQuoted\"||a.type===\"Escaped\")n+=I(a.value);else if(a.type===\"DoubleQuoted\"){let i=await r(e,a.parts);n+=I(i)}else if(a.type===\"ParameterExpansion\"){let i=await s(e,a);n+=k(i,!0,e.state.shoptOptions.extglob)}else{let i=await s(e,a);n+=I(i)}return n}async function Bn(e,t,r,s){if(t.length!==1||t[0].type!==\"DoubleQuoted\")return null;let n=t[0];if(n.parts.length!==1||n.parts[0].type!==\"ParameterExpansion\"||n.parts[0].operation?.type!==\"PatternReplacement\")return null;let a=n.parts[0],i=a.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[([@*])\\]$/);if(!i)return null;let l=i[1],o=i[2]===\"*\",c=a.operation,u=P(e,l),f=u.map(([,E])=>E);if(u.length===0){let E=e.state.env.get(l);E!==void 0&&f.push(E)}if(f.length===0)return{values:[],quoted:!0};let h=\"\";c.pattern&&(h=await ws(e,c.pattern,r,s));let d=c.replacement?await r(e,c.replacement.parts):\"\",m=h;c.anchor===\"start\"?m=`^${h}`:c.anchor===\"end\"&&(m=`${h}$`);let g=[];try{let E=O(m,c.all?\"g\":\"\");for(let A of f)g.push(E.replace(A,d))}catch{g.push(...f)}if(o){let E=N(e.state.env);return{values:[g.join(E)],quoted:!0}}return{values:g,quoted:!0}}async function Fn(e,t,r,s){if(t.length!==1||t[0].type!==\"DoubleQuoted\")return null;let n=t[0];if(n.parts.length!==1||n.parts[0].type!==\"ParameterExpansion\"||n.parts[0].operation?.type!==\"PatternRemoval\")return null;let a=n.parts[0],i=a.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[([@*])\\]$/);if(!i)return null;let l=i[1],o=i[2]===\"*\",c=a.operation,u=P(e,l),f=u.map(([,g])=>g);if(u.length===0){let g=e.state.env.get(l);g!==void 0&&f.push(g)}if(f.length===0)return{values:[],quoted:!0};let h=\"\",d=e.state.shoptOptions.extglob;if(c.pattern)for(let g of c.pattern.parts)if(g.type===\"Glob\")h+=k(g.pattern,c.greedy,d);else if(g.type===\"Literal\")h+=k(g.value,c.greedy,d);else if(g.type===\"SingleQuoted\"||g.type===\"Escaped\")h+=I(g.value);else if(g.type===\"DoubleQuoted\"){let E=await r(e,g.parts);h+=I(E)}else if(g.type===\"ParameterExpansion\"){let E=await s(e,g);h+=k(E,c.greedy,d)}else{let E=await s(e,g);h+=I(E)}let m=[];for(let g of f)m.push(se(g,h,c.side,c.greedy));if(o){let g=N(e.state.env);return{values:[m.join(g)],quoted:!0}}return{values:m,quoted:!0}}async function zn(e,t){if(t.length!==1||t[0].type!==\"DoubleQuoted\")return null;let r=t[0];if(r.parts.length!==1||r.parts[0].type!==\"ParameterExpansion\"||r.parts[0].operation?.type!==\"DefaultValue\"&&r.parts[0].operation?.type!==\"UseAlternative\"&&r.parts[0].operation?.type!==\"AssignDefault\")return null;let s=r.parts[0],n=s.operation,a=s.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[([@*])\\]$/),i,l=!1;if(a){let o=a[1];l=a[2]===\"*\";let c=P(e,o),u=c.length>0||e.state.env.has(o),f=c.length===0||c.length===1&&c.every(([,d])=>d===\"\"),h=n.checkEmpty??!1;if(n.type===\"UseAlternative\"?i=u&&!(h&&f):i=!u||h&&f,!i){if(c.length>0){let m=c.map(([,g])=>g);if(l){let g=N(e.state.env);return{values:[m.join(g)],quoted:!0}}return{values:m,quoted:!0}}let d=e.state.env.get(o);return d!==void 0?{values:[d],quoted:!0}:{values:[],quoted:!0}}}else{let o=s.parameter,c=await te(e,o),u=await v(e,o),f=u===\"\",h=n.checkEmpty??!1;if(n.type===\"UseAlternative\"?i=c&&!(h&&f):i=!c||h&&f,!i)return{values:[u],quoted:!0}}if(i&&n.word){let o=n.word.parts,c=null,u=!1;for(let f of o)if(f.type===\"ParameterExpansion\"&&!f.operation){let h=f.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[([@*])\\]$/);if(h){c=h[1],u=h[2]===\"*\";break}}if(c){let f=P(e,c);if(f.length>0){let d=f.map(([,m])=>m);if(u||l){let m=N(e.state.env);return{values:[d.join(m)],quoted:!0}}return{values:d,quoted:!0}}let h=e.state.env.get(c);return h!==void 0?{values:[h],quoted:!0}:{values:[],quoted:!0}}}return null}async function Gn(e,t,r,s,n){if(!r||t.length!==1||t[0].type!==\"DoubleQuoted\")return null;let a=t[0],i=-1,l=\"\",o=!1,c=null;for(let g=0;g<a.parts.length;g++){let E=a.parts[g];if(E.type===\"ParameterExpansion\"&&(E.operation?.type===\"PatternRemoval\"||E.operation?.type===\"PatternReplacement\")){let A=E.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[([@*])\\]$/);if(A){i=g,l=A[1],o=A[2]===\"*\",c=E.operation;break}}}if(i===-1||i===0&&i===a.parts.length-1)return null;let u=\"\";for(let g=0;g<i;g++)u+=await s(e,a.parts[g]);let f=\"\";for(let g=i+1;g<a.parts.length;g++)f+=await s(e,a.parts[g]);let h=P(e,l),d=h.map(([,g])=>g);if(h.length===0){let g=e.state.env.get(l);if(g!==void 0)d=[g];else{if(o)return{values:[u+f],quoted:!0};let E=u+f;return{values:E?[E]:[],quoted:!0}}}if(c?.type===\"PatternRemoval\"){let g=c,E=\"\",A=e.state.shoptOptions.extglob;if(g.pattern)for(let S of g.pattern.parts)if(S.type===\"Glob\")E+=k(S.pattern,g.greedy,A);else if(S.type===\"Literal\")E+=k(S.value,g.greedy,A);else if(S.type===\"SingleQuoted\"||S.type===\"Escaped\")E+=I(S.value);else if(S.type===\"DoubleQuoted\"){let y=await n(e,S.parts);E+=I(y)}else if(S.type===\"ParameterExpansion\"){let y=await s(e,S);E+=k(y,g.greedy,A)}else{let y=await s(e,S);E+=I(y)}d=d.map(S=>se(S,E,g.side,g.greedy))}else if(c?.type===\"PatternReplacement\"){let g=c,E=\"\";if(g.pattern)for(let y of g.pattern.parts)if(y.type===\"Glob\")E+=k(y.pattern,!0,e.state.shoptOptions.extglob);else if(y.type===\"Literal\")E+=k(y.value,!0,e.state.shoptOptions.extglob);else if(y.type===\"SingleQuoted\"||y.type===\"Escaped\")E+=I(y.value);else if(y.type===\"DoubleQuoted\"){let b=await n(e,y.parts);E+=I(b)}else if(y.type===\"ParameterExpansion\"){let b=await s(e,y);E+=k(b,!0,e.state.shoptOptions.extglob)}else{let b=await s(e,y);E+=I(b)}let A=g.replacement?await n(e,g.replacement.parts):\"\",S=E;g.anchor===\"start\"?S=`^${E}`:g.anchor===\"end\"&&(S=`${E}$`);try{let y=O(S,g.all?\"g\":\"\");d=d.map(b=>y.replace(b,A))}catch{}}if(o){let g=N(e.state.env);return{values:[u+d.join(g)+f],quoted:!0}}return d.length===1?{values:[u+d[0]+f],quoted:!0}:{values:[u+d[0],...d.slice(1,-1),d[d.length-1]+f],quoted:!0}}async function Qn(e,t,r,s){if(!r||t.length!==1||t[0].type!==\"DoubleQuoted\")return null;let n=t[0],a=-1,i=\"\",l=!1;for(let d=0;d<n.parts.length;d++){let m=n.parts[d];if(m.type===\"ParameterExpansion\"&&!m.operation){let g=m.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[([@*])\\]$/);if(g){a=d,i=g[1],l=g[2]===\"*\";break}}}if(a===-1)return null;let o=\"\";for(let d=0;d<a;d++)o+=await s(e,n.parts[d]);let c=\"\";for(let d=a+1;d<n.parts.length;d++)c+=await s(e,n.parts[d]);let u=P(e,i),f=u.map(([,d])=>d);if(u.length===0){let d=e.state.env.get(i);if(d!==void 0)return{values:[o+d+c],quoted:!0};if(l)return{values:[o+c],quoted:!0};let m=o+c;return{values:m?[m]:[],quoted:!0}}if(l){let d=N(e.state.env);return{values:[o+f.join(d)+c],quoted:!0}}return f.length===1?{values:[o+f[0]+c],quoted:!0}:{values:[o+f[0],...f.slice(1,-1),f[f.length-1]+c],quoted:!0}}async function Zn(e,t,r){if(t.length!==1||t[0].type!==\"DoubleQuoted\")return null;let s=t[0];if(s.parts.length!==1||s.parts[0].type!==\"ParameterExpansion\"||s.parts[0].operation?.type!==\"Substring\")return null;let n=s.parts[0],a=n.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[([@*])\\]$/);if(!a)return null;let i=a[1],l=a[2]===\"*\",o=n.operation;if(e.state.associativeArrays?.has(i))throw new K(1,\"\",`bash: \\${${i}[@]: 0: 3}: bad substitution\n`);let c=o.offset?await r(e,o.offset.expression):0,u=o.length?await r(e,o.length.expression):void 0,f=P(e,i),h=0;if(c<0){if(f.length>0){let m=f[f.length-1][0],E=(typeof m==\"number\"?m:0)+1+c;if(E<0)return{values:[],quoted:!0};h=f.findIndex(([A])=>typeof A==\"number\"&&A>=E),h<0&&(h=f.length)}}else h=f.findIndex(([m])=>typeof m==\"number\"&&m>=c),h<0&&(h=f.length);let d;if(u!==void 0){if(u<0)throw new C(`${i}[@]: substring expression < 0`);d=f.slice(h,h+u).map(([,m])=>m)}else d=f.slice(h).map(([,m])=>m);if(d.length===0)return{values:[],quoted:!0};if(l){let m=N(e.state.env);return{values:[d.join(m)],quoted:!0}}return{values:d,quoted:!0}}function Un(e,t){if(t.length!==1||t[0].type!==\"DoubleQuoted\")return null;let r=t[0];if(r.parts.length!==1||r.parts[0].type!==\"ParameterExpansion\"||r.parts[0].operation?.type!==\"Transform\")return null;let s=r.parts[0],n=s.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[([@*])\\]$/);if(!n)return null;let a=n[1],i=n[2]===\"*\",l=s.operation,o=P(e,a);if(o.length===0){let f=e.state.env.get(a);if(f!==void 0){let h;switch(l.operator){case\"a\":h=\"\";break;case\"P\":h=we(e,f);break;case\"Q\":h=le(f);break;default:h=f}return{values:[h],quoted:!0}}return i?{values:[\"\"],quoted:!0}:{values:[],quoted:!0}}let c=ue(e,a),u;switch(l.operator){case\"a\":u=o.map(()=>c);break;case\"P\":u=o.map(([,f])=>we(e,f));break;case\"Q\":u=o.map(([,f])=>le(f));break;case\"u\":u=o.map(([,f])=>f.charAt(0).toUpperCase()+f.slice(1));break;case\"U\":u=o.map(([,f])=>f.toUpperCase());break;case\"L\":u=o.map(([,f])=>f.toLowerCase());break;default:u=o.map(([,f])=>f)}if(i){let f=N(e.state.env);return{values:[u.join(f)],quoted:!0}}return{values:u,quoted:!0}}function Hn(e,t){if(t.length!==1||t[0].type!==\"DoubleQuoted\")return null;let r=t[0];if(r.parts.length!==1||r.parts[0].type!==\"ParameterExpansion\")return null;let s=r.parts[0];if(s.operation)return null;let n=s.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[(@)\\]$/);if(!n)return null;let a=n[1];if(W(e,a)){let o=Se(e,a);if(o?.endsWith(\"[@]\")||o?.endsWith(\"[*]\"))return{values:[],quoted:!0}}let i=P(e,a);if(i.length>0)return{values:i.map(([,o])=>o),quoted:!0};let l=e.state.env.get(a);return l!==void 0?{values:[l],quoted:!0}:{values:[],quoted:!0}}function jn(e,t){if(t.length!==1||t[0].type!==\"DoubleQuoted\")return null;let r=t[0];if(r.parts.length!==1||r.parts[0].type!==\"ParameterExpansion\"||r.parts[0].operation)return null;let n=r.parts[0].parameter;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n)||!W(e,n))return null;let a=Se(e,n);if(!a)return null;let i=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[(@)\\]$/);if(!i)return null;let l=i[1],o=P(e,l);if(o.length>0)return{values:o.map(([,u])=>u),quoted:!0};let c=e.state.env.get(l);return c!==void 0?{values:[c],quoted:!0}:{values:[],quoted:!0}}async function Kn(e,t,r,s,n){if(!r||t.length!==1||t[0].type!==\"DoubleQuoted\")return null;let a=t[0];if(a.parts.length!==1||a.parts[0].type!==\"ParameterExpansion\"||a.parts[0].operation?.type!==\"Indirection\")return null;let i=a.parts[0],l=i.operation,o=await v(e,i.parameter),c=o.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[([@*])\\]$/);if(!c){if(!l.innerOp&&(o===\"@\"||o===\"*\")){let m=Number.parseInt(e.state.env.get(\"#\")||\"0\",10),g=[];for(let E=1;E<=m;E++)g.push(e.state.env.get(String(E))||\"\");return o===\"*\"?{values:[g.join(N(e.state.env))],quoted:!0}:{values:g,quoted:!0}}return null}let u=c[1],f=c[2]===\"*\",h=P(e,u);if(l.innerOp){if(l.innerOp.type===\"Substring\")return Ns(e,h,u,f,l.innerOp);if(l.innerOp.type===\"DefaultValue\"||l.innerOp.type===\"UseAlternative\"||l.innerOp.type===\"AssignDefault\"||l.innerOp.type===\"ErrorIfUnset\")return ks(e,h,u,f,l.innerOp,n);if(l.innerOp.type===\"Transform\"&&l.innerOp.operator===\"a\"){let g=ue(e,u),E=h.map(()=>g);return f?{values:[E.join(N(e.state.env))],quoted:!0}:{values:E,quoted:!0}}let m=[];for(let[,g]of h){let E={type:\"ParameterExpansion\",parameter:\"_indirect_elem_\",operation:l.innerOp},A=e.state.env.get(\"_indirect_elem_\");e.state.env.set(\"_indirect_elem_\",g);try{let S=await s(e,E,!0);m.push(S)}finally{A!==void 0?e.state.env.set(\"_indirect_elem_\",A):e.state.env.delete(\"_indirect_elem_\")}}return f?{values:[m.join(N(e.state.env))],quoted:!0}:{values:m,quoted:!0}}if(h.length>0){let m=h.map(([,g])=>g);return f?{values:[m.join(N(e.state.env))],quoted:!0}:{values:m,quoted:!0}}let d=e.state.env.get(u);return d!==void 0?{values:[d],quoted:!0}:{values:[],quoted:!0}}async function Ns(e,t,r,s,n){let a=n.offset?await R(e,n.offset.expression):0,i=n.length?await R(e,n.length.expression):void 0,l=0;if(a<0){if(t.length>0){let u=t[t.length-1][0],h=(typeof u==\"number\"?u:0)+1+a;if(h<0)return{values:[],quoted:!0};if(l=t.findIndex(([d])=>typeof d==\"number\"&&d>=h),l<0)return{values:[],quoted:!0}}}else if(l=t.findIndex(([u])=>typeof u==\"number\"&&u>=a),l<0)return{values:[],quoted:!0};let o;if(i!==void 0){if(i<0)throw new C(`${r}[@]: substring expression < 0`);o=t.slice(l,l+i)}else o=t.slice(l);let c=o.map(([,u])=>u);return s?{values:[c.join(N(e.state.env))],quoted:!0}:{values:c,quoted:!0}}async function ks(e,t,r,s,n,a){let i=n.checkEmpty??!1,l=t.map(([,u])=>u),o=t.length===0,c=t.length===0;if(n.type===\"UseAlternative\")return!c&&!(i&&o)&&n.word?{values:[await a(e,n.word.parts,!0)],quoted:!0}:{values:[],quoted:!0};if(n.type===\"DefaultValue\")return(c||i&&o)&&n.word?{values:[await a(e,n.word.parts,!0)],quoted:!0}:s?{values:[l.join(N(e.state.env))],quoted:!0}:{values:l,quoted:!0};if(n.type===\"AssignDefault\"){if((c||i&&o)&&n.word){let f=await a(e,n.word.parts,!0);return e.state.env.set(`${r}_0`,f),e.state.env.set(`${r}__length`,\"1\"),{values:[f],quoted:!0}}return s?{values:[l.join(N(e.state.env))],quoted:!0}:{values:l,quoted:!0}}return s?{values:[l.join(N(e.state.env))],quoted:!0}:{values:l,quoted:!0}}async function Xn(e,t){if(t.length!==1||t[0].type!==\"ParameterExpansion\"||t[0].operation?.type!==\"UseAlternative\"&&t[0].operation?.type!==\"DefaultValue\")return null;let r=t[0],s=r.operation,n=s?.word;if(!n||n.parts.length!==1||n.parts[0].type!==\"DoubleQuoted\")return null;let a=n.parts[0];if(a.parts.length!==1||a.parts[0].type!==\"ParameterExpansion\"||a.parts[0].operation?.type!==\"Indirection\")return null;let i=a.parts[0],o=(await v(e,i.parameter)).match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[([@*])\\]$/);if(!o)return null;let c=await te(e,r.parameter),u=await v(e,r.parameter)===\"\",f=s.checkEmpty??!1,h;if(s.type===\"UseAlternative\"?h=c&&!(f&&u):h=!c||f&&u,h){let d=o[1],m=o[2]===\"*\",g=P(e,d);if(g.length>0){let A=g.map(([,S])=>S);return m?{values:[A.join(N(e.state.env))],quoted:!0}:{values:A,quoted:!0}}let E=e.state.env.get(d);return E!==void 0?{values:[E],quoted:!0}:{values:[],quoted:!0}}return{values:[],quoted:!1}}async function Jn(e,t){if(t.length!==1||t[0].type!==\"ParameterExpansion\"||t[0].operation?.type!==\"Indirection\")return null;let r=t[0],n=r.operation.innerOp;if(!n||n.type!==\"UseAlternative\"&&n.type!==\"DefaultValue\")return null;let a=n.word;if(!a||a.parts.length!==1||a.parts[0].type!==\"DoubleQuoted\")return null;let i=a.parts[0];if(i.parts.length!==1||i.parts[0].type!==\"ParameterExpansion\"||i.parts[0].operation?.type!==\"Indirection\")return null;let l=i.parts[0],c=(await v(e,l.parameter)).match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[([@*])\\]$/);if(!c)return null;let u=await v(e,r.parameter),f=await te(e,r.parameter),h=u===\"\",d=n.checkEmpty??!1,m;if(n.type===\"UseAlternative\"?m=f&&!(d&&h):m=!f||d&&h,m){let g=c[1],E=c[2]===\"*\",A=P(e,g);if(A.length>0){let y=A.map(([,b])=>b);return E?{values:[y.join(N(e.state.env))],quoted:!0}:{values:y,quoted:!0}}let S=e.state.env.get(g);return S!==void 0?{values:[S],quoted:!0}:{values:[],quoted:!0}}return{values:[],quoted:!1}}function Yn(e){let t=Number.parseInt(e.state.env.get(\"#\")||\"0\",10),r=[];for(let s=1;s<=t;s++)r.push(e.state.env.get(String(s))||\"\");return r}async function er(e,t,r,s){if(t.length!==1||t[0].type!==\"DoubleQuoted\")return null;let n=t[0],a=-1,i=!1;for(let S=0;S<n.parts.length;S++){let y=n.parts[S];if(y.type===\"ParameterExpansion\"&&(y.parameter===\"@\"||y.parameter===\"*\")&&y.operation?.type===\"Substring\"){a=S,i=y.parameter===\"*\";break}}if(a===-1)return null;let o=n.parts[a].operation,c=o.offset?await r(e,o.offset.expression):0,u=o.length?await r(e,o.length.expression):void 0,f=Number.parseInt(e.state.env.get(\"#\")||\"0\",10),h=[];for(let S=1;S<=f;S++)h.push(e.state.env.get(String(S))||\"\");let d=e.state.env.get(\"0\")||\"bash\",m;if(c<=0){let S=[d,...h],y=S.length+c;if(y<0)m=[];else{let b=c<0?y:0;if(u!==void 0){let D=u<0?S.length+u:b+u;m=S.slice(b,Math.max(b,D))}else m=S.slice(b)}}else{let S=c-1;if(S>=h.length)m=[];else if(u!==void 0){let y=u<0?h.length+u:S+u;m=h.slice(S,Math.max(S,y))}else m=h.slice(S)}let g=\"\";for(let S=0;S<a;S++)g+=await s(e,n.parts[S]);let E=\"\";for(let S=a+1;S<n.parts.length;S++)E+=await s(e,n.parts[S]);if(m.length===0){let S=g+E;return{values:S?[S]:[],quoted:!0}}if(i){let S=N(e.state.env);return{values:[g+m.join(S)+E],quoted:!0}}return m.length===1?{values:[g+m[0]+E],quoted:!0}:{values:[g+m[0],...m.slice(1,-1),m[m.length-1]+E],quoted:!0}}async function tr(e,t,r,s){if(t.length!==1||t[0].type!==\"DoubleQuoted\")return null;let n=t[0],a=-1,i=!1;for(let A=0;A<n.parts.length;A++){let S=n.parts[A];if(S.type===\"ParameterExpansion\"&&(S.parameter===\"@\"||S.parameter===\"*\")&&S.operation?.type===\"PatternReplacement\"){a=A,i=S.parameter===\"*\";break}}if(a===-1)return null;let o=n.parts[a].operation,c=Yn(e),u=\"\";for(let A=0;A<a;A++)u+=await r(e,n.parts[A]);let f=\"\";for(let A=a+1;A<n.parts.length;A++)f+=await r(e,n.parts[A]);if(c.length===0){let A=u+f;return{values:A?[A]:[],quoted:!0}}let h=\"\";if(o.pattern)for(let A of o.pattern.parts)if(A.type===\"Glob\")h+=k(A.pattern,!0,e.state.shoptOptions.extglob);else if(A.type===\"Literal\")h+=k(A.value,!0,e.state.shoptOptions.extglob);else if(A.type===\"SingleQuoted\"||A.type===\"Escaped\")h+=I(A.value);else if(A.type===\"DoubleQuoted\"){let S=await s(e,A.parts);h+=I(S)}else if(A.type===\"ParameterExpansion\"){let S=await r(e,A);h+=k(S,!0,e.state.shoptOptions.extglob)}else{let S=await r(e,A);h+=I(S)}let d=o.replacement?await s(e,o.replacement.parts):\"\",m=h;o.anchor===\"start\"?m=`^${h}`:o.anchor===\"end\"&&(m=`${h}$`);let g=[];try{let A=O(m,o.all?\"g\":\"\");for(let S of c)g.push(A.replace(S,d))}catch{g.push(...c)}if(i){let A=N(e.state.env);return{values:[u+g.join(A)+f],quoted:!0}}return g.length===1?{values:[u+g[0]+f],quoted:!0}:{values:[u+g[0],...g.slice(1,-1),g[g.length-1]+f],quoted:!0}}async function nr(e,t,r,s){if(t.length!==1||t[0].type!==\"DoubleQuoted\")return null;let n=t[0],a=-1,i=!1;for(let E=0;E<n.parts.length;E++){let A=n.parts[E];if(A.type===\"ParameterExpansion\"&&(A.parameter===\"@\"||A.parameter===\"*\")&&A.operation?.type===\"PatternRemoval\"){a=E,i=A.parameter===\"*\";break}}if(a===-1)return null;let o=n.parts[a].operation,c=Yn(e),u=\"\";for(let E=0;E<a;E++)u+=await r(e,n.parts[E]);let f=\"\";for(let E=a+1;E<n.parts.length;E++)f+=await r(e,n.parts[E]);if(c.length===0){let E=u+f;return{values:E?[E]:[],quoted:!0}}let h=\"\",d=e.state.shoptOptions.extglob;if(o.pattern)for(let E of o.pattern.parts)if(E.type===\"Glob\")h+=k(E.pattern,o.greedy,d);else if(E.type===\"Literal\")h+=k(E.value,o.greedy,d);else if(E.type===\"SingleQuoted\"||E.type===\"Escaped\")h+=I(E.value);else if(E.type===\"DoubleQuoted\"){let A=await s(e,E.parts);h+=I(A)}else if(E.type===\"ParameterExpansion\"){let A=await r(e,E);h+=k(A,o.greedy,d)}else{let A=await r(e,E);h+=I(A)}let m=[];for(let E of c)m.push(se(E,h,o.side,o.greedy));if(i){let E=N(e.state.env);return{values:[u+m.join(E)+f],quoted:!0}}return m.length===1?{values:[u+m[0]+f],quoted:!0}:{values:[u+m[0],...m.slice(1,-1),m[m.length-1]+f],quoted:!0}}async function rr(e,t,r){if(t.length!==1||t[0].type!==\"DoubleQuoted\")return null;let s=t[0],n=-1,a=!1;for(let h=0;h<s.parts.length;h++){let d=s.parts[h];if(d.type===\"ParameterExpansion\"&&(d.parameter===\"@\"||d.parameter===\"*\")){n=h,a=d.parameter===\"*\";break}}if(n===-1)return null;let i=s.parts[n];if(i.type===\"ParameterExpansion\"&&i.operation)return null;let l=Number.parseInt(e.state.env.get(\"#\")||\"0\",10),o=\"\";for(let h=0;h<n;h++)o+=await r(e,s.parts[h]);let c=\"\";for(let h=n+1;h<s.parts.length;h++)c+=await r(e,s.parts[h]);if(l===0){if(a)return{values:[o+c],quoted:!0};let h=o+c;return{values:h?[h]:[],quoted:!0}}let u=[];for(let h=1;h<=l;h++)u.push(e.state.env.get(String(h))||\"\");if(a){let h=N(e.state.env);return{values:[o+u.join(h)+c],quoted:!0}}return u.length===1?{values:[o+u[0]+c],quoted:!0}:{values:[o+u[0],...u.slice(1,-1),u[u.length-1]+c],quoted:!0}}function Ps(e){return new oe(e.fs,e.state.cwd,e.state.env,{globstar:e.state.shoptOptions.globstar,nullglob:e.state.shoptOptions.nullglob,failglob:e.state.shoptOptions.failglob,dotglob:e.state.shoptOptions.dotglob,extglob:e.state.shoptOptions.extglob,globskipdots:e.state.shoptOptions.globskipdots,maxGlobOperations:e.limits.maxGlobOperations})}async function Te(e,t){if(e.state.options.noglob)return t;let r=Ps(e),s=[];for(let n of t)if(ne(n,e.state.shoptOptions.extglob)){let a=await r.expand(n);if(a.length>0)s.push(...a);else{if(r.hasFailglob())throw new Pe(n);r.hasNullglob()||s.push(n)}}else s.push(n);return s}async function sr(e,t,r,s){let n=-1,a=\"\",i=!1;for(let S=0;S<t.length;S++){let y=t[S];if(y.type===\"ParameterExpansion\"&&y.operation?.type===\"PatternReplacement\"){let b=y.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[([@*])\\]$/);if(b){n=S,a=b[1],i=b[2]===\"*\";break}}}if(n===-1)return null;let o=t[n].operation,c=P(e,a),u=c.map(([,S])=>S);if(c.length===0){let S=e.state.env.get(a);S!==void 0&&(u=[S])}if(u.length===0)return{values:[],quoted:!1};let f=\"\";if(o.pattern)for(let S of o.pattern.parts)if(S.type===\"Glob\")f+=k(S.pattern,!0,e.state.shoptOptions.extglob);else if(S.type===\"Literal\")f+=k(S.value,!0,e.state.shoptOptions.extglob);else if(S.type===\"SingleQuoted\"||S.type===\"Escaped\")f+=I(S.value);else if(S.type===\"DoubleQuoted\"){let y=await r(e,S.parts);f+=I(y)}else if(S.type===\"ParameterExpansion\"){let y=await s(e,S);f+=k(y,!0,e.state.shoptOptions.extglob)}else{let y=await s(e,S);f+=I(y)}let h=o.replacement?await r(e,o.replacement.parts):\"\",d=f;o.anchor===\"start\"?d=`^${f}`:o.anchor===\"end\"&&(d=`${f}$`);let m=[];try{let S=O(d,o.all?\"g\":\"\");for(let y of u)m.push(S.replace(y,h))}catch{m.push(...u)}let g=T(e.state.env),E=q(e.state.env);if(i){let S=N(e.state.env),y=m.join(S);return E?{values:y?[y]:[],quoted:!1}:{values:x(y,g),quoted:!1}}if(E)return{values:m,quoted:!1};let A=[];for(let S of m)S===\"\"?A.push(\"\"):A.push(...x(S,g));return{values:A,quoted:!1}}async function ir(e,t,r,s){let n=-1,a=\"\",i=!1;for(let A=0;A<t.length;A++){let S=t[A];if(S.type===\"ParameterExpansion\"&&S.operation?.type===\"PatternRemoval\"){let y=S.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[([@*])\\]$/);if(y){n=A,a=y[1],i=y[2]===\"*\";break}}}if(n===-1)return null;let o=t[n].operation,c=P(e,a),u=c.map(([,A])=>A);if(c.length===0){let A=e.state.env.get(a);A!==void 0&&(u=[A])}if(u.length===0)return{values:[],quoted:!1};let f=\"\",h=e.state.shoptOptions.extglob;if(o.pattern)for(let A of o.pattern.parts)if(A.type===\"Glob\")f+=k(A.pattern,o.greedy,h);else if(A.type===\"Literal\")f+=k(A.value,o.greedy,h);else if(A.type===\"SingleQuoted\"||A.type===\"Escaped\")f+=I(A.value);else if(A.type===\"DoubleQuoted\"){let S=await r(e,A.parts);f+=I(S)}else if(A.type===\"ParameterExpansion\"){let S=await s(e,A);f+=k(S,o.greedy,h)}else{let S=await s(e,A);f+=I(S)}let d=[];for(let A of u)d.push(se(A,f,o.side,o.greedy));let m=T(e.state.env),g=q(e.state.env);if(i){let A=N(e.state.env),S=d.join(A);return g?{values:S?[S]:[],quoted:!1}:{values:x(S,m),quoted:!1}}if(g)return{values:d,quoted:!1};let E=[];for(let A of d)A===\"\"?E.push(\"\"):E.push(...x(A,m));return{values:E,quoted:!1}}async function ar(e,t,r,s){let n=-1,a=!1;for(let E=0;E<t.length;E++){let A=t[E];if(A.type===\"ParameterExpansion\"&&(A.parameter===\"@\"||A.parameter===\"*\")&&A.operation?.type===\"PatternRemoval\"){n=E,a=A.parameter===\"*\";break}}if(n===-1)return null;let l=t[n].operation,o=Number.parseInt(e.state.env.get(\"#\")||\"0\",10),c=[];for(let E=1;E<=o;E++)c.push(e.state.env.get(String(E))||\"\");if(c.length===0)return{values:[],quoted:!1};let u=\"\",f=e.state.shoptOptions.extglob;if(l.pattern)for(let E of l.pattern.parts)if(E.type===\"Glob\")u+=k(E.pattern,l.greedy,f);else if(E.type===\"Literal\")u+=k(E.value,l.greedy,f);else if(E.type===\"SingleQuoted\"||E.type===\"Escaped\")u+=I(E.value);else if(E.type===\"DoubleQuoted\"){let A=await r(e,E.parts);u+=I(A)}else if(E.type===\"ParameterExpansion\"){let A=await s(e,E);u+=k(A,l.greedy,f)}else{let A=await s(e,E);u+=I(A)}let h=[];for(let E of c)h.push(se(E,u,l.side,l.greedy));let d=T(e.state.env),m=q(e.state.env);if(a){let E=N(e.state.env),A=h.join(E);return m?{values:A?[A]:[],quoted:!1}:{values:x(A,d),quoted:!1}}if(m)return{values:h,quoted:!1};let g=[];for(let E of h)E===\"\"?g.push(\"\"):g.push(...x(E,d));return{values:g,quoted:!1}}async function or(e,t,r,s){let n=-1,a=!1;for(let y=0;y<t.length;y++){let b=t[y];if(b.type===\"ParameterExpansion\"&&(b.parameter===\"@\"||b.parameter===\"*\")&&b.operation?.type===\"Substring\"){n=y,a=b.parameter===\"*\";break}}if(n===-1)return null;let l=t[n].operation,o=l.offset?await r(e,l.offset.expression):0,c=l.length?await r(e,l.length.expression):void 0,u=Number.parseInt(e.state.env.get(\"#\")||\"0\",10),f=[];for(let y=1;y<=u;y++)f.push(e.state.env.get(String(y))||\"\");let h=e.state.env.get(\"0\")||\"bash\",d;if(o<=0){let y=[h,...f],b=y.length+o;if(b<0)d=[];else{let D=o<0?b:0;if(c!==void 0){let Q=c<0?y.length+c:D+c;d=y.slice(D,Math.max(D,Q))}else d=y.slice(D)}}else{let y=o-1;if(y>=f.length)d=[];else if(c!==void 0){let b=c<0?f.length+c:y+c;d=f.slice(y,Math.max(y,b))}else d=f.slice(y)}let m=\"\";for(let y=0;y<n;y++)m+=await s(e,t[y]);let g=\"\";for(let y=n+1;y<t.length;y++)g+=await s(e,t[y]);let E=T(e.state.env),A=q(e.state.env);if(d.length===0){let y=m+g;return y?A?{values:[y],quoted:!1}:{values:x(y,E),quoted:!1}:{values:[],quoted:!1}}let S;if(a){let y=N(e.state.env),b=m+d.join(y)+g;A?S=b?[b]:[]:S=x(b,E)}else if(A)d.length===1?S=[m+d[0]+g]:S=[m+d[0],...d.slice(1,-1),d[d.length-1]+g];else{S=[];for(let y=0;y<d.length;y++){let b=d[y];if(y===0&&(b=m+b),y===d.length-1&&(b=b+g),b===\"\")S.push(\"\");else{let D=x(b,E);S.push(...D)}}}return{values:await Te(e,S),quoted:!1}}async function lr(e,t){if(t.length!==1||t[0].type!==\"ParameterExpansion\"||t[0].parameter!==\"@\"&&t[0].parameter!==\"*\"||t[0].operation)return null;let r=t[0].parameter===\"*\",s=Number.parseInt(e.state.env.get(\"#\")||\"0\",10);if(s===0)return{values:[],quoted:!1};let n=[];for(let c=1;c<=s;c++)n.push(e.state.env.get(String(c))||\"\");let a=T(e.state.env),i=q(e.state.env),l=Ce(e.state.env),o;if(r)if(i)o=n.filter(c=>c!==\"\");else{let c=N(e.state.env),u=n.join(c);o=x(u,a)}else if(i)o=n.filter(c=>c!==\"\");else if(l){o=[];for(let c of n){if(c===\"\")continue;let u=x(c,a);o.push(...u)}}else{o=[];for(let c of n)if(c===\"\")o.push(\"\");else{let u=x(c,a);o.push(...u)}for(;o.length>0&&o[o.length-1]===\"\";)o.pop()}return{values:await Te(e,o),quoted:!1}}async function ur(e,t){if(t.length!==1||t[0].type!==\"ParameterExpansion\"||t[0].operation)return null;let r=t[0].parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[([@*])\\]$/);if(!r)return null;let s=r[1],n=r[2]===\"*\",a=P(e,s),i;if(a.length===0){let f=e.state.env.get(s);if(f!==void 0)i=[f];else return{values:[],quoted:!1}}else i=a.map(([,f])=>f);let l=T(e.state.env),o=q(e.state.env),c=Ce(e.state.env),u;if(n)if(o)u=i.filter(f=>f!==\"\");else{let f=N(e.state.env),h=i.join(f);u=x(h,l)}else if(o)u=i.filter(f=>f!==\"\");else if(c){u=[];for(let f of i){if(f===\"\")continue;let h=x(f,l);u.push(...h)}}else{u=[];for(let f of i)if(f===\"\")u.push(\"\");else{let h=x(f,l);u.push(...h)}for(;u.length>0&&u[u.length-1]===\"\";)u.pop()}return{values:await Te(e,u),quoted:!1}}function cr(e,t){if(t.length!==1||t[0].type!==\"ParameterExpansion\"||t[0].operation?.type!==\"VarNamePrefix\")return null;let r=t[0].operation,s=me(e,r.prefix);if(s.length===0)return{values:[],quoted:!1};let n=T(e.state.env),a=q(e.state.env),i;if(r.star)if(a)i=s;else{let l=N(e.state.env),o=s.join(l);i=x(o,n)}else if(a)i=s;else{i=[];for(let l of s){let o=x(l,n);i.push(...o)}}return{values:i,quoted:!1}}function fr(e,t){if(t.length!==1||t[0].type!==\"ParameterExpansion\"||t[0].operation?.type!==\"ArrayKeys\")return null;let r=t[0].operation,n=P(e,r.array).map(([o])=>String(o));if(n.length===0)return{values:[],quoted:!1};let a=T(e.state.env),i=q(e.state.env),l;if(r.star)if(i)l=n;else{let o=N(e.state.env),c=n.join(o);l=x(c,a)}else if(i)l=n;else{l=[];for(let o of n){let c=x(o,a);l.push(...c)}}return{values:l,quoted:!1}}async function hr(e,t,r){let s=-1;for(let h=0;h<t.length;h++){let d=t[h];if(d.type===\"ParameterExpansion\"&&(d.parameter===\"@\"||d.parameter===\"*\")&&!d.operation){s=h;break}}if(s===-1||t.length<=1)return null;let n=Number.parseInt(e.state.env.get(\"#\")||\"0\",10),a=[];for(let h=1;h<=n;h++)a.push(e.state.env.get(String(h))||\"\");let i=\"\";for(let h=0;h<s;h++)i+=await r(e,t[h]);let l=\"\";for(let h=s+1;h<t.length;h++)l+=await r(e,t[h]);let o=T(e.state.env),c=q(e.state.env),u=Ce(e.state.env);if(n===0){let h=i+l;return{values:h?[h]:[],quoted:!1}}let f;{let h=[];for(let d=0;d<a.length;d++){let m=a[d];d===0&&(m=i+m),d===a.length-1&&(m=m+l),h.push(m)}if(c)f=h.filter(d=>d!==\"\");else if(u){f=[];for(let d of h){if(d===\"\")continue;let m=x(d,o);f.push(...m)}}else{f=[];for(let d of h)if(d===\"\")f.push(\"\");else{let m=x(d,o);f.push(...m)}for(;f.length>0&&f[f.length-1]===\"\";)f.pop()}}return f.length===0?{values:[],quoted:!1}:{values:await Te(e,f),quoted:!1}}async function mr(e,t,r){e.coverage?.hit(\"bash:expansion:word_glob\");let s=t.parts,{hasQuoted:n,hasCommandSub:a,hasArrayVar:i,hasArrayAtExpansion:l,hasParamExpansion:o,hasVarNamePrefixExpansion:c,hasIndirection:u}=Ae(s),h=r.hasBraceExpansion(s)?await r.expandWordWithBracesAsync(e,t):null;if(h&&h.length>1)return Rs(e,h,n);let d=await Is(e,s,l,c,u,r);if(d!==null)return d;let m=await Ds(e,s,r);if(m!==null)return m;let g=await xs(e,s,r);if(g!==null)return g;let E=await $s(e,s,r.expandPart);if(E!==null)return dr(e,E);if((a||i||o)&&!q(e.state.env)){let S=T(e.state.env),y=r.buildIfsCharClassPattern(S),b=await r.smartWordSplit(e,s,S,y,r.expandPart);return dr(e,b)}let A=await r.expandWordAsync(e,t);return Cs(e,t,s,A,n,r.expandWordForGlobbing)}async function Rs(e,t,r){let s=[];for(let n of t)if(!(!r&&n===\"\"))if(!r&&!e.state.options.noglob&&ne(n,e.state.shoptOptions.extglob)){let a=await Me(e,n);s.push(...a)}else s.push(n);return{values:s,quoted:!1}}async function Is(e,t,r,s,n,a){if(r){let i=Hn(e,t);if(i!==null)return i}{let i=jn(e,t);if(i!==null)return i}{let i=await zn(e,t);if(i!==null)return i}{let i=await Gn(e,t,r,a.expandPart,a.expandWordPartsAsync);if(i!==null)return i}{let i=await Qn(e,t,r,a.expandPart);if(i!==null)return i}{let i=await Zn(e,t,a.evaluateArithmetic);if(i!==null)return i}{let i=Un(e,t);if(i!==null)return i}{let i=await Bn(e,t,a.expandWordPartsAsync,a.expandPart);if(i!==null)return i}{let i=await Fn(e,t,a.expandWordPartsAsync,a.expandPart);if(i!==null)return i}if(s&&t.length===1&&t[0].type===\"DoubleQuoted\"){let i=vs(e,t);if(i!==null)return i}{let i=await Kn(e,t,n,a.expandParameterAsync,a.expandWordPartsAsync);if(i!==null)return i}{let i=await Xn(e,t);if(i!==null)return i}{let i=await Jn(e,t);if(i!==null)return i}return null}function vs(e,t){let r=t[0];if(r.type!==\"DoubleQuoted\")return null;if(r.parts.length===1&&r.parts[0].type===\"ParameterExpansion\"&&r.parts[0].operation?.type===\"VarNamePrefix\"){let s=r.parts[0].operation,n=me(e,s.prefix);return s.star?{values:[n.join(N(e.state.env))],quoted:!0}:{values:n,quoted:!0}}if(r.parts.length===1&&r.parts[0].type===\"ParameterExpansion\"&&r.parts[0].operation?.type===\"ArrayKeys\"){let s=r.parts[0].operation,a=P(e,s.array).map(([i])=>String(i));return s.star?{values:[a.join(N(e.state.env))],quoted:!0}:{values:a,quoted:!0}}return null}async function Ds(e,t,r){{let s=await er(e,t,r.evaluateArithmetic,r.expandPart);if(s!==null)return s}{let s=await tr(e,t,r.expandPart,r.expandWordPartsAsync);if(s!==null)return s}{let s=await nr(e,t,r.expandPart,r.expandWordPartsAsync);if(s!==null)return s}{let s=await rr(e,t,r.expandPart);if(s!==null)return s}return null}async function xs(e,t,r){{let s=await sr(e,t,r.expandWordPartsAsync,r.expandPart);if(s!==null)return s}{let s=await ir(e,t,r.expandWordPartsAsync,r.expandPart);if(s!==null)return s}{let s=await ar(e,t,r.expandWordPartsAsync,r.expandPart);if(s!==null)return s}{let s=await or(e,t,r.evaluateArithmetic,r.expandPart);if(s!==null)return s}{let s=await lr(e,t);if(s!==null)return s}{let s=await ur(e,t);if(s!==null)return s}{let s=cr(e,t);if(s!==null)return s}{let s=fr(e,t);if(s!==null)return s}{let s=await hr(e,t,r.expandPart);if(s!==null)return s}return null}function pr(e){if(e.type!==\"DoubleQuoted\")return null;for(let t=0;t<e.parts.length;t++){let r=e.parts[t];if(r.type!==\"ParameterExpansion\"||r.operation)continue;let s=r.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[([@*])\\]$/);if(s)return{type:\"array\",name:s[1],atIndex:t,isStar:s[2]===\"*\"};if(r.parameter===\"@\"||r.parameter===\"*\")return{type:\"positional\",atIndex:t,isStar:r.parameter===\"*\"}}return null}async function _s(e,t,r,s){let n=\"\";for(let l=0;l<r.atIndex;l++)n+=await s(e,t.parts[l]);let a=\"\";for(let l=r.atIndex+1;l<t.parts.length;l++)a+=await s(e,t.parts[l]);let i;if(r.type===\"array\"){if(i=P(e,r.name).map(([,o])=>o),i.length===0){let o=e.state.env.get(r.name);o!==void 0&&(i=[o])}}else{let l=Number.parseInt(e.state.env.get(\"#\")||\"0\",10);i=[];for(let o=1;o<=l;o++)i.push(e.state.env.get(String(o))||\"\")}if(r.isStar){let l=N(e.state.env),o=i.join(l);return[n+o+a]}if(i.length===0){let l=n+a;return l?[l]:[]}return i.length===1?[n+i[0]+a]:[n+i[0],...i.slice(1,-1),i[i.length-1]+a]}async function $s(e,t,r){if(t.length<2)return null;let s=!1;for(let o of t)if(pr(o)){s=!0;break}if(!s)return null;let n=T(e.state.env),a=q(e.state.env),i=[];for(let o of t){let c=pr(o);if(c&&o.type===\"DoubleQuoted\"){let u=await _s(e,o,c,r);i.push(u)}else if(o.type===\"DoubleQuoted\"||o.type===\"SingleQuoted\"){let u=await r(e,o);i.push([u])}else if(o.type===\"Literal\")i.push([o.value]);else if(o.type===\"ParameterExpansion\"){let u=await r(e,o);if(a)i.push(u?[u]:[]);else{let f=x(u,n);i.push(f)}}else{let u=await r(e,o);if(a)i.push(u?[u]:[]);else{let f=x(u,n);i.push(f)}}}let l=[];for(let o of i)if(o.length!==0)if(l.length===0)l.push(...o);else{let c=l.length-1;l[c]=l[c]+o[0];for(let u=1;u<o.length;u++)l.push(o[u])}return l}async function dr(e,t){if(e.state.options.noglob)return{values:t,quoted:!1};let r=[];for(let s of t)if(ne(s,e.state.shoptOptions.extglob)){let n=await Me(e,s);r.push(...n)}else r.push(s);return{values:r,quoted:!1}}async function Me(e,t){let r=new oe(e.fs,e.state.cwd,e.state.env,{globstar:e.state.shoptOptions.globstar,nullglob:e.state.shoptOptions.nullglob,failglob:e.state.shoptOptions.failglob,dotglob:e.state.shoptOptions.dotglob,extglob:e.state.shoptOptions.extglob,globskipdots:e.state.shoptOptions.globskipdots,maxGlobOperations:e.limits.maxGlobOperations}),s=await r.expand(t);if(s.length>0)return s;if(r.hasFailglob())throw new Pe(t);return r.hasNullglob()?[]:[t]}async function Cs(e,t,r,s,n,a){let i=r.some(l=>l.type===\"Glob\");if(!e.state.options.noglob&&i){let l=await a(e,t);if(ne(l,e.state.shoptOptions.extglob)){let c=await Me(e,l);if(c.length>0&&c[0]!==l)return{values:c,quoted:!1};if(c.length===0)return{values:[],quoted:!1}}let o=St(s);if(!q(e.state.env)){let c=T(e.state.env);return{values:x(o,c),quoted:!1}}return{values:[o],quoted:!1}}if(!n&&!e.state.options.noglob&&ne(s,e.state.shoptOptions.extglob)){let l=await a(e,t);if(ne(l,e.state.shoptOptions.extglob)){let o=await Me(e,l);if(o.length>0&&o[0]!==l)return{values:o,quoted:!1}}}if(s===\"\"&&!n)return{values:[],quoted:!1};if(i&&!n){let l=St(s);if(!q(e.state.env)){let o=T(e.state.env);return{values:x(l,o),quoted:!1}}return{values:[l],quoted:!1}}return{values:[s],quoted:n}}async function yr(e,t){let r=t.operation;if(!r||r.type!==\"DefaultValue\"&&r.type!==\"AssignDefault\"&&r.type!==\"UseAlternative\")return null;let s=r.word;if(!s||s.parts.length===0)return null;let n=await te(e,t.parameter),i=await v(e,t.parameter,!1)===\"\",l=r.checkEmpty??!1,o;return r.type===\"UseAlternative\"?o=n&&!(l&&i):o=!n||l&&i,o?s.parts:null}function Os(e){return e.type===\"SingleQuoted\"?!0:e.type===\"DoubleQuoted\"?e.parts.every(r=>r.type===\"Literal\"):!1}async function Ls(e,t){if(t.type!==\"ParameterExpansion\")return null;let r=await yr(e,t);if(!r||r.length<=1)return null;let s=r.some(a=>Os(a)),n=r.some(a=>a.type===\"Literal\"||a.type===\"ParameterExpansion\"||a.type===\"CommandSubstitution\"||a.type===\"ArithmeticExpansion\");return s&&n?r:null}function Ws(e){return e.type===\"DoubleQuoted\"||e.type===\"SingleQuoted\"||e.type===\"Literal\"?!1:e.type===\"Glob\"?dt(e.pattern):!(!(e.type===\"ParameterExpansion\"||e.type===\"CommandSubstitution\"||e.type===\"ArithmeticExpansion\")||e.type===\"ParameterExpansion\"&&gn(e))}async function Er(e,t,r,s,n){if(e.coverage?.hit(\"bash:expansion:word_split\"),t.length===1&&t[0].type===\"ParameterExpansion\"){let h=t[0],d=await yr(e,h);if(d&&d.length>0&&d.length>1&&d.some(g=>g.type===\"DoubleQuoted\"||g.type===\"SingleQuoted\")&&d.some(g=>g.type===\"Literal\"||g.type===\"ParameterExpansion\"||g.type===\"CommandSubstitution\"||g.type===\"ArithmeticExpansion\"))return gr(e,d,r,s,n)}let a=[],i=!1;for(let h of t){let d=Ws(h),m=h.type===\"DoubleQuoted\"||h.type===\"SingleQuoted\",g=d?await Ls(e,h):null,E=await n(e,h);a.push({value:E,isSplittable:d,isQuoted:m,mixedDefaultParts:g??void 0}),d&&(i=!0)}if(!i){let h=a.map(d=>d.value).join(\"\");return h?[h]:[]}let l=[],o=\"\",c=!1,u=!1,f=!1;for(let h of a)if(!h.isSplittable)u?h.isQuoted&&h.value===\"\"?(o!==\"\"&&l.push(o),l.push(\"\"),c=!0,o=\"\",u=!1,f=!0):h.value!==\"\"?(o!==\"\"&&l.push(o),o=h.value,u=!1,f=!1):(o+=h.value,f=!1):(o+=h.value,f=h.isQuoted&&h.value===\"\");else if(h.mixedDefaultParts){let d=await gr(e,h.mixedDefaultParts,r,s,n);if(d.length!==0)if(d.length===1)o+=d[0],c=!0;else{o+=d[0],l.push(o),c=!0;for(let m=1;m<d.length-1;m++)l.push(d[m]);o=d[d.length-1]}u=!1,f=!1}else{let{words:d,hadLeadingDelimiter:m,hadTrailingDelimiter:g}=Oe(h.value,r);if(f&&m&&o===\"\"&&(l.push(\"\"),c=!0),d.length===0)g&&(u=!0);else if(d.length===1)o+=d[0],c=!0,u=g;else{o+=d[0],l.push(o),c=!0;for(let E=1;E<d.length-1;E++)l.push(d[E]);o=d[d.length-1],u=g}f=!1}return o!==\"\"?l.push(o):l.length===0&&c&&l.push(\"\"),l}function Ts(e,t){return e.length>0&&t.includes(e[0])}async function gr(e,t,r,s,n){let a=[];for(let u of t){let h=!(u.type===\"DoubleQuoted\"||u.type===\"SingleQuoted\"),d=await n(e,u);a.push({value:d,isSplittable:h})}let i=[],l=\"\",o=!1,c=!1;for(let u of a)if(!u.isSplittable)c&&u.value!==\"\"?(l!==\"\"&&i.push(l),l=u.value,c=!1):l+=u.value;else{Ts(u.value,r)&&l!==\"\"&&(i.push(l),l=\"\",o=!0);let{words:h,hadTrailingDelimiter:d}=Oe(u.value,r);if(h.length===0)d&&(c=!0);else if(h.length===1)l+=h[0],o=!0,c=d;else{l+=h[0],i.push(l),o=!0;for(let m=1;m<h.length-1;m++)i.push(h[m]);l=h[h.length-1],c=d}}return l!==\"\"?i.push(l):i.length===0&&o&&i.push(\"\"),i}function Ar(e){switch(e.type){case\"Literal\":return e.value;case\"SingleQuoted\":return e.value;case\"Escaped\":return e.value;default:return null}}function Sr(e){switch(e.type){case\"SingleQuoted\":case\"Escaped\":case\"DoubleQuoted\":return!0;case\"Literal\":return e.value===\"\";default:return!1}}function ce(e,t,r){if(e.length>t)throw new L(`${r}: string length limit exceeded (${t} bytes)`,\"string_length\")}async function J(e,t,r=!1){let s=[];for(let n of t)s.push(await U(e,n,r));return s.join(\"\")}function Ms(e){return Sr(e)}function Al(e){if(e.parts.length===0)return!0;for(let t of e.parts)if(!Ms(t))return!1;return!0}function Vs(e,t,r=!1){let s=Ar(t);if(s!==null)return s;switch(t.type){case\"TildeExpansion\":return r?t.user===null?\"~\":`~${t.user}`:(e.coverage?.hit(\"bash:expansion:tilde\"),t.user===null?e.state.env.get(\"HOME\")??\"/home/user\":t.user===\"root\"?\"/root\":`~${t.user}`);case\"Glob\":return Nt(e,t.pattern);default:return null}}async function Pt(e,t){return Rt(e,t)}async function Sl(e,t){let r=[];for(let s of t.parts)if(s.type===\"Escaped\")r.push(`\\\\${s.value}`);else if(s.type===\"SingleQuoted\")r.push(s.value);else if(s.type===\"DoubleQuoted\"){let n=await J(e,s.parts);r.push(n)}else if(s.type===\"TildeExpansion\"){let n=await U(e,s);r.push(bt(n))}else r.push(await U(e,s));return r.join(\"\")}async function bl(e,t){let r=[];for(let s of t.parts)if(s.type===\"Escaped\"){let n=s.value;\"()|*?[]\".includes(n)?r.push(`\\\\${n}`):r.push(n)}else if(s.type===\"SingleQuoted\")r.push(X(s.value));else if(s.type===\"DoubleQuoted\"){let n=await J(e,s.parts);r.push(X(n))}else r.push(await U(e,s));return r.join(\"\")}async function br(e,t){let r=[];for(let s of t.parts)if(s.type===\"SingleQuoted\")r.push(X(s.value));else if(s.type===\"Escaped\"){let n=s.value;\"*?[]\\\\()|\".includes(n)?r.push(`\\\\${n}`):r.push(n)}else if(s.type===\"DoubleQuoted\"){let n=await J(e,s.parts);r.push(X(n))}else s.type===\"Glob\"?Tn(s.pattern)?r.push(await Vn(e,s.pattern)):r.push(Nt(e,s.pattern)):s.type===\"Literal\"?r.push(s.value):r.push(await U(e,s));return r.join(\"\")}function qe(e){for(let t of e)if(t.type===\"BraceExpansion\"||t.type===\"DoubleQuoted\"&&qe(t.parts))return!0;return!1}var kt=1e5;async function wr(e,t,r={count:0}){if(r.count>kt)return[[]];let s=[[]];for(let n of t)if(n.type===\"BraceExpansion\"){let a=[],i=!1,l=\"\";for(let u of n.items)if(u.type===\"Range\"){let f=At(u.start,u.end,u.step,u.startStr,u.endStr);if(f.expanded)for(let h of f.expanded)r.count++,a.push(h);else{i=!0,l=f.literal;break}}else{let f=await wr(e,u.word.parts,r);for(let h of f){r.count++;let d=[];for(let m of h)typeof m==\"string\"?d.push(m):d.push(await U(e,m));a.push(d.join(\"\"))}}if(i){for(let u of s)r.count++,u.push(l);continue}if(s.length*a.length>e.limits.maxBraceExpansionResults||r.count>kt)return s;let c=[];for(let u of s)for(let f of a){if(r.count++,r.count>kt)return c.length>0?c:s;c.push([...u,f])}s=c}else for(let a of s)r.count++,a.push(n);return s}async function Nr(e,t){let r=t.parts;if(!qe(r))return[await Pt(e,t)];let s=await wr(e,r),n=[];for(let a of s){let i=[];for(let l of a)typeof l==\"string\"?i.push(l):i.push(await U(e,l));n.push(qn(e,i.join(\"\")))}return n}function qs(){return{expandWordAsync:Rt,expandWordForGlobbing:br,expandWordWithBracesAsync:Nr,expandWordPartsAsync:J,expandPart:U,expandParameterAsync:Ve,hasBraceExpansion:qe,evaluateArithmetic:R,buildIfsCharClassPattern:An,smartWordSplit:Er}}async function wl(e,t){return mr(e,t,qs())}function Bs(e){for(let t of e){if(t.type===\"ParameterExpansion\")return t.parameter;if(t.type===\"Literal\")return t.value}return\"\"}function Fs(e,t){if(Number.parseInt(e.state.env.get(\"#\")||\"0\",10)<2)return!1;function s(n){for(let a of n)if(a.type===\"DoubleQuoted\"){for(let i of a.parts)if(i.type===\"ParameterExpansion\"&&i.parameter===\"@\"&&!i.operation)return!0}return!1}return s(t.parts)}async function Nl(e,t){if(Fs(e,t))return{error:`bash: $@: ambiguous redirect\n`};let r=t.parts,{hasQuoted:s}=Ae(r);if(qe(r)&&(await Nr(e,t)).length>1)return{error:`bash: ${r.map(d=>d.type===\"Literal\"?d.value:d.type===\"BraceExpansion\"?`{${d.items.map(g=>{if(g.type===\"Range\"){let E=g.step?`..${g.step}`:\"\";return`${g.startStr??g.start}..${g.endStr??g.end}${E}`}return g.word.parts.map(E=>E.type===\"Literal\"?E.value:\"\").join(\"\")}).join(\",\")}}`:\"\").join(\"\")}: ambiguous redirect\n`};let n=await Rt(e,t),{hasParamExpansion:a,hasCommandSub:i}=Ae(r);if((a||i)&&!s&&!q(e.state.env)){let f=T(e.state.env);if(x(n,f).length>1)return{error:`bash: $${Bs(r)}: ambiguous redirect\n`}}if(s||e.state.options.noglob)return{target:n};let o=await br(e,t);if(!ne(o,e.state.shoptOptions.extglob))return{target:n};let c=new oe(e.fs,e.state.cwd,e.state.env,{globstar:e.state.shoptOptions.globstar,nullglob:e.state.shoptOptions.nullglob,failglob:e.state.shoptOptions.failglob,dotglob:e.state.shoptOptions.dotglob,extglob:e.state.shoptOptions.extglob,globskipdots:e.state.shoptOptions.globskipdots,maxGlobOperations:e.limits.maxGlobOperations}),u=await c.expand(o);return u.length===0?c.hasFailglob()?{error:`bash: no match: ${n}\n`}:{target:n}:u.length===1?{target:u[0]}:{error:`bash: ${n}: ambiguous redirect\n`}}async function Rt(e,t){let r=t.parts,s=r.length;if(s===1){let i=await U(e,r[0]);return ce(i,e.limits.maxStringLength,\"word expansion\"),i}let n=[];for(let i=0;i<s;i++)n.push(await U(e,r[i]));let a=n.join(\"\");return ce(a,e.limits.maxStringLength,\"word expansion\"),a}async function U(e,t,r=!1){if(t.type===\"ParameterExpansion\")return Ve(e,t,r);let s=Vs(e,t,r);if(s!==null)return s;switch(t.type){case\"DoubleQuoted\":{let n=[];for(let a of t.parts)n.push(await U(e,a,!0));return n.join(\"\")}case\"CommandSubstitution\":{let n=wn(t.body);if(n)try{let h=await Pt(e,n.target),d=h.startsWith(\"/\")?h:`${e.state.cwd}/${h}`,m=await e.fs.readFile(d);e.state.lastExitCode=0,e.state.env.set(\"?\",\"0\");let g=m.replace(/\\n+$/,\"\");return ce(g,e.limits.maxStringLength,\"command substitution\"),g}catch(h){if(h instanceof L)throw h;return e.state.lastExitCode=1,e.state.env.set(\"?\",\"1\"),\"\"}let a=e.substitutionDepth??0,i=e.limits.maxSubstitutionDepth;if(a>=i)throw new L(`Command substitution nesting limit exceeded (${i})`,\"substitution_depth\");let l=e.substitutionDepth;e.substitutionDepth=a+1;let o=e.state.bashPid;e.state.bashPid=e.state.nextVirtualPid++;let c=new Map(e.state.env),u=e.state.cwd,f=e.state.suppressVerbose;e.state.suppressVerbose=!0;try{let h=await e.executeScript(t.body),d=h.exitCode;e.state.env=c,e.state.cwd=u,e.state.suppressVerbose=f,e.state.lastExitCode=d,e.state.env.set(\"?\",String(d)),h.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||\"\")+h.stderr),e.state.bashPid=o,e.substitutionDepth=l;let m=h.stdout.replace(/\\n+$/,\"\");return ce(m,e.limits.maxStringLength,\"command substitution\"),m}catch(h){if(e.state.env=c,e.state.cwd=u,e.state.bashPid=o,e.substitutionDepth=l,e.state.suppressVerbose=f,h instanceof L)throw h;if(h instanceof K){e.state.lastExitCode=h.exitCode,e.state.env.set(\"?\",String(h.exitCode)),h.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||\"\")+h.stderr);let d=h.stdout.replace(/\\n+$/,\"\");return ce(d,e.limits.maxStringLength,\"command substitution\"),d}throw h}}case\"ArithmeticExpansion\":{let n=t.expression.originalText;if(n&&/\\$[a-zA-Z_][a-zA-Z0-9_]*(?![{[(])/.test(n)){let i=await bn(e,n),l=new V,o=M(l,i);return String(await R(e,o.expression,!0))}return String(await R(e,t.expression.expression,!0))}case\"BraceExpansion\":{let n=[];for(let a of t.items)if(a.type===\"Range\"){let i=At(a.start,a.end,a.step,a.startStr,a.endStr);if(i.expanded)n.push(...i.expanded);else return i.literal}else n.push(await Pt(e,a.word));return n.join(\" \")}default:return\"\"}}async function Ve(e,t,r=!1){let{parameter:s}=t,{operation:n}=t,a=s.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[(.+)\\]$/);if(a){let[,h,d]=a;if(e.state.associativeArrays?.has(h)||d.includes(\"$(\")||d.includes(\"`\")||d.includes(\"${\")){let g=await Et(e,d);s=`${h}[${g}]`}}else if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(s)&&W(e,s)){let h=he(e,s);if(h&&h!==s){let d=h.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[(.+)\\]$/);if(d){let[,m,g]=d;if(e.state.associativeArrays?.has(m)||g.includes(\"$(\")||g.includes(\"`\")||g.includes(\"${\")){let A=await Et(e,g);s=`${m}[${A}]`}}}}let i=n&&(n.type===\"DefaultValue\"||n.type===\"AssignDefault\"||n.type===\"UseAlternative\"||n.type===\"ErrorIfUnset\"),l=await v(e,s,!i);if(!n)return l;let o=!await te(e,s),{isEmpty:c,effectiveValue:u}=Wn(e,s,l,r),f={value:l,isUnset:o,isEmpty:c,effectiveValue:u,inDoubleQuotes:r};switch(n.type){case\"DefaultValue\":return Nn(e,n,f,J);case\"AssignDefault\":return kn(e,s,n,f,J);case\"ErrorIfUnset\":return Pn(e,s,n,f,J);case\"UseAlternative\":return Rn(e,n,f,J);case\"PatternRemoval\":{let h=await In(e,l,n,J,U);return ce(h,e.limits.maxStringLength,\"pattern removal\"),h}case\"PatternReplacement\":{let h=await vn(e,l,n,J,U);return ce(h,e.limits.maxStringLength,\"pattern replacement\"),h}case\"Length\":return Dn(e,s,l);case\"LengthSliceError\":throw new re(s);case\"BadSubstitution\":throw new re(n.text);case\"Substring\":return xn(e,s,l,n);case\"CaseModification\":{let h=await _n(e,l,n,J,Ve);return ce(h,e.limits.maxStringLength,\"case modification\"),h}case\"Transform\":return $n(e,s,l,o,n);case\"Indirection\":return Cn(e,s,l,o,n,Ve,r);case\"ArrayKeys\":return On(e,n);case\"VarNamePrefix\":return Ln(e,n);default:return l}}export{xi as a,_i as b,pe as c,G as d,M as e,V as f,di as g,mt as h,Ci as i,gt as j,Oi as k,En as l,T as m,Wi as n,Ti as o,W as p,Vi as q,qi as r,Bi as s,Fi as t,us as u,he as v,Se as w,zi as x,P as y,be as z,v as A,X as B,bt as C,pa as D,wt as E,da as F,ma as G,ga as H,Al as I,Pt as J,Sl as K,bl as L,wl as M,Fs as N,Nl as O,R as P};\n","import { join, relative, sep } from \"node:path\";\nimport { readdir, stat } from \"node:fs/promises\";\nimport { readFileSync } from \"node:fs\";\n//#region src/discovery/entry-from-file.ts\nconst SOURCE_EXT = /\\.(ts|mts|mjs|js)$/;\nconst DECLARATION_FILE$1 = /\\.d\\.(ts|mts|cts)$/;\nfunction entryIdFromFile(rootDir, filePath, options) {\n\tif (DECLARATION_FILE$1.test(filePath)) return null;\n\tconst baseName = filePath.split(sep).at(-1) ?? \"\";\n\tif (/\\.(int\\.)?test\\.(ts|mts)$/.test(baseName)) return null;\n\tconst segments = relative(rootDir, filePath).replace(SOURCE_EXT, \"\").split(sep).filter((segment) => segment.length > 0);\n\tif (segments.length === 1) return segments[0] ?? null;\n\tconst last = segments.at(-1);\n\tconst entryNames = new Set([options.nestedEntry]);\n\tif (options.allowIndex !== false) entryNames.add(\"index\");\n\tif (!last || !entryNames.has(last)) return null;\n\tconst id = segments.slice(0, -1).join(\"/\");\n\treturn id.length > 0 ? id : null;\n}\n//#endregion\n//#region src/discovery/walk-typescript-files.ts\nconst SOURCE_FILE = /\\.(ts|mts|mjs|js)$/;\nconst TEST_FILE = /\\.(int\\.)?test\\.(ts|mts)$/;\nconst DECLARATION_FILE = /\\.d\\.(ts|mts|cts)$/;\nconst JUNK_FILE = /^\\._|\\.DS_Store$/;\nasync function walkTypeScriptFiles(dir) {\n\tlet names;\n\ttry {\n\t\tnames = await readdir(dir);\n\t} catch (error) {\n\t\tif (error.code === \"ENOENT\") return [];\n\t\tthrow error;\n\t}\n\tconst files = [];\n\tfor (const name of names) {\n\t\tconst path = join(dir, name);\n\t\tif ((await stat(path)).isDirectory()) files.push(...await walkTypeScriptFiles(path));\n\t\telse if (!JUNK_FILE.test(name) && SOURCE_FILE.test(name) && !DECLARATION_FILE.test(name) && !TEST_FILE.test(name)) files.push(path);\n\t}\n\treturn files;\n}\n//#endregion\n//#region src/discovery/discover-entries.ts\nasync function discoverEntries(rootDir, options) {\n\tconst files = await walkTypeScriptFiles(rootDir);\n\tconst byKey = /* @__PURE__ */ new Map();\n\tfor (const filePath of files) {\n\t\tconst id = entryIdFromFile(rootDir, filePath, options);\n\t\tif (!id) continue;\n\t\tconst key = options.formatKey(id);\n\t\tconst moduleFile = relative(rootDir, filePath);\n\t\tconst existing = byKey.get(key);\n\t\tif (existing) throw new Error(`Duplicate ${options.duplicateLabel} ${key}: ${existing.filePath} and ${filePath}`);\n\t\tbyKey.set(key, {\n\t\t\tkey,\n\t\t\tfilePath,\n\t\t\tmoduleFile\n\t\t});\n\t}\n\treturn [...byKey.values()];\n}\n//#endregion\n//#region src/discovery/discover-module-entries.ts\nasync function discoverModuleFileEntries(rootDir, options) {\n\treturn (await discoverEntries(rootDir, {\n\t\tnestedEntry: options.nestedEntry,\n\t\tformatKey: (id) => id,\n\t\tduplicateLabel: options.duplicateLabel\n\t})).filter((entry) => options.shouldDiscoverFile?.(entry.filePath) ?? true).map(({ filePath, moduleFile }) => ({\n\t\tfilePath,\n\t\tmoduleFile\n\t}));\n}\nfunction moduleFileKeyFromPath(rootDir, filePath, nestedEntry) {\n\treturn entryIdFromFile(rootDir, filePath, { nestedEntry });\n}\n//#endregion\n//#region src/discovery/keystroke-ignore-directive.ts\nconst HEADER_BYTES = 2048;\nconst DIRECTIVE_RE = /@keystroke\\s+ignore(?::([a-z]+))?/;\n/** Parse `@keystroke ignore` directives from a file header snippet. */\nfunction parseKeystrokeIgnoreDirective(header) {\n\tfor (const line of header.slice(0, HEADER_BYTES).split(\"\\n\")) {\n\t\tconst trimmed = line.trim();\n\t\tif (trimmed.length === 0) continue;\n\t\tif (!isCommentLine(trimmed)) break;\n\t\tconst match = DIRECTIVE_RE.exec(trimmed);\n\t\tif (!match) continue;\n\t\tconst scope = match[1];\n\t\tif (!scope) return \"ignore\";\n\t\tif (scope === \"deploy\") return \"ignore:deploy\";\n\t\tthrow new Error(`Unknown @keystroke ignore target \"${scope}\" in directive \"@keystroke ignore:${scope}\"`);\n\t}\n\treturn null;\n}\n/** Read `@keystroke ignore` directives from the top of a module file. */\nfunction readKeystrokeIgnoreDirective(filePath) {\n\treturn parseKeystrokeIgnoreDirective(readFileSync(filePath, \"utf8\").slice(0, HEADER_BYTES));\n}\n/** Whether a discovered module file should be skipped for the given build phase. */\nfunction shouldSkipKeystrokeModuleFile(directive, phase) {\n\tif (!directive) return false;\n\tif (directive === \"ignore\") return true;\n\treturn phase === \"deploy\";\n}\nfunction isCommentLine(line) {\n\treturn line.startsWith(\"//\") || line.startsWith(\"/*\") || line.startsWith(\"*\");\n}\n//#endregion\n//#region src/discovery/validate-unique-module-keys.ts\nfunction validateUniqueModuleKeys(entries) {\n\tconst byKey = /* @__PURE__ */ new Map();\n\tfor (const entry of entries) {\n\t\tconst list = byKey.get(entry.key) ?? [];\n\t\tlist.push(entry);\n\t\tbyKey.set(entry.key, list);\n\t}\n\tfor (const [key, clashes] of byKey) {\n\t\tif (clashes.length <= 1) continue;\n\t\tconst detail = clashes.map((entry) => `${entry.kind} (${entry.filePath})`).join(\", \");\n\t\tthrow new Error(`Duplicate module key \"${key}\": ${detail}`);\n\t}\n}\n//#endregion\nexport { discoverModuleFileEntries as a, walkTypeScriptFiles as c, shouldSkipKeystrokeModuleFile as i, entryIdFromFile as l, parseKeystrokeIgnoreDirective as n, moduleFileKeyFromPath as o, readKeystrokeIgnoreDirective as r, discoverEntries as s, validateUniqueModuleKeys as t };\n\n//# sourceMappingURL=discovery-CWjr_liZ.mjs.map","import { a as writeWorkspaceFileIfAbsent, n as resolveAgentRoot, t as ensureWorkspaceDir } from \"./sandbox-dirs-DMDj1_61.mjs\";\nimport { createRequire } from \"node:module\";\nimport { basename, dirname, join, relative, resolve } from \"node:path\";\nimport { z } from \"zod\";\nimport { existsSync, readFileSync, readdirSync, statSync } from \"node:fs\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { fileURLToPath } from \"node:url\";\n//#region src/files/schemas.ts\nconst SandboxModeSchema = z.enum([\"in-process\", \"vm\"]);\nconst SandboxFileContentSchema = z.object({\n\tpath: z.string(),\n\tfile: z.string()\n});\n/** Destination path under `/workspace`. For `dir`, used as a prefix. */\nconst SandboxFileSchema = z.object({\n\tpath: z.string(),\n\t/** Single file body — typically from a build-time import (`import doc from \"./doc.md\"`). */\n\tfile: z.string().optional(),\n\t/** Directory contents — each path is relative to `path`. */\n\tdir: z.array(SandboxFileContentSchema).optional()\n});\n/** Author-facing project file set reference under `src/files/`. */\nconst SandboxProjectFilesSchema = z.union([z.literal(true), z.string()]);\n/** Author-facing sandbox files: inline entries or a project file set. */\nconst SandboxFilesInputSchema = z.union([z.array(SandboxFileSchema), SandboxProjectFilesSchema]);\n/** Author-facing sandbox definition (`defineSandbox`, agent `sandbox`). */\nconst SandboxDefinitionInputSchema = z.object({\n\tkey: z.string().optional(),\n\t/** Sandbox execution mode. Defaults to in-process when omitted. */\n\tmode: SandboxModeSchema.optional(),\n\tfiles: SandboxFilesInputSchema.optional()\n});\n/** Normalized sandbox definition after project file sets are resolved. */\nconst SandboxDefinitionSchema = z.object({\n\tkey: z.string().optional(),\n\tmode: SandboxModeSchema.optional(),\n\tfiles: z.array(SandboxFileSchema).optional()\n});\n//#endregion\n//#region src/files/define-sandbox.ts\n/** Define a reusable sandbox file layout. */\nfunction defineSandbox(def) {\n\treturn def;\n}\n//#endregion\n//#region src/files/flatten-sandbox-files.ts\n/** Expand directory entries into flat `{ path, file }` records under `/workspace`. */\nfunction flattenSandboxFiles(files) {\n\tif (!files?.length) return [];\n\tconst flattened = [];\n\tfor (const entry of files) {\n\t\tif (entry.dir !== void 0) {\n\t\t\tconst prefix = entry.path.replace(/\\/+$/, \"\");\n\t\t\tfor (const child of entry.dir) flattened.push({\n\t\t\t\tpath: prefix ? `${prefix}/${child.path}` : child.path,\n\t\t\t\tfile: child.file\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (entry.file === void 0) continue;\n\t\tflattened.push({\n\t\t\tpath: entry.path,\n\t\t\tfile: entry.file\n\t\t});\n\t}\n\treturn flattened;\n}\n//#endregion\n//#region src/files/materialize-sandbox.ts\nasync function materializeSandbox(options) {\n\tconst root = resolveAgentRoot(options.workspacesRoot, options.agentId);\n\tawait ensureWorkspaceDir(root);\n\tconst files = flattenSandboxFiles(options.definition?.files);\n\tif (files.length) await applySandboxFiles(root, files);\n\treturn {\n\t\troot,\n\t\tagentId: options.agentId,\n\t\t...options.definition !== void 0 ? { definition: options.definition } : {}\n\t};\n}\nasync function applySandboxFiles(root, files) {\n\tfor (const entry of files) await writeWorkspaceFileIfAbsent(resolve(root, entry.path), entry.file);\n}\n//#endregion\n//#region src/files/pack-dir.ts\nconst SKIP_DIRS$1 = new Set([\".git\", \"node_modules\"]);\n/** Recursively read a host file or directory into sandbox-relative `{ path, file }` entries. */\nfunction packDirFromDisk(rootPath) {\n\tconst stat = statSync(rootPath);\n\tif (stat.isFile()) return [{\n\t\tpath: basename(rootPath),\n\t\tfile: readFileSync(rootPath, \"utf8\")\n\t}];\n\tif (!stat.isDirectory()) throw new Error(`Expected a file or directory at ${rootPath}`);\n\tconst files = [];\n\twalkDir(rootPath, rootPath, files);\n\treturn files;\n}\nfunction walkDir(rootPath, currentPath, files) {\n\tfor (const name of readdirSync(currentPath)) {\n\t\tif (SKIP_DIRS$1.has(name)) continue;\n\t\tconst entryPath = join(currentPath, name);\n\t\tconst stat = statSync(entryPath);\n\t\tif (stat.isDirectory()) {\n\t\t\twalkDir(rootPath, entryPath, files);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!stat.isFile()) continue;\n\t\tfiles.push({\n\t\t\tpath: relative(rootPath, entryPath),\n\t\t\tfile: readFileSync(entryPath, \"utf8\")\n\t\t});\n\t}\n}\n//#endregion\n//#region src/files/pack-asset-dirs.ts\nconst SKIP_DIRS = new Set([\".git\", \"node_modules\"]);\n/** Pack every subdir under `src/skills/` and `src/files/` into an asset manifest. */\nfunction packAssetDirs(appRoot, srcDir = \"src\") {\n\treturn {\n\t\tskills: packAssetRoot(join(appRoot, srcDir, \"skills\")),\n\t\tfiles: packAssetRoot(join(appRoot, srcDir, \"files\"))\n\t};\n}\nfunction packAssetRoot(rootPath) {\n\tif (!statSync(rootPath, { throwIfNoEntry: false })?.isDirectory()) return {};\n\tconst manifest = {};\n\tfor (const name of readdirSync(rootPath)) {\n\t\tif (SKIP_DIRS.has(name)) continue;\n\t\tconst entryPath = join(rootPath, name);\n\t\tif (!statSync(entryPath).isDirectory()) continue;\n\t\tmanifest[name] = packDirFromDisk(entryPath);\n\t}\n\treturn manifest;\n}\n//#endregion\n//#region src/files/app-root-scope.ts\nconst appRootStorage = new AsyncLocalStorage();\n/** Run with an explicit user-app root (parallel-safe alternative to mutating `KEYSTROKE_ROOT`). */\nfunction runWithAppRoot(appRoot, fn) {\n\treturn appRootStorage.run(appRoot, fn);\n}\nfunction getBoundAppRoot() {\n\treturn appRootStorage.getStore();\n}\n//#endregion\n//#region src/files/resolve-sandbox-definition.ts\nfunction parseAssetModule(source) {\n\tconst trimmed = source.trim();\n\tif (!trimmed.startsWith(\"export default \")) return null;\n\tconst json = trimmed.slice(15).replace(/;\\s*$/, \"\");\n\treturn JSON.parse(json);\n}\nfunction loadBuiltManifest(appRoot) {\n\tconst candidates = [\n\t\tjoin(appRoot, \"dist/.keystroke/assets.mjs\"),\n\t\tjoin(appRoot, \"dist/.agent/assets.mjs\"),\n\t\tjoin(appRoot, \".keystroke/assets.mjs\"),\n\t\tjoin(appRoot, \".agent/assets.mjs\")\n\t];\n\tfor (const candidate of candidates) {\n\t\tif (!existsSync(candidate)) continue;\n\t\ttry {\n\t\t\tconst fromSource = parseAssetModule(readFileSync(candidate, \"utf8\"));\n\t\t\tif (fromSource) return fromSource;\n\t\t} catch {}\n\t\ttry {\n\t\t\tconst mod = createRequire(join(appRoot, \"package.json\"))(candidate);\n\t\t\treturn mod.default ?? mod;\n\t\t} catch {}\n\t}\n\treturn null;\n}\nfunction loadAssetManifest(appRoot) {\n\treturn loadBuiltManifest(appRoot) ?? packAssetDirs(appRoot);\n}\nfunction resolveProjectSetKey(set, options) {\n\tif (set === true) {\n\t\tconst projectSlug = options.projectSlug?.trim();\n\t\tif (!projectSlug) throw new Error(\"sandbox files: true requires a project slug at resolve time (e.g. defineAgent({ slug: \\\"support\\\", sandbox: defineSandbox({ files: true }) }))\");\n\t\treturn projectSlug;\n\t}\n\treturn set;\n}\nfunction loadProjectFileSet(set, options) {\n\tconst setKey = resolveProjectSetKey(set, options);\n\tconst files = loadAssetManifest(options.appRoot ?? getBoundAppRoot() ?? process.env.KEYSTROKE_ROOT ?? process.cwd()).files[setKey];\n\tif (!files?.length) throw new Error(`Unknown file set \"${setKey}\" — expected src/files/${setKey}/`);\n\treturn files.map((entry) => ({\n\t\tpath: entry.path,\n\t\tfile: entry.file\n\t}));\n}\nfunction resolveSandboxFiles(files, options) {\n\tif (files === void 0) return;\n\tif (Array.isArray(files)) return files;\n\treturn loadProjectFileSet(files, options);\n}\n/** Resolve author sandbox input into a normalized definition for materialization/runtime. */\nfunction resolveSandboxDefinition(input, options = {}) {\n\tconst resolvedFiles = resolveSandboxFiles(input.files, options);\n\treturn {\n\t\t...input.key !== void 0 ? { key: input.key } : {},\n\t\t...input.mode !== void 0 ? { mode: input.mode } : {},\n\t\t...resolvedFiles !== void 0 ? { files: resolvedFiles } : {}\n\t};\n}\n//#endregion\n//#region src/files/resolve-app-root.ts\n/** Walk upward from a module file to find the user app root (`src/agents`, `src/skills`, etc.). */\nfunction resolveAppRoot(fromPath) {\n\tlet dir = statSync(fromPath).isDirectory() ? fromPath : dirname(fromPath);\n\twhile (dir !== dirname(dir)) {\n\t\tif (hasAppLayout(dir)) return dir;\n\t\tdir = dirname(dir);\n\t}\n\treturn process.env.KEYSTROKE_ROOT ?? process.cwd();\n}\n/** Resolve app root from an agent (or other) module URL. */\nfunction resolveAppRootFromModule(moduleUrl) {\n\treturn resolveAppRoot(fileURLToPath(moduleUrl));\n}\nfunction hasAppLayout(dir) {\n\tconst src = join(dir, \"src\");\n\tconst dist = join(dir, \"dist\");\n\treturn existsSync(join(src, \"agents\")) || existsSync(join(src, \"skills\")) || existsSync(join(src, \"files\")) || existsSync(join(dist, \"agents\")) || existsSync(join(dist, \".keystroke\", \"assets.mjs\"));\n}\n//#endregion\nexport { SandboxModeSchema as _, getBoundAppRoot as a, packDirFromDisk as c, defineSandbox as d, SandboxDefinitionInputSchema as f, SandboxFilesInputSchema as g, SandboxFileSchema as h, resolveSandboxDefinition as i, materializeSandbox as l, SandboxFileContentSchema as m, resolveAppRootFromModule as n, runWithAppRoot as o, SandboxDefinitionSchema as p, loadAssetManifest as r, packAssetDirs as s, resolveAppRoot as t, flattenSandboxFiles as u, SandboxProjectFilesSchema as v };\n\n//# sourceMappingURL=files-BOUCjfCQ.mjs.map","/** TypeBox instantiation metrics */\nexport const Metrics = {\n assign: 0,\n create: 0,\n clone: 0,\n discard: 0,\n update: 0\n};\n","import * as String from './string.mjs';\n// --------------------------------------------------------------------------\n// Guards\n// --------------------------------------------------------------------------\n/** Returns true if this value is an array */\nexport function IsArray(value) {\n return Array.isArray(value);\n}\n/** Returns true if this value is an async iterator */\nexport function IsAsyncIterator(value) {\n return IsObject(value) && Symbol.asyncIterator in value;\n}\n/** Returns true if this value is bigint */\nexport function IsBigInt(value) {\n return IsEqual(typeof value, 'bigint');\n}\n/** Returns true if this value is a boolean */\nexport function IsBoolean(value) {\n return IsEqual(typeof value, 'boolean');\n}\n/** Returns true if this value is a constructor */\nexport function IsConstructor(value) {\n if (IsUndefined(value) || !IsFunction(value))\n return false;\n const result = Function.prototype.toString.call(value);\n if (/^class\\s/.test(result))\n return true;\n if (/\\[native code\\]/.test(result))\n return true;\n return false;\n}\n/** Returns true if this value is a function */\nexport function IsFunction(value) {\n return IsEqual(typeof value, 'function');\n}\n/** Returns true if this value is integer */\nexport function IsInteger(value) {\n return Number.isInteger(value);\n}\n/** Returns true if this value is an iterator */\nexport function IsIterator(value) {\n return IsObject(value) && Symbol.iterator in value;\n}\n/** Returns true if this value is null */\nexport function IsNull(value) {\n return IsEqual(value, null);\n}\n/** Returns true if this value is number */\nexport function IsNumber(value) {\n return Number.isFinite(value);\n}\n/** Returns true if this value is an object but not an array */\nexport function IsObjectNotArray(value) {\n return IsObject(value) && !IsArray(value);\n}\n/** Returns true if this value is an object */\nexport function IsObject(value) {\n return IsEqual(typeof value, 'object') && !(IsNull(value));\n}\n/** Returns true if this value is string */\nexport function IsString(value) {\n return IsEqual(typeof value, 'string');\n}\n/** Returns true if this value is symbol */\nexport function IsSymbol(value) {\n return IsEqual(typeof value, 'symbol');\n}\n/** Returns true if this value is undefined */\nexport function IsUndefined(value) {\n return IsEqual(value, undefined);\n}\n// --------------------------------------------------------------------------\n// Relational\n// --------------------------------------------------------------------------\nexport function IsEqual(left, right) {\n return left === right;\n}\nexport function IsGreaterThan(left, right) {\n return left > right;\n}\nexport function IsLessThan(left, right) {\n return left < right;\n}\nexport function IsLessEqualThan(left, right) {\n return left <= right;\n}\nexport function IsGreaterEqualThan(left, right) {\n return left >= right;\n}\n// --------------------------------------------------------------------------\n// MultipleOf\n// --------------------------------------------------------------------------\nexport function IsMultipleOf(dividend, divisor) {\n if (IsBigInt(dividend) || IsBigInt(divisor)) {\n return BigInt(dividend) % BigInt(divisor) === 0n;\n }\n const tolerance = 1e-10;\n if (!IsNumber(dividend))\n return true;\n if (IsInteger(dividend) && (1 / divisor) % 1 === 0)\n return true;\n const mod = dividend % divisor;\n return Math.min(Math.abs(mod), Math.abs(mod - divisor)) < tolerance;\n}\n// ------------------------------------------------------------------\n// IsClassInstance\n// ------------------------------------------------------------------\n/** Returns true if the value appears to be an instance of a class. */\nexport function IsClassInstance(value) {\n if (!IsObject(value))\n return false;\n const proto = globalThis.Object.getPrototypeOf(value);\n if (IsNull(proto))\n return false;\n return IsEqual(typeof proto.constructor, 'function') &&\n !(IsEqual(proto.constructor, globalThis.Object) ||\n IsEqual(proto.constructor.name, 'Object'));\n}\n// ------------------------------------------------------------------\n// IsValueLike\n// ------------------------------------------------------------------\nexport function IsValueLike(value) {\n return IsBigInt(value) ||\n IsBoolean(value) ||\n IsNull(value) ||\n IsNumber(value) ||\n IsString(value) ||\n IsUndefined(value);\n}\n// --------------------------------------------------------------------------\n// String\n// --------------------------------------------------------------------------\n/** Returns the number of grapheme clusters in the string */\nexport function GraphemeCount(value) {\n return String.GraphemeCount(value);\n}\n/** Returns true if the string has at most the given number of graphemes */\nexport function IsMaxLength(value, length) {\n return String.IsMaxLengthFast(value, length);\n}\n/** Returns true if the string has at least the given number of graphemes */\nexport function IsMinLength(value, length) {\n return String.IsMinLengthFast(value, length);\n}\n// --------------------------------------------------------------------------\n// Array\n// --------------------------------------------------------------------------\n/** Returns true if all elements from offset satisfy the callback, short-circuiting on the first failure */\nexport function Every(value, offset, callback) {\n for (let index = offset; index < value.length; index++) {\n if (!callback(value[index], index))\n return false;\n }\n return true;\n}\n/** Returns true if all elements from offset satisfy the callback, visiting every element regardless of failure */\nexport function EveryAll(value, offset, callback) {\n let result = true;\n for (let index = offset; index < value.length; index++) {\n if (!callback(value[index], index))\n result = false;\n }\n return result;\n}\n/** Takes the left-most element from an array and dispatches to the true arm, or the false arm if empty */\nexport function TakeLeft(array, true_, false_) {\n return (IsEqual(array.length, 0) ? false_() : true_(array[0], array.slice(1)));\n}\n// --------------------------------------------------------------------------\n// Object\n// --------------------------------------------------------------------------\n/** Returns true if the PropertyKey is Unsafe (ref: prototype-pollution). */\nexport function IsUnsafePropertyKey(key) {\n return IsEqual(key, '__proto__') || IsEqual(key, 'constructor') || IsEqual(key, 'prototype');\n}\n/** Returns true if this value has this property key */\nexport function HasPropertyKey(value, key) {\n return IsUnsafePropertyKey(key) ? Object.prototype.hasOwnProperty.call(value, key) : key in value;\n}\n/** Returns object entries as `[RegExp, Value][]` */\nexport function EntriesRegExp(value) {\n return Keys(value).map((key) => [new RegExp(`^${key}$`), value[key]]);\n}\n/** Returns object entries as `[string, Value][]` */\nexport function Entries(value) {\n return Object.entries(value);\n}\n/** Returns property keys for this object via `Object.getOwnPropertyKeys({ ... })` */\nexport function Keys(value) {\n return Object.getOwnPropertyNames(value);\n}\n/** Returns the property keys for this object via `Object.getOwnPropertyKeys({ ... })` */\nexport function Symbols(value) {\n return Object.getOwnPropertySymbols(value);\n}\n/** Returns the property values for the given object via `Object.values()` */\nexport function Values(value) {\n return Object.values(value);\n}\n// ------------------------------------------------------------------\n// IsDeepEqual\n// ------------------------------------------------------------------\nfunction DeepEqualObject(left, right) {\n if (!IsObject(right))\n return false;\n const keys = Keys(left);\n return IsEqual(keys.length, Keys(right).length) &&\n keys.every((key) => IsDeepEqual(left[key], right[key]));\n}\nfunction DeepEqualArray(left, right) {\n return IsArray(right) && IsEqual(left.length, right.length) &&\n left.every((_, index) => IsDeepEqual(left[index], right[index]));\n}\n/** Tests values for deep equality */\nexport function IsDeepEqual(left, right) {\n return (IsArray(left) ? DeepEqualArray(left, right) : IsObject(left) ? DeepEqualObject(left, right) : IsEqual(left, right));\n}\n","// deno-fmt-ignore-file\nimport { Guard } from '../../guard/index.mjs';\nimport { Metrics } from './metrics.mjs';\n// ------------------------------------------------------------------\n// Guard\n// ------------------------------------------------------------------\nfunction IsGuard(value) {\n return Guard.IsObject(value) && Guard.HasPropertyKey(value, '~guard');\n}\nfunction FromGuard(value) {\n return value; // non-clonable\n}\n// ------------------------------------------------------------------\n// Array\n// ------------------------------------------------------------------\nfunction FromArray(value) {\n return value.map((value) => FromValue(value));\n}\n// ------------------------------------------------------------------\n// Object\n// ------------------------------------------------------------------\nfunction FromObject(value) {\n const result = {};\n const descriptors = Object.getOwnPropertyDescriptors(value);\n for (const key of Object.keys(descriptors)) {\n const descriptor = descriptors[key];\n if (Guard.HasPropertyKey(descriptor, 'value')) {\n Object.defineProperty(result, key, { ...descriptor, value: FromValue(descriptor.value) });\n }\n }\n return result;\n}\n// ------------------------------------------------------------------\n// RegExp\n// ------------------------------------------------------------------\nfunction FromRegExp(value) {\n return new RegExp(value.source, value.flags);\n}\n// ------------------------------------------------------------------\n// RegExp\n// ------------------------------------------------------------------\nfunction FromUnknown(value) {\n return value;\n}\n// ------------------------------------------------------------------\n// Value\n// ------------------------------------------------------------------\nfunction FromValue(value) {\n return (value instanceof RegExp ? FromRegExp(value) :\n IsGuard(value) ? FromGuard(value) :\n Guard.IsArray(value) ? FromArray(value) :\n Guard.IsObject(value) ? FromObject(value) :\n FromUnknown(value));\n}\n/**\n * Clones a value using the TypeBox type cloning strategy. This function preserves non-enumerable\n * properties from the source value. This is to ensure cloned types retain discriminable\n * hidden properties.\n */\nexport function Clone(value) {\n Metrics.clone += 1;\n return FromValue(value);\n}\n","import { Guard } from '../../guard/index.mjs';\n// Internal mutable state\nconst settings = {\n immutableTypes: false,\n maxErrors: 8,\n useAcceleration: true,\n exactOptionalPropertyTypes: false,\n enumerableKind: false,\n correctiveParse: false\n};\n/** Resets system settings to defaults */\nexport function Reset() {\n settings.immutableTypes = false;\n settings.maxErrors = 8;\n settings.useAcceleration = true;\n settings.exactOptionalPropertyTypes = false;\n settings.enumerableKind = false;\n settings.correctiveParse = false;\n}\n/** Sets system settings */\nexport function Set(options) {\n for (const key of Guard.Keys(options)) {\n const value = options[key];\n if (value !== undefined) {\n Object.defineProperty(settings, key, { value });\n }\n }\n}\n/** Gets current system settings */\nexport function Get() {\n return settings;\n}\n","// deno-lint-ignore-file no-explicit-any\n// deno-fmt-ignore-file\nimport { Settings } from '../settings/index.mjs';\nimport { Metrics } from './metrics.mjs';\nfunction MergeHidden(left, right) {\n for (const key of Object.keys(right)) {\n Object.defineProperty(left, key, {\n configurable: true,\n writable: true,\n enumerable: false,\n value: right[key]\n });\n }\n return left;\n}\nfunction Merge(left, right) {\n return { ...left, ...right };\n}\n/**\n * Creates an object with hidden, enumerable, and optional property sets. This function\n * ensures types are instantiated according to configuration rules for enumerable and\n * non-enumerable properties.\n */\nexport function Create(hidden, enumerable, options = {}) {\n Metrics.create += 1;\n const settings = Settings.Get();\n const withOptions = Merge(enumerable, options);\n const withHidden = settings.enumerableKind ? Merge(withOptions, hidden) : MergeHidden(withOptions, hidden);\n return settings.immutableTypes ? Object.freeze(withHidden) : withHidden;\n}\n","// deno-fmt-ignore-file\nimport { Settings } from '../settings/index.mjs';\nimport { Metrics } from './metrics.mjs';\nimport { Clone } from './clone.mjs';\n/**\n * Updates a value with new properties while preserving property enumerability. Use this function to modify\n * existing types without altering their configuration.\n */\nexport function Update(current, hidden, enumerable) {\n Metrics.update += 1;\n const settings = Settings.Get();\n const result = Clone(current);\n // hidden\n for (const key of Object.keys(hidden)) {\n Object.defineProperty(result, key, {\n configurable: true,\n writable: true,\n enumerable: settings.enumerableKind,\n value: hidden[key]\n });\n }\n // enumerable\n for (const key of Object.keys(enumerable)) {\n Object.defineProperty(result, key, {\n configurable: true,\n enumerable: true,\n writable: true,\n value: enumerable[key]\n });\n }\n return result;\n}\n","// deno-lint-ignore-file\n// deno-fmt-ignore-file\nimport { Guard } from '../../guard/index.mjs';\n// ------------------------------------------------------------------\n// Kind\n// ------------------------------------------------------------------\nexport function IsKind(value, kind) {\n return Guard.IsObject(value) && Guard.HasPropertyKey(value, '~kind') && Guard.IsEqual(value[\"~kind\"], kind);\n}\n// ------------------------------------------------------------------\n// Guard\n// ------------------------------------------------------------------\nexport function IsSchema(value) {\n return Guard.IsObject(value);\n}\n","// deno-fmt-ignore-file\nimport { Guard } from '../../guard/index.mjs';\nimport { Memory } from '../../system/memory/index.mjs';\nimport { IsSchema } from './schema.mjs';\n/** Removes Optional from the given type. */\nexport function OptionalRemove(type) {\n const result = Memory.Discard(type, ['~optional']);\n return result;\n}\n/** Adds Optional to the given type. */\nexport function OptionalAdd(type) {\n return Memory.Update(type, { '~optional': true }, {});\n}\n// ------------------------------------------------------------------\n// Factory\n// ------------------------------------------------------------------\n/** Applies an Optional modifier to the given type. */\nexport function Optional(type) {\n return OptionalAdd(type);\n}\n// ------------------------------------------------------------------\n// Guard\n// ------------------------------------------------------------------\n/** Returns true if the given value is TOptional */\nexport function IsOptional(value) {\n return IsSchema(value) && Guard.HasPropertyKey(value, '~optional');\n}\n","// deno-fmt-ignore-file\nimport { Memory } from '../../system/memory/index.mjs';\nimport { IsKind } from './schema.mjs';\n// ------------------------------------------------------------------\n// Factory\n// ------------------------------------------------------------------\n/** Creates an Array type. */\nexport function _Array_(items, options) {\n return Memory.Create({ '~kind': 'Array' }, { type: 'array', items }, options);\n}\nexport { _Array_ as Array }; // Prevent Collision With Global Scope\n// ------------------------------------------------------------------\n// Guard\n// ------------------------------------------------------------------\n/** Returns true if the given value is a TArray. */\nexport function IsArray(value) {\n return IsKind(value, 'Array');\n}\n// ------------------------------------------------------------------\n// Options\n// ------------------------------------------------------------------\n/** Extracts options from a TArray. */\nexport function ArrayOptions(type) {\n return Memory.Discard(type, ['~kind', 'type', 'items']);\n}\n","// deno-fmt-ignore-file\nimport { Guard } from '../../guard/index.mjs';\nimport { IsOptional } from './_optional.mjs';\n/** Creates a RequiredArray derived from the given TProperties value. */\nexport function RequiredArray(properties) {\n return Guard.Keys(properties).filter((key) => !IsOptional(properties[key]));\n}\n/** Extracts a tuple of keys from a TProperties value. */\nexport function PropertyKeys(properties) {\n return Guard.Keys(properties);\n}\n/** Extracts a tuple of property values from a TProperties value. */\nexport function PropertyValues(properties) {\n return Guard.Values(properties);\n}\n","// deno-fmt-ignore-file\nimport { Memory } from '../../system/memory/index.mjs';\nimport { IsKind } from './schema.mjs';\nimport { RequiredArray } from './properties.mjs';\n// ------------------------------------------------------------------\n// Factory\n// ------------------------------------------------------------------\n/** Creates an Object type. */\nexport function _Object_(properties, options = {}) {\n const requiredKeys = RequiredArray(properties);\n const required = requiredKeys.length > 0 ? { required: requiredKeys } : {};\n return Memory.Create({ '~kind': 'Object' }, { type: 'object', ...required, properties }, options);\n}\nexport { _Object_ as Object }; // Prevent Collision With Global Scope\n// ------------------------------------------------------------------\n// Guard\n// ------------------------------------------------------------------\n/** Returns true if the given value is TObject. */\nexport function IsObject(value) {\n return IsKind(value, 'Object');\n}\n// ------------------------------------------------------------------\n// Options\n// ------------------------------------------------------------------\n/** Extracts options from a TObject. */\nexport function ObjectOptions(type) {\n return Memory.Discard(type, ['~kind', 'type', 'properties', 'required']);\n}\n","// deno-fmt-ignore-file\nimport { Unreachable } from '../unreachable/index.mjs';\nimport { Guard, GlobalsGuard } from '../../guard/index.mjs';\n// ------------------------------------------------------------------\n// InstanceKeys\n//\n// Retrieves all enumerable and non-enumerable own property keys \n// and inherited prototype keys (excluding symbols and the 'constructor') \n// from an object instance.\n//\n// This function is useful for differentiating between class instances \n// based on their structural keys rather than relying on the \n// constructor name. It provides a more reliable structural comparison \n// by capturing both own and prototype properties.\n//\n// ------------------------------------------------------------------\nfunction InstanceKeys(value) {\n const propertyKeys = new Set();\n let current = value;\n while (current && current !== Object.prototype) {\n for (const key of Reflect.ownKeys(current)) {\n if (key !== 'constructor' && typeof key !== 'symbol')\n propertyKeys.add(key);\n }\n current = Object.getPrototypeOf(current);\n }\n return [...propertyKeys];\n}\n// ------------------------------------------------------------------\n// IsIEEE754\n//\n// TypeBox guards do not consider +/- Infinity or NaN as valid\n// numbers, but they are valid IEEE754 numbers. We use a special\n// guard to ensure these numbers are considered for hashing.\n//\n// ------------------------------------------------------------------\nfunction IsIEEE754(value) {\n return typeof value === 'number';\n}\n// ------------------------------------------------------------------\n// ByteMarker\n// ------------------------------------------------------------------\nvar ByteMarker;\n(function (ByteMarker) {\n ByteMarker[ByteMarker[\"Array\"] = 0] = \"Array\";\n ByteMarker[ByteMarker[\"BigInt\"] = 1] = \"BigInt\";\n ByteMarker[ByteMarker[\"Boolean\"] = 2] = \"Boolean\";\n ByteMarker[ByteMarker[\"Date\"] = 3] = \"Date\";\n ByteMarker[ByteMarker[\"Constructor\"] = 4] = \"Constructor\";\n ByteMarker[ByteMarker[\"Function\"] = 5] = \"Function\";\n ByteMarker[ByteMarker[\"Null\"] = 6] = \"Null\";\n ByteMarker[ByteMarker[\"Number\"] = 7] = \"Number\";\n ByteMarker[ByteMarker[\"Object\"] = 8] = \"Object\";\n ByteMarker[ByteMarker[\"RegExp\"] = 9] = \"RegExp\";\n ByteMarker[ByteMarker[\"String\"] = 10] = \"String\";\n ByteMarker[ByteMarker[\"Symbol\"] = 11] = \"Symbol\";\n ByteMarker[ByteMarker[\"TypeArray\"] = 12] = \"TypeArray\";\n ByteMarker[ByteMarker[\"Undefined\"] = 13] = \"Undefined\";\n})(ByteMarker || (ByteMarker = {}));\n// ------------------------------------------------------------------\n// State\n// ------------------------------------------------------------------\nlet Accumulator = BigInt('14695981039346656037');\nconst [Prime, Size] = [BigInt('1099511628211'), BigInt('18446744073709551616' /* 2 ^ 64 */)];\nconst Bytes = Array.from({ length: 256 }).map((_, i) => BigInt(i));\nconst F64 = new Float64Array(1);\nconst F64In = new DataView(F64.buffer);\nconst F64Out = new Uint8Array(F64.buffer);\n// ------------------------------------------------------------------\n// Operation\n// ------------------------------------------------------------------\nfunction FNV1A64_OP(byte) {\n Accumulator = Accumulator ^ Bytes[byte];\n Accumulator = (Accumulator * Prime) % Size;\n}\n// ------------------------------------------------------------------\n// Array\n// ------------------------------------------------------------------\nfunction FromArray(value) {\n FNV1A64_OP(ByteMarker.Array);\n for (const item of value) {\n FromValue(item);\n }\n}\n// ------------------------------------------------------------------\n// BigInt\n// ------------------------------------------------------------------\nfunction FromBigInt(value) {\n FNV1A64_OP(ByteMarker.BigInt);\n F64In.setBigInt64(0, value);\n for (const byte of F64Out) {\n FNV1A64_OP(byte);\n }\n}\n// ------------------------------------------------------------------\n// Boolean\n// ------------------------------------------------------------------\nfunction FromBoolean(value) {\n FNV1A64_OP(ByteMarker.Boolean);\n FNV1A64_OP(value ? 1 : 0);\n}\n// ------------------------------------------------------------------\n// Constructor\n// ------------------------------------------------------------------\nfunction FromConstructor(value) {\n FNV1A64_OP(ByteMarker.Constructor);\n FromValue(value.toString());\n}\n// ------------------------------------------------------------------\n// Date\n// ------------------------------------------------------------------\nfunction FromDate(value) {\n FNV1A64_OP(ByteMarker.Date);\n FromValue(value.getTime());\n}\n// ------------------------------------------------------------------\n// Function\n// ------------------------------------------------------------------\nfunction FromFunction(value) {\n FNV1A64_OP(ByteMarker.Function);\n FromValue(value.toString());\n}\n// ------------------------------------------------------------------\n// Null\n// ------------------------------------------------------------------\nfunction FromNull(_value) {\n FNV1A64_OP(ByteMarker.Null);\n}\n// ------------------------------------------------------------------\n// Number | IEEE754\n// ------------------------------------------------------------------\nfunction FromNumber(value) {\n FNV1A64_OP(ByteMarker.Number);\n F64In.setFloat64(0, value, true /* little-endian */);\n for (const byte of F64Out) {\n FNV1A64_OP(byte);\n }\n}\n// ------------------------------------------------------------------\n// Object\n// ------------------------------------------------------------------\nfunction FromObject(value) {\n FNV1A64_OP(ByteMarker.Object);\n for (const key of InstanceKeys(value).sort()) {\n FromValue(key);\n FromValue(value[key]);\n }\n}\n// ------------------------------------------------------------------\n// RegExp\n// ------------------------------------------------------------------\nfunction FromRegExp(value) {\n FNV1A64_OP(ByteMarker.RegExp);\n FromString(value.toString());\n}\n// ------------------------------------------------------------------\n// String\n// ------------------------------------------------------------------\nconst encoder = new TextEncoder();\nfunction FromString(value) {\n FNV1A64_OP(ByteMarker.String);\n for (const byte of encoder.encode(value)) {\n FNV1A64_OP(byte);\n }\n}\n// ------------------------------------------------------------------\n// Symbol\n// ------------------------------------------------------------------\nfunction FromSymbol(value) {\n FNV1A64_OP(ByteMarker.Symbol);\n FromValue(value.toString());\n}\n// ------------------------------------------------------------------\n// TypeArray\n// ------------------------------------------------------------------\nfunction FromTypeArray(value) {\n FNV1A64_OP(ByteMarker.TypeArray);\n const buffer = new Uint8Array(value.buffer);\n for (let i = 0; i < buffer.length; i++) {\n FNV1A64_OP(buffer[i]);\n }\n}\n// ------------------------------------------------------------------\n// Undefined\n// ------------------------------------------------------------------\nfunction FromUndefined(_value) {\n return FNV1A64_OP(ByteMarker.Undefined);\n}\n// ------------------------------------------------------------------\n// Hash\n//\n// deno-coverage-ignore-start - unreachable\n//\n// This function should all JavaScript values so we can't reach the\n// fall-through. We use Unreachable to assert that no values pass\n// through. We will need to handle these should they arise.\n//\n// ------------------------------------------------------------------\nfunction FromValue(value) {\n return (GlobalsGuard.IsTypeArray(value) ? FromTypeArray(value) :\n GlobalsGuard.IsDate(value) ? FromDate(value) :\n GlobalsGuard.IsRegExp(value) ? FromRegExp(value) :\n GlobalsGuard.IsBoolean(value) ? FromBoolean(value.valueOf()) :\n GlobalsGuard.IsString(value) ? FromString(value.valueOf()) :\n GlobalsGuard.IsNumber(value) ? FromNumber(value.valueOf()) :\n IsIEEE754(value) ? FromNumber(value) :\n Guard.IsArray(value) ? FromArray(value) :\n Guard.IsBoolean(value) ? FromBoolean(value) :\n Guard.IsBigInt(value) ? FromBigInt(value) :\n Guard.IsConstructor(value) ? FromConstructor(value) :\n Guard.IsNull(value) ? FromNull(value) :\n Guard.IsObject(value) ? FromObject(value) :\n Guard.IsString(value) ? FromString(value) :\n Guard.IsSymbol(value) ? FromSymbol(value) :\n Guard.IsUndefined(value) ? FromUndefined(value) :\n Guard.IsFunction(value) ? FromFunction(value) :\n Unreachable());\n}\n// deno-coverage-ignore-stop\n// ------------------------------------------------------------------\n// Hash\n// ------------------------------------------------------------------\n/** Generates a FNV1A-64 non cryptographic hash of the given value */\nexport function HashCode(value) {\n Accumulator = BigInt('14695981039346656037');\n FromValue(value);\n return Accumulator;\n}\n/** Generates a FNV1A-64 non cryptographic hash of the given value */\nexport function Hash(value) {\n return HashCode(value).toString(16).padStart(16, '0');\n}\n","// deno-fmt-ignore-file\nimport { Memory } from '../../system/memory/index.mjs';\nimport { IsKind } from './schema.mjs';\n// ------------------------------------------------------------------\n// Pattern\n// ------------------------------------------------------------------\nexport const IntegerPattern = '-?(?:0|[1-9][0-9]*)';\n// ------------------------------------------------------------------\n// Factory\n// ------------------------------------------------------------------\n/** Creates a Integer type. */\nexport function Integer(options) {\n return Memory.Create({ '~kind': 'Integer' }, { type: 'integer' }, options);\n}\n// ------------------------------------------------------------------\n// Guard\n// ------------------------------------------------------------------\n/** Returns true if the given value is TInteger. */\nexport function IsInteger(value) {\n return IsKind(value, 'Integer');\n}\n","// deno-fmt-ignore-file\nimport { Memory } from '../../system/memory/index.mjs';\nimport { IsKind } from './schema.mjs';\n// ------------------------------------------------------------------\n// Pattern\n// ------------------------------------------------------------------\nexport const NumberPattern = '-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?';\n// ------------------------------------------------------------------\n// Factory\n// ------------------------------------------------------------------\n/** Creates a Number type. */\nexport function Number(options) {\n return Memory.Create({ '~kind': 'Number' }, { type: 'number' }, options);\n}\n// ------------------------------------------------------------------\n// Guard\n// ------------------------------------------------------------------\n/** Returns true if the given value is a TNumber. */\nexport function IsNumber(value) {\n return IsKind(value, 'Number');\n}\n","// deno-lint-ignore-file\n// deno-fmt-ignore-file\nimport { Memory } from '../../system/memory/index.mjs';\nimport { IsKind } from './schema.mjs';\n// ------------------------------------------------------------------\n// StringPattern\n// ------------------------------------------------------------------\nexport const StringPattern = '.*';\n// ------------------------------------------------------------------\n// Factory\n// ------------------------------------------------------------------\n/** Creates a String type. */\nexport function String(options) {\n return Memory.Create({ '~kind': 'String' }, { type: 'string' }, options);\n}\n// ------------------------------------------------------------------\n// Guard\n// ------------------------------------------------------------------\n/** Returns true if the given value is TString. */\nexport function IsString(value) {\n return IsKind(value, 'String');\n}\n","// deno-fmt-ignore-file\nimport { Memory } from '../../system/memory/index.mjs';\nimport { Guard } from '../../guard/index.mjs';\nimport { IsKind } from './schema.mjs';\nimport { Integer, IntegerPattern } from './integer.mjs';\nimport { Number, NumberPattern } from './number.mjs';\nimport { String, StringPattern } from './string.mjs';\nimport { Deferred } from './deferred.mjs';\nimport { TemplateLiteralDecodeUnsafe } from '../engine/template_literal/decode.mjs';\nimport { CreateRecord } from '../engine/record/record_create.mjs';\nimport { RecordAction } from '../engine/record/instantiate.mjs';\nexport const IntegerKey = `^${IntegerPattern}$`;\nexport const NumberKey = `^${NumberPattern}$`;\nexport const StringKey = `^${StringPattern}$`;\n/** Represents a deferred Record action. */\nexport function RecordDeferred(key, value, options = {}) {\n return Deferred('Record', [key, value], options);\n}\n// -------------------------------------------------------------------\n// Factory\n// -------------------------------------------------------------------\n/** Creates a Record type. */\nexport function Record(key, value, options = {}) {\n return RecordAction(key, value, options);\n}\n// -------------------------------------------------------------------\n// FromPattern\n// -------------------------------------------------------------------\n/** Creates a Record type from regular expression pattern. */\nexport function RecordFromPattern(key, value) {\n return CreateRecord(key, value);\n}\n/** Returns the raw string pattern used for the Record key */\nexport function RecordPattern(type) {\n return Guard.Keys(type.patternProperties)[0];\n}\n/** Returns the Record key as a TypeBox type */\nexport function RecordKey(type) {\n const pattern = RecordPattern(type);\n const result = (Guard.IsEqual(pattern, StringKey) ? String() :\n Guard.IsEqual(pattern, IntegerKey) ? Integer() :\n Guard.IsEqual(pattern, NumberKey) ? Number() :\n TemplateLiteralDecodeUnsafe(pattern));\n return result;\n}\nexport function RecordValue(type) {\n return type.patternProperties[RecordPattern(type)];\n}\n// -------------------------------------------------------------------\n// Guard\n// -------------------------------------------------------------------\nexport function IsRecord(value) {\n return IsKind(value, 'Record');\n}\n// -------------------------------------------------------------------\n// Options\n// -------------------------------------------------------------------\nexport function RecordOptions(type) {\n return Memory.Discard(type, ['~kind', 'type', 'patternProperties']);\n}\n","// deno-coverage-ignore-start - parsebox tested\n// deno-fmt-ignore-file\n// ------------------------------------------------------------------\n// Range\n// ------------------------------------------------------------------\nfunction Range(start, end) {\n return Array.from({ length: end - start + 1 }, (_, i) => String.fromCharCode(start + i));\n}\nexport const Alpha = [\n ...Range(97, 122), // Lowercase\n ...Range(65, 90) // Uppercase\n];\nexport const Zero = '0';\nexport const NonZero = Range(49, 57); // 1 - 9\nexport const Digit = [Zero, ...NonZero];\n// ------------------------------------------------------------------\n// Characters\n// ------------------------------------------------------------------\nexport const WhiteSpace = ' ';\nexport const NewLine = '\\n';\nexport const TabSpace = '\\t';\nexport const UnderScore = '_';\nexport const Dot = '.';\nexport const DollarSign = '$';\nexport const Hyphen = '-';\n// deno-coverage-ignore-stop\n","// deno-coverage-ignore-start - parsebox tested\n// deno-fmt-ignore-file\nimport { Match } from './internal/match.mjs';\nimport { Trim } from './internal/trim.mjs';\nimport { Take } from './internal/take.mjs';\nimport { Many } from './internal/many.mjs';\nimport { Digit } from './internal/char.mjs';\nimport { Zero } from './internal/char.mjs';\nimport { NonZero } from './internal/char.mjs';\nimport { UnderScore } from './internal/char.mjs';\nfunction TakeNonZero(input) {\n return Take(NonZero, input);\n}\nconst AllowedDigits = [...Digit, UnderScore];\nfunction TakeDigits(input) {\n return Many(AllowedDigits, [UnderScore], input);\n}\nfunction TakeUnsignedInteger(input) {\n return Match(Take([Zero], input), (Zero, ZeroRest) => [Zero, ZeroRest], () => Match(TakeNonZero(input), (NonZero, NonZeroRest) => Match(TakeDigits(NonZeroRest), (Digits, DigitsRest) => [`${NonZero}${Digits}`, DigitsRest], () => []), // fail: did not match Digits\n () => [])); // fail: did not match NonZero\n}\n/** Matches if next is a UnsignedInteger */\nexport function UnsignedInteger(input) {\n return TakeUnsignedInteger(Trim(input));\n}\n// deno-coverage-ignore-stop\n","// deno-coverage-ignore-start - parsebox tested\n// deno-fmt-ignore-file\nimport { Match } from './internal/match.mjs';\nimport { Trim } from './internal/trim.mjs';\nimport { Take } from './internal/take.mjs';\nimport { Alpha } from './internal/char.mjs';\nimport { Digit } from './internal/char.mjs';\nimport { UnderScore } from './internal/char.mjs';\nimport { DollarSign } from './internal/char.mjs';\nconst Initial = [...Alpha, UnderScore, DollarSign];\nfunction TakeInitial(input) {\n return Take(Initial, input);\n}\nconst Remaining = [...Initial, ...Digit];\nfunction TakeRemaining(input, result = '') {\n return Match(Take(Remaining, input), (Remaining, RemainingRest) => TakeRemaining(RemainingRest, `${result}${Remaining}`), () => [result, input]);\n}\nfunction TakeIdent(input) {\n return Match(TakeInitial(input), (Initial, InitialRest) => Match(TakeRemaining(InitialRest), (Remaining, RemainingRest) => [`${Initial}${Remaining}`, RemainingRest], () => []), // fail: did not match Remaining\n () => []); // fail: did not match Initial\n}\n/** Matches if next is an Ident */\nexport function Ident(input) {\n return TakeIdent(Trim(input));\n}\n// deno-coverage-ignore-stop\n","// deno-coverage-ignore-start - parsebox tested\n// deno-fmt-ignore-file\nimport { IsEqual } from './internal/guard.mjs';\nimport { IsMatch, Match } from './internal/match.mjs';\nimport { Trim } from './internal/trim.mjs';\nimport { Take } from './internal/take.mjs';\nimport { Many } from './internal/many.mjs';\nimport { Digit, UnderScore } from './internal/char.mjs';\nimport { Dot } from './internal/char.mjs';\nimport { UnsignedInteger } from './unsigned_integer.mjs';\nconst AllowedDigits = [...Digit, UnderScore];\nfunction IsLeadingDot(input) {\n return IsMatch(Take([Dot], input));\n}\nfunction TakeFractional(input) {\n return Match(Many(AllowedDigits, [UnderScore], input), (Digits, DigitsRest) => IsEqual(Digits, '')\n ? [] // fail: no Digits\n : [Digits, DigitsRest], () => []); // fail: did not match Digits\n}\nfunction LeadingDot(input) {\n return Match(Take([Dot], input), (Dot, DotRest) => Match(TakeFractional(DotRest), (Fractional, FractionalRest) => [`0${Dot}${Fractional}`, FractionalRest], () => []), // fail: did not match Fractional\n () => []); // fail: did not match Dot\n}\nfunction LeadingInteger(input) {\n return Match(UnsignedInteger(input), (Integer, IntegerRest) => Match(Take([Dot], IntegerRest), (Dot, DotRest) => Match(TakeFractional(DotRest), (Fractional, FractionalRest) => [`${Integer}${Dot}${Fractional}`, FractionalRest], () => [`${Integer}`, DotRest]), // fail: did not match Fractional, use Integer\n () => [`${Integer}`, IntegerRest]), // fail: did not match Dot, use Integer\n () => []); // fail: did not match Integer\n}\nfunction TakeUnsignedNumber(input) {\n return (IsLeadingDot(input)\n ? LeadingDot(input)\n : LeadingInteger(input));\n}\n/** Matches if next is a UnsignedNumber */\nexport function UnsignedNumber(input) {\n return TakeUnsignedNumber(Trim(input));\n}\n// deno-coverage-ignore-stop\n","// deno-fmt-ignore-file\nimport { IsNumber } from '../../types/number.mjs';\nimport { Never } from '../../types/never.mjs';\nimport { PropertyKeys } from '../../types/properties.mjs';\nimport { EvaluateUnion } from '../evaluate/evaluate.mjs';\nimport { ToIndexableKeys } from '../indexable/to_indexable_keys.mjs';\nimport { IntegerKey } from '../../types/record.mjs';\nimport { ExpandThis } from '../this/expand_this.mjs';\nfunction IndexProperty(properties, key) {\n const selectedType = key in properties ? properties[key] : Never();\n const result = ExpandThis(properties, selectedType);\n return result;\n}\nfunction IndexProperties(properties, keys) {\n return keys.reduce((result, left) => {\n return [...result, IndexProperty(properties, left)];\n }, []);\n}\nfunction FromIndexer(properties, indexer) {\n const keys = ToIndexableKeys(indexer);\n const variants = IndexProperties(properties, keys);\n const result = EvaluateUnion(variants);\n return result;\n}\nconst NumericKeyPattern = new RegExp(IntegerKey);\nfunction NumericKeys(keys) {\n const result = keys.filter(key => NumericKeyPattern.test(key));\n return result;\n}\nfunction FromIndexerNumber(properties) {\n const keys = PropertyKeys(properties);\n const numericKeys = NumericKeys(keys);\n const variants = IndexProperties(properties, numericKeys);\n const result = EvaluateUnion(variants);\n return result;\n}\nexport function FromObject(properties, indexer) {\n const result = IsNumber(indexer) ? FromIndexerNumber(properties) : FromIndexer(properties, indexer);\n return result;\n}\n","import { posix } from \"node:path\";\nimport { Type } from \"typebox\";\n//#region src/tools/workspace-path.ts\nconst WORKSPACE_PREFIX = \"/workspace\";\n/** Guest parent directory for agent + session mounts. */\nconst WORKSPACE_MOUNT = WORKSPACE_PREFIX;\n/** Persistent per-agent files and skills. */\nconst AGENT_MOUNT = `${WORKSPACE_PREFIX}/agent`;\n/** Ephemeral per-session scratch space. */\nconst SESSION_MOUNT = `${WORKSPACE_PREFIX}/session`;\nfunction isAgentOrSessionRelative(relative) {\n\treturn relative === \"agent\" || relative.startsWith(\"agent/\") || relative === \"session\" || relative.startsWith(\"session/\");\n}\n/** Bare relative paths (no agent/ or session/ prefix) land in session scratch. */\nfunction withSessionDefault(relative) {\n\tif (relative === \"\" || isAgentOrSessionRelative(relative)) return relative;\n\treturn posix.join(\"session\", relative);\n}\n/**\n* Map a tool-supplied path to a canonical `/workspace/...` guest path.\n*\n* Unprefixed relative paths resolve under `/workspace/session`. Use an `agent/`\n* prefix for cross-session persistence. Absolute paths must stay under `/workspace`.\n*/\nfunction normalizeWorkspacePath(path) {\n\tconst normalized = path.replace(/\\\\/g, \"/\");\n\tlet relative;\n\tif (normalized === WORKSPACE_PREFIX || normalized === `${WORKSPACE_PREFIX}/`) relative = \"\";\n\telse if (normalized.startsWith(`${WORKSPACE_PREFIX}/`)) relative = normalized.slice(11);\n\telse if (normalized.startsWith(\"/\")) throw new Error(`Path must be under ${WORKSPACE_PREFIX} (e.g. /workspace/session/file.txt). For other paths use bash.`);\n\telse relative = normalized.replace(/^\\.\\//, \"\");\n\tconst beforeDefault = posix.join(WORKSPACE_PREFIX, relative);\n\tif (beforeDefault !== WORKSPACE_PREFIX && !beforeDefault.startsWith(`${WORKSPACE_PREFIX}/`)) throw new Error(`Path escapes workspace: ${path}`);\n\trelative = withSessionDefault(relative);\n\tconst resolved = posix.join(WORKSPACE_PREFIX, relative);\n\tif (resolved !== WORKSPACE_PREFIX && !resolved.startsWith(`${WORKSPACE_PREFIX}/`)) throw new Error(`Path escapes workspace: ${path}`);\n\tlet mount = \"parent\";\n\tif (resolved === AGENT_MOUNT || resolved.startsWith(`${AGENT_MOUNT}/`)) mount = \"agent\";\n\telse if (resolved === SESSION_MOUNT || resolved.startsWith(`${SESSION_MOUNT}/`)) mount = \"session\";\n\treturn {\n\t\tpath: resolved,\n\t\tdisplayPath: resolved,\n\t\tmount\n\t};\n}\n//#endregion\n//#region src/define-tool.ts\n/**\n* Identity helper for authoring agent tools. Generic over the parameter schema\n* so `execute`'s `params` is inferred as `Static<typeof parameters>` — no cast\n* needed inside `execute`.\n*/\nfunction defineTool(tool) {\n\treturn tool;\n}\n//#endregion\n//#region src/tools/helpers/format-exec.ts\nfunction formatExecResult(result) {\n\tconst parts = [];\n\tif (result.stdout) parts.push(result.stdout);\n\tif (result.stderr) parts.push(result.stderr);\n\tif (result.exitCode !== 0) parts.push(`[exit ${result.exitCode}]`);\n\treturn parts.join(\"\\n\").trim() || \"(no output)\";\n}\n//#endregion\n//#region src/tools/bash-tool.ts\nfunction createBashTool(runtime, options = {}) {\n\treturn defineTool({\n\t\tname: \"bash\",\n\t\tlabel: \"Bash\",\n\t\tdescription: [\n\t\t\t\"Run bash in the agent sandbox (cwd /workspace).\",\n\t\t\t\"Use session/ for session scratch and agent/ for persistent cross-session files.\",\n\t\t\t\"Prefer read, write, and edit for file operations.\",\n\t\t\t\"Use bash for grep, find, ls, jq, and shell pipelines.\",\n\t\t\toptions.codemode ?? true ? \"Use js-exec for JavaScript/TypeScript scripts; call host tools from scripts via tools.<toolName>(args).\" : \"Use node or python via bash for scripts when needed.\"\n\t\t].join(\" \"),\n\t\tparameters: Type.Object({ command: Type.String({ description: \"Bash script or command to run in the sandbox\" }) }, { additionalProperties: false }),\n\t\tasync execute(_id, params) {\n\t\t\tconst { command } = params;\n\t\t\tconst result = await runtime.exec(command);\n\t\t\treturn {\n\t\t\t\tcontent: [{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: formatExecResult(result)\n\t\t\t\t}],\n\t\t\t\tdetails: result\n\t\t\t};\n\t\t}\n\t});\n}\n//#endregion\n//#region src/tools/helpers/edit-apply.ts\nfunction applyEditsToOriginal(content, edits) {\n\tif (edits.length === 0) throw new Error(\"edits must contain at least one replacement\");\n\tconst ranges = [];\n\tfor (const edit of edits) {\n\t\tconst start = content.indexOf(edit.oldText);\n\t\tif (start === -1) throw new Error(\"oldText not found in file\");\n\t\tif (content.indexOf(edit.oldText, start + edit.oldText.length) !== -1) throw new Error(\"oldText must be unique in file\");\n\t\tranges.push({\n\t\t\tstart,\n\t\t\tend: start + edit.oldText.length,\n\t\t\tnewText: edit.newText\n\t\t});\n\t}\n\tconst sorted = [...ranges].sort((a, b) => a.start - b.start);\n\tfor (let i = 1; i < sorted.length; i++) {\n\t\tconst prev = sorted[i - 1];\n\t\tif (sorted[i].start < prev.end) throw new Error(\"edits must not overlap\");\n\t}\n\tlet result = \"\";\n\tlet cursor = 0;\n\tfor (const range of sorted) {\n\t\tresult += content.slice(cursor, range.start);\n\t\tresult += range.newText;\n\t\tcursor = range.end;\n\t}\n\tresult += content.slice(cursor);\n\treturn result;\n}\n//#endregion\n//#region src/tools/edit-tool.ts\nconst replaceEditSchema = Type.Object({\n\toldText: Type.String({ description: \"Exact text to replace. Must be unique in the file and must not overlap other edits in this call.\" }),\n\tnewText: Type.String({ description: \"Replacement text\" })\n}, { additionalProperties: false });\nconst editSchema = Type.Object({\n\tpath: Type.String({ description: \"Path under /workspace (e.g. session/out.txt or agent/data.json)\" }),\n\tedits: Type.Array(replaceEditSchema, { description: \"Replacements applied against the original file (not chained). Each oldText must be unique and non-overlapping.\" })\n}, { additionalProperties: false });\nfunction createEditTool(runtime) {\n\treturn defineTool({\n\t\tname: \"edit\",\n\t\tlabel: \"edit\",\n\t\tdescription: \"Edit a file under /workspace using exact text replacement. Unprefixed paths resolve under session/; prefix agent/ for cross-session files. Each edits[].oldText must match the original file uniquely. Merge nearby changes into one edit when possible.\",\n\t\tparameters: editSchema,\n\t\tasync execute(_id, params, signal) {\n\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\tconst { path, edits } = params;\n\t\t\tconst { path: filePath, displayPath } = normalizeWorkspacePath(path);\n\t\t\tconst updated = applyEditsToOriginal(await runtime.readFile(filePath), edits);\n\t\t\tawait runtime.writeFile(filePath, updated);\n\t\t\treturn {\n\t\t\t\tcontent: [{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: `Successfully replaced ${edits.length} block(s) in ${displayPath}`\n\t\t\t\t}],\n\t\t\t\tdetails: {\n\t\t\t\t\tpath: displayPath,\n\t\t\t\t\teditCount: edits.length\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t});\n}\n//#endregion\n//#region src/tools/helpers/truncate.ts\nconst DEFAULT_MAX_LINES = 2e3;\nconst DEFAULT_MAX_BYTES = 256 * 1024;\nfunction truncateHead(text, maxLines = DEFAULT_MAX_LINES, maxBytes = DEFAULT_MAX_BYTES) {\n\tconst lines = text.split(\"\\n\");\n\tconst totalLines = lines.length;\n\tlet truncatedBy;\n\tlet sliceEnd = lines.length;\n\tif (lines.length > maxLines) {\n\t\tsliceEnd = maxLines;\n\t\ttruncatedBy = \"lines\";\n\t}\n\tlet content = lines.slice(0, sliceEnd).join(\"\\n\");\n\tconst buf = Buffer.from(content, \"utf-8\");\n\tif (buf.byteLength > maxBytes) {\n\t\tcontent = buf.subarray(0, maxBytes).toString(\"utf-8\");\n\t\ttruncatedBy = \"bytes\";\n\t}\n\tconst outputLines = content.split(\"\\n\").length;\n\treturn {\n\t\tcontent,\n\t\ttruncated: truncatedBy !== void 0,\n\t\toutputLines,\n\t\ttotalLines,\n\t\ttruncatedBy\n\t};\n}\n//#endregion\n//#region src/tools/read-tool.ts\nconst readSchema = Type.Object({\n\tpath: Type.String({ description: \"Path under /workspace (e.g. session/out.txt or agent/data.json)\" }),\n\toffset: Type.Optional(Type.Number({ description: \"Line number to start reading from (1-indexed)\" })),\n\tlimit: Type.Optional(Type.Number({ description: \"Maximum number of lines to read\" }))\n});\nfunction createReadTool(runtime) {\n\treturn defineTool({\n\t\tname: \"read\",\n\t\tlabel: \"read\",\n\t\tdescription: `Read a file under /workspace. Unprefixed paths resolve under session/; prefix agent/ for cross-session files. Text is truncated to ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB. Use offset/limit to continue. Prefer read over cat.`,\n\t\tparameters: readSchema,\n\t\tasync execute(_id, params, signal) {\n\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\tconst { path, offset, limit } = params;\n\t\t\tconst { path: filePath, displayPath } = normalizeWorkspacePath(path);\n\t\t\tconst allLines = (await runtime.readFile(filePath)).split(\"\\n\");\n\t\t\tconst startLine = offset ? Math.max(0, offset - 1) : 0;\n\t\t\tif (startLine >= allLines.length) throw new Error(`Offset ${offset} is beyond end of file (${allLines.length} lines total)`);\n\t\t\tlet selected;\n\t\t\tif (limit !== void 0) {\n\t\t\t\tconst endLine = Math.min(startLine + limit, allLines.length);\n\t\t\t\tselected = allLines.slice(startLine, endLine).join(\"\\n\");\n\t\t\t} else selected = allLines.slice(startLine).join(\"\\n\");\n\t\t\tconst truncation = truncateHead(selected);\n\t\t\tlet output = truncation.content;\n\t\t\tconst startDisplay = startLine + 1;\n\t\t\tif (truncation.truncated) {\n\t\t\t\tconst nextOffset = startDisplay + truncation.outputLines;\n\t\t\t\toutput += `\\n\\n[Truncated. Use offset=${nextOffset} on ${displayPath} to continue.]`;\n\t\t\t} else if (limit !== void 0 && startLine + limit < allLines.length) {\n\t\t\t\tconst nextOffset = startLine + limit + 1;\n\t\t\t\toutput += `\\n\\n[More lines in file. Use offset=${nextOffset} to continue.]`;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tcontent: [{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: output\n\t\t\t\t}],\n\t\t\t\tdetails: {\n\t\t\t\t\tpath: displayPath,\n\t\t\t\t\ttruncation\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t});\n}\n//#endregion\n//#region src/tools/write-tool.ts\nconst writeSchema = Type.Object({\n\tpath: Type.String({ description: \"Path under /workspace (e.g. session/out.txt or agent/data.json)\" }),\n\tcontent: Type.String({ description: \"Content to write to the file\" })\n});\nfunction createWriteTool(runtime) {\n\treturn defineTool({\n\t\tname: \"write\",\n\t\tlabel: \"write\",\n\t\tdescription: \"Write content to a file under /workspace. Unprefixed paths go to session/; prefix agent/ for cross-session persistence. Creates parent directories if needed. Overwrites existing files. Use write for new files or full rewrites; use edit for partial changes.\",\n\t\tparameters: writeSchema,\n\t\tasync execute(_id, params, signal) {\n\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\tconst { path, content } = params;\n\t\t\tconst { path: filePath, displayPath } = normalizeWorkspacePath(path);\n\t\t\tawait runtime.writeFile(filePath, content);\n\t\t\treturn {\n\t\t\t\tcontent: [{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: `Successfully wrote ${content.length} bytes to ${displayPath}`\n\t\t\t\t}],\n\t\t\t\tdetails: { path: displayPath }\n\t\t\t};\n\t\t}\n\t});\n}\n//#endregion\n//#region src/tools/create-coding-tools.ts\nfunction createCodingTools(runtime, options = {}) {\n\tconst codemode = options.codemode ?? true;\n\treturn [\n\t\tcreateReadTool(runtime),\n\t\tcreateWriteTool(runtime),\n\t\tcreateEditTool(runtime),\n\t\tcreateBashTool(runtime, { codemode })\n\t];\n}\n//#endregion\nexport { WORKSPACE_MOUNT as a, SESSION_MOUNT as i, defineTool as n, AGENT_MOUNT as r, createCodingTools as t };\n\n//# sourceMappingURL=create-coding-tools-d9-WzxBW.mjs.map","import{createRequire} from\"node:module\";const require=createRequire(import.meta.url);\nimport{B as on,C as an,D as de,E as et,F as se,G as ke,H as Kt,I as ln,J as L,K as cn,L as un,M as xe,N as Us,O as Xt,P as H,a as Yr,b as Ms,c as Qr,d as qt,e as ee,f as B,g as fe,h as ne,i as Oe,j as He,k as Ws,l as Gt,m as Jr,n as zs,o as en,p as Ee,q as We,r as tn,s as sn,t as Vs,u as Bs,v as Ze,w as rn,x as nn,y as Ae,z as js}from\"./chunks/chunk-G5EVRAOO.js\";import{a as Fe,b as Me,c as be}from\"./chunks/chunk-WNH3HOQA.js\";import{c as Fs}from\"./chunks/chunk-HBVMHTO5.js\";import{a as Mt,b as Wt}from\"./chunks/chunk-XRFHFXFP.js\";import{a as Ls}from\"./chunks/chunk-L2UW7DWF.js\";import{a as Ue,b as ve,c as Ct}from\"./chunks/chunk-DLL7UR66.js\";import{a as _t,b as Xr}from\"./chunks/chunk-L64BMZUV.js\";import{a as Ve,b as me}from\"./chunks/chunk-TN7HHBQW.js\";import{a as kt}from\"./chunks/chunk-4RUAZWKT.js\";import{a as At,b as zt,c as io,d as Be,e as oo,f as Vt,g as ao,h as Bt,i as lo,j as co}from\"./chunks/chunk-NRSASXYY.js\";import{a as ye,b as ge,c as ue,d as we,e as Gr,f as j,g as Je,h as jt,i as Ut,j as Kr,k as J,l as Ht,m as je,n as Zt,o as Pe}from\"./chunks/chunk-SAI2SPQQ.js\";import\"./chunks/chunk-STHBFACM.js\";import{a as Le}from\"./chunks/chunk-FOCWZZDE.js\";import{a as Ie}from\"./chunks/chunk-W5DWRFSU.js\";import{a as Is}from\"./chunks/chunk-BZUGFHVS.js\";var tt=[{name:\"echo\",load:async()=>(await import(\"./chunks/echo-NDWZZHPO.js\")).echoCommand},{name:\"cat\",load:async()=>(await import(\"./chunks/cat-TSFMZVYS.js\")).catCommand},{name:\"printf\",load:async()=>(await import(\"./chunks/printf-TWGXF445.js\")).printfCommand},{name:\"ls\",load:async()=>(await import(\"./chunks/ls-ZJGQER7M.js\")).lsCommand},{name:\"mkdir\",load:async()=>(await import(\"./chunks/mkdir-MEPGZOB6.js\")).mkdirCommand},{name:\"rmdir\",load:async()=>(await import(\"./chunks/rmdir-OC4ZLPYA.js\")).rmdirCommand},{name:\"touch\",load:async()=>(await import(\"./chunks/touch-UA33VN3N.js\")).touchCommand},{name:\"rm\",load:async()=>(await import(\"./chunks/rm-SSGETQVQ.js\")).rmCommand},{name:\"cp\",load:async()=>(await import(\"./chunks/cp-BISAAS7A.js\")).cpCommand},{name:\"mv\",load:async()=>(await import(\"./chunks/mv-W5BIQ646.js\")).mvCommand},{name:\"ln\",load:async()=>(await import(\"./chunks/ln-4LGSXXGD.js\")).lnCommand},{name:\"chmod\",load:async()=>(await import(\"./chunks/chmod-TFEPA42X.js\")).chmodCommand},{name:\"pwd\",load:async()=>(await import(\"./chunks/pwd-WE6EN5AV.js\")).pwdCommand},{name:\"readlink\",load:async()=>(await import(\"./chunks/readlink-OPJF4DL5.js\")).readlinkCommand},{name:\"head\",load:async()=>(await import(\"./chunks/head-442HYESI.js\")).headCommand},{name:\"tail\",load:async()=>(await import(\"./chunks/tail-R4PCA2C4.js\")).tailCommand},{name:\"wc\",load:async()=>(await import(\"./chunks/wc-LF7NU4LA.js\")).wcCommand},{name:\"stat\",load:async()=>(await import(\"./chunks/stat-CD34IZ4P.js\")).statCommand},{name:\"grep\",load:async()=>(await import(\"./chunks/grep-V3LQVMRQ.js\")).grepCommand},{name:\"fgrep\",load:async()=>(await import(\"./chunks/grep-V3LQVMRQ.js\")).fgrepCommand},{name:\"egrep\",load:async()=>(await import(\"./chunks/grep-V3LQVMRQ.js\")).egrepCommand},{name:\"rg\",load:async()=>(await import(\"./chunks/rg-S4FXYXWB.js\")).rgCommand},{name:\"sed\",load:async()=>(await import(\"./chunks/sed-S5UIK574.js\")).sedCommand},{name:\"awk\",load:async()=>(await import(\"./chunks/awk2-LA3USKJP.js\")).awkCommand2},{name:\"sort\",load:async()=>(await import(\"./chunks/sort-SW2YEO5B.js\")).sortCommand},{name:\"uniq\",load:async()=>(await import(\"./chunks/uniq-XSIZR6PB.js\")).uniqCommand},{name:\"comm\",load:async()=>(await import(\"./chunks/comm-VV2LDX2J.js\")).commCommand},{name:\"cut\",load:async()=>(await import(\"./chunks/cut-OKARJCCV.js\")).cutCommand},{name:\"paste\",load:async()=>(await import(\"./chunks/paste-7JC6S4DX.js\")).pasteCommand},{name:\"tr\",load:async()=>(await import(\"./chunks/tr-36LHWFRQ.js\")).trCommand},{name:\"rev\",load:async()=>(await import(\"./chunks/rev-5EHFX4EJ.js\")).rev},{name:\"nl\",load:async()=>(await import(\"./chunks/nl-WSDW7I4O.js\")).nl},{name:\"fold\",load:async()=>(await import(\"./chunks/fold-4TQNYMSW.js\")).fold},{name:\"expand\",load:async()=>(await import(\"./chunks/expand-JSPG6VOP.js\")).expand},{name:\"unexpand\",load:async()=>(await import(\"./chunks/unexpand-CADSA4VO.js\")).unexpand},{name:\"strings\",load:async()=>(await import(\"./chunks/strings-6WDHLGMX.js\")).strings},{name:\"split\",load:async()=>(await import(\"./chunks/split-4KKZZXXE.js\")).split},{name:\"column\",load:async()=>(await import(\"./chunks/column-XT6UFXNQ.js\")).column},{name:\"join\",load:async()=>(await import(\"./chunks/join-TBRGI3LQ.js\")).join},{name:\"tee\",load:async()=>(await import(\"./chunks/tee-YUZ2FKCJ.js\")).teeCommand},{name:\"find\",load:async()=>(await import(\"./chunks/find-INTH3OLC.js\")).findCommand},{name:\"basename\",load:async()=>(await import(\"./chunks/basename-UB3CIYNI.js\")).basenameCommand},{name:\"dirname\",load:async()=>(await import(\"./chunks/dirname-MPHRFUTI.js\")).dirnameCommand},{name:\"tree\",load:async()=>(await import(\"./chunks/tree-YLD52CNT.js\")).treeCommand},{name:\"du\",load:async()=>(await import(\"./chunks/du-572XNP42.js\")).duCommand},{name:\"env\",load:async()=>(await import(\"./chunks/env-36M5BO7M.js\")).envCommand},{name:\"printenv\",load:async()=>(await import(\"./chunks/env-36M5BO7M.js\")).printenvCommand},{name:\"alias\",load:async()=>(await import(\"./chunks/alias-RTYYYW3D.js\")).aliasCommand},{name:\"unalias\",load:async()=>(await import(\"./chunks/alias-RTYYYW3D.js\")).unaliasCommand},{name:\"history\",load:async()=>(await import(\"./chunks/history-WYYKSLSZ.js\")).historyCommand},{name:\"xargs\",load:async()=>(await import(\"./chunks/xargs-MGZPH7AX.js\")).xargsCommand},{name:\"true\",load:async()=>(await import(\"./chunks/true-FHQXJXBE.js\")).trueCommand},{name:\"false\",load:async()=>(await import(\"./chunks/true-FHQXJXBE.js\")).falseCommand},{name:\"clear\",load:async()=>(await import(\"./chunks/clear-HKGFEOF6.js\")).clearCommand},{name:\"bash\",load:async()=>(await import(\"./chunks/bash-YZ33HQZQ.js\")).bashCommand},{name:\"sh\",load:async()=>(await import(\"./chunks/bash-YZ33HQZQ.js\")).shCommand},{name:\"jq\",load:async()=>(await import(\"./chunks/jq-4XLYLOS5.js\")).jqCommand},{name:\"base64\",load:async()=>(await import(\"./chunks/base64-C2AIWVNC.js\")).base64Command},{name:\"diff\",load:async()=>(await import(\"./chunks/diff-MWJFIG7X.js\")).diffCommand},{name:\"date\",load:async()=>(await import(\"./chunks/date-UUUPW43J.js\")).dateCommand},{name:\"sleep\",load:async()=>(await import(\"./chunks/sleep-X22JJINO.js\")).sleepCommand},{name:\"timeout\",load:async()=>(await import(\"./chunks/timeout-YDCRSLPQ.js\")).timeoutCommand},{name:\"time\",load:async()=>(await import(\"./chunks/time-D4LNBSWX.js\")).timeCommand},{name:\"seq\",load:async()=>(await import(\"./chunks/seq-M5EC7Q57.js\")).seqCommand},{name:\"expr\",load:async()=>(await import(\"./chunks/expr-5JAACS4X.js\")).exprCommand},{name:\"md5sum\",load:async()=>(await import(\"./chunks/md5sum-SPU24VSG.js\")).md5sumCommand},{name:\"sha1sum\",load:async()=>(await import(\"./chunks/sha1sum-2PTOAFR6.js\")).sha1sumCommand},{name:\"sha256sum\",load:async()=>(await import(\"./chunks/sha256sum-NS7D3IXX.js\")).sha256sumCommand},{name:\"file\",load:async()=>(await import(\"./chunks/file-IPZJC3FQ.js\")).fileCommand},{name:\"html-to-markdown\",load:async()=>(await import(\"./chunks/html-to-markdown-JW4MSQZO.js\")).htmlToMarkdownCommand},{name:\"help\",load:async()=>(await import(\"./chunks/help-HZ6M2CKN.js\")).helpCommand},{name:\"which\",load:async()=>(await import(\"./chunks/which-XEM24D5D.js\")).whichCommand},{name:\"tac\",load:async()=>(await import(\"./chunks/tac-2STMMJYW.js\")).tac},{name:\"hostname\",load:async()=>(await import(\"./chunks/hostname-C4HQXXUP.js\")).hostname},{name:\"whoami\",load:async()=>(await import(\"./chunks/whoami-XMTX52VE.js\")).whoami},{name:\"od\",load:async()=>(await import(\"./chunks/od-WOKFDJTP.js\")).od},{name:\"gzip\",load:async()=>(await import(\"./chunks/gzip-O5ASJAFY.js\")).gzipCommand},{name:\"gunzip\",load:async()=>(await import(\"./chunks/gzip-O5ASJAFY.js\")).gunzipCommand},{name:\"zcat\",load:async()=>(await import(\"./chunks/gzip-O5ASJAFY.js\")).zcatCommand}];(typeof __BROWSER__>\"u\"||!__BROWSER__)&&(tt.push({name:\"tar\",load:async()=>(await import(\"./chunks/tar-STHHZTZ6.js\")).tarCommand}),tt.push({name:\"yq\",load:async()=>(await import(\"./chunks/yq-4QJW3EQG.js\")).yqCommand}),tt.push({name:\"xan\",load:async()=>(await import(\"./chunks/xan-Y6WF3IRG.js\")).xanCommand}),tt.push({name:\"sqlite3\",load:async()=>(await import(\"./chunks/sqlite3-CGOEFJAO.js\")).sqlite3Command}));var Yt=[];(typeof __BROWSER__>\"u\"||!__BROWSER__)&&(Yt.push({name:\"python3\",load:async()=>(await import(\"./chunks/python3-POMOR4OA.js\")).python3Command}),Yt.push({name:\"python\",load:async()=>(await import(\"./chunks/python3-POMOR4OA.js\")).pythonCommand}));var Qt=[];(typeof __BROWSER__>\"u\"||!__BROWSER__)&&(Qt.push({name:\"js-exec\",load:async()=>(await import(\"./chunks/js-exec-N5KEZBH7.js\")).jsExecCommand}),Qt.push({name:\"node\",load:async()=>(await import(\"./chunks/js-exec-N5KEZBH7.js\")).nodeStubCommand}));var dn=[{name:\"curl\",load:async()=>(await import(\"./chunks/curl-LV5Y3AMS.js\")).curlCommand}],fn=new Map;function Jt(e){return{name:e.name,async execute(t,s){let r=fn.get(e.name);if(r||(r=await me.runTrustedAsync(()=>e.load()),fn.set(e.name,r)),s.coverage&&(typeof __BROWSER__>\"u\"||!__BROWSER__)){let{emitFlagCoverage:n}=await import(\"./chunks/flag-coverage-XWSYNE72.js\");n(s.coverage,e.name,t)}return r.execute(t,s)}}}function uo(){return tt.map(e=>e.name)}function fo(){return dn.map(e=>e.name)}function hn(e){return(e?tt.filter(s=>e.includes(s.name)):tt).map(Jt)}function pn(){return dn.map(Jt)}function ho(){return Yt.map(e=>e.name)}function mn(){return Yt.map(Jt)}function po(){return Qt.map(e=>e.name)}function yn(){return Qt.map(Jt)}function gn(e){return\"load\"in e&&typeof e.load==\"function\"}function mo(e,t){return{name:e,trusted:!0,execute:t}}function wn(e){let t=null;return{name:e.name,trusted:!0,async execute(s,r){return t||(t=await e.load()),t.execute(s,r)}}}function O(e){if(!e||e===\"/\")return\"/\";let t=e.endsWith(\"/\")&&e!==\"/\"?e.slice(0,-1):e;t.startsWith(\"/\")||(t=`/${t}`);let s=t.split(\"/\").filter(n=>n&&n!==\".\"),r=[];for(let n of s)n===\"..\"?r.pop():r.push(n);return`/${r.join(\"/\")}`||\"/\"}function x(e,t){if(e.includes(\"\\0\"))throw new Error(`ENOENT: path contains null byte, ${t} '${e}'`)}function st(e){let t=O(e);if(t===\"/\")return\"/\";let s=t.lastIndexOf(\"/\");return s===0?\"/\":t.slice(0,s)}function qe(e,t){if(t.startsWith(\"/\"))return O(t);let s=e===\"/\"?`/${t}`:`${e}/${t}`;return O(s)}function Ge(e,t){return e===\"/\"?`/${t}`:`${e}/${t}`}function ct(e,t){if(t.startsWith(\"/\"))return O(t);let s=st(e);return O(Ge(s,t))}var ut=new TextEncoder;function yo(e){return typeof e==\"object\"&&e!==null&&!(e instanceof Uint8Array)&&\"content\"in e}var ze=class{data=new Map;constructor(t){if(this.data.set(\"/\",{type:\"directory\",mode:493,mtime:new Date}),t)for(let[s,r]of Object.entries(t))typeof r==\"function\"?this.writeFileLazy(s,r):yo(r)?this.writeFileSync(s,r.content,void 0,{mode:r.mode,mtime:r.mtime}):this.writeFileSync(s,r)}ensureParentDirs(t){let s=st(t);s!==\"/\"&&(this.data.has(s)||(this.ensureParentDirs(s),this.data.set(s,{type:\"directory\",mode:493,mtime:new Date})))}writeFileSync(t,s,r,n){x(t,\"write\");let i=O(t);this.ensureParentDirs(i);let o=be(r),a=Fe(s,o);this.data.set(i,{type:\"file\",content:a,mode:n?.mode??420,mtime:n?.mtime??new Date})}writeFileLazy(t,s,r){x(t,\"write\");let n=O(t);this.ensureParentDirs(n),this.data.set(n,{type:\"file\",lazy:s,mode:r?.mode??420,mtime:r?.mtime??new Date})}async materializeLazy(t,s){let r=await s.lazy(),i={type:\"file\",content:typeof r==\"string\"?ut.encode(r):r,mode:s.mode,mtime:s.mtime};return this.data.set(t,i),i}async readFile(t,s){let r=await this.readFileBuffer(t),n=be(s);return Me(r,n)}async readFileBytes(t){let s=await this.readFileBuffer(t);return Me(s,\"binary\")}async readFileBuffer(t){x(t,\"open\");let s=this.resolvePathWithSymlinks(t),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, open '${t}'`);if(r.type!==\"file\")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);if(\"lazy\"in r){let n=await this.materializeLazy(s,r);return n.content instanceof Uint8Array?n.content:ut.encode(n.content)}return r.content instanceof Uint8Array?r.content:ut.encode(r.content)}async writeFile(t,s,r){this.writeFileSync(t,s,r)}async appendFile(t,s,r){x(t,\"append\");let n=O(t),i=this.data.get(n);if(i&&i.type===\"directory\")throw new Error(`EISDIR: illegal operation on a directory, write '${t}'`);let o=be(r),a=Fe(s,o);if(i?.type===\"file\"){let l=i;\"lazy\"in l&&(l=await this.materializeLazy(n,l));let c=\"content\"in l&&l.content instanceof Uint8Array?l.content:ut.encode(\"content\"in l?l.content:\"\"),u=new Uint8Array(c.length+a.length);u.set(c),u.set(a,c.length),this.data.set(n,{type:\"file\",content:u,mode:l.mode,mtime:new Date})}else this.writeFileSync(t,s,r)}async exists(t){if(t.includes(\"\\0\"))return!1;try{let s=this.resolvePathWithSymlinks(t);return this.data.has(s)}catch{return!1}}async stat(t){x(t,\"stat\");let s=this.resolvePathWithSymlinks(t),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);r.type===\"file\"&&\"lazy\"in r&&(r=await this.materializeLazy(s,r));let n=0;return r.type===\"file\"&&\"content\"in r&&r.content&&(r.content instanceof Uint8Array?n=r.content.length:n=ut.encode(r.content).length),{isFile:r.type===\"file\",isDirectory:r.type===\"directory\",isSymbolicLink:!1,mode:r.mode,size:n,mtime:r.mtime||new Date}}async lstat(t){x(t,\"lstat\");let s=this.resolveIntermediateSymlinks(t),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);if(r.type===\"symlink\")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:r.mode,size:r.target.length,mtime:r.mtime||new Date};r.type===\"file\"&&\"lazy\"in r&&(r=await this.materializeLazy(s,r));let n=0;return r.type===\"file\"&&\"content\"in r&&r.content&&(r.content instanceof Uint8Array?n=r.content.length:n=ut.encode(r.content).length),{isFile:r.type===\"file\",isDirectory:r.type===\"directory\",isSymbolicLink:!1,mode:r.mode,size:n,mtime:r.mtime||new Date}}resolveIntermediateSymlinks(t){let s=O(t);if(s===\"/\")return\"/\";let r=s.slice(1).split(\"/\");if(r.length<=1)return s;let n=\"\",i=new Set;for(let o=0;o<r.length-1;o++){let a=r[o];n=`${n}/${a}`;let l=this.data.get(n),c=0,u=40;for(;l&&l.type===\"symlink\"&&c<u;){if(i.has(n))throw new Error(`ELOOP: too many levels of symbolic links, lstat '${t}'`);i.add(n),n=ct(n,l.target),l=this.data.get(n),c++}if(c>=u)throw new Error(`ELOOP: too many levels of symbolic links, lstat '${t}'`)}return`${n}/${r[r.length-1]}`}resolvePathWithSymlinks(t){let s=O(t);if(s===\"/\")return\"/\";let r=s.slice(1).split(\"/\"),n=\"\",i=new Set;for(let o of r){n=`${n}/${o}`;let a=this.data.get(n),l=0,c=40;for(;a&&a.type===\"symlink\"&&l<c;){if(i.has(n))throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`);i.add(n),n=ct(n,a.target),a=this.data.get(n),l++}if(l>=c)throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`)}return n}async mkdir(t,s){this.mkdirSync(t,s)}mkdirSync(t,s){x(t,\"mkdir\");let r=O(t);if(this.data.has(r)){if(this.data.get(r)?.type===\"file\")throw new Error(`EEXIST: file already exists, mkdir '${t}'`);if(!s?.recursive)throw new Error(`EEXIST: directory already exists, mkdir '${t}'`);return}let n=st(r);if(n!==\"/\"&&!this.data.has(n))if(s?.recursive)this.mkdirSync(n,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${t}'`);this.data.set(r,{type:\"directory\",mode:493,mtime:new Date})}async readdir(t){return(await this.readdirWithFileTypes(t)).map(r=>r.name)}async readdirWithFileTypes(t){x(t,\"scandir\");let s=O(t),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);let n=new Set;for(;r&&r.type===\"symlink\";){if(n.has(s))throw new Error(`ELOOP: too many levels of symbolic links, scandir '${t}'`);n.add(s),s=ct(s,r.target),r=this.data.get(s)}if(!r)throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);if(r.type!==\"directory\")throw new Error(`ENOTDIR: not a directory, scandir '${t}'`);let i=s===\"/\"?\"/\":`${s}/`,o=new Map;for(let[a,l]of this.data.entries())if(a!==s&&a.startsWith(i)){let c=a.slice(i.length),u=c.split(\"/\")[0];u&&!c.includes(\"/\",u.length)&&!o.has(u)&&o.set(u,{name:u,isFile:l.type===\"file\",isDirectory:l.type===\"directory\",isSymbolicLink:l.type===\"symlink\"})}return Array.from(o.values()).sort((a,l)=>a.name<l.name?-1:a.name>l.name?1:0)}async rm(t,s){x(t,\"rm\");let r=O(t),n=this.data.get(r);if(!n){if(s?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${t}'`)}if(n.type===\"directory\"){let i=await this.readdir(r);if(i.length>0){if(!s?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${t}'`);for(let o of i){let a=Ge(r,o);await this.rm(a,s)}}}this.data.delete(r)}async cp(t,s,r){x(t,\"cp\"),x(s,\"cp\");let n=O(t),i=O(s),o=this.data.get(n);if(!o)throw new Error(`ENOENT: no such file or directory, cp '${t}'`);if(o.type===\"file\")if(this.ensureParentDirs(i),\"content\"in o){let a=o.content instanceof Uint8Array?new Uint8Array(o.content):o.content;this.data.set(i,{...o,content:a})}else this.data.set(i,{...o});else if(o.type===\"symlink\")this.ensureParentDirs(i),this.data.set(i,{...o});else if(o.type===\"directory\"){if(!r?.recursive)throw new Error(`EISDIR: is a directory, cp '${t}'`);await this.mkdir(i,{recursive:!0});let a=await this.readdir(n);for(let l of a){let c=Ge(n,l),u=Ge(i,l);await this.cp(c,u,r)}}}async mv(t,s){await this.cp(t,s,{recursive:!0}),await this.rm(t,{recursive:!0})}getAllPaths(){return Array.from(this.data.keys())}resolvePath(t,s){return qe(t,s)}async chmod(t,s){x(t,\"chmod\");let r=O(t),n=this.data.get(r);if(!n)throw new Error(`ENOENT: no such file or directory, chmod '${t}'`);n.mode=s}async symlink(t,s){x(s,\"symlink\");let r=O(s);if(this.data.has(r))throw new Error(`EEXIST: file already exists, symlink '${s}'`);this.ensureParentDirs(r),this.data.set(r,{type:\"symlink\",target:t,mode:511,mtime:new Date})}async link(t,s){x(t,\"link\"),x(s,\"link\");let r=O(t),n=O(s),i=this.data.get(r);if(!i)throw new Error(`ENOENT: no such file or directory, link '${t}'`);if(i.type!==\"file\")throw new Error(`EPERM: operation not permitted, link '${t}'`);if(this.data.has(n))throw new Error(`EEXIST: file already exists, link '${s}'`);let o=i;\"lazy\"in o&&(o=await this.materializeLazy(r,o)),this.ensureParentDirs(n),this.data.set(n,{type:\"file\",content:o.content,mode:o.mode,mtime:o.mtime})}async readlink(t){x(t,\"readlink\");let s=O(t),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);if(r.type!==\"symlink\")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);return r.target}async realpath(t){x(t,\"realpath\");let s=this.resolvePathWithSymlinks(t);if(!this.data.has(s))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);return s}async utimes(t,s,r){x(t,\"utimes\");let n=O(t),i=this.resolvePathWithSymlinks(n),o=this.data.get(i);if(!o)throw new Error(`ENOENT: no such file or directory, utimes '${t}'`);o.mtime=r}};function go(e){let t=e;return typeof t.mkdirSync==\"function\"&&typeof t.writeFileSync==\"function\"}function wo(e,t){e.mkdirSync(\"/bin\",{recursive:!0}),e.mkdirSync(\"/usr/bin\",{recursive:!0}),t&&(e.mkdirSync(\"/home/user\",{recursive:!0}),e.mkdirSync(\"/tmp\",{recursive:!0}))}function vo(e){e.mkdirSync(\"/dev\",{recursive:!0}),e.writeFileSync(\"/dev/null\",\"\"),e.writeFileSync(\"/dev/zero\",new Uint8Array(0)),e.writeFileSync(\"/dev/stdin\",\"\"),e.writeFileSync(\"/dev/stdout\",\"\"),e.writeFileSync(\"/dev/stderr\",\"\")}function bo(e,t){e.mkdirSync(\"/proc/self/fd\",{recursive:!0}),e.writeFileSync(\"/proc/version\",`${Yr}\n`),e.writeFileSync(\"/proc/self/exe\",\"/bin/bash\"),e.writeFileSync(\"/proc/self/cmdline\",\"bash\\0\"),e.writeFileSync(\"/proc/self/comm\",`bash\n`),e.writeFileLazy?e.writeFileLazy(\"/proc/self/status\",()=>Ms(t)):e.writeFileSync(\"/proc/self/status\",Ms(t)),e.writeFileSync(\"/proc/self/fd/0\",\"/dev/stdin\"),e.writeFileSync(\"/proc/self/fd/1\",\"/dev/stdout\"),e.writeFileSync(\"/proc/self/fd/2\",\"/dev/stderr\")}function vn(e,t,s={pid:1,ppid:0,uid:1e3,gid:1e3}){go(e)&&(wo(e,t),vo(e),bo(e,s))}var Eo=[\"allexport\",\"errexit\",\"noglob\",\"noclobber\",\"noexec\",\"nounset\",\"pipefail\",\"posix\",\"verbose\",\"xtrace\"],$o=[\"braceexpand\",\"hashall\",\"interactive-comments\"];function Zs(e){let t=[],s=[...$o.map(r=>({name:r,enabled:!0})),...Eo.map(r=>({name:r,enabled:e[r]}))].sort((r,n)=>r.name.localeCompare(n.name));for(let r of s)r.enabled&&t.push(r.name);return t.join(\":\")}function dt(e){e.state.env.set(\"SHELLOPTS\",Zs(e.state.options))}var So=[\"dotglob\",\"expand_aliases\",\"extglob\",\"failglob\",\"globskipdots\",\"globstar\",\"lastpipe\",\"nocaseglob\",\"nocasematch\",\"nullglob\",\"xpg_echo\"];function qs(e){let t=[];for(let s of So)e[s]&&t.push(s);return t.join(\":\")}function Gs(e){e.state.env.set(\"BASHOPTS\",qs(e.state.shoptOptions))}var Po=\"BASH_ALIAS_\";function bn(e){return e.parts.length!==1?!1:e.parts[0].type===\"Literal\"}function En(e){if(e.parts.length!==1)return null;let t=e.parts[0];return t.type===\"Literal\"?t.value:null}function $n(e,t){return e.env.get(`${Po}${t}`)}function Ks(e,t,s){if(!t.name||!bn(t.name))return t;let r=En(t.name);if(!r)return t;let n=$n(e,r);if(!n||s.has(r))return t;try{s.add(r);let i=new B,o=n,a=n.endsWith(\" \");if(!a)for(let f of t.args){let d=Pn(f);o+=` ${d}`}let l;try{l=i.parse(o)}catch(f){if(f instanceof qt)throw f;return t}if(l.statements.length!==1||l.statements[0].pipelines.length!==1||l.statements[0].pipelines[0].commands.length!==1)return Sn(t,n);let c=l.statements[0].pipelines[0].commands[0];if(c.type!==\"SimpleCommand\")return Sn(t,n);let u={...c,assignments:[...t.assignments,...c.assignments],redirections:[...c.redirections,...t.redirections],line:t.line};if(a&&t.args.length>0&&(u={...u,args:[...u.args,...t.args]},u.args.length>0)){let f=u.args[0];if(bn(f)){let d=En(f);if(d&&$n(e,d)){let p={type:\"SimpleCommand\",name:f,args:u.args.slice(1),assignments:[],redirections:[]},y=Ks(e,p,s);y!==p&&(u={...u,name:y.name,args:[...y.args]})}}}return u}catch(i){throw s.delete(r),i}}function Sn(e,t){let s=t;for(let o of e.args){let a=Pn(o);s+=` ${a}`}let r=new B,n=r.parseWordFromString(\"eval\",!1,!1),i=r.parseWordFromString(`'${s.replace(/'/g,\"'\\\\''\")}'`,!1,!1);return{type:\"SimpleCommand\",name:n,args:[i],assignments:e.assignments,redirections:e.redirections,line:e.line}}function Pn(e){let t=\"\";for(let s of e.parts)switch(s.type){case\"Literal\":t+=s.value.replace(/([\\s\"'$`\\\\*?[\\]{}()<>|&;#!])/g,\"\\\\$1\");break;case\"SingleQuoted\":t+=`'${s.value}'`;break;case\"DoubleQuoted\":t+=`\"${s.parts.map(r=>r.type===\"Literal\"?r.value:`$${r.type}`).join(\"\")}\"`;break;case\"ParameterExpansion\":t+=`\\${${s.parameter}}`;break;case\"CommandSubstitution\":t+=\"$(...)\";break;case\"ArithmeticExpansion\":t+=`$((${s.expression}))`;break;case\"Glob\":t+=s.pattern;break;default:break}return t}async function An(e,t){let s=t.parts.map(u=>u.type===\"Literal\"?u.value:\"\\0\").join(\"\"),r=s.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\\(/);if(!r||!s.endsWith(\")\"))return null;let n=r[1],i=[],o=!1,a=\"\",l=!1;for(let u of t.parts)if(u.type===\"Literal\"){let f=u.value;if(!o){let d=f.indexOf(\"=(\");d!==-1&&(o=!0,f=f.slice(d+2))}if(o){f.endsWith(\")\")&&(f=f.slice(0,-1));let d=f.split(/(\\s+)/);for(let p of d)/^\\s+$/.test(p)?(a||l)&&(i.push(a),a=\"\",l=!1):p&&(a+=p)}}else if(o)if(u.type===\"BraceExpansion\")if(/^\\[.+\\]=/.test(a))a+=Gt({type:\"Word\",parts:[u]});else{(a||l)&&(i.push(a),a=\"\",l=!1);let d=await xe(e,{type:\"Word\",parts:[u]});i.push(...d.values)}else{(u.type===\"SingleQuoted\"||u.type===\"DoubleQuoted\"||u.type===\"Escaped\")&&(l=!0);let f=await L(e,{type:\"Word\",parts:[u]});a+=f}(a||l)&&i.push(a);let c=i.map(u=>/^\\[.+\\]=/.test(u)?u:u===\"\"?\"''\":/[\\s\"'\\\\$`!*?[\\]{}|&;<>()]/.test(u)&&!u.startsWith(\"'\")&&!u.startsWith('\"')?`'${u.replace(/'/g,\"'\\\\''\")}'`:u);return`${n}=(${c.join(\" \")})`}async function kn(e,t){let s=-1,r=-1,n=!1;for(let h=0;h<t.parts.length;h++){let w=t.parts[h];if(w.type===\"Literal\"){let E=w.value.indexOf(\"+=\");if(E!==-1){let b=w.value.slice(0,E);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(b)){s=h,r=E,n=!0;break}if(/^[a-zA-Z_][a-zA-Z0-9_]*\\[[^\\]]+\\]$/.test(b)){s=h,r=E,n=!0;break}}let g=w.value.indexOf(\"=\");if(g!==-1&&(g===0||w.value[g-1]!==\"+\")){let b=w.value.slice(0,g);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(b)||/^[a-zA-Z_][a-zA-Z0-9_]*\\[[^\\]]+\\]$/.test(b)){s=h,r=g;break}}}}if(s===-1)return null;let i=t.parts.slice(0,s),o=t.parts[s];if(o.type!==\"Literal\")return null;let a=n?2:1,l=o.value.slice(0,r),c=o.value.slice(r+a),u=t.parts.slice(s+1),f=\"\";for(let h of i)f+=await L(e,{type:\"Word\",parts:[h]});f+=l;let d={type:\"Word\",parts:c!==\"\"?[{type:\"Literal\",value:c},...u]:u},p=d.parts.length>0?await L(e,d):\"\";return`${f}${n?\"+=\":\"=\"}${p}`}var Ao=[\"tar\",\"yq\",\"xan\",\"sqlite3\",\"python3\",\"python\"];function _n(e){return Ao.includes(e)}var W=Object.freeze({stdout:\"\",stderr:\"\",exitCode:0});function z(e=\"\"){return{stdout:e,stderr:\"\",exitCode:0}}function A(e,t=1){return{stdout:\"\",stderr:e,exitCode:t}}function _(e,t,s){return{stdout:e,stderr:t,exitCode:s}}function Q(e){return{stdout:\"\",stderr:\"\",exitCode:e?0:1}}function Te(e,t,s=\"\",r=\"\"){throw new J(e,t,s,r)}function le(e){let t=e.state.fileDescriptors;if(t&&t.size>=e.limits.maxFileDescriptors)throw new J(`too many open file descriptors (max ${e.limits.maxFileDescriptors})`,\"file_descriptors\")}function Xs(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new je;return W}if(t.length>1)throw new j(1,\"\",`bash: break: too many arguments\n`);let s=1;if(t.length>0){let r=Number.parseInt(t[0],10);if(Number.isNaN(r)||r<1)throw new j(128,\"\",`bash: break: ${t[0]}: numeric argument required\n`);s=r}throw new ye(s)}async function Ys(e,t){let s,r=!1,n=!1,i=0;for(;i<t.length;)if(t[i]===\"--\"){i++;break}else if(t[i]===\"-L\")n=!1,i++;else if(t[i]===\"-P\")n=!0,i++;else if(t[i].startsWith(\"-\")&&t[i]!==\"-\")i++;else break;let o=t.slice(i);if(o.length===0||o[0]===\"~\"?s=e.state.env.get(\"HOME\")||\"/\":o[0]===\"-\"?(s=e.state.previousDir,r=!0):s=o[0],!s.startsWith(\"/\")&&!s.startsWith(\"./\")&&!s.startsWith(\"../\")&&s!==\".\"&&s!==\"..\"){let f=e.state.env.get(\"CDPATH\");if(f){let d=f.split(\":\").filter(p=>p);for(let p of d){let y=p.startsWith(\"/\")?`${p}/${s}`:`${e.state.cwd}/${p}/${s}`;try{if((await e.fs.stat(y)).isDirectory){s=y,r=!0;break}}catch{}}}}let l=(s.startsWith(\"/\")?s:`${e.state.cwd}/${s}`).split(\"/\").filter(f=>f&&f!==\".\"),c=\"\";for(let f of l)if(f===\"..\")c=c.split(\"/\").slice(0,-1).join(\"/\")||\"/\";else{c=c?`${c}/${f}`:`/${f}`;try{if(!(await e.fs.stat(c)).isDirectory)return A(`bash: cd: ${s}: Not a directory\n`)}catch{return A(`bash: cd: ${s}: No such file or directory\n`)}}let u=c||\"/\";if(n)try{u=await e.fs.realpath(u)}catch{}return e.state.previousDir=e.state.cwd,e.state.cwd=u,e.state.env.set(\"PWD\",e.state.cwd),e.state.env.set(\"OLDPWD\",e.state.previousDir),z(r?`${u}\n`:\"\")}function Qs(e,t){return e.fs.resolvePath(e.state.cwd,t)}var ko=[\"-e\",\"-a\",\"-f\",\"-d\",\"-r\",\"-w\",\"-x\",\"-s\",\"-L\",\"-h\",\"-k\",\"-g\",\"-u\",\"-G\",\"-O\",\"-b\",\"-c\",\"-p\",\"-S\",\"-t\",\"-N\"];function ts(e){return ko.includes(e)}async function ss(e,t,s){let r=Qs(e,s);switch(t){case\"-e\":case\"-a\":return e.fs.exists(r);case\"-f\":return await e.fs.exists(r)?(await e.fs.stat(r)).isFile:!1;case\"-d\":return await e.fs.exists(r)?(await e.fs.stat(r)).isDirectory:!1;case\"-r\":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&256)!==0:!1;case\"-w\":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&128)!==0:!1;case\"-x\":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&64)!==0:!1;case\"-s\":return await e.fs.exists(r)?(await e.fs.stat(r)).size>0:!1;case\"-L\":case\"-h\":try{return(await e.fs.lstat(r)).isSymbolicLink}catch{return!1}case\"-k\":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&512)!==0:!1;case\"-g\":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&1024)!==0:!1;case\"-u\":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&2048)!==0:!1;case\"-G\":case\"-O\":return e.fs.exists(r);case\"-b\":return!1;case\"-c\":return[\"/dev/null\",\"/dev/zero\",\"/dev/random\",\"/dev/urandom\",\"/dev/tty\",\"/dev/stdin\",\"/dev/stdout\",\"/dev/stderr\"].includes(r);case\"-p\":return!1;case\"-S\":return!1;case\"-t\":return!1;case\"-N\":return e.fs.exists(r);default:return!1}}var _o=[\"-nt\",\"-ot\",\"-ef\"];function rs(e){return _o.includes(e)}async function ns(e,t,s,r){let n=Qs(e,s),i=Qs(e,r);switch(t){case\"-nt\":try{let o=await e.fs.stat(n),a=await e.fs.stat(i);return o.mtime>a.mtime}catch{return!1}case\"-ot\":try{let o=await e.fs.stat(n),a=await e.fs.stat(i);return o.mtime<a.mtime}catch{return!1}case\"-ef\":try{if(!await e.fs.exists(n)||!await e.fs.exists(i))return!1;let o=e.fs.resolvePath(e.state.cwd,n),a=e.fs.resolvePath(e.state.cwd,i);return o===a}catch{return!1}default:return!1}}var Co=new Set([\"-eq\",\"-ne\",\"-lt\",\"-le\",\"-gt\",\"-ge\"]);function is(e){return Co.has(e)}function os(e,t,s){switch(e){case\"-eq\":return t===s;case\"-ne\":return t!==s;case\"-lt\":return t<s;case\"-le\":return t<=s;case\"-gt\":return t>s;case\"-ge\":return t>=s}}function Nt(e){return e===\"=\"||e===\"==\"||e===\"!=\"}function as(e,t,s,r=!1,n=!1,i=!1){if(r){let a=ht(t,s,n,i);return e===\"!=\"?!a:a}if(n){let a=t.toLowerCase()===s.toLowerCase();return e===\"!=\"?!a:a}let o=t===s;return e===\"!=\"?!o:o}var No=new Set([\"-z\",\"-n\"]);function ls(e){return No.has(e)}function cs(e,t){switch(e){case\"-z\":return t===\"\";case\"-n\":return t!==\"\"}}async function us(e,t){let s=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[(.+)\\]$/);if(s){let r=s[1],n=s[2];if(e.state.associativeArrays?.has(r)){let a=n;return(a.startsWith(\"'\")&&a.endsWith(\"'\")||a.startsWith('\"')&&a.endsWith('\"'))&&(a=a.slice(1,-1)),a=a.replace(/\\$([a-zA-Z_][a-zA-Z0-9_]*)/g,(l,c)=>e.state.env.get(c)||\"\"),e.state.env.has(`${r}_${a}`)}let o;try{let a=new B,l=ee(a,n);o=await H(e,l.expression)}catch{if(/^-?\\d+$/.test(n))o=Number.parseInt(n,10);else{let a=e.state.env.get(n);o=a?Number.parseInt(a,10):0}}if(o<0){let a=ne(e,r),l=e.state.currentLine;if(a.length===0)return e.state.expansionStderr=(e.state.expansionStderr||\"\")+`bash: line ${l}: ${r}: bad array subscript\n`,!1;if(o=Math.max(...a)+1+o,o<0)return e.state.expansionStderr=(e.state.expansionStderr||\"\")+`bash: line ${l}: ${r}: bad array subscript\n`,!1}return e.state.env.has(`${r}_${o}`)}return e.state.env.has(t)?!0:e.state.associativeArrays?.has(t)?He(e,t).length>0:ne(e,t).length>0}async function Ke(e,t){switch(t.type){case\"CondBinary\":{let s=await L(e,t.left),r=t.right.parts.length>0&&t.right.parts.every(i=>i.type===\"SingleQuoted\"||i.type===\"DoubleQuoted\"||i.type===\"Escaped\"&&t.operator!==\"=~\"),n;if(t.operator===\"=~\")if(r){let i=await L(e,t.right);n=an(i)}else n=await cn(e,t.right);else Nt(t.operator)&&!r?n=await un(e,t.right):n=await L(e,t.right);if(Nt(t.operator)){let i=e.state.shoptOptions.nocasematch;return as(t.operator,s,n,!r,i,!0)}if(is(t.operator))return os(t.operator,await Nn(e,s),await Nn(e,n));if(rs(t.operator))return ns(e,t.operator,s,n);switch(t.operator){case\"=~\":try{let i=e.state.shoptOptions.nocasematch,o=Do(n),l=kt(o,i?\"i\":\"\").match(s);if(Oe(e,\"BASH_REMATCH\"),l)for(let c=0;c<l.length;c++)e.state.env.set(`BASH_REMATCH_${c}`,l[c]||\"\");return l!==null}catch{throw new Error(\"syntax error in regular expression\")}case\"<\":return s<n;case\">\":return s>n;default:return!1}}case\"CondUnary\":{let s=await L(e,t.operand);return ts(t.operator)?ss(e,t.operator,s):ls(t.operator)?cs(t.operator,s):t.operator===\"-v\"?await us(e,s):t.operator===\"-o\"?er(e,s):!1}case\"CondNot\":return e.state.shoptOptions.extglob&&t.operand.type===\"CondGroup\"&&t.operand.expression.type===\"CondWord\"?`!(${await L(e,t.operand.expression.word)})`!==\"\":!await Ke(e,t.operand);case\"CondAnd\":return await Ke(e,t.left)?await Ke(e,t.right):!1;case\"CondOr\":return await Ke(e,t.left)?!0:await Ke(e,t.right);case\"CondGroup\":return await Ke(e,t.expression);case\"CondWord\":return await L(e,t.word)!==\"\";default:return!1}}async function Ot(e,t){if(t.length===0)return _(\"\",\"\",1);if(t.length===1)return Q(!!t[0]);if(t.length===2){let r=t[0],n=t[1];return r===\"(\"?A(`test: '(' without matching ')'\n`,2):ts(r)?Q(await ss(e,r,n)):ls(r)?Q(cs(r,n)):r===\"!\"?Q(!n):r===\"-v\"?Q(await us(e,n)):r===\"-o\"?Q(er(e,n)):r===\"=\"||r===\"==\"||r===\"!=\"||r===\"<\"||r===\">\"||r===\"-eq\"||r===\"-ne\"||r===\"-lt\"||r===\"-le\"||r===\"-gt\"||r===\"-ge\"||r===\"-nt\"||r===\"-ot\"||r===\"-ef\"?A(`test: ${r}: unary operator expected\n`,2):_(\"\",\"\",1)}if(t.length===3){let r=t[0],n=t[1],i=t[2];if(Nt(n))return Q(as(n,r,i));if(is(n)){let o=fs(r),a=fs(i);return!o.valid||!a.valid?_(\"\",\"\",2):Q(os(n,o.value,a.value))}if(rs(n))return Q(await ns(e,n,r,i));switch(n){case\"-a\":return Q(r!==\"\"&&i!==\"\");case\"-o\":return Q(r!==\"\"||i!==\"\");case\">\":return Q(r>i);case\"<\":return Q(r<i)}if(r===\"!\"){let o=await Ot(e,[n,i]);return _(\"\",o.stderr,o.exitCode===0?1:o.exitCode===1?0:o.exitCode)}if(r===\"(\"&&i===\")\")return Q(n!==\"\")}if(t.length===4){if(t[0]===\"!\"){let r=await Ot(e,t.slice(1));return _(\"\",r.stderr,r.exitCode===0?1:r.exitCode===1?0:r.exitCode)}if(t[0]===\"(\"&&t[3]===\")\")return Ot(e,[t[1],t[2]])}let s=await xn(e,t,0);return s.pos<t.length?A(`test: too many arguments\n`,2):Q(s.value)}async function xn(e,t,s){return Oo(e,t,s)}async function Oo(e,t,s){let{value:r,pos:n}=await Cn(e,t,s);for(;t[n]===\"-o\";){let i=await Cn(e,t,n+1);r=r||i.value,n=i.pos}return{value:r,pos:n}}async function Cn(e,t,s){let{value:r,pos:n}=await Js(e,t,s);for(;t[n]===\"-a\";){let i=await Js(e,t,n+1);r=r&&i.value,n=i.pos}return{value:r,pos:n}}async function Js(e,t,s){if(t[s]===\"!\"){let{value:r,pos:n}=await Js(e,t,s+1);return{value:!r,pos:n}}return xo(e,t,s)}async function xo(e,t,s){let r=t[s];if(r===\"(\"){let{value:i,pos:o}=await xn(e,t,s+1);return{value:i,pos:t[o]===\")\"?o+1:o}}let n=t[s+1];if(Nt(n)){let i=r,o=t[s+2]??\"\";return{value:as(n,i,o),pos:s+3}}if(is(n)){let i=fs(r),o=fs(t[s+2]??\"0\");return!i.valid||!o.valid?{value:!1,pos:s+3}:{value:os(n,i.value,o.value),pos:s+3}}if(rs(n)){let i=r,o=t[s+2]??\"\";return{value:await ns(e,n,i,o),pos:s+3}}if(ts(r)){let i=t[s+1]??\"\";return{value:await ss(e,r,i),pos:s+2}}if(ls(r)){let i=t[s+1]??\"\";return{value:cs(r,i),pos:s+2}}if(r===\"-v\"){let i=t[s+1]??\"\";return{value:await us(e,i),pos:s+2}}if(r===\"-o\"){let i=t[s+1]??\"\";return{value:er(e,i),pos:s+2}}return{value:r!==void 0&&r!==\"\",pos:s+1}}function ht(e,t,s=!1,r=!1){let n=`^${Tn(t,r)}$`;return kt(n,s?\"is\":\"s\").test(e)}function Tn(e,t){let s=\"\";for(let r=0;r<e.length;r++){let n=e[r];if(t&&(n===\"@\"||n===\"*\"||n===\"+\"||n===\"?\"||n===\"!\")&&r+1<e.length&&e[r+1]===\"(\"){let i=Dn(e,r+1);if(i!==-1){let o=e.slice(r+2,i),a=Rn(o),l=a.map(u=>Tn(u,t)),c=l.length>0?l.join(\"|\"):\"(?:)\";if(n===\"@\")s+=`(?:${c})`;else if(n===\"*\")s+=`(?:${c})*`;else if(n===\"+\")s+=`(?:${c})+`;else if(n===\"?\")s+=`(?:${c})?`;else if(n===\"!\")if(i<e.length-1){let f=a.map(p=>In(p,t));if(f.every(p=>p!==null)&&f.every(p=>p===f[0])&&f[0]!==null){let p=f[0];if(p===0)s+=\"(?:.+)\";else{let y=[];p>0&&y.push(`.{0,${p-1}}`),y.push(`.{${p+1},}`),y.push(`(?!(?:${c})).{${p}}`),s+=`(?:${y.join(\"|\")})`}}else s+=`(?:(?!(?:${c})).)*?`}else s+=`(?!(?:${c})$).*`;r=i;continue}}if(n===\"\\\\\")if(r+1<e.length){let i=e[r+1];/[\\\\^$.|+(){}[\\]*?]/.test(i)?s+=`\\\\${i}`:s+=i,r++}else s+=\"\\\\\\\\\";else if(n===\"*\")s+=\".*\";else if(n===\"?\")s+=\".\";else if(n===\"[\"){let i=e.indexOf(\"]\",r+1);i!==-1?(s+=e.slice(r,i+1),r=i):s+=\"\\\\[\"}else/[\\\\^$.|+(){}]/.test(n)?s+=`\\\\${n}`:s+=n}return s}function Dn(e,t){let s=1,r=t+1;for(;r<e.length&&s>0;){let n=e[r];if(n===\"\\\\\"){r+=2;continue}if(n===\"(\")s++;else if(n===\")\"&&(s--,s===0))return r;r++}return-1}function Rn(e){let t=[],s=\"\",r=0,n=0;for(;n<e.length;){let i=e[n];if(i===\"\\\\\"){s+=i,n+1<e.length?(s+=e[n+1],n+=2):n++;continue}i===\"(\"?(r++,s+=i):i===\")\"?(r--,s+=i):i===\"|\"&&r===0?(t.push(s),s=\"\"):s+=i,n++}return t.push(s),t}function In(e,t){let s=0,r=0;for(;r<e.length;){let n=e[r];if(t&&(n===\"@\"||n===\"*\"||n===\"+\"||n===\"?\"||n===\"!\")&&r+1<e.length&&e[r+1]===\"(\"){let i=Dn(e,r+1);if(i!==-1){if(n===\"@\"){let o=e.slice(r+2,i),l=Rn(o).map(c=>In(c,t));if(l.every(c=>c!==null)&&l.every(c=>c===l[0])){s+=l[0],r=i+1;continue}return null}return null}}if(n===\"*\")return null;if(n===\"?\"){s+=1,r++;continue}if(n===\"[\"){let i=e.indexOf(\"]\",r+1);if(i!==-1){s+=1,r=i+1;continue}s+=1,r++;continue}if(n===\"\\\\\"){s+=1,r+=2;continue}s+=1,r++}return s}function er(e,t){let r=new Map([[\"errexit\",()=>e.state.options.errexit===!0],[\"nounset\",()=>e.state.options.nounset===!0],[\"pipefail\",()=>e.state.options.pipefail===!0],[\"xtrace\",()=>e.state.options.xtrace===!0],[\"e\",()=>e.state.options.errexit===!0],[\"u\",()=>e.state.options.nounset===!0],[\"x\",()=>e.state.options.xtrace===!0]]).get(t);return r?r():!1}async function Nn(e,t){if(t=t.trim(),t===\"\")return 0;if(/^[+-]?(\\d+#[a-zA-Z0-9@_]+|0[xX][0-9a-fA-F]+|0[0-7]+|\\d+)$/.test(t))return On(t);try{let s=new B,r=ee(s,t);return await H(e,r.expression)}catch{return On(t)}}function To(e,t){let s=0;for(let r of e){let n;if(r>=\"0\"&&r<=\"9\")n=r.charCodeAt(0)-48;else if(r>=\"a\"&&r<=\"z\")n=r.charCodeAt(0)-97+10;else if(r>=\"A\"&&r<=\"Z\")n=r.charCodeAt(0)-65+36;else if(r===\"@\")n=62;else if(r===\"_\")n=63;else return Number.NaN;if(n>=t)return Number.NaN;s=s*t+n}return s}function On(e){if(e=e.trim(),e===\"\")return 0;let t=!1;e.startsWith(\"-\")?(t=!0,e=e.slice(1)):e.startsWith(\"+\")&&(e=e.slice(1));let s,r=e.match(/^(\\d+)#([a-zA-Z0-9@_]+)$/);if(r){let n=Number.parseInt(r[1],10);n>=2&&n<=64?s=To(r[2],n):s=0}else/^0[xX][0-9a-fA-F]+$/.test(e)?s=Number.parseInt(e,16):/^0[0-7]+$/.test(e)?s=Number.parseInt(e,8):s=Number.parseInt(e,10);return Number.isNaN(s)&&(s=0),t?-s:s}function fs(e){if(e=e.trim(),e===\"\")return{value:0,valid:!0};let t=!1;if(e.startsWith(\"-\")?(t=!0,e=e.slice(1)):e.startsWith(\"+\")&&(e=e.slice(1)),!/^\\d+$/.test(e))return{value:0,valid:!1};let s=Number.parseInt(e,10);return Number.isNaN(s)?{value:0,valid:!1}:{value:t?-s:s,valid:!0}}function Do(e){let t=\"\",s=0;for(;s<e.length;)if(e[s]===\"\\\\\"&&s+1<e.length)t+=e[s]+e[s+1],s+=2;else if(e[s]===\"[\"){let r=Ro(e,s);t+=r.converted,s=r.endIndex}else t+=e[s],s++;return t}function Ro(e,t){let s=t+1,r=\"[\";s<e.length&&(e[s]===\"^\"||e[s]===\"!\")&&(r+=\"^\",s++);let n=!1;s<e.length&&e[s]===\"]\"&&(n=!0,s++);let i=!1;s<e.length&&e[s]===\"[\"&&s+1<e.length&&e[s+1]!==\":\"&&(i=!0,s++);let o=\"\",a=!1;for(;s<e.length;){let l=e[s];if(l===\"]\"){a=!0,s++;break}if(l===\"[\"&&s+1<e.length&&e[s+1]===\":\"){let c=e.indexOf(\":]\",s+2);if(c!==-1){let u=e.slice(s+2,c);o+=Io(u),s=c+2;continue}}if(l===\"[\"&&s+1<e.length){let c=e[s+1];if(c===\".\"||c===\"=\"){let u=`${c}]`,f=e.indexOf(u,s+2);if(f!==-1){let d=e.slice(s+2,f);o+=d,s=f+2;continue}}}if(l===\"\\\\\"&&s+1<e.length){o+=l+e[s+1],s+=2;continue}o+=l,s++}return a?(n&&(r+=\"\\\\]\"),i&&(r+=\"\\\\[\"),r+=o,r+=\"]\",{converted:r,endIndex:s}):{converted:\"\\\\[\",endIndex:t+1}}function Io(e){return new Map([[\"alnum\",\"a-zA-Z0-9\"],[\"alpha\",\"a-zA-Z\"],[\"ascii\",\"\\\\x00-\\\\x7F\"],[\"blank\",\" \\\\t\"],[\"cntrl\",\"\\\\x00-\\\\x1F\\\\x7F\"],[\"digit\",\"0-9\"],[\"graph\",\"!-~\"],[\"lower\",\"a-z\"],[\"print\",\" -~\"],[\"punct\",\"!-/:-@\\\\[-`{-~\"],[\"space\",\" \\\\t\\\\n\\\\r\\\\f\\\\v\"],[\"upper\",\"A-Z\"],[\"word\",\"a-zA-Z0-9_\"],[\"xdigit\",\"0-9A-Fa-f\"]]).get(e)??\"\"}function De(e){let t=[],s=\"\",r=!1,n=!1,i=!1,o=!1;for(let a of e){if(i){s+=a,i=!1,o=!0;continue}if(a===\"\\\\\"){i=!0;continue}if(a===\"'\"&&!n){r||(o=!0),r=!r;continue}if(a==='\"'&&!r){n||(o=!0),n=!n;continue}if((a===\" \"||a===\"\t\"||a===`\n`)&&!r&&!n){o&&(t.push(s),s=\"\",o=!1);continue}s+=a,o=!0}return o&&t.push(s),t}function ds(e){let t=[],s=0;for(;s<e.length;){for(;s<e.length&&/\\s/.test(e[s]);)s++;if(s>=e.length)break;if(e[s]!==\"[\"){s++;continue}s++;let r=\"\";if(e[s]===\"'\"||e[s]==='\"'){let i=e[s];for(s++;s<e.length&&e[s]!==i;)r+=e[s],s++;e[s]===i&&s++}else for(;s<e.length&&e[s]!==\"]\"&&e[s]!==\"=\";)r+=e[s],s++;for(;s<e.length&&e[s]!==\"]\";)s++;if(e[s]===\"]\"&&s++,e[s]!==\"=\")continue;s++;let n=\"\";if(e[s]===\"'\"||e[s]==='\"'){let i=e[s];for(s++;s<e.length&&e[s]!==i;)e[s]===\"\\\\\"&&s+1<e.length&&s++,n+=e[s],s++;e[s]===i&&s++}else for(;s<e.length&&!/\\s/.test(e[s]);)n+=e[s],s++;t.push([r,n])}return t}function Ln(e){let t=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\\((.*)\\)$/s);if(t)return{name:t[1],isArray:!0,arrayElements:De(t[2])};let s=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[([^\\]]+)\\]=(.*)$/s);if(s)return{name:s[1],isArray:!1,arrayIndex:s[2],value:s[3]};if(e.includes(\"=\")){let r=e.indexOf(\"=\");return{name:e.slice(0,r),isArray:!1,value:e.slice(r+1)}}return{name:e,isArray:!1}}async function Lo(e,t){try{let s=new B,r=ee(s,t);return await H(e,r.expression)}catch{let s=parseInt(t,10);return Number.isNaN(s)?0:s}}async function Fn(e,t,s={}){let{name:r,isArray:n,arrayElements:i,value:o,arrayIndex:a}=t,{makeReadonly:l=!1,checkReadonly:c=!0}=s;if(c){let u=se(e,r);if(u)return u}if(n&&i){for(let u=0;u<i.length;u++)e.state.env.set(`${r}_${u}`,i[u]);e.state.env.set(`${r}__length`,String(i.length))}else if(a!==void 0&&o!==void 0){let u=await Lo(e,a);e.state.env.set(`${r}_${u}`,o);let f=parseInt(e.state.env.get(`${r}__length`)??\"0\",10);u>=f&&e.state.env.set(`${r}__length`,String(u+1))}else o!==void 0&&e.state.env.set(r,o);return l&&de(e,r),null}function Xe(e,t){e.state.localVarDepth=e.state.localVarDepth||new Map,e.state.localVarDepth.set(t,e.state.callDepth)}function pt(e,t){return e.state.localVarDepth?.get(t)}function hs(e,t){e.state.localVarDepth?.delete(t)}function Mn(e,t,s){e.state.localVarStack=e.state.localVarStack||new Map;let r=e.state.localVarStack.get(t)||[];r.push({value:s,scopeIndex:e.state.localScopes.length-1}),e.state.localVarStack.set(t,r)}function ps(e,t){let s=e.state.localVarStack?.get(t);if(!(!s||s.length===0))return s.pop()}function Wn(e,t){if(e.state.localVarStack)for(let[s,r]of e.state.localVarStack.entries()){for(;r.length>0&&r[r.length-1].scopeIndex===t;)r.pop();r.length===0&&e.state.localVarStack.delete(s)}}var tr=new Set([\":\",\".\",\"break\",\"continue\",\"eval\",\"exec\",\"exit\",\"export\",\"readonly\",\"return\",\"set\",\"shift\",\"trap\",\"unset\"]);function zn(e){return tr.has(e)}var sr=new Set([\"if\",\"then\",\"else\",\"elif\",\"fi\",\"case\",\"esac\",\"for\",\"select\",\"while\",\"until\",\"do\",\"done\",\"in\",\"function\",\"{\",\"}\",\"time\",\"[[\",\"]]\",\"!\"]),mt=new Set([\":\",\"true\",\"false\",\"cd\",\"export\",\"unset\",\"exit\",\"local\",\"set\",\"break\",\"continue\",\"return\",\"eval\",\"shift\",\"getopts\",\"compgen\",\"complete\",\"compopt\",\"pushd\",\"popd\",\"dirs\",\"source\",\".\",\"read\",\"mapfile\",\"readarray\",\"declare\",\"typeset\",\"readonly\",\"let\",\"command\",\"shopt\",\"exec\",\"test\",\"[\",\"echo\",\"printf\",\"pwd\",\"alias\",\"unalias\",\"type\",\"hash\",\"ulimit\",\"umask\",\"trap\",\"times\",\"wait\",\"kill\",\"jobs\",\"fg\",\"bg\",\"disown\",\"suspend\",\"fc\",\"history\",\"help\",\"enable\",\"builtin\",\"caller\"]);async function rt(e,t,s,r){try{if((await e.fs.stat(t)).isDirectory)return`bash: ${s}: Is a directory\n`;if(r.checkNoclobber&&e.state.options.noclobber&&!r.isClobber&&s!==\"/dev/null\")return`bash: ${s}: cannot overwrite existing file\n`}catch{}return null}function Ye(e){let s=Math.min(e.length,8192);for(let r=0;r<s;r++)if(e.charCodeAt(r)>127)return\"utf8\";return\"binary\"}function Fo(e){if(!e.startsWith(\"__rw__:\"))return null;let t=e.slice(7),s=t.indexOf(\":\");if(s===-1)return null;let r=Number.parseInt(t.slice(0,s),10);if(Number.isNaN(r)||r<0)return null;let n=s+1,i=t.slice(n,n+r),o=n+r+1,a=t.slice(o),l=a.indexOf(\":\");if(l===-1)return null;let c=Number.parseInt(a.slice(0,l),10);if(Number.isNaN(c)||c<0)return null;let u=a.slice(l+1);return{path:i,position:c,content:u}}async function Vn(e,t){let s=new Map;for(let r=0;r<t.length;r++){let n=t[r];if(n.target.type===\"HereDoc\")continue;if(n.operator===\">&\"||n.operator===\"<&\"){if(Us(e,n.target))return{targets:s,error:`bash: $@: ambiguous redirect\n`};s.set(r,await L(e,n.target))}else{let o=await Xt(e,n.target);if(\"error\"in o)return{targets:s,error:o.error};s.set(r,o.target)}}return{targets:s}}function Mo(e){e.state.nextFd===void 0&&(e.state.nextFd=10);let t=e.state.nextFd,s=e.limits.maxFileDescriptors;if(t>=s)throw new Error(`bash: cannot allocate file descriptor: too many open files (max ${s})`);return e.state.nextFd++,t}async function ms(e,t){for(let s of t){if(!s.fdVariable)continue;if(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),(s.operator===\">&\"||s.operator===\"<&\")&&s.target.type===\"Word\"&&await L(e,s.target)===\"-\"){let i=e.state.env.get(s.fdVariable);if(i!==void 0){let o=Number.parseInt(i,10);Number.isNaN(o)||e.state.fileDescriptors.delete(o)}continue}let r=Mo(e);if(e.state.env.set(s.fdVariable,String(r)),s.target.type===\"Word\"){let n=await L(e,s.target);if(s.operator===\">&\"||s.operator===\"<&\"){let i=Number.parseInt(n,10);if(!Number.isNaN(i)){let o=e.state.fileDescriptors.get(i);o!==void 0&&(le(e),e.state.fileDescriptors.set(r,o));continue}}if(s.operator===\">\"||s.operator===\">>\"||s.operator===\">|\"||s.operator===\"&>\"||s.operator===\"&>>\"){let i=e.fs.resolvePath(e.state.cwd,n);(s.operator===\">\"||s.operator===\">|\"||s.operator===\"&>\")&&await e.fs.writeFile(i,\"\",\"binary\"),le(e),e.state.fileDescriptors.set(r,`__file__:${i}`)}else if(s.operator===\"<<<\")le(e),e.state.fileDescriptors.set(r,`${n}\n`);else if(s.operator===\"<\"||s.operator===\"<>\")try{let i=e.fs.resolvePath(e.state.cwd,n),o=await e.fs.readFile(i);le(e),e.state.fileDescriptors.set(r,o)}catch{return _(\"\",`bash: ${n}: No such file or directory\n`,1)}}}return null}async function Re(e,t){for(let s of t){if(s.target.type===\"HereDoc\")continue;let r=s.operator===\">&\";if(s.operator!==\">\"&&s.operator!==\">|\"&&s.operator!==\"&>\"&&!r)continue;let n;if(r){if(n=await L(e,s.target),n===\"-\"||!Number.isNaN(Number.parseInt(n,10))||s.fd!=null)continue}else{let a=await Xt(e,s.target);if(\"error\"in a)return _(\"\",a.error,1);n=a.target}let i=e.fs.resolvePath(e.state.cwd,n),o=s.operator===\">|\";if(i.includes(\"\\0\"))return _(\"\",`bash: ${n}: No such file or directory\n`,1);try{let a=await e.fs.stat(i);if(a.isDirectory)return _(\"\",`bash: ${n}: Is a directory\n`,1);if(e.state.options.noclobber&&!o&&!a.isDirectory&&n!==\"/dev/null\")return _(\"\",`bash: ${n}: cannot overwrite existing file\n`,1)}catch{}if(n!==\"/dev/null\"&&n!==\"/dev/stdout\"&&n!==\"/dev/stderr\"&&n!==\"/dev/full\"&&await e.fs.writeFile(i,\"\",\"binary\"),n===\"/dev/full\")return _(\"\",`bash: /dev/full: No space left on device\n`,1)}return null}async function K(e,t,s,r){let{stdout:n,stderr:i,exitCode:o}=t,l=t.stdoutKind===\"bytes\"||t.stdoutKind===void 0&&t.stdoutEncoding===\"binary\"?\"binary\":\"utf8\",c=p=>l;for(let p=0;p<s.length;p++){let y=s[p];if(y.target.type===\"HereDoc\")continue;let h,w=r?.get(p);if(w!==void 0)h=w;else if(y.operator===\">&\"||y.operator===\"<&\"){if(Us(e,y.target)){i+=`bash: $@: ambiguous redirect\n`,o=1,n=\"\";continue}h=await L(e,y.target)}else{let g=await Xt(e,y.target);if(\"error\"in g){i+=g.error,o=1,n=\"\";continue}h=g.target}if(!y.fdVariable){if(h.includes(\"\\0\")){i+=`bash: ${h.replace(/\\0/g,\"\")}: No such file or directory\n`,o=1,n=\"\";continue}switch(y.operator){case\">\":case\">|\":{let E=y.fd??1,g=y.operator===\">|\";if(E===1){if(h===\"/dev/stdout\")break;if(h===\"/dev/stderr\"){i+=n,n=\"\";break}if(h===\"/dev/full\"){i+=`bash: echo: write error: No space left on device\n`,o=1,n=\"\";break}let b=e.fs.resolvePath(e.state.cwd,h),m=await rt(e,b,h,{checkNoclobber:!0,isClobber:g});if(m){i+=m,o=1,n=\"\";break}await e.fs.writeFile(b,n,c(n)),n=\"\"}else if(E===2){if(h===\"/dev/stderr\")break;if(h===\"/dev/stdout\"){n+=i,i=\"\";break}if(h===\"/dev/full\"){i+=`bash: echo: write error: No space left on device\n`,o=1;break}if(h===\"/dev/null\")i=\"\";else{let b=e.fs.resolvePath(e.state.cwd,h),m=await rt(e,b,h,{checkNoclobber:!0,isClobber:g});if(m){i+=m,o=1;break}await e.fs.writeFile(b,i,Ye(i)),i=\"\"}}break}case\">>\":{let E=y.fd??1;if(E===1){if(h===\"/dev/stdout\")break;if(h===\"/dev/stderr\"){i+=n,n=\"\";break}if(h===\"/dev/full\"){i+=`bash: echo: write error: No space left on device\n`,o=1,n=\"\";break}let g=e.fs.resolvePath(e.state.cwd,h),b=await rt(e,g,h,{});if(b){i+=b,o=1,n=\"\";break}await e.fs.appendFile(g,n,c(n)),n=\"\"}else if(E===2){if(h===\"/dev/stderr\")break;if(h===\"/dev/stdout\"){n+=i,i=\"\";break}if(h===\"/dev/full\"){i+=`bash: echo: write error: No space left on device\n`,o=1;break}let g=e.fs.resolvePath(e.state.cwd,h),b=await rt(e,g,h,{});if(b){i+=b,o=1;break}await e.fs.appendFile(g,i,Ye(i)),i=\"\"}break}case\">&\":case\"<&\":{let E=y.fd??1;if(h===\"-\")break;if(h.endsWith(\"-\")){let g=h.slice(0,-1),b=Number.parseInt(g,10);if(!Number.isNaN(b)){let m=e.state.fileDescriptors?.get(b);m!==void 0?(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),e.state.fileDescriptors.set(E,m),b>=3&&e.state.fileDescriptors?.delete(b)):b===1||b===2?(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),e.state.fileDescriptors.set(E,`__dupout__:${b}`)):b===0?(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),e.state.fileDescriptors.set(E,`__dupin__:${b}`)):b>=3&&(i+=`bash: ${b}: Bad file descriptor\n`,o=1)}break}if(h===\"2\"||h===\"&2\")E===1&&(i+=n,n=\"\");else if(h===\"1\"||h===\"&1\")n+=i,i=\"\";else{let g=Number.parseInt(h,10);if(Number.isNaN(g)){if(y.operator===\">&\"){let b=e.fs.resolvePath(e.state.cwd,h),m=await rt(e,b,h,{checkNoclobber:!0});if(m){i=m,o=1,n=\"\";break}if(y.fd==null){let v=n+i;await e.fs.writeFile(b,v,c(v)),n=\"\",i=\"\"}else E===1?(await e.fs.writeFile(b,n,c(n)),n=\"\"):E===2&&(await e.fs.writeFile(b,i,Ye(i)),i=\"\")}}else{let b=e.state.fileDescriptors?.get(g);if(b?.startsWith(\"__file__:\")){let m=b.slice(9);E===1?(await e.fs.appendFile(m,n,c(n)),n=\"\"):E===2&&(await e.fs.appendFile(m,i,Ye(i)),i=\"\")}else if(b?.startsWith(\"__rw__:\")){let m=Fo(b);m&&(E===1?(await e.fs.appendFile(m.path,n,c(n)),n=\"\"):E===2&&(await e.fs.appendFile(m.path,i,Ye(i)),i=\"\"))}else if(b?.startsWith(\"__dupout__:\")){let m=Number.parseInt(b.slice(11),10);if(m!==1)if(m===2)E===1&&(i+=n,n=\"\");else{let v=e.state.fileDescriptors?.get(m);if(v?.startsWith(\"__file__:\")){let $=v.slice(9);E===1?(await e.fs.appendFile($,n,c(n)),n=\"\"):E===2&&(await e.fs.appendFile($,i,Ye(i)),i=\"\")}}}else b?.startsWith(\"__dupin__:\")?(i+=`bash: ${g}: Bad file descriptor\n`,o=1,n=\"\"):g>=3&&(i+=`bash: ${g}: Bad file descriptor\n`,o=1,n=\"\")}}break}case\"&>\":{if(h===\"/dev/full\"){i=`bash: echo: write error: No space left on device\n`,o=1,n=\"\";break}let E=e.fs.resolvePath(e.state.cwd,h),g=await rt(e,E,h,{checkNoclobber:!0});if(g){i=g,o=1,n=\"\";break}let b=n+i;await e.fs.writeFile(E,b,c(b)),n=\"\",i=\"\";break}case\"&>>\":{if(h===\"/dev/full\"){i=`bash: echo: write error: No space left on device\n`,o=1,n=\"\";break}let E=e.fs.resolvePath(e.state.cwd,h),g=await rt(e,E,h,{});if(g){i=g,o=1,n=\"\";break}let b=n+i;await e.fs.appendFile(E,b,c(b)),n=\"\",i=\"\";break}}}}let u=e.state.fileDescriptors?.get(1);if(u){if(u===\"__dupout__:2\")i+=n,n=\"\";else if(u.startsWith(\"__file__:\")){let p=u.slice(9);await e.fs.appendFile(p,n,c(n)),n=\"\"}else if(u.startsWith(\"__file_append__:\")){let p=u.slice(16);await e.fs.appendFile(p,n,c(n)),n=\"\"}}let f=e.state.fileDescriptors?.get(2);if(f){if(f===\"__dupout__:1\")n+=i,i=\"\";else if(f.startsWith(\"__file__:\")){let p=f.slice(9);await e.fs.appendFile(p,i,Ye(i)),i=\"\"}else if(f.startsWith(\"__file_append__:\")){let p=f.slice(16);await e.fs.appendFile(p,i,Ye(i)),i=\"\"}}let d=_(n,i,o);return t.stdoutKind&&(d.stdoutKind=t.stdoutKind),t.stdoutEncoding===\"binary\"&&(d.stdoutEncoding=\"binary\"),d}function Bn(e,t){if(e.state.options.posix&&tr.has(t.name)){let r=`bash: line ${e.state.currentLine}: \\`${t.name}': is a special builtin\n`;throw new j(2,\"\",r)}let s={...t,sourceFile:t.sourceFile??e.state.currentSource??\"main\"};return e.state.functions.set(t.name,s),W}async function Wo(e,t){let s=\"\";for(let r of t)if((r.operator===\"<<\"||r.operator===\"<<-\")&&r.target.type===\"HereDoc\"){let n=r.target,i=await L(e,n.content);n.stripTabs&&(i=i.split(`\n`).map(a=>a.replace(/^\\t+/,\"\")).join(`\n`)),(r.fd??0)===0&&(s=i)}else if(r.operator===\"<<<\"&&r.target.type===\"Word\")s=`${await L(e,r.target)}\n`;else if(r.operator===\"<\"&&r.target.type===\"Word\"){let n=await L(e,r.target),i=e.fs.resolvePath(e.state.cwd,n);try{s=await e.fs.readFile(i)}catch{}}return s}async function ys(e,t,s,r=\"\",n){e.state.callDepth++,e.state.callDepth>e.limits.maxCallDepth&&(e.state.callDepth--,Te(`${t.name}: maximum recursion depth (${e.limits.maxCallDepth}) exceeded, increase executionLimits.maxCallDepth`,\"recursion\")),e.state.funcNameStack||(e.state.funcNameStack=[]),e.state.callLineStack||(e.state.callLineStack=[]),e.state.sourceStack||(e.state.sourceStack=[]),e.state.funcNameStack.unshift(t.name),e.state.callLineStack.unshift(n??e.state.currentLine),e.state.sourceStack.unshift(t.sourceFile??\"main\"),e.state.localScopes.push(new Map),e.state.localExportedVars||(e.state.localExportedVars=[]),e.state.localExportedVars.push(new Set);let i=new Map;for(let c=0;c<s.length;c++)i.set(String(c+1),e.state.env.get(String(c+1))),e.state.env.set(String(c+1),s[c]);i.set(\"@\",e.state.env.get(\"@\")),i.set(\"#\",e.state.env.get(\"#\")),e.state.env.set(\"@\",s.join(\" \")),e.state.env.set(\"#\",String(s.length));let o=()=>{let c=e.state.localScopes.length-1,u=e.state.localScopes.pop();if(u)for(let[f,d]of u)d===void 0?e.state.env.delete(f):e.state.env.set(f,d);if(Wn(e,c),e.state.fullyUnsetLocals)for(let[f,d]of e.state.fullyUnsetLocals.entries())d===c&&e.state.fullyUnsetLocals.delete(f);if(e.state.localExportedVars&&e.state.localExportedVars.length>0){let f=e.state.localExportedVars.pop();if(f)for(let d of f)e.state.exportedVars?.delete(d)}for(let[f,d]of i)d===void 0?e.state.env.delete(f):e.state.env.set(f,d);e.state.funcNameStack?.shift(),e.state.callLineStack?.shift(),e.state.sourceStack?.shift(),e.state.callDepth--},{targets:a,error:l}=await Vn(e,t.redirections);if(l)return o(),_(\"\",l,1);try{let c=await Wo(e,t.redirections),u=r||c,f=await e.executeCommand(t.body,u);return o(),K(e,f,t.redirections,a)}catch(c){if(o(),c instanceof ue){let u=_(c.stdout,c.stderr,c.exitCode);return K(e,u,t.redirections,a)}throw c}}var Un=[\"!\",\"[[\",\"]]\",\"case\",\"do\",\"done\",\"elif\",\"else\",\"esac\",\"fi\",\"for\",\"function\",\"if\",\"in\",\"then\",\"time\",\"until\",\"while\",\"{\",\"}\"],nr=[\".\",\":\",\"[\",\"alias\",\"bg\",\"bind\",\"break\",\"builtin\",\"caller\",\"cd\",\"command\",\"compgen\",\"complete\",\"compopt\",\"continue\",\"declare\",\"dirs\",\"disown\",\"echo\",\"enable\",\"eval\",\"exec\",\"exit\",\"export\",\"false\",\"fc\",\"fg\",\"getopts\",\"hash\",\"help\",\"history\",\"jobs\",\"kill\",\"let\",\"local\",\"logout\",\"mapfile\",\"popd\",\"printf\",\"pushd\",\"pwd\",\"read\",\"readarray\",\"readonly\",\"return\",\"set\",\"shift\",\"shopt\",\"source\",\"suspend\",\"test\",\"times\",\"trap\",\"true\",\"type\",\"typeset\",\"ulimit\",\"umask\",\"unalias\",\"unset\",\"wait\"],zo=[\"autocd\",\"assoc_expand_once\",\"cdable_vars\",\"cdspell\",\"checkhash\",\"checkjobs\",\"checkwinsize\",\"cmdhist\",\"compat31\",\"compat32\",\"compat40\",\"compat41\",\"compat42\",\"compat43\",\"compat44\",\"complete_fullquote\",\"direxpand\",\"dirspell\",\"dotglob\",\"execfail\",\"expand_aliases\",\"extdebug\",\"extglob\",\"extquote\",\"failglob\",\"force_fignore\",\"globasciiranges\",\"globstar\",\"gnu_errfmt\",\"histappend\",\"histreedit\",\"histverify\",\"hostcomplete\",\"huponexit\",\"inherit_errexit\",\"interactive_comments\",\"lastpipe\",\"lithist\",\"localvar_inherit\",\"localvar_unset\",\"login_shell\",\"mailwarn\",\"no_empty_cmd_completion\",\"nocaseglob\",\"nocasematch\",\"nullglob\",\"progcomp\",\"progcomp_alias\",\"promptvars\",\"restricted_shell\",\"shift_verbose\",\"sourcepath\",\"xpg_echo\"],Vo=nr;async function ir(e,t){let s=[],r=null,n=\"\",i=\"\",o=null,a=!1,l=!1,c=!1,u=null,f=null,d=null,p=[],y=[\"alias\",\"arrayvar\",\"binding\",\"builtin\",\"command\",\"directory\",\"disabled\",\"enabled\",\"export\",\"file\",\"function\",\"group\",\"helptopic\",\"hostname\",\"job\",\"keyword\",\"running\",\"service\",\"setopt\",\"shopt\",\"signal\",\"stopped\",\"user\",\"variable\"];for(let m=0;m<t.length;m++){let v=t[m];if(v===\"-v\")s.push(\"variable\");else if(v===\"-e\")s.push(\"export\");else if(v===\"-f\")s.push(\"file\");else if(v===\"-d\")s.push(\"directory\");else if(v===\"-k\")s.push(\"keyword\");else if(v===\"-A\"){if(m++,m>=t.length)return A(`compgen: -A: option requires an argument\n`,2);let $=t[m];if(!y.includes($))return A(`compgen: ${$}: invalid action name\n`,2);s.push($)}else if(v===\"-W\"){if(m++,m>=t.length)return A(`compgen: -W: option requires an argument\n`,2);r=t[m]}else if(v===\"-P\"){if(m++,m>=t.length)return A(`compgen: -P: option requires an argument\n`,2);n=t[m]}else if(v===\"-S\"){if(m++,m>=t.length)return A(`compgen: -S: option requires an argument\n`,2);i=t[m]}else if(v===\"-o\"){if(m++,m>=t.length)return A(`compgen: -o: option requires an argument\n`,2);let $=t[m];if($===\"plusdirs\")a=!0;else if($===\"dirnames\")l=!0;else if($===\"default\")c=!0;else if(!($===\"filenames\"||$===\"nospace\"||$===\"bashdefault\"||$===\"noquote\"))return A(`compgen: ${$}: invalid option name\n`,2)}else if(v===\"-F\"){if(m++,m>=t.length)return A(`compgen: -F: option requires an argument\n`,2);f=t[m]}else if(v===\"-C\"){if(m++,m>=t.length)return A(`compgen: -C: option requires an argument\n`,2);d=t[m]}else if(v===\"-X\"){if(m++,m>=t.length)return A(`compgen: -X: option requires an argument\n`,2);u=t[m]}else if(v===\"-G\"){if(m++,m>=t.length)return A(`compgen: -G: option requires an argument\n`,2)}else if(v===\"--\"){p.push(...t.slice(m+1));break}else v.startsWith(\"-\")||p.push(v)}o=p[0]??null;let h=[];if(l){let m=await rr(e,o);h.push(...m)}if(c){let m=await jn(e,o);h.push(...m)}for(let m of s)if(m===\"variable\"){let v=Bo(e,o);h.push(...v)}else if(m===\"export\"){let v=jo(e,o);h.push(...v)}else if(m===\"function\"){let v=Uo(e,o);h.push(...v)}else if(m===\"builtin\"){let v=Ho(o);h.push(...v)}else if(m===\"keyword\"){let v=Zo(o);h.push(...v)}else if(m===\"alias\"){let v=qo(e,o);h.push(...v)}else if(m===\"shopt\"){let v=Go(o);h.push(...v)}else if(m===\"helptopic\"){let v=Ko(o);h.push(...v)}else if(m===\"directory\"){let v=await rr(e,o);h.push(...v)}else if(m===\"file\"){let v=await jn(e,o);h.push(...v)}else if(m===\"user\"){let v=Xo(o);h.push(...v)}else if(m===\"command\"){let v=await Yo(e,o);h.push(...v)}if(r!==null)try{let m=await Qo(e,r),v=Jo(e,m);for(let $ of v)(o===null||$.startsWith(o))&&h.push($)}catch{return _(\"\",\"\",1)}if(a){let m=await rr(e,o);for(let v of m)h.includes(v)||h.push(v)}let w=\"\";if(f!==null){let m=e.state.functions.get(f);if(m){let v=new Map;v.set(\"COMP_WORDS__length\",e.state.env.get(\"COMP_WORDS__length\")),e.state.env.set(\"COMP_WORDS__length\",\"0\"),v.set(\"COMP_CWORD\",e.state.env.get(\"COMP_CWORD\")),e.state.env.set(\"COMP_CWORD\",\"-1\"),v.set(\"COMP_LINE\",e.state.env.get(\"COMP_LINE\")),e.state.env.set(\"COMP_LINE\",\"\"),v.set(\"COMP_POINT\",e.state.env.get(\"COMP_POINT\")),e.state.env.set(\"COMP_POINT\",\"0\");let $=new Map;for(let T of e.state.env.keys())(T===\"COMPREPLY\"||T.startsWith(\"COMPREPLY_\")||T===\"COMPREPLY__length\")&&($.set(T,e.state.env.get(T)),e.state.env.delete(T));let S=[\"compgen\",p[0]??\"\",\"\"];try{let T=await ys(e,m,S,\"\");if(T.exitCode!==0)return yt(e,v),yt(e,$),_(\"\",T.stderr,1);w=T.stdout;let N=ea(e);h.push(...N)}catch{return yt(e,v),yt(e,$),_(\"\",\"\",1)}yt(e,v),yt(e,$)}}if(d!==null)try{let m=fe(d),v=await e.executeScript(m);if(v.exitCode!==0)return _(\"\",v.stderr,v.exitCode);if(v.stdout){let $=v.stdout.split(`\n`);for(let S of $)S.length>0&&h.push(S)}}catch(m){if(m.name===\"ParseException\")return A(`compgen: -C: ${m.message}\n`,2);throw m}let E=h;if(u!==null){let m=u.startsWith(\"!\"),v=m?u.slice(1):u;E=h.filter($=>{let S=ht($,v,!1,!0);return m?S:!S})}if(E.length===0&&o!==null)return _(w,\"\",1);let g=E.map(m=>`${n}${m}${i}`).join(`\n`),b=w+(g?`${g}\n`:\"\");return z(b)}function Bo(e,t){let s=new Set;for(let n of e.state.env.keys()){if(n.includes(\"_\")&&/^[a-zA-Z_][a-zA-Z0-9_]*_\\d+$/.test(n)||n.endsWith(\"__length\"))continue;let i=n.split(\"_\")[0];/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n)?s.add(n):i&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i)&&e.state.env.has(`${i}__length`)&&s.add(i)}let r=Array.from(s);return t!==null&&(r=r.filter(n=>n.startsWith(t))),r.sort()}function jo(e,t){let s=e.state.exportedVars??new Set,r=Array.from(s);return t!==null&&(r=r.filter(n=>n.startsWith(t))),r=r.filter(n=>n.includes(\"_\")&&/^[a-zA-Z_][a-zA-Z0-9_]*_\\d+$/.test(n)||n.endsWith(\"__length\")?!1:e.state.env.has(n)),r.sort()}function Uo(e,t){let s=Array.from(e.state.functions.keys());return t!==null&&(s=s.filter(r=>r.startsWith(t))),s.sort()}function Ho(e){let t=[...nr];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}function Zo(e){let t=[...Un];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}function qo(e,t){let s=[];for(let n of e.state.env.keys())if(n.startsWith(\"BASH_ALIAS_\")){let i=n.slice(11);s.push(i)}let r=s;return t!==null&&(r=r.filter(n=>n.startsWith(t))),r.sort()}function Go(e){let t=[...zo];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}function Ko(e){let t=[...Vo];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}async function rr(e,t){let s=[];try{let r=e.state.cwd,n=t??\"\";if(t){let o=t.lastIndexOf(\"/\");if(o!==-1){let a=t.slice(0,o)||\"/\";n=t.slice(o+1),a.startsWith(\"/\")?r=a:r=`${e.state.cwd}/${a}`}}let i=await e.fs.readdir(r);for(let o of i){let a=`${r}/${o}`;try{if((await e.fs.stat(a)).isDirectory&&(!n||o.startsWith(n)))if(t?.includes(\"/\")){let c=t.lastIndexOf(\"/\"),u=t.slice(0,c+1);s.push(u+o)}else s.push(o)}catch{}}}catch{}return s.sort()}async function jn(e,t){let s=[];try{let r=e.state.cwd,n=t??\"\";if(t){let o=t.lastIndexOf(\"/\");if(o!==-1){let a=t.slice(0,o)||\"/\";n=t.slice(o+1),a.startsWith(\"/\")?r=a:r=`${e.state.cwd}/${a}`}}let i=await e.fs.readdir(r);for(let o of i)if(!n||o.startsWith(n))if(t?.includes(\"/\")){let a=t.lastIndexOf(\"/\"),l=t.slice(0,a+1);s.push(l+o)}else s.push(o)}catch{}return s.sort()}function Xo(e){return[\"root\",\"nobody\"]}async function Yo(e,t){let s=new Set;for(let i of nr)s.add(i);for(let i of e.state.functions.keys())s.add(i);for(let i of e.state.env.keys())i.startsWith(\"BASH_ALIAS_\")&&s.add(i.slice(11));for(let i of Un)s.add(i);let r=e.state.env.get(\"PATH\")??\"/usr/bin:/bin\";for(let i of r.split(\":\"))if(i)try{let o=await e.fs.readdir(i);for(let a of o)s.add(a)}catch{}let n=Array.from(s);return t!==null&&(n=n.filter(i=>i.startsWith(t))),n.sort()}async function Qo(e,t){let r=new B().parseWordFromString(t,!1,!1);return await L(e,r)}function Jo(e,t){let s=e.state.env.get(\"IFS\")??` \t\n`;if(s.length===0)return[t];let r=new Set(s.split(\"\")),n=[],i=\"\",o=0;for(;o<t.length;){let a=t[o];if(a===\"\\\\\"&&o+1<t.length){let l=t[o+1];i+=l,o+=2}else r.has(a)?(i.length>0&&(n.push(i),i=\"\"),o++):(i+=a,o++)}return i.length>0&&n.push(i),n}function yt(e,t){for(let[s,r]of t)r===void 0?e.state.env.delete(s):e.state.env.set(s,r)}function ea(e){let t=[];if(e.state.env.get(\"COMPREPLY__length\")!==void 0){let n=Ae(e,\"COMPREPLY\");for(let[,i]of n)t.push(i)}else{let n=e.state.env.get(\"COMPREPLY\");n!==void 0&&t.push(n)}return t}var ta=[\"bashdefault\",\"default\",\"dirnames\",\"filenames\",\"noquote\",\"nosort\",\"nospace\",\"plusdirs\"];function ar(e,t){e.state.completionSpecs||(e.state.completionSpecs=new Map);let s=!1,r=!1,n=!1,i,o,a,l=[],c=[],u=[];for(let f=0;f<t.length;f++){let d=t[f];if(d===\"-p\")s=!0;else if(d===\"-r\")r=!0;else if(d===\"-D\")n=!0;else if(d===\"-W\"){if(f++,f>=t.length)return A(`complete: -W: option requires an argument\n`,2);i=t[f]}else if(d===\"-F\"){if(f++,f>=t.length)return A(`complete: -F: option requires an argument\n`,2);o=t[f]}else if(d===\"-o\"){if(f++,f>=t.length)return A(`complete: -o: option requires an argument\n`,2);let p=t[f];if(!ta.includes(p))return A(`complete: ${p}: invalid option name\n`,2);l.push(p)}else if(d===\"-A\"){if(f++,f>=t.length)return A(`complete: -A: option requires an argument\n`,2);c.push(t[f])}else if(d===\"-C\"){if(f++,f>=t.length)return A(`complete: -C: option requires an argument\n`,2);a=t[f]}else if(d===\"-G\"){if(f++,f>=t.length)return A(`complete: -G: option requires an argument\n`,2)}else if(d===\"-P\"){if(f++,f>=t.length)return A(`complete: -P: option requires an argument\n`,2)}else if(d===\"-S\"){if(f++,f>=t.length)return A(`complete: -S: option requires an argument\n`,2)}else if(d===\"-X\"){if(f++,f>=t.length)return A(`complete: -X: option requires an argument\n`,2)}else if(d===\"--\"){u.push(...t.slice(f+1));break}else d.startsWith(\"-\")||u.push(d)}if(r){if(u.length===0)return e.state.completionSpecs.clear(),z(\"\");for(let f of u)e.state.completionSpecs.delete(f);return z(\"\")}if(s)return u.length===0?or(e):or(e,u);if(t.length===0||u.length===0&&!i&&!o&&!a&&l.length===0&&c.length===0&&!n)return or(e);if(o&&u.length===0&&!n)return A(`complete: -F: option requires a command name\n`,2);if(n){let f={isDefault:!0};return i!==void 0&&(f.wordlist=i),o!==void 0&&(f.function=o),a!==void 0&&(f.command=a),l.length>0&&(f.options=l),c.length>0&&(f.actions=c),e.state.completionSpecs.set(\"__default__\",f),z(\"\")}for(let f of u){let d=Object.create(null);i!==void 0&&(d.wordlist=i),o!==void 0&&(d.function=o),a!==void 0&&(d.command=a),l.length>0&&(d.options=l),c.length>0&&(d.actions=c),e.state.completionSpecs.set(f,d)}return z(\"\")}function or(e,t){let s=e.state.completionSpecs;if(!s||s.size===0){if(t&&t.length>0){let i=\"\";for(let o of t)i+=`complete: ${o}: no completion specification\n`;return _(\"\",i,1)}return z(\"\")}let r=[],n=t||Array.from(s.keys());for(let i of n){if(i===\"__default__\")continue;let o=s.get(i);if(!o){if(t)return _(r.join(`\n`)+(r.length>0?`\n`:\"\"),`complete: ${i}: no completion specification\n`,1);continue}let a=\"complete\";if(o.options)for(let l of o.options)a+=` -o ${l}`;if(o.actions)for(let l of o.actions)a+=` -A ${l}`;o.wordlist!==void 0&&(o.wordlist.includes(\" \")||o.wordlist.includes(\"'\")?a+=` -W '${o.wordlist}'`:a+=` -W ${o.wordlist}`),o.function!==void 0&&(a+=` -F ${o.function}`),o.isDefault&&(a+=\" -D\"),a+=` ${i}`,r.push(a)}return r.length===0?z(\"\"):z(`${r.join(`\n`)}\n`)}var Hn=[\"bashdefault\",\"default\",\"dirnames\",\"filenames\",\"noquote\",\"nosort\",\"nospace\",\"plusdirs\"];function lr(e,t){e.state.completionSpecs||(e.state.completionSpecs=new Map);let s=!1,r=!1,n=[],i=[],o=[];for(let a=0;a<t.length;a++){let l=t[a];if(l===\"-D\")s=!0;else if(l===\"-E\")r=!0;else if(l===\"-o\"){if(a++,a>=t.length)return A(`compopt: -o: option requires an argument\n`,2);let c=t[a];if(!Hn.includes(c))return A(`compopt: ${c}: invalid option name\n`,2);n.push(c)}else if(l===\"+o\"){if(a++,a>=t.length)return A(`compopt: +o: option requires an argument\n`,2);let c=t[a];if(!Hn.includes(c))return A(`compopt: ${c}: invalid option name\n`,2);i.push(c)}else if(l===\"--\"){o.push(...t.slice(a+1));break}else!l.startsWith(\"-\")&&!l.startsWith(\"+\")&&o.push(l)}if(s){let a=e.state.completionSpecs.get(\"__default__\")??{isDefault:!0},l=new Set(a.options??[]);for(let c of n)l.add(c);for(let c of i)l.delete(c);return a.options=l.size>0?Array.from(l):void 0,e.state.completionSpecs.set(\"__default__\",a),z(\"\")}if(r){let a=e.state.completionSpecs.get(\"__empty__\")??{},l=new Set(a.options??[]);for(let c of n)l.add(c);for(let c of i)l.delete(c);return a.options=l.size>0?Array.from(l):void 0,e.state.completionSpecs.set(\"__empty__\",a),z(\"\")}if(o.length>0){for(let a of o){let l=e.state.completionSpecs.get(a)??{},c=new Set(l.options??[]);for(let u of n)c.add(u);for(let u of i)c.delete(u);l.options=c.size>0?Array.from(c):void 0,e.state.completionSpecs.set(a,l)}return z(\"\")}return A(`compopt: not currently executing completion function\n`,1)}function cr(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new je;return W}if(t.length>1)throw new j(1,\"\",`bash: continue: too many arguments\n`);let s=1;if(t.length>0){let r=Number.parseInt(t[0],10);if(Number.isNaN(r)||r<1)throw new j(1,\"\",`bash: continue: ${t[0]}: numeric argument required\n`);s=r}throw new ge(s)}function X(e,t){let s=e.state.env.get(\"HOME\")||\"/home/user\";return t.split(\":\").map(i=>i===\"~\"?s:i===\"~root\"?\"/root\":i.startsWith(\"~/\")?s+i.slice(1):i.startsWith(\"~root/\")?`/root${i.slice(5)}`:i).join(\":\")}function ur(e){for(let t=0;t<e.length;t++){let s=e.charCodeAt(t);if(s<32||s===127)return!0}return!1}function fr(e){let t=\"$'\";for(let s=0;s<e.length;s++){let r=e[s],n=e.charCodeAt(s);n===7?t+=\"\\\\a\":n===8?t+=\"\\\\b\":n===9?t+=\"\\\\t\":n===10?t+=\"\\\\n\":n===11?t+=\"\\\\v\":n===12?t+=\"\\\\f\":n===13?t+=\"\\\\r\":n===27?t+=\"\\\\e\":n===39?t+=\"\\\\'\":n===92?t+=\"\\\\\\\\\":n<32||n===127?t+=`\\\\${n.toString(8).padStart(3,\"0\")}`:t+=r}return t+=\"'\",t}function gs(e){return ur(e)?fr(e):/^[a-zA-Z0-9_/.:\\-@%+,=]*$/.test(e)?e:`'${e.replace(/'/g,\"'\\\\''\")}'`}function nt(e){return ur(e)?fr(e):`\"${e.replace(/\\\\/g,\"\\\\\\\\\").replace(/\"/g,'\\\\\"')}\"`}function dr(e){return ur(e)?fr(e):`\"${e.replace(/\\\\/g,\"\\\\\\\\\").replace(/\"/g,'\\\\\"')}\"`}function Zn(e,t){let s=\"\";return e.state.integerVars?.has(t)&&(s+=\"i\"),e.state.lowercaseVars?.has(t)&&(s+=\"l\"),Ee(e,t)&&(s+=\"n\"),e.state.readonlyVars?.has(t)&&(s+=\"r\"),e.state.uppercaseVars?.has(t)&&(s+=\"u\"),e.state.exportedVars?.has(t)&&(s+=\"x\"),s===\"\"?\"--\":`-${s}`}function hr(e){return e===\"\"?\"''\":/[\\s'\\\\]/.test(e)?`'${e.replace(/'/g,\"'\\\\''\")}'`:e}function qn(e,t){let s=\"\",r=\"\",n=!1;for(let i of t){let o=Zn(e,i);if(e.state.associativeArrays?.has(i)){let u=He(e,i);if(u.length===0)s+=`declare -A ${i}=()\n`;else{let f=u.map(d=>{let p=e.state.env.get(`${i}_${d}`)??\"\",y=hr(p);return`['${d}']=${y}`});s+=`declare -A ${i}=(${f.join(\" \")})\n`}continue}let l=ne(e,i);if(l.length>0){let u=l.map(f=>{let d=e.state.env.get(`${i}_${f}`)??\"\";return`[${f}]=${nt(d)}`});s+=`declare -a ${i}=(${u.join(\" \")})\n`;continue}if(e.state.env.has(`${i}__length`)){s+=`declare -a ${i}=()\n`;continue}let c=e.state.env.get(i);if(c!==void 0)s+=`declare ${o} ${i}=${dr(c)}\n`;else{let u=e.state.declaredVars?.has(i),f=e.state.localVarDepth?.has(i);u||f?s+=`declare ${o} ${i}\n`:(r+=`bash: declare: ${i}: not found\n`,n=!0)}}return _(s,r,n?1:0)}function Gn(e,t){let{filterExport:s,filterReadonly:r,filterNameref:n,filterIndexedArray:i,filterAssocArray:o}=t,a=s||r||n||i||o,l=\"\",c=new Set;for(let f of e.state.env.keys()){if(f.startsWith(\"BASH_\"))continue;if(f.endsWith(\"__length\")){let p=f.slice(0,-8);c.add(p);continue}let d=f.lastIndexOf(\"_\");if(d>0){let p=f.slice(0,d),y=f.slice(d+1);if(/^\\d+$/.test(y)||e.state.associativeArrays?.has(p)){c.add(p);continue}}c.add(f)}if(e.state.localVarDepth)for(let f of e.state.localVarDepth.keys())c.add(f);if(e.state.associativeArrays)for(let f of e.state.associativeArrays)c.add(f);let u=Array.from(c).sort();for(let f of u){let d=Zn(e,f),p=e.state.associativeArrays?.has(f),y=ne(e,f),h=!p&&(y.length>0||e.state.env.has(`${f}__length`));if(a&&(o&&!p||i&&!h||s&&!e.state.exportedVars?.has(f)||r&&!e.state.readonlyVars?.has(f)||n&&!Ee(e,f)))continue;if(p){let E=He(e,f);if(E.length===0)l+=`declare -A ${f}=()\n`;else{let g=E.map(b=>{let m=e.state.env.get(`${f}_${b}`)??\"\",v=hr(m);return`['${b}']=${v}`});l+=`declare -A ${f}=(${g.join(\" \")})\n`}continue}if(y.length>0){let E=y.map(g=>{let b=e.state.env.get(`${f}_${g}`)??\"\";return`[${g}]=${nt(b)}`});l+=`declare -a ${f}=(${E.join(\" \")})\n`;continue}if(e.state.env.has(`${f}__length`)){l+=`declare -a ${f}=()\n`;continue}let w=e.state.env.get(f);w!==void 0&&(l+=`declare ${d} ${f}=${dr(w)}\n`)}return z(l)}function Kn(e){let t=\"\",s=Array.from(e.state.associativeArrays??[]).sort();for(let r of s){let n=He(e,r);if(n.length===0)t+=`declare -A ${r}=()\n`;else{let i=n.map(o=>{let a=e.state.env.get(`${r}_${o}`)??\"\",l=hr(a);return`['${o}']=${l}`});t+=`declare -A ${r}=(${i.join(\" \")})\n`}}return z(t)}function Xn(e){let t=\"\",s=new Set;for(let n of e.state.env.keys()){if(n.startsWith(\"BASH_\"))continue;if(n.endsWith(\"__length\")){let o=n.slice(0,-8);e.state.associativeArrays?.has(o)||s.add(o);continue}let i=n.lastIndexOf(\"_\");if(i>0){let o=n.slice(0,i),a=n.slice(i+1);/^\\d+$/.test(a)&&(e.state.associativeArrays?.has(o)||s.add(o))}}let r=Array.from(s).sort();for(let n of r){let i=ne(e,n);if(i.length===0)t+=`declare -a ${n}=()\n`;else{let o=i.map(a=>{let l=e.state.env.get(`${n}_${a}`)??\"\";return`[${a}]=${nt(l)}`});t+=`declare -a ${n}=(${o.join(\" \")})\n`}}return z(t)}function Yn(e){let t=\"\",s=new Set;for(let n of e.state.env.keys()){if(n.startsWith(\"BASH_\"))continue;if(n.endsWith(\"__length\")){let o=n.slice(0,-8);s.add(o);continue}let i=n.lastIndexOf(\"_\");if(i>0){let o=n.slice(0,i),a=n.slice(i+1);if(/^\\d+$/.test(a)||e.state.associativeArrays?.has(o)){s.add(o);continue}}s.add(n)}let r=Array.from(s).sort();for(let n of r){if(e.state.associativeArrays?.has(n)||ne(e,n).length>0||e.state.env.has(`${n}__length`))continue;let a=e.state.env.get(n);a!==void 0&&(t+=`${n}=${gs(a)}\n`)}return z(t)}function pr(e,t){e.state.integerVars??=new Set,e.state.integerVars.add(t)}function xt(e,t){return e.state.integerVars?.has(t)??!1}function mr(e,t){e.state.lowercaseVars??=new Set,e.state.lowercaseVars.add(t),e.state.uppercaseVars?.delete(t)}function sa(e,t){return e.state.lowercaseVars?.has(t)??!1}function yr(e,t){e.state.uppercaseVars??=new Set,e.state.uppercaseVars.add(t),e.state.lowercaseVars?.delete(t)}function ra(e,t){return e.state.uppercaseVars?.has(t)??!1}function gt(e,t,s){return sa(e,t)?s.toLowerCase():ra(e,t)?s.toUpperCase():s}async function Qn(e,t){try{let s=new B,r=ee(s,t),n=await H(e,r.expression);return String(n)}catch{return\"0\"}}function na(e){let t=e.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);if(!t)return null;let s=t[0],r=s.length;if(e[r]!==\"[\")return null;let n=0,i=r+1;for(;r<e.length;r++)if(e[r]===\"[\")n++;else if(e[r]===\"]\"&&(n--,n===0))break;if(n!==0)return null;let o=e.slice(i,r);if(r++,e[r]!==\"=\")return null;r++;let a=e.slice(r);return{name:s,indexExpr:o,value:a}}async function gr(e,t){let s=!1,r=!1,n=!1,i=!1,o=!1,a=!1,l=!1,c=!1,u=!1,f=!1,d=!1,p=!1,y=!1,h=!1,w=!1,E=[];for(let N=0;N<t.length;N++){let F=t[N];if(F===\"-a\")s=!0;else if(F===\"-A\")r=!0;else if(F===\"-r\")n=!0;else if(F===\"-x\")i=!0;else if(F===\"-p\")o=!0;else if(F===\"-n\")a=!0;else if(F===\"+n\")l=!0;else if(F===\"+a\")c=!0;else if(F===\"+x\")u=!0;else if(F===\"--\"){E.push(...t.slice(N+1));break}else if(F.startsWith(\"+\")){for(let k of F.slice(1))if(k===\"n\")l=!0;else if(k===\"a\")c=!0;else if(k===\"x\")u=!0;else if(k!==\"r\"){if(k!==\"i\"){if(!(k===\"f\"||k===\"F\"))return _(\"\",`bash: typeset: +${k}: invalid option\n`,2)}}}else if(F===\"-i\")f=!0;else if(F===\"-l\")d=!0;else if(F===\"-u\")p=!0;else if(F===\"-f\")y=!0;else if(F===\"-F\")h=!0;else if(F===\"-g\")w=!0;else if(F.startsWith(\"-\"))for(let k of F.slice(1))if(k===\"a\")s=!0;else if(k===\"A\")r=!0;else if(k===\"r\")n=!0;else if(k===\"x\")i=!0;else if(k===\"p\")o=!0;else if(k===\"n\")a=!0;else if(k===\"i\")f=!0;else if(k===\"l\")d=!0;else if(k===\"u\")p=!0;else if(k===\"f\")y=!0;else if(k===\"F\")h=!0;else if(k===\"g\")w=!0;else return _(\"\",`bash: typeset: -${k}: invalid option\n`,2);else E.push(F)}let b=e.state.localScopes.length>0&&!w,m=N=>{if(!b)return;let F=e.state.localScopes[e.state.localScopes.length-1];F.has(N)||F.set(N,e.state.env.get(N))},v=N=>{if(!b)return;let F=e.state.localScopes[e.state.localScopes.length-1];F.has(N)||F.set(N,e.state.env.get(N));let k=`${N}_`;for(let D of e.state.env.keys())D.startsWith(k)&&!D.includes(\"__\")&&(F.has(D)||F.set(D,e.state.env.get(D)));let C=`${N}__length`;e.state.env.has(C)&&!F.has(C)&&F.set(C,e.state.env.get(C))},$=N=>{b&&Xe(e,N)};if(h){if(E.length===0){let k=Array.from(e.state.functions.keys()).sort(),C=\"\";for(let D of k)C+=`declare -f ${D}\n`;return z(C)}let N=!0,F=\"\";for(let k of E)e.state.functions.has(k)?F+=`${k}\n`:N=!1;return _(F,\"\",N?0:1)}if(y){if(E.length===0){let F=\"\",k=Array.from(e.state.functions.keys()).sort();for(let C of k)F+=`${C} ()\n{\n # function body\n}\n`;return z(F)}let N=!0;for(let F of E)e.state.functions.has(F)||(N=!1);return _(\"\",\"\",N?0:1)}if(o&&E.length>0)return qn(e,E);if(o&&E.length===0)return Gn(e,{filterExport:i,filterReadonly:n,filterNameref:a,filterIndexedArray:s,filterAssocArray:r});if(E.length===0&&r&&!o)return Kn(e);if(E.length===0&&s&&!o)return Xn(e);if(E.length===0&&!o)return Yn(e);let S=\"\",T=0;for(let N of E){let F=N.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\\((.*)\\)$/s);if(F&&!c){let P=F[1],R=F[2];if(r&&ne(e,P).length>0){S+=`bash: declare: ${P}: cannot convert indexed to associative array\n`,T=1;continue}if((s||!r&&!s)&&e.state.associativeArrays?.has(P)){S+=`bash: declare: ${P}: cannot convert associative to indexed array\n`,T=1;continue}if(v(P),r&&(e.state.associativeArrays??=new Set,e.state.associativeArrays.add(P)),Oe(e,P),e.state.env.delete(P),e.state.env.delete(`${P}__length`),r&&R.includes(\"[\")){let M=ds(R);for(let[te,V]of M){let Y=X(e,V);e.state.env.set(`${P}_${te}`,Y)}}else if(r){let M=De(R);for(let te=0;te<M.length;te+=2){let V=M[te],Y=te+1<M.length?X(e,M[te+1]):\"\";e.state.env.set(`${P}_${V}`,Y)}}else{let M=De(R);if(M.some(V=>/^\\[[^\\]]+\\]=/.test(V))){let V=0;for(let Y of M){let oe=Y.match(/^\\[([^\\]]+)\\]=(.*)$/);if(oe){let pe=oe[1],lt=oe[2],so=X(e,lt),Pt;if(/^-?\\d+$/.test(pe))Pt=Number.parseInt(pe,10);else try{let ro=new B,no=ee(ro,pe);Pt=await H(e,no.expression)}catch{Pt=0}e.state.env.set(`${P}_${Pt}`,so),V=Pt+1}else{let pe=X(e,Y);e.state.env.set(`${P}_${V}`,pe),V++}}}else{for(let V=0;V<M.length;V++)e.state.env.set(`${P}_${V}`,M[V]);e.state.env.set(`${P}__length`,String(M.length))}}$(P),n&&de(e,P),i&&ke(e,P);continue}if(l){let P=N.includes(\"=\")?N.slice(0,N.indexOf(\"=\")):N;if(tn(e,P),!N.includes(\"=\"))continue}if(u){let P=N.includes(\"=\")?N.slice(0,N.indexOf(\"=\")):N;if(Kt(e,P),!N.includes(\"=\"))continue}let k=na(N);if(k){let{name:P,indexExpr:R,value:M}=k,te=se(e,P);if(te)return te;v(P);let V;try{let oe=new B,pe=ee(oe,R);V=await H(e,pe.expression)}catch{let oe=parseInt(R,10);V=Number.isNaN(oe)?0:oe}e.state.env.set(`${P}_${V}`,M);let Y=parseInt(e.state.env.get(`${P}__length`)??\"0\",10);V>=Y&&e.state.env.set(`${P}__length`,String(V+1)),$(P),n&&de(e,P),i&&ke(e,P);continue}let C=N.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\+=\\((.*)\\)$/s);if(C&&!c){let P=C[1],R=C[2],M=se(e,P);if(M)return M;v(P);let te=De(R);if(e.state.associativeArrays?.has(P)){let V=ds(R);for(let[Y,oe]of V){let pe=X(e,oe);e.state.env.set(`${P}_${Y}`,pe)}}else{let V=ne(e,P),Y=0,oe=e.state.env.get(P);V.length===0&&oe!==void 0?(e.state.env.set(`${P}_0`,oe),e.state.env.delete(P),Y=1):V.length>0&&(Y=Math.max(...V)+1);for(let lt=0;lt<te.length;lt++)e.state.env.set(`${P}_${Y+lt}`,X(e,te[lt]));let pe=Y+te.length;e.state.env.set(`${P}__length`,String(pe))}$(P),n&&de(e,P),i&&ke(e,P);continue}let D=N.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\+=(.*)$/);if(D){let P=D[1],R=X(e,D[2]),M=se(e,P);if(M)return M;m(P),f&&pr(e,P),d&&mr(e,P),p&&yr(e,P);let V=ne(e,P).length>0||e.state.associativeArrays?.has(P);if(xt(e,P)){let Y=e.state.env.get(P)??\"0\",oe=parseInt(Y,10)||0,pe=parseInt(await Qn(e,R),10)||0;R=String(oe+pe),e.state.env.set(P,R)}else if(V){R=gt(e,P,R);let Y=`${P}_0`,oe=e.state.env.get(Y)??\"\";e.state.env.set(Y,oe+R)}else{R=gt(e,P,R);let Y=e.state.env.get(P)??\"\";e.state.env.set(P,Y+R)}$(P),n&&de(e,P),i&&ke(e,P),e.state.options.allexport&&!u&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(P));continue}if(N.includes(\"=\")){let P=N.indexOf(\"=\"),R=N.slice(0,P),M=N.slice(P+1);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(R)){S+=`bash: typeset: \\`${R}': not a valid identifier\n`,T=1;continue}let te=se(e,R);if(te)return te;if(m(R),a){if(M!==\"\"&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\\[.+\\])?$/.test(M)){S+=`bash: declare: \\`${M}': invalid variable name for name reference\n`,T=1;continue}e.state.env.set(R,M),We(e,R),M!==\"\"&&Bs(e,M)&&Vs(e,R),$(R),n&&de(e,R),i&&ke(e,R);continue}if(f&&pr(e,R),d&&mr(e,R),p&&yr(e,R),xt(e,R)&&(M=await Qn(e,M)),M=gt(e,R,M),Ee(e,R)){let V=Ze(e,R);V&&V!==R?e.state.env.set(V,M):e.state.env.set(R,M)}else e.state.env.set(R,M);$(R),n&&de(e,R),i&&ke(e,R),e.state.options.allexport&&!u&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(R))}else{let P=N;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(P)){S+=`bash: typeset: \\`${P}': not a valid identifier\n`,T=1;continue}if(s||r?v(P):m(P),a){We(e,P);let M=e.state.env.get(P);M!==void 0&&M!==\"\"&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\\[.+\\])?$/.test(M)?sn(e,P):M&&Bs(e,M)&&Vs(e,P),$(P),n&&de(e,P),i&&ke(e,P);continue}if(f&&pr(e,P),d&&mr(e,P),p&&yr(e,P),r){if(ne(e,P).length>0){S+=`bash: declare: ${P}: cannot convert indexed to associative array\n`,T=1;continue}e.state.associativeArrays??=new Set,e.state.associativeArrays.add(P)}let R=Array.from(e.state.env.keys()).some(M=>M.startsWith(`${P}_`)&&!M.startsWith(`${P}__length`));!e.state.env.has(P)&&!R&&(s||r?e.state.env.set(`${P}__length`,\"0\"):(e.state.declaredVars??=new Set,e.state.declaredVars.add(P))),$(P),n&&de(e,P),i&&ke(e,P)}}return _(\"\",S,T)}async function wr(e,t){let s=!1,r=!1,n=!1,i=[];for(let o=0;o<t.length;o++){let a=t[o];if(a===\"-a\")s=!0;else if(a===\"-A\")r=!0;else if(a===\"-p\")n=!0;else if(a===\"--\"){i.push(...t.slice(o+1));break}else a.startsWith(\"-\")||i.push(a)}if(i.length===0){let o=\"\",a=Array.from(e.state.readonlyVars||[]).sort();for(let l of a){let c=e.state.env.get(l);if(c!==void 0){let u=c.replace(/\\\\/g,\"\\\\\\\\\").replace(/\"/g,'\\\\\"');o+=`declare -r ${l}=\"${u}\"\n`}}return z(o)}for(let o of i){let a=o.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\+=\\((.*)\\)$/s);if(a){let f=a[1],d=a[2],p=se(e,f);if(p)return p;let y=De(d);if(e.state.associativeArrays?.has(f)){let h=ds(d);for(let[w,E]of h){let g=X(e,E);e.state.env.set(`${f}_${w}`,g)}}else{let h=ne(e,f),w=0,E=e.state.env.get(f);h.length===0&&E!==void 0?(e.state.env.set(`${f}_0`,E),e.state.env.delete(f),w=1):h.length>0&&(w=Math.max(...h)+1);for(let b=0;b<y.length;b++)e.state.env.set(`${f}_${w+b}`,X(e,y[b]));let g=w+y.length;e.state.env.set(`${f}__length`,String(g))}de(e,f);continue}let l=o.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\+=(.*)$/);if(l){let f=l[1],d=X(e,l[2]),p=se(e,f);if(p)return p;let y=e.state.env.get(f)??\"\";e.state.env.set(f,y+d),de(e,f);continue}let c=Ln(o);if(c.value===void 0&&!c.isArray){de(e,c.name);continue}let u=await Fn(e,c,{makeReadonly:!0});if(u)return u}return W}function vr(e){return e.state.directoryStack??=[],e.state.directoryStack}function Tt(e,t){return t&&e===t?\"~\":t&&e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}function ia(e){let t=e.split(\"/\").filter(r=>r&&r!==\".\"),s=[];for(let r of t)r===\"..\"?s.pop():s.push(r);return`/${s.join(\"/\")}`}async function br(e,t){let s=vr(e),r;for(let a=0;a<t.length;a++){let l=t[a];if(l===\"--\"){if(a+1<t.length){if(r!==void 0)return A(`bash: pushd: too many arguments\n`,2);r=t[a+1],a++}}else{if(l.startsWith(\"-\")&&l!==\"-\")return A(`bash: pushd: ${l}: invalid option\n`,2);if(r!==void 0)return A(`bash: pushd: too many arguments\n`,2);r=l}}if(r===void 0){if(s.length<2)return A(`bash: pushd: no other directory\n`,1);let a=s[0];s[0]=s[1],s[1]=a,r=s[0]}let n;if(r.startsWith(\"/\"))n=r;else if(r===\"..\"){let a=e.state.cwd.split(\"/\").filter(l=>l);a.pop(),n=`/${a.join(\"/\")}`}else r===\".\"?n=e.state.cwd:r.startsWith(\"~\")?n=(e.state.env.get(\"HOME\")||\"/\")+r.slice(1):n=`${e.state.cwd}/${r}`;n=ia(n);try{if(!(await e.fs.stat(n)).isDirectory)return A(`bash: pushd: ${r}: Not a directory\n`,1)}catch{return A(`bash: pushd: ${r}: No such file or directory\n`,1)}s.unshift(e.state.cwd),e.state.previousDir=e.state.cwd,e.state.cwd=n,e.state.env.set(\"PWD\",n),e.state.env.set(\"OLDPWD\",e.state.previousDir);let i=e.state.env.get(\"HOME\")||\"\",o=`${[n,...s].map(a=>Tt(a,i)).join(\" \")}\n`;return z(o)}function Er(e,t){let s=vr(e);for(let o of t)if(o!==\"--\")return o.startsWith(\"-\")&&o!==\"-\"?A(`bash: popd: ${o}: invalid option\n`,2):A(`bash: popd: too many arguments\n`,2);if(s.length===0)return A(`bash: popd: directory stack empty\n`,1);let r=s.shift();if(!r)return A(`bash: popd: directory stack empty\n`,1);e.state.previousDir=e.state.cwd,e.state.cwd=r,e.state.env.set(\"PWD\",r),e.state.env.set(\"OLDPWD\",e.state.previousDir);let n=e.state.env.get(\"HOME\")||\"\",i=`${[r,...s].map(o=>Tt(o,n)).join(\" \")}\n`;return z(i)}function $r(e,t){let s=vr(e),r=!1,n=!1,i=!1,o=!1;for(let u of t)if(u!==\"--\")if(u.startsWith(\"-\"))for(let f of u.slice(1))if(f===\"c\")r=!0;else if(f===\"l\")n=!0;else if(f===\"p\")i=!0;else if(f===\"v\")i=!0,o=!0;else return A(`bash: dirs: -${f}: invalid option\n`,2);else return A(`bash: dirs: too many arguments\n`,1);if(r)return e.state.directoryStack=[],W;let a=[e.state.cwd,...s],l=e.state.env.get(\"HOME\")||\"\",c;return o?(c=a.map((u,f)=>{let d=n?u:Tt(u,l);return` ${f} ${d}`}).join(`\n`),c+=`\n`):i?c=a.map(u=>n?u:Tt(u,l)).join(`\n`)+`\n`:c=a.map(u=>n?u:Tt(u,l)).join(\" \")+`\n`,z(c)}async function ws(e,t,s){let r=t;if(r.length>0){let a=r[0];if(a===\"--\")r=r.slice(1);else if(a.startsWith(\"-\")&&a!==\"-\"&&a.length>1)return A(`bash: eval: ${a}: invalid option\neval: usage: eval [arg ...]\n`,2)}if(r.length===0)return W;let n=r.join(\" \");if(n.trim()===\"\")return W;let i=e.state.groupStdin,o=s??e.state.groupStdin;o!==void 0&&(e.state.groupStdin=o);try{let a=fe(n);return await e.executeScript(a)}catch(a){if(a instanceof ye||a instanceof ge||a instanceof ue||a instanceof j)throw a;if(a.name===\"ParseException\")return A(`bash: eval: ${a.message}\n`);throw a}finally{e.state.groupStdin=i}}function Sr(e,t){let s,r=\"\";if(t.length===0)s=e.state.lastExitCode;else{let n=t[0],i=Number.parseInt(n,10);n===\"\"||Number.isNaN(i)||!/^-?\\d+$/.test(n)?(r=`bash: exit: ${n}: numeric argument required\n`,s=2):s=(i%256+256)%256}throw new j(s,\"\",r)}function Pr(e,t){let s=!1,r=[];for(let o of t)o===\"-n\"?s=!0:o===\"-p\"||o===\"--\"||r.push(o);if(r.length===0&&!s){let o=\"\",a=e.state.exportedVars??new Set,l=Array.from(a).sort();for(let c of l){let u=e.state.env.get(c);if(u!==void 0){let f=u.replace(/\\\\/g,\"\\\\\\\\\").replace(/\"/g,'\\\\\"');o+=`declare -x ${c}=\"${f}\"\n`}}return z(o)}if(s){for(let o of r){let a,l;if(o.includes(\"=\")){let c=o.indexOf(\"=\");a=o.slice(0,c),l=X(e,o.slice(c+1)),e.state.env.set(a,l)}else a=o;Kt(e,a)}return W}let n=\"\",i=0;for(let o of r){let a,l,c=!1,u=o.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\+=(.*)$/);if(u)a=u[1],l=X(e,u[2]),c=!0;else if(o.includes(\"=\")){let f=o.indexOf(\"=\");a=o.slice(0,f),l=X(e,o.slice(f+1))}else a=o;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(a)){n+=`bash: export: \\`${o}': not a valid identifier\n`,i=1;continue}if(l!==void 0)if(c){let f=e.state.env.get(a)??\"\";e.state.env.set(a,f+l)}else e.state.env.set(a,l);else e.state.env.has(a)||e.state.env.set(a,\"\");ke(e,a)}return _(\"\",n,i)}function vs(e,t){if(t.length<2)return A(`bash: getopts: usage: getopts optstring name [arg ...]\n`);let s=t[0],r=t[1],n=!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r),i=s.startsWith(\":\"),o=i?s.slice(1):s,a;if(t.length>2)a=t.slice(2);else{let h=Number.parseInt(e.state.env.get(\"#\")||\"0\",10);a=[];for(let w=1;w<=h;w++)a.push(e.state.env.get(String(w))||\"\")}let l=Number.parseInt(e.state.env.get(\"OPTIND\")||\"1\",10);l<1&&(l=1);let c=Number.parseInt(e.state.env.get(\"__GETOPTS_CHARINDEX\")||\"0\",10);if(e.state.env.set(\"OPTARG\",\"\"),l>a.length)return n||e.state.env.set(r,\"?\"),e.state.env.set(\"OPTIND\",String(a.length+1)),e.state.env.set(\"__GETOPTS_CHARINDEX\",\"0\"),{exitCode:n?2:1,stdout:\"\",stderr:\"\"};let u=a[l-1];if(!u||u===\"-\"||!u.startsWith(\"-\"))return n||e.state.env.set(r,\"?\"),{exitCode:n?2:1,stdout:\"\",stderr:\"\"};if(u===\"--\")return e.state.env.set(\"OPTIND\",String(l+1)),e.state.env.set(\"__GETOPTS_CHARINDEX\",\"0\"),n||e.state.env.set(r,\"?\"),{exitCode:n?2:1,stdout:\"\",stderr:\"\"};let f=c===0?1:c,d=u[f];if(!d)return e.state.env.set(\"OPTIND\",String(l+1)),e.state.env.set(\"__GETOPTS_CHARINDEX\",\"0\"),vs(e,t);let p=o.indexOf(d);if(p===-1){let h=\"\";return i?e.state.env.set(\"OPTARG\",d):h=`bash: illegal option -- ${d}\n`,n||e.state.env.set(r,\"?\"),f+1<u.length?(e.state.env.set(\"__GETOPTS_CHARINDEX\",String(f+1)),e.state.env.set(\"OPTIND\",String(l))):(e.state.env.set(\"OPTIND\",String(l+1)),e.state.env.set(\"__GETOPTS_CHARINDEX\",\"0\")),{exitCode:n?2:0,stdout:\"\",stderr:h}}if(p+1<o.length&&o[p+1]===\":\")if(f+1<u.length)e.state.env.set(\"OPTARG\",u.slice(f+1)),e.state.env.set(\"OPTIND\",String(l+1)),e.state.env.set(\"__GETOPTS_CHARINDEX\",\"0\");else{if(l>=a.length){let h=\"\";return i?(e.state.env.set(\"OPTARG\",d),n||e.state.env.set(r,\":\")):(h=`bash: option requires an argument -- ${d}\n`,n||e.state.env.set(r,\"?\")),e.state.env.set(\"OPTIND\",String(l+1)),e.state.env.set(\"__GETOPTS_CHARINDEX\",\"0\"),{exitCode:n?2:0,stdout:\"\",stderr:h}}e.state.env.set(\"OPTARG\",a[l]),e.state.env.set(\"OPTIND\",String(l+2)),e.state.env.set(\"__GETOPTS_CHARINDEX\",\"0\")}else f+1<u.length?(e.state.env.set(\"__GETOPTS_CHARINDEX\",String(f+1)),e.state.env.set(\"OPTIND\",String(l))):(e.state.env.set(\"OPTIND\",String(l+1)),e.state.env.set(\"__GETOPTS_CHARINDEX\",\"0\"));return n||e.state.env.set(r,d),{exitCode:n?2:0,stdout:\"\",stderr:\"\"}}async function Ar(e,t){e.state.hashTable||(e.state.hashTable=new Map);let s=!1,r=!1,n=!1,i=!1,o=!1,a=\"\",l=[],c=0;for(;c<t.length;){let y=t[c];if(y===\"--\"){c++,l.push(...t.slice(c));break}if(y===\"-r\")s=!0,c++;else if(y===\"-d\")r=!0,c++;else if(y===\"-l\")n=!0,c++;else if(y===\"-t\")o=!0,c++;else if(y===\"-p\"){if(i=!0,c++,c>=t.length)return A(`bash: hash: -p: option requires an argument\n`,1);a=t[c],c++}else if(y.startsWith(\"-\")&&y.length>1){for(let h of y.slice(1))if(h===\"r\")s=!0;else if(h===\"d\")r=!0;else if(h===\"l\")n=!0;else if(h===\"t\")o=!0;else return h===\"p\"?A(`bash: hash: -p: option requires an argument\n`,1):A(`bash: hash: -${h}: invalid option\n`,1);c++}else l.push(y),c++}if(s)return e.state.hashTable.clear(),W;if(r){if(l.length===0)return A(`bash: hash: -d: option requires an argument\n`,1);let y=!1,h=\"\";for(let w of l)e.state.hashTable.has(w)?e.state.hashTable.delete(w):(h+=`bash: hash: ${w}: not found\n`,y=!0);return y?A(h,1):W}if(o){if(l.length===0)return A(`bash: hash: -t: option requires an argument\n`,1);let y=\"\",h=!1,w=\"\";for(let E of l){let g=e.state.hashTable.get(E);g?l.length>1?y+=`${E}\t${g}\n`:y+=`${g}\n`:(w+=`bash: hash: ${E}: not found\n`,h=!0)}return h?{exitCode:1,stdout:y,stderr:w}:z(y)}if(i){if(l.length===0)return A(`bash: hash: usage: hash [-lr] [-p pathname] [-dt] [name ...]\n`,1);let y=l[0];return e.state.hashTable.set(y,a),W}if(l.length===0){if(e.state.hashTable.size===0)return z(`hash: hash table empty\n`);let y=\"\";if(n)for(let[h,w]of e.state.hashTable)y+=`builtin hash -p ${w} ${h}\n`;else{y=`hits\tcommand\n`;for(let[,h]of e.state.hashTable)y+=` 1\t${h}\n`}return z(y)}let u=!1,f=\"\",p=(e.state.env.get(\"PATH\")||\"/usr/bin:/bin\").split(\":\");for(let y of l){if(y.includes(\"/\")){f+=`bash: hash: ${y}: cannot use / in name\n`,u=!0;continue}let h=!1;for(let w of p){if(!w)continue;let E=`${w}/${y}`;if(await e.fs.exists(E)){e.state.hashTable.set(y,E),h=!0;break}}h||(f+=`bash: hash: ${y}: not found\n`,u=!0)}return u?A(f,1):W}var Jn=new Map([[\":\",[\": [arguments]\",`Null command.\n No effect; the command does nothing.\n Exit Status:\n Always succeeds.`]],[\".\",[\". filename [arguments]\",`Execute commands from a file in the current shell.\n Read and execute commands from FILENAME in the current shell.\n The entries in $PATH are used to find the directory containing FILENAME.\n Exit Status:\n Returns the status of the last command executed in FILENAME.`]],[\"[\",[\"[ arg... ]\",`Evaluate conditional expression.\n This is a synonym for the \"test\" builtin, but the last argument must\n be a literal \\`]', to match the opening \\`['.`]],[\"alias\",[\"alias [-p] [name[=value] ... ]\",`Define or display aliases.\n Without arguments, \\`alias' prints the list of aliases in the reusable\n form \\`alias NAME=VALUE' on standard output.\n Exit Status:\n alias returns true unless a NAME is supplied for which no alias has been\n defined.`]],[\"bg\",[\"bg [job_spec ...]\",`Move jobs to the background.\n Place the jobs identified by each JOB_SPEC in the background, as if they\n had been started with \\`&'.`]],[\"break\",[\"break [n]\",`Exit for, while, or until loops.\n Exit a FOR, WHILE or UNTIL loop. If N is specified, break N enclosing\n loops.\n Exit Status:\n The exit status is 0 unless N is not greater than or equal to 1.`]],[\"builtin\",[\"builtin [shell-builtin [arg ...]]\",`Execute shell builtins.\n Execute SHELL-BUILTIN with arguments ARGs without performing command\n lookup. This is useful when you wish to reimplement a shell builtin\n as a shell function, but need to execute the builtin within the function.\n Exit Status:\n Returns the exit status of SHELL-BUILTIN, or false if SHELL-BUILTIN is\n not a shell builtin.`]],[\"caller\",[\"caller [expr]\",`Return the context of the current subroutine call.\n Without EXPR, returns \"$line $filename\". With EXPR, returns\n \"$line $subroutine $filename\"; this extra information can be used to\n provide a stack trace.\n Exit Status:\n Returns 0 unless the shell is not executing a subroutine call or\n EXPR is invalid.`]],[\"cd\",[\"cd [-L|-P] [dir]\",`Change the shell working directory.\n Change the current directory to DIR. The default DIR is the value of the\n HOME shell variable.\n\n The variable CDPATH defines the search path for the directory containing\n DIR. Alternative directory names in CDPATH are separated by a colon (:).\n A null directory name is the same as the current directory. If DIR begins\n with a slash (/), then CDPATH is not used.\n\n If the directory is not found, and the shell option \\`cdable_vars' is set,\n the word is assumed to be a variable name. If that variable has a value,\n its value is used for DIR.\n\n Options:\n -L\tforce symbolic links to be followed\n -P\tuse the physical directory structure without following symbolic\n \tlinks\n\n The default is to follow symbolic links, as if \\`-L' were specified.\n\n Exit Status:\n Returns 0 if the directory is changed; non-zero otherwise.`]],[\"command\",[\"command [-pVv] command [arg ...]\",`Execute a simple command or display information about commands.\n Runs COMMAND with ARGS suppressing shell function lookup, or display\n information about the specified COMMANDs.\n\n Options:\n -p\tuse a default value for PATH that is guaranteed to find all of\n \tthe standard utilities\n -v\tprint a description of COMMAND similar to the \\`type' builtin\n -V\tprint a more verbose description of each COMMAND\n\n Exit Status:\n Returns exit status of COMMAND, or failure if COMMAND is not found.`]],[\"compgen\",[\"compgen [-abcdefgjksuv] [-o option] [-A action] [-G globpat] [-W wordlist] [-F function] [-C command] [-X filterpat] [-P prefix] [-S suffix] [word]\",`Display possible completions depending on the options.\n Intended to be used from within a shell function generating possible\n completions. If the optional WORD argument is supplied, matches against\n WORD are generated.\n Exit Status:\n Returns success unless an invalid option is supplied or an error occurs.`]],[\"complete\",[\"complete [-abcdefgjksuv] [-pr] [-DEI] [-o option] [-A action] [-G globpat] [-W wordlist] [-F function] [-C command] [-X filterpat] [-P prefix] [-S suffix] [name ...]\",`Specify how arguments are to be completed.\n For each NAME, specify how arguments are to be completed.\n Exit Status:\n Returns success unless an invalid option is supplied or an error occurs.`]],[\"continue\",[\"continue [n]\",`Resume for, while, or until loops.\n Resumes the next iteration of the enclosing FOR, WHILE or UNTIL loop.\n If N is specified, resumes the Nth enclosing loop.\n Exit Status:\n The exit status is 0 unless N is not greater than or equal to 1.`]],[\"declare\",[\"declare [-aAfFgilnrtux] [-p] [name[=value] ...]\",`Set variable values and attributes.\n Declare variables and give them attributes. If no NAMEs are given,\n display the attributes and values of all variables.\n\n Options:\n -a\tto make NAMEs indexed arrays (if supported)\n -A\tto make NAMEs associative arrays (if supported)\n -i\tto make NAMEs have the \\`integer' attribute\n -l\tto convert the value of each NAME to lower case on assignment\n -n\tmake NAME a reference to the variable named by its value\n -r\tto make NAMEs readonly\n -t\tto make NAMEs have the \\`trace' attribute\n -u\tto convert the value of each NAME to upper case on assignment\n -x\tto make NAMEs export\n\n Exit Status:\n Returns success unless an invalid option is supplied or a variable\n assignment error occurs.`]],[\"dirs\",[\"dirs [-clpv] [+N] [-N]\",`Display directory stack.\n Display the list of currently remembered directories. Directories\n find their way onto the list with the \\`pushd' command; you can get\n back up through the list with the \\`popd' command.\n Exit Status:\n Returns success unless an invalid option is supplied or an error occurs.`]],[\"disown\",[\"disown [-h] [-ar] [jobspec ...]\",`Remove jobs from current shell.\n Without any JOBSPECs, remove the current job.`]],[\"echo\",[\"echo [-neE] [arg ...]\",`Write arguments to the standard output.\n Display the ARGs, separated by a single space character and followed by a\n newline, on the standard output.\n\n Options:\n -n\tdo not append a newline\n -e\tenable interpretation of the following backslash escapes\n -E\texplicitly suppress interpretation of backslash escapes\n\n Exit Status:\n Returns success unless a write error occurs.`]],[\"enable\",[\"enable [-a] [-dnps] [-f filename] [name ...]\",`Enable and disable shell builtins.\n Enables and disables builtin shell commands.\n Exit Status:\n Returns success unless NAME is not a shell builtin or an error occurs.`]],[\"eval\",[\"eval [arg ...]\",`Execute arguments as a shell command.\n Combine ARGs into a single string, use the result as input to the shell,\n and execute the resulting commands.\n Exit Status:\n Returns exit status of command or success if command is null.`]],[\"exec\",[\"exec [-cl] [-a name] [command [arguments ...]] [redirection ...]\",`Replace the shell with the given command.\n Execute COMMAND, replacing this shell with the specified program.\n ARGUMENTS become the arguments to COMMAND. If COMMAND is not specified,\n any redirections take effect in the current shell.\n Exit Status:\n Returns success unless COMMAND is not found or a redirection error occurs.`]],[\"exit\",[\"exit [n]\",`Exit the shell.\n Exits the shell with a status of N. If N is omitted, the exit status\n is that of the last command executed.`]],[\"export\",[\"export [-fn] [name[=value] ...] or export -p\",`Set export attribute for shell variables.\n Marks each NAME for automatic export to the environment of subsequently\n executed commands. If VALUE is supplied, assign VALUE before exporting.\n\n Options:\n -f\trefer to shell functions\n -n\tremove the export property from each NAME\n -p\tdisplay a list of all exported variables and functions\n\n Exit Status:\n Returns success unless an invalid option is given or NAME is invalid.`]],[\"false\",[\"false\",`Return an unsuccessful result.\n Exit Status:\n Always fails.`]],[\"fc\",[\"fc [-e ename] [-lnr] [first] [last] or fc -s [pat=rep] [command]\",`Display or execute commands from the history list.\n Exit Status:\n Returns success or status of executed command.`]],[\"fg\",[\"fg [job_spec]\",`Move job to the foreground.\n Place the job identified by JOB_SPEC in the foreground, making it the\n current job.`]],[\"getopts\",[\"getopts optstring name [arg]\",`Parse option arguments.\n Getopts is used by shell procedures to parse positional parameters\n as options.\n\n OPTSTRING contains the option letters to be recognized; if a letter\n is followed by a colon, the option is expected to have an argument,\n which should be separated from it by white space.\n Exit Status:\n Returns success if an option is found; fails if the end of options is\n encountered or an error occurs.`]],[\"hash\",[\"hash [-lr] [-p pathname] [-dt] [name ...]\",`Remember or display program locations.\n Determine and remember the full pathname of each command NAME.\n Exit Status:\n Returns success unless NAME is not found or an invalid option is given.`]],[\"help\",[\"help [-s] [pattern ...]\",`Display information about builtin commands.\n Displays brief summaries of builtin commands. If PATTERN is\n specified, gives detailed help on all commands matching PATTERN,\n otherwise the list of help topics is printed.\n\n Options:\n -s\toutput only a short usage synopsis for each topic matching\n \tPATTERN\n\n Exit Status:\n Returns success unless PATTERN is not found.`]],[\"history\",[\"history [-c] [-d offset] [n] or history -anrw [filename] or history -ps arg [arg...]\",`Display or manipulate the history list.\n Display the history list with line numbers, prefixing each modified\n entry with a \\`*'.\n Exit Status:\n Returns success unless an invalid option is given or an error occurs.`]],[\"jobs\",[\"jobs [-lnprs] [jobspec ...] or jobs -x command [args]\",`Display status of jobs.\n Lists the active jobs.\n Exit Status:\n Returns success unless an invalid option is given or an error occurs.`]],[\"kill\",[\"kill [-s sigspec | -n signum | -sigspec] pid | jobspec ... or kill -l [sigspec]\",`Send a signal to a job.\n Send the processes identified by PID or JOBSPEC the signal named by\n SIGSPEC or SIGNUM.\n Exit Status:\n Returns success unless an invalid option is given or an error occurs.`]],[\"let\",[\"let arg [arg ...]\",`Evaluate arithmetic expressions.\n Evaluate each ARG as an arithmetic expression. Evaluation is done in\n fixed-width integers with no check for overflow, though division by 0\n is trapped and flagged as an error.\n Exit Status:\n If the last ARG evaluates to 0, let returns 1; 0 is returned otherwise.`]],[\"local\",[\"local [option] name[=value] ...\",`Define local variables.\n Create a local variable called NAME, and give it VALUE. OPTION can\n be any option accepted by \\`declare'.\n\n Local can only be used within a function; it makes the variable NAME\n have a visible scope restricted to that function and its children.\n Exit Status:\n Returns success unless an invalid option is supplied, a variable\n assignment error occurs, or the shell is not executing a function.`]],[\"logout\",[\"logout [n]\",`Exit a login shell.\n Exits a login shell with exit status N. Returns an error if not executed\n in a login shell.`]],[\"mapfile\",[\"mapfile [-d delim] [-n count] [-O origin] [-s count] [-t] [-u fd] [-C callback] [-c quantum] [array]\",`Read lines from the standard input into an indexed array variable.\n Read lines from the standard input into the indexed array variable ARRAY,\n or from file descriptor FD if the -u option is supplied.\n\n Options:\n -d delim\tUse DELIM to terminate lines, instead of newline\n -n count\tCopy at most COUNT lines\n -O origin\tBegin assigning to ARRAY at index ORIGIN\n -s count\tDiscard the first COUNT lines read\n -t\tRemove a trailing DELIM from each line read (default newline)\n -u fd\tRead lines from file descriptor FD instead of standard input\n\n Exit Status:\n Returns success unless an invalid option is given or ARRAY is readonly.`]],[\"popd\",[\"popd [-n] [+N | -N]\",`Remove directories from stack.\n Removes entries from the directory stack.\n Exit Status:\n Returns success unless an invalid argument is supplied or the directory\n change fails.`]],[\"printf\",[\"printf [-v var] format [arguments]\",`Formats and prints ARGUMENTS under control of the FORMAT.\n\n Options:\n -v var\tassign the output to shell variable VAR rather than\n \t\tdisplay it on the standard output\n\n FORMAT is a character string which contains three types of objects: plain\n characters, which are simply copied to standard output; character escape\n sequences, which are converted and copied to the standard output; and\n format specifications, each of which causes printing of the next successive\n argument.\n Exit Status:\n Returns success unless an invalid option is given or a write or assignment\n error occurs.`]],[\"pushd\",[\"pushd [-n] [+N | -N | dir]\",`Add directories to stack.\n Adds a directory to the top of the directory stack, or rotates\n the stack, making the new top of the stack the current working\n directory.\n Exit Status:\n Returns success unless an invalid argument is supplied or the directory\n change fails.`]],[\"pwd\",[\"pwd [-LP]\",`Print the name of the current working directory.\n\n Options:\n -L\tprint the value of $PWD if it names the current working\n \tdirectory\n -P\tprint the physical directory, without any symbolic links\n\n By default, \\`pwd' behaves as if \\`-L' were specified.\n Exit Status:\n Returns 0 unless an invalid option is given or the current directory\n cannot be read.`]],[\"read\",[\"read [-ers] [-a array] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...]\",`Read a line from the standard input and split it into fields.\n Reads a single line from the standard input, or from file descriptor FD\n if the -u option is supplied. The line is split into fields as with word\n splitting, and the first word is assigned to the first NAME, the second\n word to the second NAME, and so on, with any leftover words assigned to\n the last NAME.\n Exit Status:\n The return code is zero, unless end-of-file is encountered, read times out,\n or an invalid file descriptor is supplied as the argument to -u.`]],[\"readarray\",[\"readarray [-d delim] [-n count] [-O origin] [-s count] [-t] [-u fd] [-C callback] [-c quantum] [array]\",\"Read lines from a file into an array variable.\\n A synonym for `mapfile'.\"]],[\"readonly\",[\"readonly [-aAf] [name[=value] ...] or readonly -p\",`Mark shell variables as unchangeable.\n Mark each NAME as read-only; the values of these NAMEs may not be\n changed by subsequent assignment.\n Exit Status:\n Returns success unless an invalid option is given or NAME is invalid.`]],[\"return\",[\"return [n]\",`Return from a shell function.\n Causes a function or sourced script to exit with the return value\n specified by N. If N is omitted, the return status is that of the\n last command executed within the function or script.\n Exit Status:\n Returns N, or failure if the shell is not executing a function or script.`]],[\"set\",[\"set [-abefhkmnptuvxBCHP] [-o option-name] [--] [arg ...]\",`Set or unset values of shell options and positional parameters.\n Change the value of shell attributes and positional parameters, or\n display the names and values of shell variables.\n\n Options:\n -e Exit immediately if a command exits with a non-zero status.\n -u Treat unset variables as an error when substituting.\n -x Print commands and their arguments as they are executed.\n -o option-name\n Set the variable corresponding to option-name\n\n Exit Status:\n Returns success unless an invalid option is given.`]],[\"shift\",[\"shift [n]\",`Shift positional parameters.\n Rename the positional parameters $N+1,$N+2 ... to $1,$2 ... If N is\n not given, it is assumed to be 1.\n Exit Status:\n Returns success unless N is negative or greater than $#.`]],[\"shopt\",[\"shopt [-pqsu] [-o] [optname ...]\",`Set and unset shell options.\n Change the setting of each shell option OPTNAME. Without any option\n arguments, list each supplied OPTNAME, or all shell options if no\n OPTNAMEs are given, with an indication of whether or not each is set.\n\n Options:\n -o\trestrict OPTNAMEs to those defined for use with \\`set -o'\n -p\tprint each shell option with an indication of its status\n -q\tsuppress output\n -s\tenable (set) each OPTNAME\n -u\tdisable (unset) each OPTNAME\n\n Exit Status:\n Returns success if OPTNAME is enabled; fails if an invalid option is\n given or OPTNAME is disabled.`]],[\"source\",[\"source filename [arguments]\",`Execute commands from a file in the current shell.\n Read and execute commands from FILENAME in the current shell.\n The entries in $PATH are used to find the directory containing FILENAME.\n Exit Status:\n Returns the status of the last command executed in FILENAME.`]],[\"suspend\",[\"suspend [-f]\",`Suspend shell execution.\n Suspend the execution of this shell until it receives a SIGCONT signal.`]],[\"test\",[\"test [expr]\",`Evaluate conditional expression.\n Exits with a status of 0 (true) or 1 (false) depending on\n the evaluation of EXPR. Expressions may be unary or binary.\n Exit Status:\n Returns success if EXPR evaluates to true; fails if EXPR evaluates to\n false or an invalid argument is given.`]],[\"times\",[\"times\",`Display process times.\n Prints the accumulated user and system times for the shell and all of its\n child processes.\n Exit Status:\n Always succeeds.`]],[\"trap\",[\"trap [-lp] [[arg] signal_spec ...]\",`Trap signals and other events.\n Defines and activates handlers to be run when the shell receives signals\n or other conditions.\n Exit Status:\n Returns success unless a SIGSPEC is invalid or an invalid option is given.`]],[\"true\",[\"true\",`Return a successful result.\n Exit Status:\n Always succeeds.`]],[\"type\",[\"type [-afptP] name [name ...]\",`Display information about command type.\n For each NAME, indicate how it would be interpreted if used as a\n command name.\n\n Options:\n -a\tdisplay all locations containing an executable named NAME\n -f\tsuppress shell function lookup\n -P\tforce a PATH search for each NAME, even if it is an alias,\n \tbuiltin, or function, and returns the name of the disk file\n \tthat would be executed\n -p\treturns either the name of the disk file that would be executed,\n \tor nothing if \\`type -t NAME' would not return \\`file'\n -t\toutput a single word which is one of \\`alias', \\`keyword',\n \t\\`function', \\`builtin', \\`file' or \\`', if NAME is an alias,\n \tshell reserved word, shell function, shell builtin, disk file,\n \tor not found, respectively\n\n Exit Status:\n Returns success if all of the NAMEs are found; fails if any are not found.`]],[\"typeset\",[\"typeset [-aAfFgilnrtux] [-p] name[=value] ...\",\"Set variable values and attributes.\\n A synonym for `declare'.\"]],[\"ulimit\",[\"ulimit [-SHabcdefiklmnpqrstuvxPT] [limit]\",`Modify shell resource limits.\n Provides control over the resources available to the shell and processes\n it creates, on systems that allow such control.\n Exit Status:\n Returns success unless an invalid option is supplied or an error occurs.`]],[\"umask\",[\"umask [-p] [-S] [mode]\",`Display or set file mode mask.\n Sets the user file-creation mask to MODE. If MODE is omitted, prints\n the current value of the mask.\n Exit Status:\n Returns success unless MODE is invalid or an invalid option is given.`]],[\"unalias\",[\"unalias [-a] name [name ...]\",`Remove each NAME from the list of defined aliases.\n Exit Status:\n Returns success unless a NAME is not an existing alias.`]],[\"unset\",[\"unset [-f] [-v] [-n] [name ...]\",`Unset values and attributes of shell variables and functions.\n For each NAME, remove the corresponding variable or function.\n\n Options:\n -f\ttreat each NAME as a shell function\n -v\ttreat each NAME as a shell variable\n -n\ttreat each NAME as a name reference and unset the variable itself\n \trather than the variable it references\n\n Without options, unset first tries to unset a variable, and if that fails,\n tries to unset a function.\n Exit Status:\n Returns success unless an invalid option is given or a NAME is read-only.`]],[\"wait\",[\"wait [-fn] [id ...]\",`Wait for job completion and return exit status.\n Waits for each process identified by an ID, which may be a process ID or a\n job specification, and reports its termination status.\n Exit Status:\n Returns the status of the last ID; fails if ID is invalid or an invalid\n option is given.`]]]),ei=[...Jn.keys()].sort();function kr(e,t){let s=!1,r=[],n=0;for(;n<t.length;){let l=t[n];if(l===\"--\"){for(n++;n<t.length;)r.push(t[n]),n++;break}if(l.startsWith(\"-\")&&l.length>1){for(let c=1;c<l.length;c++){let u=l[c];if(u===\"s\")s=!0;else return A(`bash: help: -${u}: invalid option\n`,2)}n++}else r.push(l),n++}if(r.length===0)return aa();let i=\"\",o=!1,a=\"\";for(let l of r){let c=oa(l);if(c.length===0){a+=`bash: help: no help topics match \\`${l}'. Try \\`help help' or \\`man -k ${l}' or \\`info ${l}'.\n`,o=!0;continue}for(let u of c){let f=Jn.get(u);if(!f)continue;let[d,p]=f;s?i+=`${u}: ${d}\n`:i+=`${u}: ${d}\n${p}\n`}}return{exitCode:o?1:0,stdout:i,stderr:a}}function oa(e){let t=e.replace(/[.+^${}()|[\\]\\\\]/g,\"\\\\$&\").replace(/\\*/g,\".*\").replace(/\\?/g,\".\"),s=kt(`^${t}$`);return ei.filter(r=>s.test(r))}function aa(){let e=[];e.push(\"just-bash shell builtins\"),e.push(\"These shell commands are defined internally. Type `help' to see this list.\"),e.push(\"Type `help name' to find out more about the function `name'.\"),e.push(\"\");let t=36,s=ei.slice(),r=Math.ceil(s.length/2);for(let n=0;n<r;n++){let i=s[n]||\"\",o=s[n+r]||\"\",a=i.padEnd(t);e.push(o?`${a}${o}`:i)}return z(`${e.join(`\n`)}\n`)}function la(e){let t=[],s=\"\",r=0;for(let n of e){for(let i of n)i===\"(\"?r++:i===\")\"&&r--;s?s+=` ${n}`:s=n,r===0&&(t.push(s),s=\"\")}return s&&t.push(s),t}async function _r(e,t){if(t.length===0)return A(`bash: let: expression expected\n`);let s=la(t),r=0;for(let n of s)try{let o=fe(`(( ${n} ))`).statements[0];if(o&&o.pipelines.length>0&&o.pipelines[0].commands.length>0){let a=o.pipelines[0].commands[0];a.type===\"ArithmeticCommand\"&&(r=await H(e,a.expression.expression))}}catch(i){return A(`bash: let: ${n}: ${i.message}\n`)}return _(\"\",\"\",r===0?1:0)}async function Cr(e,t){if(e.state.localScopes.length===0)return A(`bash: local: can only be used in a function\n`);let s=e.state.localScopes[e.state.localScopes.length-1],r=\"\",n=0,i=!1,o=!1,a=!1,l=[];for(let c of t)if(c===\"-n\")i=!0;else if(c===\"-a\")o=!0;else if(c===\"-p\")a=!0;else if(c.startsWith(\"-\")&&!c.includes(\"=\"))for(let u of c.slice(1))u===\"n\"?i=!0:u===\"a\"?o=!0:u===\"p\"&&(a=!0);else l.push(c);if(l.length===0){let c=\"\",u=Array.from(s.keys()).filter(f=>!f.includes(\"_\")||!f.match(/_\\d+$/)).filter(f=>!f.includes(\"__length\")).sort();for(let f of u){let d=e.state.env.get(f);d!==void 0&&(c+=`${f}=${d}\n`)}return _(c,\"\",0)}for(let c of l){let u,f,d=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\\((.*)\\)$/s);if(d){u=d[1];let E=d[2];if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(u)){r+=`bash: local: \\`${c}': not a valid identifier\n`,n=1;continue}if(se(e,u,\"bash\"),!s.has(u)){s.set(u,e.state.env.get(u));let m=`${u}_`;for(let v of e.state.env.keys())v.startsWith(m)&&!v.includes(\"__\")&&(s.has(v)||s.set(v,e.state.env.get(v)))}let g=`${u}_`;for(let m of e.state.env.keys())m.startsWith(g)&&!m.includes(\"__\")&&e.state.env.delete(m);let b=De(E);for(let m=0;m<b.length;m++)e.state.env.set(`${u}_${m}`,b[m]);e.state.env.set(`${u}__length`,String(b.length)),Xe(e,u),i&&We(e,u);continue}let p=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\+=\\((.*)\\)$/s);if(p){u=p[1];let E=p[2];if(se(e,u,\"bash\"),!s.has(u)){s.set(u,e.state.env.get(u));let S=`${u}_`;for(let N of e.state.env.keys())N.startsWith(S)&&!N.includes(\"__\")&&(s.has(N)||s.set(N,e.state.env.get(N)));let T=`${u}__length`;e.state.env.has(T)&&!s.has(T)&&s.set(T,e.state.env.get(T))}let g=De(E),b=ne(e,u),m=0,v=e.state.env.get(u);b.length===0&&v!==void 0?(e.state.env.set(`${u}_0`,v),e.state.env.delete(u),m=1):b.length>0&&(m=Math.max(...b)+1);for(let S=0;S<g.length;S++)e.state.env.set(`${u}_${m+S}`,X(e,g[S]));let $=m+g.length;e.state.env.set(`${u}__length`,String($)),Xe(e,u),i&&We(e,u);continue}let y=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\+=(.*)$/);if(y){u=y[1];let E=X(e,y[2]);se(e,u,\"bash\"),s.has(u)||s.set(u,e.state.env.get(u));let g=e.state.env.get(u)??\"\";e.state.env.set(u,g+E),Xe(e,u),i&&We(e,u);continue}let h=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[([^\\]]+)\\]=(.*)$/s);if(h){u=h[1];let E=h[2],g=X(e,h[3]);if(se(e,u,\"bash\"),!s.has(u)){s.set(u,e.state.env.get(u));let v=`${u}_`;for(let S of e.state.env.keys())S.startsWith(v)&&!S.includes(\"__\")&&(s.has(S)||s.set(S,e.state.env.get(S)));let $=`${u}__length`;e.state.env.has($)&&!s.has($)&&s.set($,e.state.env.get($))}let b;try{let v=new B,$=ee(v,E);b=await H(e,$.expression)}catch{let v=parseInt(E,10);b=Number.isNaN(v)?0:v}e.state.env.set(`${u}_${b}`,g);let m=parseInt(e.state.env.get(`${u}__length`)??\"0\",10);b>=m&&e.state.env.set(`${u}__length`,String(b+1)),Xe(e,u),i&&We(e,u);continue}if(c.includes(\"=\")){let E=c.indexOf(\"=\");u=c.slice(0,E),f=X(e,c.slice(E+1))}else u=c;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(u)){r+=`bash: local: \\`${c}': not a valid identifier\n`,n=1;continue}let w=s.has(u);if(f!==void 0){let E=e.state.env.get(u);if(e.state.tempEnvBindings){let g=e.state.accessedTempEnvVars?.has(u),b=e.state.mutatedTempEnvVars?.has(u);if(!g&&!b)for(let m=e.state.tempEnvBindings.length-1;m>=0;m--){let v=e.state.tempEnvBindings[m];if(v.has(u)){E=v.get(u);break}}}Mn(e,u,E)}if(!w){let E=e.state.env.get(u);if(e.state.tempEnvBindings)for(let g=e.state.tempEnvBindings.length-1;g>=0;g--){let b=e.state.tempEnvBindings[g];if(b.has(u)){E=b.get(u);break}}if(s.set(u,E),o){let g=`${u}_`;for(let m of e.state.env.keys())m.startsWith(g)&&!m.includes(\"__\")&&(s.has(m)||s.set(m,e.state.env.get(m)));let b=`${u}__length`;e.state.env.has(b)&&!s.has(b)&&s.set(b,e.state.env.get(b))}}if(o&&f===void 0){let E=`${u}_`;for(let g of e.state.env.keys())g.startsWith(E)&&!g.includes(\"__\")&&e.state.env.delete(g);e.state.env.set(`${u}__length`,\"0\")}else if(f!==void 0){if(se(e,u,\"bash\"),i&&f!==\"\"&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\\[.+\\])?$/.test(f)){r+=`bash: local: \\`${f}': invalid variable name for name reference\n`,n=1;continue}e.state.env.set(u,f),e.state.options.allexport&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(u))}else{let E=e.state.tempEnvBindings?.some(g=>g.has(u));!w&&!E&&e.state.env.delete(u)}Xe(e,u),i&&We(e,u)}return _(\"\",r,n)}function Nr(e,t,s){let r=`\n`,n=0,i=0,o=0,a=!1,l=\"MAPFILE\",c=0;for(;c<t.length;){let g=t[c];g===\"-d\"&&c+1<t.length?(r=t[c+1]===\"\"?\"\\0\":t[c+1]||`\n`,c+=2):g===\"-n\"&&c+1<t.length?(n=Number.parseInt(t[c+1],10)||0,c+=2):g===\"-O\"&&c+1<t.length?(i=Number.parseInt(t[c+1],10)||0,c+=2):g===\"-s\"&&c+1<t.length?(o=Number.parseInt(t[c+1],10)||0,c+=2):g===\"-t\"?(a=!0,c++):g===\"-u\"||g===\"-C\"||g===\"-c\"?c+=2:(g.startsWith(\"-\")||(l=g),c++)}let u=s;!u&&e.state.groupStdin!==void 0&&(u=e.state.groupStdin);let f=[],d=u,p=0,y=0,h=e.limits?.maxArrayElements??1e5;for(;d.length>0;){let g=d.indexOf(r);if(g===-1){if(d.length>0){if(y<o)y++;else if(n===0||p<n){if(i+p>=h)return _(\"\",`mapfile: array element limit exceeded (${h})\n`,1);let v=d,$=v.indexOf(\"\\0\");$!==-1&&(v=v.substring(0,$)),f.push(v),p++}}break}let b=d.substring(0,g),m=b.indexOf(\"\\0\");if(m!==-1&&(b=b.substring(0,m)),!a&&r!==\"\\0\"&&(b+=r),d=d.substring(g+r.length),y<o){y++;continue}if(n>0&&p>=n)break;if(i+p>=h)return _(\"\",`mapfile: array element limit exceeded (${h})\n`,1);f.push(b),p++}i===0&&Oe(e,l);for(let g=0;g<f.length;g++)e.state.env.set(`${l}_${i+g}`,f[g]);let w=parseInt(e.state.env.get(`${l}__length`)||\"0\",10),E=i+f.length;return e.state.env.set(`${l}__length`,String(Math.max(w,E))),e.state.groupStdin!==void 0&&!s&&(e.state.groupStdin=\"\"),_(\"\",\"\",0)}function ca(e){if(!e.startsWith(\"__rw__:\"))return null;let t=e.slice(7),s=t.indexOf(\":\");if(s===-1)return null;let r=Number.parseInt(t.slice(0,s),10);if(Number.isNaN(r)||r<0)return null;let n=s+1,i=t.slice(n,n+r),o=n+r+1,a=t.slice(o),l=a.indexOf(\":\");if(l===-1)return null;let c=Number.parseInt(a.slice(0,l),10);if(Number.isNaN(c)||c<0)return null;let u=a.slice(l+1);return{path:i,position:c,content:u}}function ua(e,t,s){return`__rw__:${e.length}:${e}:${t}:${s}`}function Or(e,t,s,r=-1){let n=!1,i=`\n`,o=\"\",a=-1,l=-1,c=null,u=-1,f=-1,d=[],p=0,y=!1,h=(k,C)=>{let D=1;for(;D<k.length;){let P=k[D];if(P===\"r\")n=!0,D++;else if(P===\"s\")D++;else{if(P===\"d\")return D+1<k.length?(i=k.substring(D+1),{nextArgIndex:C+1}):C+1<t.length?(i=t[C+1],{nextArgIndex:C+2}):{nextArgIndex:C+1};if(P===\"n\"){if(D+1<k.length){let R=k.substring(D+1);return a=Number.parseInt(R,10),(Number.isNaN(a)||a<0)&&(y=!0,a=0),{nextArgIndex:C+1}}else if(C+1<t.length)return a=Number.parseInt(t[C+1],10),(Number.isNaN(a)||a<0)&&(y=!0,a=0),{nextArgIndex:C+2};return{nextArgIndex:C+1}}else if(P===\"N\"){if(D+1<k.length){let R=k.substring(D+1);return l=Number.parseInt(R,10),(Number.isNaN(l)||l<0)&&(y=!0,l=0),{nextArgIndex:C+1}}else if(C+1<t.length)return l=Number.parseInt(t[C+1],10),(Number.isNaN(l)||l<0)&&(y=!0,l=0),{nextArgIndex:C+2};return{nextArgIndex:C+1}}else{if(P===\"a\")return D+1<k.length?(c=k.substring(D+1),{nextArgIndex:C+1}):C+1<t.length?(c=t[C+1],{nextArgIndex:C+2}):{nextArgIndex:C+1};if(P===\"p\")return D+1<k.length?(o=k.substring(D+1),{nextArgIndex:C+1}):C+1<t.length?(o=t[C+1],{nextArgIndex:C+2}):{nextArgIndex:C+1};if(P===\"u\"){if(D+1<k.length){let R=k.substring(D+1);return u=Number.parseInt(R,10),Number.isNaN(u)||u<0?{nextArgIndex:-2}:{nextArgIndex:C+1}}else if(C+1<t.length)return u=Number.parseInt(t[C+1],10),Number.isNaN(u)||u<0?{nextArgIndex:-2}:{nextArgIndex:C+2};return{nextArgIndex:C+1}}else if(P===\"t\"){if(D+1<k.length){let R=k.substring(D+1);return f=Number.parseFloat(R),Number.isNaN(f)&&(f=0),{nextArgIndex:C+1}}else if(C+1<t.length)return f=Number.parseFloat(t[C+1]),Number.isNaN(f)&&(f=0),{nextArgIndex:C+2};return{nextArgIndex:C+1}}else if(P===\"e\"||P===\"i\"||P===\"P\"){if(P===\"i\"&&C+1<t.length)return{nextArgIndex:C+2};D++}else D++}}}return{nextArgIndex:C+1}};for(;p<t.length;){let k=t[p];if(k.startsWith(\"-\")&&k.length>1&&k!==\"--\"){let C=h(k,p);if(C.nextArgIndex===-1)return{stdout:\"\",stderr:\"\",exitCode:2};if(C.nextArgIndex===-2)return{stdout:\"\",stderr:\"\",exitCode:1};p=C.nextArgIndex}else if(k===\"--\")for(p++;p<t.length;)d.push(t[p]),p++;else d.push(k),p++}if(y)return _(\"\",\"\",1);if(d.length===0&&c===null&&d.push(\"REPLY\"),f===0){if(c)Oe(e,c);else{for(let k of d)e.state.env.set(k,\"\");d.length===0&&e.state.env.set(\"REPLY\",\"\")}return _(\"\",\"\",0)}if(f<0&&f!==-1)return _(\"\",\"\",1);let w=s;u>=0?e.state.fileDescriptors?w=e.state.fileDescriptors.get(u)||\"\":w=\"\":!w&&e.state.groupStdin!==void 0&&(w=e.state.groupStdin);let E=i===\"\"?\"\\0\":i,g=\"\",b=0,m=!0,v=k=>{if(u>=0&&e.state.fileDescriptors)e.state.fileDescriptors.set(u,w.substring(k));else if(r>=0&&e.state.fileDescriptors){let C=e.state.fileDescriptors.get(r);if(C?.startsWith(\"__rw__:\")){let D=ca(C);if(D){let P=D.position+k;e.state.fileDescriptors.set(r,ua(D.path,P,D.content))}}}else e.state.groupStdin!==void 0&&!s&&(e.state.groupStdin=w.substring(k))};if(l>=0){let k=Math.min(l,w.length);g=w.substring(0,k),b=k,m=k>=l,v(b);let C=d[0]||\"REPLY\";e.state.env.set(C,g);for(let D=1;D<d.length;D++)e.state.env.set(d[D],\"\");return _(\"\",\"\",m?0:1)}else if(a>=0){let k=0,C=0,D=!1;for(;C<w.length&&k<a;){let P=w[C];if(P===E){b=C+1,D=!0;break}if(!n&&P===\"\\\\\"&&C+1<w.length){let R=w[C+1];if(R===E&&E===`\n`){C+=2,b=C;continue}if(R===E){C+=2,k++,g+=R,b=C;continue}g+=R,C+=2,k++,b=C}else g+=P,C++,k++,b=C}m=k>=a||D,v(b)}else{b=0;let k=0;for(;k<w.length;){let C=w[k];if(C===E){b=k+E.length,m=!0;break}if(!n&&C===\"\\\\\"&&k+1<w.length){let D=w[k+1];if(D===`\n`){k+=2;continue}if(D===E){g+=D,k+=2;continue}g+=C,g+=D,k+=2;continue}g+=C,k++}if(k>=w.length&&(m=!1,b=k,g.length===0&&w.length===0)){for(let C of d)e.state.env.set(C,\"\");return c&&Oe(e,c),_(\"\",\"\",1)}v(b)}E===`\n`&&g.endsWith(`\n`)&&(g=g.slice(0,-1));let $=k=>n?k:k.replace(/\\\\(.)/g,\"$1\");if(d.length===1&&d[0]===\"REPLY\")return e.state.env.set(\"REPLY\",$(g)),_(\"\",\"\",m?0:1);let S=Jr(e.state.env);if(c){let{words:k}=zs(g,S,void 0,n),C=e.limits?.maxArrayElements??1e5;if(k.length>C)return _(\"\",`read: array element limit exceeded (${C})\n`,1);Oe(e,c);for(let D=0;D<k.length;D++)e.state.env.set(`${c}_${D}`,$(k[D]));return _(\"\",\"\",m?0:1)}let T=d.length,{words:N,wordStarts:F}=zs(g,S,T,n);for(let k=0;k<d.length;k++){let C=d[k];if(k<d.length-1)e.state.env.set(C,$(N[k]??\"\"));else if(k<F.length){let D=g.substring(F[k]);D=en(D,S,n),D=$(D),e.state.env.set(C,D)}else e.state.env.set(C,\"\")}return _(\"\",\"\",m?0:1)}function xr(e,t){if(e.state.callDepth===0&&e.state.sourceDepth===0)return A(\"bash: return: can only `return' from a function or sourced script\\n\");let s=e.state.lastExitCode;if(t.length>0){let r=t[0],n=Number.parseInt(r,10);if(r===\"\"||Number.isNaN(n)||!/^-?\\d+$/.test(r))return A(`bash: return: ${r}: numeric argument required\n`,2);s=(n%256+256)%256}throw new ue(s)}var bs=`set: usage: set [-eux] [+eux] [-o option] [+o option]\nOptions:\n -e Exit immediately if a command exits with non-zero status\n +e Disable -e\n -u Treat unset variables as an error when substituting\n +u Disable -u\n -x Print commands and their arguments as they are executed\n +x Disable -x\n -o errexit Same as -e\n +o errexit Disable errexit\n -o nounset Same as -u\n +o nounset Disable nounset\n -o pipefail Return status of last failing command in pipeline\n +o pipefail Disable pipefail\n -o xtrace Same as -x\n +o xtrace Disable xtrace\n`,ti=new Map([[\"e\",\"errexit\"],[\"u\",\"nounset\"],[\"x\",\"xtrace\"],[\"v\",\"verbose\"],[\"f\",\"noglob\"],[\"C\",\"noclobber\"],[\"a\",\"allexport\"],[\"n\",\"noexec\"],[\"h\",null],[\"b\",null],[\"m\",null],[\"B\",null],[\"H\",null],[\"P\",null],[\"T\",null],[\"E\",null],[\"p\",null]]),si=new Map([[\"errexit\",\"errexit\"],[\"pipefail\",\"pipefail\"],[\"nounset\",\"nounset\"],[\"xtrace\",\"xtrace\"],[\"verbose\",\"verbose\"],[\"noclobber\",\"noclobber\"],[\"noglob\",\"noglob\"],[\"allexport\",\"allexport\"],[\"noexec\",\"noexec\"],[\"posix\",\"posix\"],[\"vi\",\"vi\"],[\"emacs\",\"emacs\"],[\"notify\",null],[\"monitor\",null],[\"braceexpand\",null],[\"histexpand\",null],[\"physical\",null],[\"functrace\",null],[\"errtrace\",null],[\"privileged\",null],[\"hashall\",null],[\"ignoreeof\",null],[\"interactive-comments\",null],[\"keyword\",null],[\"onecmd\",null]]),ri=[\"errexit\",\"nounset\",\"pipefail\",\"verbose\",\"xtrace\",\"posix\",\"allexport\",\"noclobber\",\"noglob\",\"noexec\",\"vi\",\"emacs\"],ni=[\"braceexpand\",\"errtrace\",\"functrace\",\"hashall\",\"histexpand\",\"history\",\"ignoreeof\",\"interactive-comments\",\"keyword\",\"monitor\",\"nolog\",\"notify\",\"onecmd\",\"physical\",\"privileged\"];function ii(e,t,s){t!==null&&(s&&(t===\"vi\"?e.state.options.emacs=!1:t===\"emacs\"&&(e.state.options.vi=!1)),e.state.options[t]=s,dt(e))}function fa(e,t){return t+1<e.length&&!e[t+1].startsWith(\"-\")&&!e[t+1].startsWith(\"+\")}function da(e,t){let s=ne(e,t);if(s.length===0)return`${t}=()`;let r=s.map(n=>{let i=e.state.env.get(`${t}_${n}`)??\"\";return`[${n}]=${nt(i)}`});return`${t}=(${r.join(\" \")})`}function ha(e){return/^[a-zA-Z0-9_]+$/.test(e)?e:`\"${e.replace(/\\\\/g,\"\\\\\\\\\").replace(/\"/g,'\\\\\"')}\"`}function pa(e,t){let s=He(e,t);if(s.length===0)return`${t}=()`;let r=s.map(n=>{let i=e.state.env.get(`${t}_${n}`)??\"\";return`[${ha(n)}]=${nt(i)}`});return`${t}=(${r.join(\" \")} )`}function ma(e){let t=new Set,s=e.state.associativeArrays??new Set;for(let r of e.state.env.keys()){let n=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)_(\\d+)$/);if(n){let i=n[1];s.has(i)||t.add(i)}}return t}function ya(e){return e.state.associativeArrays??new Set}function Dr(e,t){if(t.includes(\"--help\"))return z(bs);if(t.length===0){let r=ma(e),n=ya(e),i=l=>{for(let c of n){let u=`${c}_`,f=`${c}__length`;if(l!==f&&l.startsWith(u)){if(l.slice(u.length).startsWith(\"_length\"))continue;return!0}}return!1},o=[];for(let[l,c]of e.state.env){if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(l)||r.has(l)||n.has(l))continue;let u=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)_(\\d+)$/);if(u&&r.has(u[1]))continue;let f=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)__length$/);f&&r.has(f[1])||i(l)||f&&n.has(f[1])||o.push([l,c])}let a=[];for(let[l,c]of o.sort(([u],[f])=>u<f?-1:u>f?1:0))a.push(`${l}=${gs(c)}`);for(let l of[...r].sort((c,u)=>c<u?-1:c>u?1:0))a.push(da(e,l));for(let l of[...n].sort((c,u)=>c<u?-1:c>u?1:0))a.push(pa(e,l));return a.sort((l,c)=>{let u=l.split(\"=\")[0],f=c.split(\"=\")[0];return u<f?-1:u>f?1:0}),z(a.length>0?`${a.join(`\n`)}\n`:\"\")}let s=0;for(;s<t.length;){let r=t[s];if((r===\"-o\"||r===\"+o\")&&fa(t,s)){let n=t[s+1];if(!si.has(n)){let i=`bash: set: ${n}: invalid option name\n${bs}`;if(e.state.options.posix)throw new Pe(1,\"\",i);return A(i)}ii(e,si.get(n)??null,r===\"-o\"),s+=2;continue}if(r===\"-o\"){let n=ri.map(a=>`${a.padEnd(16)}${e.state.options[a]?\"on\":\"off\"}`),i=ni.map(a=>`${a.padEnd(16)}off`),o=[...n,...i].sort();return z(`${o.join(`\n`)}\n`)}if(r===\"+o\"){let n=ri.map(a=>`set ${e.state.options[a]?\"-o\":\"+o\"} ${a}`),i=ni.map(a=>`set +o ${a}`),o=[...n,...i].sort();return z(`${o.join(`\n`)}\n`)}if(r.length>1&&(r[0]===\"-\"||r[0]===\"+\")&&r[1]!==\"-\"){let n=r[0]===\"-\";for(let i=1;i<r.length;i++){let o=r[i];if(!ti.has(o)){let a=`bash: set: ${r[0]}${o}: invalid option\n${bs}`;if(e.state.options.posix)throw new Pe(1,\"\",a);return A(a)}ii(e,ti.get(o)??null,n)}s++;continue}if(r===\"--\")return Tr(e,t.slice(s+1)),W;if(r===\"-\"){if(e.state.options.xtrace=!1,e.state.options.verbose=!1,dt(e),s+1<t.length)return Tr(e,t.slice(s+1)),W;s++;continue}if(r===\"+\"){s++;continue}if(r.startsWith(\"-\")||r.startsWith(\"+\")){let n=`bash: set: ${r}: invalid option\n${bs}`;if(e.state.options.posix)throw new Pe(1,\"\",n);return A(n)}return Tr(e,t.slice(s)),W}return W}function Tr(e,t){let s=1;for(;e.state.env.has(String(s));)e.state.env.delete(String(s)),s++;for(let r=0;r<t.length;r++)e.state.env.set(String(r+1),t[r]);e.state.env.set(\"#\",String(t.length)),e.state.env.set(\"@\",t.join(\" \")),e.state.env.set(\"*\",t.join(\" \"))}function Rr(e,t){let s=1;if(t.length>0){let o=Number.parseInt(t[0],10);if(Number.isNaN(o)||o<0){let a=`bash: shift: ${t[0]}: numeric argument required\n`;if(e.state.options.posix)throw new Pe(1,\"\",a);return A(a)}s=o}let r=Number.parseInt(e.state.env.get(\"#\")||\"0\",10);if(s>r){let o=`bash: shift: shift count out of range\n`;if(e.state.options.posix)throw new Pe(1,\"\",o);return A(o)}if(s===0)return W;let n=[];for(let o=1;o<=r;o++)n.push(e.state.env.get(String(o))||\"\");let i=n.slice(s);for(let o=1;o<=r;o++)e.state.env.delete(String(o));for(let o=0;o<i.length;o++)e.state.env.set(String(o+1),i[o]);return e.state.env.set(\"#\",String(i.length)),e.state.env.set(\"@\",i.join(\" \")),W}async function Ir(e,t){let s=t;if(s.length>0&&s[0]===\"--\"&&(s=s.slice(1)),s.length===0)return _(\"\",`bash: source: filename argument required\n`,2);let r=s[0],n=null,i=null;if(r.includes(\"/\")){let c=e.fs.resolvePath(e.state.cwd,r);try{i=await e.fs.readFile(c),n=c}catch{}}else{let u=(e.state.env.get(\"PATH\")||\"\").split(\":\").filter(f=>f);for(let f of u){let d=e.fs.resolvePath(e.state.cwd,`${f}/${r}`);try{if((await e.fs.stat(d)).isDirectory)continue;i=await e.fs.readFile(d),n=d;break}catch{}}if(i===null){let f=e.fs.resolvePath(e.state.cwd,r);try{i=await e.fs.readFile(f),n=f}catch{}}}if(i===null)return A(`bash: ${r}: No such file or directory\n`);let o=new Map;if(s.length>1){for(let u=1;u<=9;u++)o.set(String(u),e.state.env.get(String(u)));o.set(\"#\",e.state.env.get(\"#\")),o.set(\"@\",e.state.env.get(\"@\"));let c=s.slice(1);e.state.env.set(\"#\",String(c.length)),e.state.env.set(\"@\",c.join(\" \"));for(let u=0;u<c.length&&u<9;u++)e.state.env.set(String(u+1),c[u]);for(let u=c.length+1;u<=9;u++)e.state.env.delete(String(u))}let a=e.state.currentSource,l=()=>{if(e.state.sourceDepth--,e.state.currentSource=a,s.length>1)for(let[c,u]of o)u===void 0?e.state.env.delete(c):e.state.env.set(c,u)};if(e.state.sourceDepth++,e.state.sourceDepth>e.limits.maxSourceDepth)throw e.state.sourceDepth--,new J(`source: maximum nesting depth (${e.limits.maxSourceDepth}) exceeded, increase executionLimits.maxSourceDepth`,\"recursion\");e.state.currentSource=r;try{let c=fe(i),u=await e.executeScript(c);return l(),u}catch(c){if(l(),c instanceof j)throw c;if(c instanceof ue)return _(c.stdout,c.stderr,c.exitCode);if(c.name===\"ParseException\")return A(`bash: ${r}: ${c.message}\n`);throw c}}function oi(e){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}function ga(e){return e.startsWith(\"'\")&&e.endsWith(\"'\")||e.startsWith('\"')&&e.endsWith('\"')}async function ai(e,t){if(ga(t))return null;try{let s=new B,r=ee(s,t);return await H(e,r.expression)}catch{let s=parseInt(t,10);return Number.isNaN(s)?0:s}}function li(e,t){if(e.state.localVarStack?.has(t)){let r=ps(e,t);if(r){r.value===void 0?e.state.env.delete(t):e.state.env.set(t,r.value);let n=e.state.localVarStack?.get(t);if(!n||n.length===0)hs(e,t),e.state.localVarStack?.delete(t),e.state.fullyUnsetLocals=e.state.fullyUnsetLocals||new Map,e.state.fullyUnsetLocals.set(t,r.scopeIndex),Lr(e,t);else{let i=n[n.length-1];e.state.localVarDepth=e.state.localVarDepth||new Map,e.state.localVarDepth.set(t,i.scopeIndex+1)}return!0}return e.state.env.delete(t),hs(e,t),e.state.localVarStack?.delete(t),e.state.fullyUnsetLocals=e.state.fullyUnsetLocals||new Map,e.state.fullyUnsetLocals.set(t,0),!0}for(let r=e.state.localScopes.length-1;r>=0;r--){let n=e.state.localScopes[r];if(n.has(t)){let i=n.get(t);i===void 0?e.state.env.delete(t):e.state.env.set(t,i),n.delete(t);let o=!1;for(let a=r-1;a>=0;a--)if(e.state.localScopes[a].has(t)){e.state.localVarDepth&&e.state.localVarDepth.set(t,a+1),o=!0;break}return o||hs(e,t),!0}}return!1}function Lr(e,t){if(!e.state.tempEnvBindings||e.state.tempEnvBindings.length===0)return!1;for(let s=e.state.tempEnvBindings.length-1;s>=0;s--){let r=e.state.tempEnvBindings[s];if(r.has(t)){let n=r.get(t);return n===void 0?e.state.env.delete(t):e.state.env.set(t,n),r.delete(t),!0}}return!1}async function ci(e,t){if(t.startsWith(\"'\")&&t.endsWith(\"'\"))return t.slice(1,-1);if(t.startsWith('\"')&&t.endsWith('\"')){let s=t.slice(1,-1),n=new B().parseWordFromString(s,!0,!1);return L(e,n)}if(t.includes(\"$\")){let r=new B().parseWordFromString(t,!1,!1);return L(e,r)}return t}async function Fr(e,t){let s=\"both\",r=\"\",n=0;for(let i of t){if(i===\"-v\"){s=\"variable\";continue}if(i===\"-f\"){s=\"function\";continue}if(s===\"function\"){e.state.functions.delete(i);continue}if(s===\"variable\"){let c=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[(.+)\\]$/);if(c){let d=c[1],p=c[2];if(p===\"@\"||p===\"*\"){let b=Ae(e,d);for(let[m]of b)e.state.env.delete(`${d}_${m}`);e.state.env.delete(d);continue}let y=e.state.associativeArrays?.has(d);if(y){let b=await ci(e,p);e.state.env.delete(`${d}_${b}`);continue}let h=js(e,d),w=e.state.declaredVars?.has(d);if((e.state.env.has(d)||w)&&!h&&!y){r+=`bash: unset: ${d}: not an array variable\n`,n=1;continue}let g=await ai(e,p);if(g===null&&h){r+=`bash: unset: ${p}: not a valid identifier\n`,n=1;continue}if(g===null)continue;if(g<0){let b=Ae(e,d),m=b.length,v=e.state.currentLine;if(m===0){r+=`bash: line ${v}: unset: [${g}]: bad array subscript\n`,n=1;continue}let $=m+g;if($<0){r+=`bash: line ${v}: unset: [${g}]: bad array subscript\n`,n=1;continue}let S=b[$][0];e.state.env.delete(`${d}_${S}`);continue}e.state.env.delete(`${d}_${g}`);continue}if(!oi(i)){r+=`bash: unset: \\`${i}': not a valid identifier\n`,n=1;continue}let u=i;if(Ee(e,i)){let d=Ze(e,i);d&&d!==i&&(u=d)}if(et(e,u)){r+=`bash: unset: ${u}: cannot unset: readonly variable\n`,n=1;continue}let f=pt(e,u);if(f!==void 0&&f!==e.state.callDepth)li(e,u);else if(e.state.fullyUnsetLocals?.has(u))e.state.env.delete(u);else if(f!==void 0){let d=e.state.accessedTempEnvVars?.has(u),p=e.state.mutatedTempEnvVars?.has(u);if((d||p)&&e.state.localVarStack?.has(u)){let y=ps(e,u);y?y.value===void 0?e.state.env.delete(u):e.state.env.set(u,y.value):e.state.env.delete(u)}else e.state.env.delete(u)}else Lr(e,u)||e.state.env.delete(u);e.state.exportedVars?.delete(u);continue}let o=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[(.+)\\]$/);if(o){let c=o[1],u=o[2];if(u===\"@\"||u===\"*\"){let h=Ae(e,c);for(let[w]of h)e.state.env.delete(`${c}_${w}`);e.state.env.delete(c);continue}let f=e.state.associativeArrays?.has(c);if(f){let h=await ci(e,u);e.state.env.delete(`${c}_${h}`);continue}let d=js(e,c);if(e.state.env.has(c)&&!d&&!f){r+=`bash: unset: ${c}: not an array variable\n`,n=1;continue}let y=await ai(e,u);if(y===null&&d){r+=`bash: unset: ${u}: not a valid identifier\n`,n=1;continue}if(y===null)continue;if(y<0){let h=Ae(e,c),w=h.length,E=e.state.currentLine;if(w===0){r+=`bash: line ${E}: unset: [${y}]: bad array subscript\n`,n=1;continue}let g=w+y;if(g<0){r+=`bash: line ${E}: unset: [${y}]: bad array subscript\n`,n=1;continue}let b=h[g][0];e.state.env.delete(`${c}_${b}`);continue}e.state.env.delete(`${c}_${y}`);continue}if(!oi(i)){r+=`bash: unset: \\`${i}': not a valid identifier\n`,n=1;continue}let a=i;if(Ee(e,i)){let c=Ze(e,i);c&&c!==i&&(a=c)}if(et(e,a)){r+=`bash: unset: ${a}: cannot unset: readonly variable\n`,n=1;continue}let l=pt(e,a);if(l!==void 0&&l!==e.state.callDepth)li(e,a);else if(e.state.fullyUnsetLocals?.has(a))e.state.env.delete(a);else if(l!==void 0){let c=e.state.accessedTempEnvVars?.has(a),u=e.state.mutatedTempEnvVars?.has(a);if((c||u)&&e.state.localVarStack?.has(a)){let f=ps(e,a);f?f.value===void 0?e.state.env.delete(a):e.state.env.set(a,f.value):e.state.env.delete(a)}else e.state.env.delete(a)}else Lr(e,a)||e.state.env.delete(a);e.state.exportedVars?.delete(a),e.state.functions.delete(i)}return _(\"\",r,n)}var Mr=[\"extglob\",\"dotglob\",\"nullglob\",\"failglob\",\"globstar\",\"globskipdots\",\"nocaseglob\",\"nocasematch\",\"expand_aliases\",\"lastpipe\",\"xpg_echo\"],wa=[\"autocd\",\"cdable_vars\",\"cdspell\",\"checkhash\",\"checkjobs\",\"checkwinsize\",\"cmdhist\",\"compat31\",\"compat32\",\"compat40\",\"compat41\",\"compat42\",\"compat43\",\"compat44\",\"complete_fullquote\",\"direxpand\",\"dirspell\",\"execfail\",\"extdebug\",\"extquote\",\"force_fignore\",\"globasciiranges\",\"gnu_errfmt\",\"histappend\",\"histreedit\",\"histverify\",\"hostcomplete\",\"huponexit\",\"inherit_errexit\",\"interactive_comments\",\"lithist\",\"localvar_inherit\",\"localvar_unset\",\"login_shell\",\"mailwarn\",\"no_empty_cmd_completion\",\"progcomp\",\"progcomp_alias\",\"promptvars\",\"restricted_shell\",\"shift_verbose\",\"sourcepath\"];function Es(e){return Mr.includes(e)}function va(e){return wa.includes(e)}function ui(e,t){let s=!1,r=!1,n=!1,i=!1,o=!1,a=[],l=0;for(;l<t.length;){let d=t[l];if(d===\"--\"){l++;break}if(d.startsWith(\"-\")&&d.length>1){for(let p=1;p<d.length;p++){let y=d[p];switch(y){case\"s\":s=!0;break;case\"u\":r=!0;break;case\"p\":n=!0;break;case\"q\":i=!0;break;case\"o\":o=!0;break;default:return{exitCode:2,stdout:\"\",stderr:`shopt: -${y}: invalid option\n`}}}l++}else break}for(;l<t.length;)a.push(t[l]),l++;if(o)return ba(e,a,s,r,n,i);if(s&&r)return{exitCode:1,stdout:\"\",stderr:`shopt: cannot set and unset shell options simultaneously\n`};if(a.length===0){if(s||r){let p=[];for(let y of Mr){let h=e.state.shoptOptions[y];s&&h?p.push(n?`shopt -s ${y}`:`${y}\t\ton`):r&&!h&&p.push(n?`shopt -u ${y}`:`${y}\t\toff`)}return{exitCode:0,stdout:p.length>0?`${p.join(`\n`)}\n`:\"\",stderr:\"\"}}let d=[];for(let p of Mr){let y=e.state.shoptOptions[p];d.push(n?`shopt ${y?\"-s\":\"-u\"} ${p}`:`${p}\t\t${y?\"on\":\"off\"}`)}return{exitCode:0,stdout:`${d.join(`\n`)}\n`,stderr:\"\"}}let c=!1,u=\"\",f=[];for(let d of a){if(!Es(d)&&!va(d)){u+=`shopt: ${d}: invalid shell option name\n`,c=!0;continue}if(s)Es(d)&&(e.state.shoptOptions[d]=!0,Gs(e));else if(r)Es(d)&&(e.state.shoptOptions[d]=!1,Gs(e));else if(Es(d)){let p=e.state.shoptOptions[d];i?p||(c=!0):n?(f.push(`shopt ${p?\"-s\":\"-u\"} ${d}`),p||(c=!0)):(f.push(`${d}\t\t${p?\"on\":\"off\"}`),p||(c=!0))}else i?c=!0:n?(f.push(`shopt -u ${d}`),c=!0):(f.push(`${d}\t\toff`),c=!0)}return{exitCode:c?1:0,stdout:f.length>0?`${f.join(`\n`)}\n`:\"\",stderr:u}}function ba(e,t,s,r,n,i){let o=new Map([[\"errexit\",\"errexit\"],[\"pipefail\",\"pipefail\"],[\"nounset\",\"nounset\"],[\"xtrace\",\"xtrace\"],[\"verbose\",\"verbose\"],[\"posix\",\"posix\"],[\"allexport\",\"allexport\"],[\"noclobber\",\"noclobber\"],[\"noglob\",\"noglob\"],[\"noexec\",\"noexec\"],[\"vi\",\"vi\"],[\"emacs\",\"emacs\"]]),a=[\"braceexpand\",\"errtrace\",\"functrace\",\"hashall\",\"histexpand\",\"history\",\"ignoreeof\",\"interactive-comments\",\"keyword\",\"monitor\",\"nolog\",\"notify\",\"onecmd\",\"physical\",\"privileged\"],l=[...o.keys(),...a].sort();if(t.length===0){let d=[];for(let p of l){let y=a.includes(p),h=o.get(p),w=y||!h?!1:e.state.options[h];s&&!w||r&&w||d.push(n?`set ${w?\"-o\":\"+o\"} ${p}`:`${p}\t\t${w?\"on\":\"off\"}`)}return{exitCode:0,stdout:d.length>0?`${d.join(`\n`)}\n`:\"\",stderr:\"\"}}let c=!1,u=\"\",f=[];for(let d of t){let p=o.has(d),y=a.includes(d);if(!p&&!y){u+=`shopt: ${d}: invalid option name\n`,c=!0;continue}if(y){s||r||(i?c=!0:n?(f.push(`set +o ${d}`),c=!0):(f.push(`${d}\t\toff`),c=!0));continue}let h=o.get(d);if(h)if(s)h===\"vi\"?e.state.options.emacs=!1:h===\"emacs\"&&(e.state.options.vi=!1),e.state.options[h]=!0,dt(e);else if(r)e.state.options[h]=!1,dt(e);else{let w=e.state.options[h];i?w||(c=!0):n?(f.push(`set ${w?\"-o\":\"+o\"} ${d}`),w||(c=!0)):(f.push(`${d}\t\t${w?\"on\":\"off\"}`),w||(c=!0))}}return{exitCode:c?1:0,stdout:f.length>0?`${f.join(`\n`)}\n`:\"\",stderr:u}}async function fi(e,t,s){if(t.includes(\"/\")){let o=e.fs.resolvePath(e.state.cwd,t);if(!await e.fs.exists(o))return{error:\"not_found\",path:o};let a=o.split(\"/\").pop()||t,l=e.commands.get(a);try{let c=await e.fs.stat(o);return c.isDirectory?{error:\"permission_denied\",path:o}:l?{cmd:l,path:o}:(c.mode&73)!==0?{script:!0,path:o}:{error:\"permission_denied\",path:o}}catch{return{error:\"not_found\",path:o}}}if(!s&&e.state.hashTable){let o=e.state.hashTable.get(t);if(o)if(await e.fs.exists(o)){let a=e.commands.get(t);if(a)return{cmd:a,path:o};try{let l=await e.fs.stat(o);if(!l.isDirectory&&(l.mode&73)!==0)return{script:!0,path:o}}catch{}}else e.state.hashTable.delete(t)}let n=(s??e.state.env.get(\"PATH\")??\"/usr/bin:/bin\").split(\":\");for(let o of n){if(!o)continue;let l=`${o.startsWith(\"/\")?o:e.fs.resolvePath(e.state.cwd,o)}/${t}`;if(await e.fs.exists(l))try{let c=await e.fs.stat(l);if(c.isDirectory)continue;let u=(c.mode&73)!==0,f=e.commands.get(t),d=o===\"/bin\"||o===\"/usr/bin\";if(f&&d)return{cmd:f,path:l};if(u){if(f&&!d)return{script:!0,path:l};if(!f)return{script:!0,path:l}}}catch{}}if(!await e.fs.exists(\"/usr/bin\")){let o=e.commands.get(t);if(o)return{cmd:o,path:`/usr/bin/${t}`}}return null}async function $s(e,t){let s=[];if(t.includes(\"/\")){let i=e.fs.resolvePath(e.state.cwd,t);if(await e.fs.exists(i))try{let o=await e.fs.stat(i);o.isDirectory||(o.mode&73)!==0&&s.push(t)}catch{}return s}let n=(e.state.env.get(\"PATH\")||\"/usr/bin:/bin\").split(\":\");for(let i of n){if(!i)continue;let a=`${i.startsWith(\"/\")?i:e.fs.resolvePath(e.state.cwd,i)}/${t}`;if(await e.fs.exists(a)){try{if((await e.fs.stat(a)).isDirectory)continue}catch{continue}s.push(i.startsWith(\"/\")?a:`${i}/${t}`)}}return s}function Ea(e){return e!==null&&typeof e==\"object\"&&\"then\"in e&&typeof e.then==\"function\"}function G(e,t,s,r){return((...n)=>{_t(t,s,`${r} call`);let i=e(...n);return Ea(i)?i.then(o=>(_t(t,s,`${r} post-await`),o),o=>{throw _t(t,s,`${r} post-await`),o}):(_t(t,s,`${r} return`),i)})}function $a(e,t,s){let r={readFile:G(e.readFile.bind(e),t,s,\"fs.readFile\"),...typeof e.readFileBytes==\"function\"?{readFileBytes:G(e.readFileBytes.bind(e),t,s,\"fs.readFileBytes\")}:Object.create(null),readFileBuffer:G(e.readFileBuffer.bind(e),t,s,\"fs.readFileBuffer\"),writeFile:G(e.writeFile.bind(e),t,s,\"fs.writeFile\"),appendFile:G(e.appendFile.bind(e),t,s,\"fs.appendFile\"),exists:G(e.exists.bind(e),t,s,\"fs.exists\"),stat:G(e.stat.bind(e),t,s,\"fs.stat\"),mkdir:G(e.mkdir.bind(e),t,s,\"fs.mkdir\"),readdir:G(e.readdir.bind(e),t,s,\"fs.readdir\"),rm:G(e.rm.bind(e),t,s,\"fs.rm\"),cp:G(e.cp.bind(e),t,s,\"fs.cp\"),mv:G(e.mv.bind(e),t,s,\"fs.mv\"),resolvePath:G(e.resolvePath.bind(e),t,s,\"fs.resolvePath\"),getAllPaths:G(e.getAllPaths.bind(e),t,s,\"fs.getAllPaths\"),chmod:G(e.chmod.bind(e),t,s,\"fs.chmod\"),symlink:G(e.symlink.bind(e),t,s,\"fs.symlink\"),link:G(e.link.bind(e),t,s,\"fs.link\"),readlink:G(e.readlink.bind(e),t,s,\"fs.readlink\"),lstat:G(e.lstat.bind(e),t,s,\"fs.lstat\"),realpath:G(e.realpath.bind(e),t,s,\"fs.realpath\"),utimes:G(e.utimes.bind(e),t,s,\"fs.utimes\")};return e.readdirWithFileTypes&&(r.readdirWithFileTypes=G(e.readdirWithFileTypes.bind(e),t,s,\"fs.readdirWithFileTypes\")),r}function di(e,t){if(!e.requireDefenseContext)return e;let s=`command:${t}`,r={...e,fs:$a(e.fs,e.requireDefenseContext,s)};return e.exec&&(r.exec=G(e.exec,e.requireDefenseContext,s,\"exec\")),e.fetch&&(r.fetch=G(e.fetch,e.requireDefenseContext,s,\"fetch\")),e.sleep&&(r.sleep=G(e.sleep,e.requireDefenseContext,s,\"sleep\")),e.getRegisteredCommands&&(r.getRegisteredCommands=G(e.getRegisteredCommands,e.requireDefenseContext,s,\"getRegisteredCommands\")),r}async function yi(e,t,s,r){let n=!1,i=!1,o=!1,a=!1,l=!1,c=[];for(let h of t)if(h.startsWith(\"-\")&&h.length>1)for(let w of h.slice(1))w===\"t\"?n=!0:w===\"p\"?i=!0:w===\"P\"?o=!0:w===\"a\"?a=!0:w===\"f\"&&(l=!0);else c.push(h);let u=\"\",f=\"\",d=0,p=!1,y=!1;for(let h of c){let w=!1;if(o){if(a){let $=await r(h);if($.length>0){for(let S of $)u+=`${S}\n`;p=!0,w=!0}}else{let $=await s(h);$&&(u+=`${$}\n`,p=!0,w=!0)}w||(y=!0);continue}let E=!l&&e.state.functions.has(h);if(a&&E){if(!i)if(n)u+=`function\n`;else{let $=e.state.functions.get(h),S=$?hi(h,$):`${h} is a function\n`;u+=S}w=!0}let g=e.state.env.get(`BASH_ALIAS_${h}`);if(g!==void 0&&(a||!w)&&(i||(n?u+=`alias\n`:u+=`${h} is aliased to \\`${g}'\n`),w=!0,!a)||sr.has(h)&&(a||!w)&&(i||(n?u+=`keyword\n`:u+=`${h} is a shell keyword\n`),w=!0,!a))continue;if(!a&&E&&!w){if(!i)if(n)u+=`function\n`;else{let $=e.state.functions.get(h),S=$?hi(h,$):`${h} is a function\n`;u+=S}w=!0;continue}if(!(mt.has(h)&&(a||!w)&&(i||(n?u+=`builtin\n`:u+=`${h} is a shell builtin\n`),w=!0,!a))){if(a){let $=await r(h);for(let S of $)i?u+=`${S}\n`:n?u+=`file\n`:u+=`${h} is ${S}\n`,p=!0,w=!0}else if(!w){let $=await s(h);$&&(i?u+=`${$}\n`:n?u+=`file\n`:u+=`${h} is ${$}\n`,p=!0,w=!0)}if(!w&&(y=!0,!n&&!i)){let $=!0;if(h.includes(\"/\")){let S=e.fs.resolvePath(e.state.cwd,h);await e.fs.exists(S)&&($=!1)}$&&(f+=`bash: type: ${h}: not found\n`)}}}return i?d=y&&!p?1:0:d=y?1:0,_(u,f,d)}function hi(e,t){let s;return t.body.type===\"Group\"?s=t.body.body.map(n=>Dt(n)).join(\"; \"):s=Dt(t.body),`${e} is a function\n${e} () \n{ \n ${s}\n}\n`}function Dt(e){if(Array.isArray(e))return e.map(t=>Dt(t)).join(\"; \");if(e.type===\"Statement\"){let t=[];for(let s=0;s<e.pipelines.length;s++){let r=e.pipelines[s];t.push(Sa(r)),e.operators[s]&&t.push(e.operators[s])}return t.join(\" \")}if(e.type===\"SimpleCommand\"){let t=e,s=[];t.name&&s.push(pi(t.name));for(let r of t.args)s.push(pi(r));return s.join(\" \")}return e.type===\"Group\"?`{ ${e.body.map(r=>Dt(r)).join(\"; \")}; }`:\"...\"}function Sa(e){let t=e.commands.map(s=>Dt(s));return(e.negated?\"! \":\"\")+t.join(\" | \")}function pi(e){let t=\"\";for(let s of e.parts)s.type===\"Literal\"?t+=s.value:s.type===\"DoubleQuoted\"?t+=`\"${s.parts.map(r=>mi(r)).join(\"\")}\"`:s.type===\"SingleQuoted\"?t+=`'${s.value}'`:t+=mi(s);return t}function mi(e){let t=e;return t.type===\"Literal\"?t.value??\"\":t.type===\"Variable\"?`$${t.name}`:\"\"}async function gi(e,t,s,r){let n=\"\",i=\"\",o=0;for(let a of t){if(!a){o=1;continue}let l=e.state.env.get(`BASH_ALIAS_${a}`);if(l!==void 0)r?n+=`${a} is an alias for \"${l}\"\n`:n+=`alias ${a}='${l}'\n`;else if(sr.has(a))r?n+=`${a} is a shell keyword\n`:n+=`${a}\n`;else if(mt.has(a))r?n+=`${a} is a shell builtin\n`:n+=`${a}\n`;else if(e.state.functions.has(a))r?n+=`${a} is a function\n`:n+=`${a}\n`;else if(a.includes(\"/\")){let c=e.fs.resolvePath(e.state.cwd,a),u=!1;if(await e.fs.exists(c))try{let f=await e.fs.stat(c);f.isDirectory||(f.mode&73)!==0&&(r?n+=`${a} is ${a}\n`:n+=`${a}\n`,u=!0)}catch{}u||(r&&(i+=`${a}: not found\n`),o=1)}else if(e.commands.has(a)){let u=(e.state.env.get(\"PATH\")??\"/usr/bin:/bin\").split(\":\"),f=null;for(let d of u){if(!d)continue;let p=`${d}/${a}`;try{let y=await e.fs.stat(p);if(!y.isDirectory&&(y.mode&73)!==0){f=p;break}}catch{}}f||(f=`/usr/bin/${a}`),r?n+=`${a} is ${f}\n`:n+=`${f}\n`}else r&&(i+=`${a}: not found\n`),o=1}return _(n,i,o)}async function wi(e,t){if(t.includes(\"/\")){let n=e.fs.resolvePath(e.state.cwd,t);if(await e.fs.exists(n)){try{let i=await e.fs.stat(n);if(i.isDirectory||!((i.mode&73)!==0))return null}catch{return null}return t}return null}let r=(e.state.env.get(\"PATH\")??\"/usr/bin:/bin\").split(\":\");for(let n of r){if(!n)continue;let o=`${n.startsWith(\"/\")?n:e.fs.resolvePath(e.state.cwd,n)}/${t}`;if(await e.fs.exists(o)){try{if((await e.fs.stat(o)).isDirectory)continue}catch{continue}return`${n}/${t}`}}if(e.commands.has(t)){for(let n of r)if(n===\"/usr/bin\"||n===\"/bin\")return`${n}/${t}`;return`/usr/bin/${t}`}return null}async function vi(e,t,s,r,n,i,o,a){let{ctx:l,runCommand:c}=e;if(l.coverage&&mt.has(t)&&l.coverage.hit(`bash:builtin:${t}`),t===\"export\")return Pr(l,s);if(t===\"unset\")return Fr(l,s);if(t===\"exit\")return Sr(l,s);if(t===\"local\")return Cr(l,s);if(t===\"set\")return Dr(l,s);if(t===\"break\")return Xs(l,s);if(t===\"continue\")return cr(l,s);if(t===\"return\")return xr(l,s);if(t===\"eval\"&&l.state.options.posix)return ws(l,s,n);if(t===\"shift\")return Rr(l,s);if(t===\"getopts\")return vs(l,s);if(t===\"compgen\")return ir(l,s);if(t===\"complete\")return ar(l,s);if(t===\"compopt\")return lr(l,s);if(t===\"pushd\")return await br(l,s);if(t===\"popd\")return Er(l,s);if(t===\"dirs\")return $r(l,s);if(t===\"source\"||t===\".\")return Ir(l,s);if(t===\"read\")return Or(l,s,n,a);if(t===\"mapfile\"||t===\"readarray\")return Nr(l,s,n);if(t===\"declare\"||t===\"typeset\")return gr(l,s);if(t===\"readonly\")return wr(l,s);if(!i){let u=l.state.functions.get(t);if(u)return ys(l,u,s,n)}if(t===\"eval\")return ws(l,s,n);if(t===\"cd\")return await Ys(l,s);if(t===\":\"||t===\"true\")return W;if(t===\"false\")return Q(!1);if(t===\"let\")return _r(l,s);if(t===\"command\")return Pa(e,s,n);if(t===\"builtin\")return Aa(e,s,n);if(t===\"shopt\")return ui(l,s);if(t===\"exec\"){if(s.length===0)return W;let[u,...f]=s;return c(u,f,[],n,!1,!1,-1)}if(t===\"wait\")return W;if(t===\"type\")return await yi(l,s,u=>wi(l,u),u=>$s(l,u));if(t===\"hash\")return Ar(l,s);if(t===\"help\")return kr(l,s);if(t===\"[\"||t===\"test\"){let u=s;if(t===\"[\"){if(s[s.length-1]!==\"]\")return A(\"[: missing `]'\\n\",2);u=s.slice(0,-1)}return Ot(l,u)}return null}async function Pa(e,t,s){let{ctx:r,runCommand:n}=e;if(t.length===0)return W;let i=!1,o=!1,a=!1,l=t;for(;l.length>0&&l[0].startsWith(\"-\");){let f=l[0];if(f===\"--\"){l=l.slice(1);break}for(let d of f.slice(1))d===\"p\"?i=!0:d===\"V\"?o=!0:d===\"v\"&&(a=!0);l=l.slice(1)}if(l.length===0)return W;if(a||o)return await gi(r,l,a,o);let[c,...u]=l;return n(c,u,[],s,!0,i,-1)}async function Aa(e,t,s){let{runCommand:r}=e;if(t.length===0)return W;let n=t;if(n[0]===\"--\"&&(n=n.slice(1),n.length===0))return W;let i=n[0];if(!mt.has(i))return A(`bash: builtin: ${i}: not a shell builtin\n`);let[,...o]=n;return r(i,o,[],s,!0,!1,-1)}async function bi(e,t,s,r,n){let{ctx:i,buildExportedEnv:o,executeUserScript:a}=e,c=await fi(i,t,n?\"/usr/bin:/bin\":void 0);if(!c)return _n(t)?A(`bash: ${t}: command not available in browser environments. Exclude '${t}' from your commands or use the Node.js bundle.\n`,127):A(`bash: ${t}: command not found\n`,127);if(\"error\"in c)return c.error===\"permission_denied\"?A(`bash: ${t}: Permission denied\n`,126):A(`bash: ${t}: No such file or directory\n`,127);if(\"script\"in c)return t.includes(\"/\")||(i.state.hashTable||(i.state.hashTable=new Map),i.state.hashTable.set(t,c.path)),await a(c.path,s,r);let{cmd:u,path:f}=c;t.includes(\"/\")||(i.state.hashTable||(i.state.hashTable=new Map),i.state.hashTable.set(t,f));let d=r||i.state.groupStdin||\"\",p=o(),y={fs:i.fs,cwd:i.state.cwd,env:i.state.env,exportedEnv:p,stdin:d,limits:i.limits,exec:i.execFn,fetch:i.fetch,getRegisteredCommands:()=>Array.from(i.commands.keys()),sleep:i.sleep,trace:i.trace,fileDescriptors:i.state.fileDescriptors,xpgEcho:i.state.shoptOptions.xpg_echo,coverage:i.coverage,signal:i.state.signal,requireDefenseContext:i.requireDefenseContext,jsBootstrapCode:i.jsBootstrapCode,invokeTool:i.invokeTool},h=di(y,t);try{let w=()=>Xr(i.requireDefenseContext,\"command\",`${t} execution`,()=>u.execute(s,h));return u.trusted?await me.runTrustedAsync(()=>w()):await w()}catch(w){if(w instanceof J||w instanceof Ve)throw w;return A(`${t}: ${Le(Ie(w))}\n`)}}async function Wr(e,t){let s=e.state.inCondition;e.state.inCondition=!0;let r=\"\",n=\"\",i=0;try{for(let o of t){let a=await e.executeStatement(o);r+=a.stdout,n+=a.stderr,i=a.exitCode}}finally{e.state.inCondition=s}return{stdout:r,stderr:n,exitCode:i}}function Rt(e,t,s,r){if(e instanceof ye)return t+=e.stdout,s+=e.stderr,e.levels>1&&r>1?(e.levels--,e.stdout=t,e.stderr=s,{action:\"rethrow\",stdout:t,stderr:s,error:e}):{action:\"break\",stdout:t,stderr:s};if(e instanceof ge)return t+=e.stdout,s+=e.stderr,e.levels>1&&r>1?(e.levels--,e.stdout=t,e.stderr=s,{action:\"rethrow\",stdout:t,stderr:s,error:e}):{action:\"continue\",stdout:t,stderr:s};if(e instanceof ue||e instanceof we||e instanceof j||e instanceof J)return e.prependOutput(t,s),{action:\"rethrow\",stdout:t,stderr:s,error:e};let n=Ie(e);return{action:\"error\",stdout:t,stderr:`${s}${n}\n`,exitCode:1}}async function Ss(e,t,s=\"\",r=\"\"){let n=s,i=r,o=0;try{for(let a of t){let l=await e.executeStatement(a);n+=l.stdout,i+=l.stderr,o=l.exitCode}}catch(a){if(Zt(a)||a instanceof we||a instanceof j||a instanceof J||a instanceof je)throw a.prependOutput(n,i),a;return{stdout:n,stderr:`${i}${Ie(a)}\n`,exitCode:1}}return{stdout:n,stderr:i,exitCode:o}}async function Ei(e,t){let s=\"\",r=\"\";for(let n of t.clauses){let i=await Wr(e,n.condition);if(s+=i.stdout,r+=i.stderr,i.exitCode===0)return Ss(e,n.body,s,r)}return t.elseBody?Ss(e,t.elseBody,s,r):_(s,r,0)}async function $i(e,t){let s=await Re(e,t.redirections);if(s)return s;let r=\"\",n=\"\",i=0,o=0;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t.variable))return A(`bash: \\`${t.variable}': not a valid identifier\n`);let a=[];if(t.words===null)a=(e.state.env.get(\"@\")||\"\").split(\" \").filter(Boolean);else if(t.words.length===0)a=[];else try{for(let c of t.words){let u=await xe(e,c);a.push(...u.values)}}catch(c){if(c instanceof Ut)return{stdout:\"\",stderr:c.stderr,exitCode:1};throw c}e.state.loopDepth++;try{for(let c of a){o++,o>e.limits.maxLoopIterations&&Te(`for loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,\"iterations\",r,n),e.state.env.set(t.variable,c);try{for(let u of t.body){let f=await e.executeStatement(u);r+=f.stdout,n+=f.stderr,i=f.exitCode}}catch(u){let f=Rt(u,r,n,e.state.loopDepth);if(r=f.stdout,n=f.stderr,f.action===\"break\")break;if(f.action===\"continue\")continue;if(f.action===\"error\"){let d=_(r,n,f.exitCode??1);return K(e,d,t.redirections)}throw f.error}}}finally{e.state.loopDepth--}let l=_(r,n,i);return K(e,l,t.redirections)}async function Si(e,t){let s=await Re(e,t.redirections);if(s)return s;let r=t.line;r!==void 0&&(e.state.currentLine=r);let n=\"\",i=\"\",o=0,a=0;t.init&&await H(e,t.init.expression),e.state.loopDepth++;try{for(;a++,a>e.limits.maxLoopIterations&&Te(`for loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,\"iterations\",n,i),!(t.condition&&(r!==void 0&&(e.state.currentLine=r),await H(e,t.condition.expression)===0));){try{for(let c of t.body){let u=await e.executeStatement(c);n+=u.stdout,i+=u.stderr,o=u.exitCode}}catch(c){let u=Rt(c,n,i,e.state.loopDepth);if(n=u.stdout,i=u.stderr,u.action===\"break\")break;if(u.action===\"continue\"){t.update&&await H(e,t.update.expression);continue}if(u.action===\"error\"){let f=_(n,i,u.exitCode??1);return K(e,f,t.redirections)}throw u.error}t.update&&await H(e,t.update.expression)}}finally{e.state.loopDepth--}let l=_(n,i,o);return K(e,l,t.redirections)}async function Pi(e,t,s=\"\"){let r=\"\",n=\"\",i=0,o=0,a=s;for(let c of t.redirections)if((c.operator===\"<<\"||c.operator===\"<<-\")&&c.target.type===\"HereDoc\"){let u=c.target,f=await L(e,u.content);u.stripTabs&&(f=f.split(`\n`).map(d=>d.replace(/^\\t+/,\"\")).join(`\n`)),a=f}else if(c.operator===\"<<<\"&&c.target.type===\"Word\")a=`${await L(e,c.target)}\n`;else if(c.operator===\"<\"&&c.target.type===\"Word\")try{let u=await L(e,c.target),f=e.fs.resolvePath(e.state.cwd,u);a=await e.fs.readFile(f)}catch{let u=await L(e,c.target);return A(`bash: ${u}: No such file or directory\n`)}let l=e.state.groupStdin;a&&(e.state.groupStdin=a),e.state.loopDepth++;try{for(;;){o++,o>e.limits.maxLoopIterations&&Te(`while loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,\"iterations\",r,n);let c=0,u=!1,f=!1,d=e.state.inCondition;e.state.inCondition=!0;try{for(let p of t.condition){let y=await e.executeStatement(p);r+=y.stdout,n+=y.stderr,c=y.exitCode}}catch(p){if(p instanceof ye){if(r+=p.stdout,n+=p.stderr,p.levels>1&&e.state.loopDepth>1)throw p.levels--,p.stdout=r,p.stderr=n,e.state.inCondition=d,p;u=!0}else if(p instanceof ge){if(r+=p.stdout,n+=p.stderr,p.levels>1&&e.state.loopDepth>1)throw p.levels--,p.stdout=r,p.stderr=n,e.state.inCondition=d,p;f=!0}else throw e.state.inCondition=d,p}finally{e.state.inCondition=d}if(u)break;if(!f){if(c!==0)break;try{for(let p of t.body){let y=await e.executeStatement(p);r+=y.stdout,n+=y.stderr,i=y.exitCode}}catch(p){let y=Rt(p,r,n,e.state.loopDepth);if(r=y.stdout,n=y.stderr,y.action===\"break\")break;if(y.action===\"continue\")continue;if(y.action===\"error\")return _(r,n,y.exitCode??1);throw y.error}}}}finally{e.state.loopDepth--,e.state.groupStdin=l}return _(r,n,i)}async function Ai(e,t){let s=\"\",r=\"\",n=0,i=0;e.state.loopDepth++;try{for(;;){i++,i>e.limits.maxLoopIterations&&Te(`until loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,\"iterations\",s,r);let o=await Wr(e,t.condition);if(s+=o.stdout,r+=o.stderr,o.exitCode===0)break;try{for(let a of t.body){let l=await e.executeStatement(a);s+=l.stdout,r+=l.stderr,n=l.exitCode}}catch(a){let l=Rt(a,s,r,e.state.loopDepth);if(s=l.stdout,r=l.stderr,l.action===\"break\")break;if(l.action===\"continue\")continue;if(l.action===\"error\")return _(s,r,l.exitCode??1);throw l.error}}}finally{e.state.loopDepth--}return _(s,r,n)}async function ki(e,t){let s=await Re(e,t.redirections);if(s)return s;let r=\"\",n=\"\",i=0,o=await L(e,t.word),a=!1;for(let c=0;c<t.items.length;c++){let u=t.items[c],f=a;if(!a)for(let d of u.patterns){let p=await L(e,d);ln(d)&&(p=on(p));let y=e.state.shoptOptions.nocasematch,h=e.state.shoptOptions.extglob;if(ht(o,p,y,h)){f=!0;break}}if(f){let d=await Ss(e,u.body,r,n);if(r=d.stdout,n=d.stderr,i=d.exitCode,u.terminator===\";;\")break;u.terminator===\";&\"?a=!0:a=!1}else a=!1}let l=_(r,n,i);return K(e,l,t.redirections)}function zr(e,t){if(e.parts.length!==1)return!1;let s=e.parts[0];return s.type!==\"Literal\"?!1:t.includes(s.value)}function _i(e){if(!e.startsWith(\"__rw__:\"))return null;let t=e.slice(7),s=t.indexOf(\":\");if(s===-1)return null;let r=Number.parseInt(t.slice(0,s),10);if(Number.isNaN(r)||r<0)return null;let n=s+1,i=t.slice(n,n+r),o=n+r+1,a=t.slice(o),l=a.indexOf(\":\");if(l===-1)return null;let c=Number.parseInt(a.slice(0,l),10);if(Number.isNaN(c)||c<0)return null;let u=a.slice(l+1);return{path:i,position:c,content:u}}var Ci=\"+ \";async function Ni(e){let t=e.state.env.get(\"PS4\");if(t===void 0)return Ci;if(t===\"\")return\"\";try{let r=new B().parseWordFromString(t,!1,!1);return await L(e,r)}catch{return e.state.expansionStderr=`${e.state.expansionStderr||\"\"}bash: ${t}: bad substitution\n`,t||Ci}}function ka(e){return e.map(t=>_a(t)).join(\" \")}function _a(e){if(e===\"\")return\"''\";if(!/[\\s'\"\\\\$`!*?[\\]{}|&;<>()~#\\n\\t]/.test(e))return e;let s=/[\\x00-\\x1f\\x7f]/.test(e),r=e.includes(`\n`),n=e.includes(\"\t\"),i=e.includes(\"\\\\\"),o=e.includes(\"'\");if(s||r||n||i){let l=\"\";for(let c of e){let u=c.charCodeAt(0);c===`\n`?l+=\"\\\\n\":c===\"\t\"?l+=\"\\\\t\":c===\"\\\\\"?l+=\"\\\\\\\\\":c===\"'\"?l+=\"'\":c==='\"'?l+='\"':u<32||u===127?u<256?l+=`\\\\x${u.toString(16).padStart(2,\"0\")}`:l+=`\\\\u${u.toString(16).padStart(4,\"0\")}`:l+=c}return`$'${l}'`}return o?`\"${e.replace(/([\\\\$`\"])/g,\"\\\\$1\")}\"`:`'${e}'`}async function Oi(e,t,s){if(!e.state.options.xtrace)return\"\";let r=await Ni(e),n=[t,...s],i=ka(n);return`${r}${i}\n`}async function xi(e,t,s){return e.state.options.xtrace?`${await Ni(e)}${t}=${s}\n`:\"\"}async function Ti(e,t,s){let r=t.timed?Fs():0,n=\"\",i=W,o=0,a=[],l=\"\",c=t.commands.length>1,u=e.state.lastArg;for(let d=0;d<t.commands.length;d++){let p=t.commands[d],y=d===t.commands.length-1,h=d===0;c&&(e.state.lastArg=\"\",h||(e.state.groupStdin=void 0));let E=c&&(!y||!e.state.shoptOptions.lastpipe)?new Map(e.state.env):null,g;try{g=await s(p,n)}catch(b){if(b instanceof jt)g={stdout:b.stdout,stderr:b.stderr,exitCode:1};else if(b instanceof j&&t.commands.length>1)g={stdout:b.stdout,stderr:b.stderr,exitCode:b.exitCode};else if(b instanceof we&&t.commands.length>1)g={stdout:b.stdout,stderr:b.stderr,exitCode:b.exitCode};else throw E&&(e.state.env=E),b}E&&(e.state.env=E),a.push(g.exitCode),g.exitCode!==0&&(o=g.exitCode),y?i=g:(t.pipeStderr?.[d]??!1?n=Be(g.stderr)+Bt(g):(n=Bt(g),l+=g.stderr),i={stdout:\"\",stderr:\"\",exitCode:g.exitCode})}if(l&&(i={...i,stderr:l+i.stderr}),t.commands.length>1||t.commands.length===1&&t.commands[0].type===\"SimpleCommand\"){for(let d of e.state.env.keys())d.startsWith(\"PIPESTATUS_\")&&e.state.env.delete(d);for(let d=0;d<a.length;d++)e.state.env.set(`PIPESTATUS_${d}`,String(a[d]));e.state.env.set(\"PIPESTATUS__length\",String(a.length))}if(e.state.options.pipefail&&o!==0&&(i={...i,exitCode:o}),t.negated&&(i={...i,exitCode:i.exitCode===0?1:0}),t.timed){let p=(Fs()-r)/1e3,y=Math.floor(p/60),h=p%60,w;t.timePosix?w=`real ${p.toFixed(2)}\nuser 0.00\nsys 0.00\n`:w=`\nreal\t${`${y}m${h.toFixed(3)}s`}\nuser\t0m0.000s\nsys\t0m0.000s\n`,i={...i,stderr:i.stderr+w}}return c&&!e.state.shoptOptions.lastpipe&&(e.state.lastArg=u),i}async function Di(e,t){let s=new Map,r=\"\";for(let n of t.assignments){let i=n.name;if(n.array){let u=await Ca(e,t,i,n.array,n.append,s);if(u.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:s,error:u.error};if(r+=u.xtraceOutput,u.continueToNext)continue}let o=n.value?await L(e,n.value):\"\";if(i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[\\]$/))return{continueToNext:!1,xtraceOutput:r,tempAssignments:s,error:_(\"\",`bash: ${i}: bad array subscript\n`,1)};let l=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[(.+)\\]$/);if(l){let u=await Da(e,t,l[1],l[2],o,n.append,s);if(u.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:s,error:u.error};if(u.continueToNext)continue}let c=await Ia(e,t,i,o,n.append,s);if(c.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:s,error:c.error};r+=c.xtraceOutput,c.continueToNext}return{continueToNext:!1,xtraceOutput:r,tempAssignments:s}}async function Ca(e,t,s,r,n,i){let o=\"\";if(/\\[.+\\]$/.test(s))return{continueToNext:!1,xtraceOutput:\"\",error:_(\"\",`bash: ${s}: cannot assign list to array member\n`,1)};if(Ee(e,s)){let u=rn(e,s);if(u===void 0||u===\"\")throw new j(1,\"\",\"\");let f=Ze(e,s);if(f&&/^[a-zA-Z_][a-zA-Z0-9_]*\\[@\\]$/.test(f))return{continueToNext:!1,xtraceOutput:\"\",error:_(\"\",`bash: ${s}: cannot assign list to array member\n`,1)}}if(et(e,s)){if(t.name)return o+=`bash: ${s}: readonly variable\n`,{continueToNext:!0,xtraceOutput:o};let u=se(e,s);if(u)return{continueToNext:!1,xtraceOutput:\"\",error:u}}let a=e.state.associativeArrays?.has(s),l=Na(r),c=()=>{let u=`${s}_`;for(let f of e.state.env.keys())f.startsWith(u)&&!f.includes(\"__\")&&e.state.env.delete(f);e.state.env.delete(s)};if(a&&l?await Oa(e,t,s,r,n,c,u=>{o+=u}):l?await xa(e,s,r,n,c):await Ta(e,s,r,n,c),t.name){i.set(s,e.state.env.get(s));let f=`(${r.map(d=>Gt(d)).join(\" \")})`;e.state.env.set(s,f)}return{continueToNext:!0,xtraceOutput:o}}function Na(e){return e.some(t=>{if(t.parts.length>=2){let s=t.parts[0],r=t.parts[1];if(s.type!==\"Glob\"||!s.pattern.startsWith(\"[\"))return!1;if(s.pattern===\"[\"&&(r.type===\"DoubleQuoted\"||r.type===\"SingleQuoted\")){if(t.parts.length<3)return!1;let n=t.parts[2];return n.type!==\"Literal\"?!1:n.value.startsWith(\"]=\")||n.value.startsWith(\"]+=\")}return r.type!==\"Literal\"?!1:r.value.startsWith(\"]\")?r.value.startsWith(\"]=\")||r.value.startsWith(\"]+=\"):s.pattern.endsWith(\"]\")?r.value.startsWith(\"=\")||r.value.startsWith(\"+=\"):!1}return!1})}async function Oa(e,t,s,r,n,i,o){let a=[];for(let l of r){let c=Ws(l);if(c){let{key:u,valueParts:f,append:d}=c,p;f.length>0?p=await L(e,{type:\"Word\",parts:f}):p=\"\",p=X(e,p),a.push({type:\"keyed\",key:u,value:p,append:d})}else{let u=await L(e,l);a.push({type:\"invalid\",expandedValue:u})}}n||i();for(let l of a)if(l.type===\"keyed\")if(l.append){let c=e.state.env.get(`${s}_${l.key}`)??\"\";e.state.env.set(`${s}_${l.key}`,c+l.value)}else e.state.env.set(`${s}_${l.key}`,l.value);else{let c=t.line??e.state.currentLine??1;o(`bash: line ${c}: ${s}: ${l.expandedValue}: must use subscript when assigning associative array\n`)}}async function xa(e,t,s,r,n){let i=[];for(let a of s){let l=Ws(a);if(l){let{key:c,valueParts:u,append:f}=l,d;u.length>0?d=await L(e,{type:\"Word\",parts:u}):d=\"\",d=X(e,d),i.push({type:\"keyed\",indexExpr:c,value:d,append:f})}else{let c=await xe(e,a);i.push({type:\"non-keyed\",values:c.values})}}r||n();let o=0;for(let a of i)if(a.type===\"keyed\"){let l;try{let c=new B,u=ee(c,a.indexExpr);l=await H(e,u.expression,!1)}catch{if(/^-?\\d+$/.test(a.indexExpr))l=Number.parseInt(a.indexExpr,10);else{let c=e.state.env.get(a.indexExpr);l=c?Number.parseInt(c,10):0,Number.isNaN(l)&&(l=0)}}if(a.append){let c=e.state.env.get(`${t}_${l}`)??\"\";e.state.env.set(`${t}_${l}`,c+a.value)}else e.state.env.set(`${t}_${l}`,a.value);o=l+1}else for(let l of a.values)e.state.env.set(`${t}_${o++}`,l)}async function Ta(e,t,s,r,n){let i=[];for(let a of s){let l=await xe(e,a);i.push(...l.values)}let o=0;if(r){let a=Ae(e,t);if(a.length>0)o=Math.max(...a.map(([c])=>typeof c==\"number\"?c:0))+1;else{let l=e.state.env.get(t);l!==void 0&&(e.state.env.set(`${t}_0`,l),e.state.env.delete(t),o=1)}}else n();for(let a=0;a<i.length;a++)e.state.env.set(`${t}_${o+a}`,i[a]);r||e.state.env.set(`${t}__length`,String(i.length))}async function Da(e,t,s,r,n,i,o){let a=s;if(Ee(e,s)){let f=Ze(e,s);if(f&&f!==s){if(f.includes(\"[\"))return{continueToNext:!1,xtraceOutput:\"\",error:_(\"\",`bash: \\`${f}': not a valid identifier\n`,1)};a=f}}if(et(e,a)){if(t.name)return{continueToNext:!0,xtraceOutput:\"\"};let f=se(e,a);if(f)return{continueToNext:!1,xtraceOutput:\"\",error:f}}let l=e.state.associativeArrays?.has(a),c;if(l)c=await Ri(e,a,r);else{let f=await Ra(e,a,r);if(f.error)return{continueToNext:!1,xtraceOutput:\"\",error:f.error};c=`${a}_${f.index}`}let u=i?(e.state.env.get(c)||\"\")+n:n;if(t.name)o.set(c,e.state.env.get(c)),e.state.env.set(c,u);else{let f=pt(e,a);if(f!==void 0&&f===e.state.callDepth&&e.state.localScopes.length>0){let d=e.state.localScopes[e.state.localScopes.length-1];d.has(c)||d.set(c,e.state.env.get(c))}e.state.env.set(c,u)}return{continueToNext:!0,xtraceOutput:\"\"}}async function Ri(e,t,s){let r;if(s.startsWith(\"'\")&&s.endsWith(\"'\"))r=s.slice(1,-1);else if(s.startsWith('\"')&&s.endsWith('\"')){let n=s.slice(1,-1),o=new B().parseWordFromString(n,!0,!1);r=await L(e,o)}else if(s.includes(\"$\")){let i=new B().parseWordFromString(s,!1,!1);r=await L(e,i)}else r=s;return`${t}_${r}`}async function Ra(e,t,s){let r=s;s.startsWith('\"')&&s.endsWith('\"')&&s.length>=2&&(r=s.slice(1,-1));let n;if(/^-?\\d+$/.test(r))n=Number.parseInt(r,10);else{try{let i=new B,o=ee(i,r);n=await H(e,o.expression,!1)}catch(i){if(i instanceof Je){let l=`bash: line ${e.state.currentLine}: ${s}: ${i.message}\n`;if(i.fatal)throw new j(1,\"\",l);return{index:0,error:_(\"\",l,1)}}let o=e.state.env.get(s);n=o?Number.parseInt(o,10):0}Number.isNaN(n)&&(n=0)}if(n<0){let i=Ae(e,t);if(i.length===0){let a=e.state.currentLine;return{index:0,error:_(\"\",`bash: line ${a}: ${t}[${s}]: bad array subscript\n`,1)}}if(n=Math.max(...i.map(([a])=>typeof a==\"number\"?a:0))+1+n,n<0){let a=e.state.currentLine;return{index:0,error:_(\"\",`bash: line ${a}: ${t}[${s}]: bad array subscript\n`,1)}}}return{index:n}}async function Ia(e,t,s,r,n,i){let o=\"\",a=s,l=null;if(Ee(e,s)){let f=nn(e,s,r);if(f===void 0)return{continueToNext:!1,xtraceOutput:\"\",error:_(\"\",`bash: ${s}: circular name reference\n`,1)};if(f===null)return{continueToNext:!0,xtraceOutput:\"\"};a=f;let d=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\\[(.+)\\]$/);d&&(l={arrayName:d[1],subscriptExpr:d[2]},a=d[1])}if(et(e,a)){if(t.name)return o+=`bash: ${a}: readonly variable\n`,{continueToNext:!0,xtraceOutput:o};let f=se(e,a);if(f)return{continueToNext:!1,xtraceOutput:\"\",error:f}}let c;if(xt(e,a))try{let f=new B;if(n){let p=`(${e.state.env.get(a)||\"0\"}) + (${r})`,y=ee(f,p);c=String(await H(e,y.expression))}else{let d=ee(f,r);c=String(await H(e,d.expression))}}catch{c=\"0\"}else{let{isArray:f}=await import(\"./chunks/expansion-R25BK4W3.js\"),d=f(e,a)?`${a}_0`:a;c=n?(e.state.env.get(d)||\"\")+r:r}c=gt(e,a,c),o+=await xi(e,a,c);let u=a;if(l)u=await La(e,l);else{let{isArray:f}=await import(\"./chunks/expansion-R25BK4W3.js\");f(e,a)&&(u=`${a}_0`)}return t.name?(i.set(u,e.state.env.get(u)),e.state.env.set(u,c)):(e.state.env.set(u,c),e.state.options.allexport&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(a)),e.state.tempEnvBindings?.some(f=>f.has(a))&&(e.state.mutatedTempEnvVars=e.state.mutatedTempEnvVars||new Set,e.state.mutatedTempEnvVars.add(a))),{continueToNext:!1,xtraceOutput:o}}async function La(e,t){let{arrayName:s,subscriptExpr:r}=t;if(e.state.associativeArrays?.has(s))return Ri(e,s,r);let i;if(/^-?\\d+$/.test(r))i=Number.parseInt(r,10);else{try{let o=new B,a=ee(o,r);i=await H(e,a.expression,!1)}catch{let o=e.state.env.get(r);i=o?Number.parseInt(o,10):0}Number.isNaN(i)&&(i=0)}if(i<0){let o=Ae(e,s);o.length>0&&(i=Math.max(...o.map(l=>l[0]))+1+i)}return`${s}_${i}`}async function Ii(e,t,s,r){let n=await Re(e,t.redirections);if(n)return n;let i=new Map(e.state.env),o=e.state.cwd,a={...e.state.options},l=new Map(e.state.functions),c=e.state.localScopes,u=e.state.localVarStack,f=e.state.localVarDepth,d=e.state.fullyUnsetLocals;if(e.state.localScopes=c.map(S=>new Map(S)),u){e.state.localVarStack=new Map;for(let[S,T]of u.entries())e.state.localVarStack.set(S,T.map(N=>({...N})))}f&&(e.state.localVarDepth=new Map(f)),d&&(e.state.fullyUnsetLocals=new Map(d));let p=e.state.loopDepth,y=e.state.parentHasLoopContext;e.state.parentHasLoopContext=p>0,e.state.loopDepth=0;let h=e.state.lastArg,w=e.state.bashPid;e.state.bashPid=e.state.nextVirtualPid++;let E=e.state.groupStdin;s&&(e.state.groupStdin=s);let g=\"\",b=\"\",m=0,v=()=>{e.state.env=i,e.state.cwd=o,e.state.options=a,e.state.functions=l,e.state.localScopes=c,e.state.localVarStack=u,e.state.localVarDepth=f,e.state.fullyUnsetLocals=d,e.state.loopDepth=p,e.state.parentHasLoopContext=y,e.state.groupStdin=E,e.state.bashPid=w,e.state.lastArg=h};try{for(let S of t.body){let T=await r(S);g+=T.stdout,b+=T.stderr,m=T.exitCode}}catch(S){if(v(),S instanceof J)throw S;if(S instanceof je){g+=S.stdout,b+=S.stderr;let N=_(g,b,0);return K(e,N,t.redirections)}if(S instanceof ye||S instanceof ge){g+=S.stdout,b+=S.stderr;let N=_(g,b,0);return K(e,N,t.redirections)}if(S instanceof j){g+=S.stdout,b+=S.stderr;let N=_(g,b,S.exitCode);return K(e,N,t.redirections)}if(S instanceof ue){g+=S.stdout,b+=S.stderr;let N=_(g,b,S.exitCode);return K(e,N,t.redirections)}if(S instanceof we){let N=_(g+S.stdout,b+S.stderr,S.exitCode);return K(e,N,t.redirections)}let T=_(g,`${b}${Ie(S)}\n`,1);return K(e,T,t.redirections)}v();let $=_(g,b,m);return K(e,$,t.redirections)}async function Li(e,t,s,r){let n=\"\",i=\"\",o=0,a=await ms(e,t.redirections);if(a)return a;let l=s;for(let f of t.redirections)if((f.operator===\"<<\"||f.operator===\"<<-\")&&f.target.type===\"HereDoc\"){let d=f.target,p=await L(e,d.content);d.stripTabs&&(p=p.split(`\n`).map(h=>h.replace(/^\\t+/,\"\")).join(`\n`));let y=f.fd??0;y!==0?(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),le(e),e.state.fileDescriptors.set(y,p)):l=p}else if(f.operator===\"<<<\"&&f.target.type===\"Word\")l=`${await L(e,f.target)}\n`;else if(f.operator===\"<\"&&f.target.type===\"Word\")try{let d=await L(e,f.target),p=e.fs.resolvePath(e.state.cwd,d);l=await e.fs.readFile(p)}catch{let d=await L(e,f.target);return _(\"\",`bash: ${d}: No such file or directory\n`,1)}let c=e.state.groupStdin;l&&(e.state.groupStdin=l);try{for(let f of t.body){let d=await r(f);n+=d.stdout,i+=d.stderr,o=d.exitCode}}catch(f){if(e.state.groupStdin=c,f instanceof J)throw f;if(Zt(f)||f instanceof we||f instanceof j)throw f.prependOutput(n,i),f;return _(n,`${i}${Ie(f)}\n`,1)}e.state.groupStdin=c;let u=_(n,i,o);return K(e,u,t.redirections)}async function Fi(e,t,s,r,n){let i;try{i=await e.fs.readFile(t)}catch{return A(`bash: ${t}: No such file or directory\n`,127)}if(i.startsWith(\"#!\")){let w=i.indexOf(`\n`);w!==-1&&(i=i.slice(w+1))}let o=new Map(e.state.env),a=e.state.cwd,l={...e.state.options},c=e.state.loopDepth,u=e.state.parentHasLoopContext,f=e.state.lastArg,d=e.state.bashPid,p=e.state.groupStdin,y=e.state.currentSource;e.state.parentHasLoopContext=c>0,e.state.loopDepth=0,e.state.bashPid=e.state.nextVirtualPid++,r&&(e.state.groupStdin=r),e.state.currentSource=t,e.state.env.set(\"0\",t),e.state.env.set(\"#\",String(s.length)),e.state.env.set(\"@\",s.join(\" \")),e.state.env.set(\"*\",s.join(\" \"));for(let w=0;w<s.length&&w<9;w++)e.state.env.set(String(w+1),s[w]);for(let w=s.length+1;w<=9;w++)e.state.env.delete(String(w));let h=()=>{e.state.env=o,e.state.cwd=a,e.state.options=l,e.state.loopDepth=c,e.state.parentHasLoopContext=u,e.state.lastArg=f,e.state.bashPid=d,e.state.groupStdin=p,e.state.currentSource=y};try{let E=new B().parse(i),g=await n(E);return h(),g}catch(w){if(h(),w instanceof j||w instanceof J)throw w;if(w.name===\"ParseException\")return A(`bash: ${t}: ${w.message}\n`);throw w}}var It=class{ctx;constructor(t,s){this.ctx={state:s,fs:t.fs,commands:t.commands,limits:t.limits,execFn:t.exec,executeScript:this.executeScript.bind(this),executeStatement:this.executeStatement.bind(this),executeCommand:this.executeCommand.bind(this),fetch:t.fetch,sleep:t.sleep,trace:t.trace,coverage:t.coverage,requireDefenseContext:t.requireDefenseContext??!1,jsBootstrapCode:t.jsBootstrapCode,invokeTool:t.invokeTool}}assertDefenseContext(t){if(!this.ctx.requireDefenseContext||me.isInSandboxedContext())return;let s=`interpreter ${t} attempted outside defense context`;throw new Ve(s,{timestamp:Date.now(),type:\"missing_defense_context\",message:s,path:\"DefenseInDepthBox.context\",stack:new Error().stack,executionId:me.getCurrentExecutionId()})}buildExportedEnv(){let t=this.ctx.state.exportedVars,s=this.ctx.state.tempExportedVars,r=new Set;if(t)for(let i of t)r.add(i);if(s)for(let i of s)r.add(i);if(r.size===0)return Object.create(null);let n=Object.create(null);for(let i of r){let o=this.ctx.state.env.get(i);o!==void 0&&(n[i]=o)}return n}async executeScript(t){this.assertDefenseContext(\"execution\");let s=\"\",r=\"\",n=0,i=this.ctx.limits.maxOutputSize,o=(a,l)=>{s.length+r.length+a.length+l.length>i&&Te(`total output size exceeded (>${i} bytes), increase executionLimits.maxOutputSize`,\"output_size\"),s+=a,r+=l};for(let a of t.statements)try{let l=await this.executeStatement(a);o(l.stdout,l.stderr),n=l.exitCode,this.ctx.state.lastExitCode=n,this.ctx.state.env.set(\"?\",String(n))}catch(l){if(l instanceof j)throw l.prependOutput(s,r),l;if(l instanceof Pe)return o(l.stdout,l.stderr),n=l.exitCode,this.ctx.state.lastExitCode=n,this.ctx.state.env.set(\"?\",String(n)),{stdout:s,stderr:r,exitCode:n,env:Ue(this.ctx.state.env)};if(l instanceof J)throw l;if(l instanceof we)return o(l.stdout,l.stderr),n=l.exitCode,this.ctx.state.lastExitCode=n,this.ctx.state.env.set(\"?\",String(n)),{stdout:s,stderr:r,exitCode:n,env:Ue(this.ctx.state.env)};if(l instanceof Gr)return o(l.stdout,l.stderr),n=1,this.ctx.state.lastExitCode=n,this.ctx.state.env.set(\"?\",String(n)),{stdout:s,stderr:r,exitCode:n,env:Ue(this.ctx.state.env)};if(l instanceof jt)return o(l.stdout,l.stderr),n=1,this.ctx.state.lastExitCode=n,this.ctx.state.env.set(\"?\",String(n)),{stdout:s,stderr:r,exitCode:n,env:Ue(this.ctx.state.env)};if(l instanceof Je){o(l.stdout,l.stderr),n=1,this.ctx.state.lastExitCode=n,this.ctx.state.env.set(\"?\",String(n));continue}if(l instanceof Kr){o(l.stdout,l.stderr),n=1,this.ctx.state.lastExitCode=n,this.ctx.state.env.set(\"?\",String(n));continue}if(l instanceof ye||l instanceof ge){if(this.ctx.state.loopDepth>0)throw l.prependOutput(s,r),l;o(l.stdout,l.stderr);continue}throw l instanceof ue&&l.prependOutput(s,r),l}return{stdout:s,stderr:r,exitCode:n,env:Ue(this.ctx.state.env)}}async executeUserScript(t,s,r=\"\"){return Fi(this.ctx,t,s,r,n=>this.executeScript(n))}async executeStatement(t){if(this.assertDefenseContext(\"statement\"),this.ctx.state.signal?.aborted)throw new Ht;if(this.ctx.state.commandCount++,this.ctx.state.commandCount>this.ctx.limits.maxCommandCount&&Te(`too many commands executed (>${this.ctx.limits.maxCommandCount}), increase executionLimits.maxCommandCount`,\"commands\"),t.deferredError)throw new qt(t.deferredError.message,t.line??1,1);if(this.ctx.state.options.noexec)return W;this.ctx.state.errexitSafe=!1;let s=\"\",r=\"\";this.ctx.state.options.verbose&&!this.ctx.state.suppressVerbose&&t.sourceText&&(r+=`${t.sourceText}\n`);let n=0,i=-1,o=!1;for(let c=0;c<t.pipelines.length;c++){let u=t.pipelines[c],f=c>0?t.operators[c-1]:null;if(f===\"&&\"&&n!==0||f===\"||\"&&n===0)continue;let d=await this.executePipeline(u);s+=d.stdout,r+=d.stderr,n=d.exitCode,i=c,o=u.negated,this.ctx.state.lastExitCode=n,this.ctx.state.env.set(\"?\",String(n))}let a=i<t.pipelines.length-1,l=this.ctx.state.errexitSafe;if(this.ctx.state.errexitSafe=a||o||l,this.ctx.state.options.errexit&&n!==0&&i===t.pipelines.length-1&&!o&&!this.ctx.state.inCondition&&!l)throw new we(n,s,r);return _(s,r,n)}async executePipeline(t){return Ti(this.ctx,t,(s,r)=>this.executeCommand(s,r))}async executeCommand(t,s){switch(this.assertDefenseContext(\"command\"),this.ctx.coverage?.hit(`bash:cmd:${t.type}`),t.type){case\"SimpleCommand\":return this.executeSimpleCommand(t,s);case\"If\":return Ei(this.ctx,t);case\"For\":return $i(this.ctx,t);case\"CStyleFor\":return Si(this.ctx,t);case\"While\":return Pi(this.ctx,t,s);case\"Until\":return Ai(this.ctx,t);case\"Case\":return ki(this.ctx,t);case\"Subshell\":return this.executeSubshell(t,s);case\"Group\":return this.executeGroup(t,s);case\"FunctionDef\":return Bn(this.ctx,t);case\"ArithmeticCommand\":return this.executeArithmeticCommand(t);case\"ConditionalCommand\":return this.executeConditionalCommand(t);default:return W}}async executeSimpleCommand(t,s){try{return await this.executeSimpleCommandInner(t,s)}catch(r){if(r instanceof Ut)return A(r.stderr);throw r}}async executeSimpleCommandInner(t,s){if(t.line!==void 0&&(this.ctx.state.currentLine=t.line),this.ctx.state.shoptOptions.expand_aliases&&t.name){let m=t,v=100;for(;v>0;){let $=this.expandAlias(m);if($===m)break;m=$,v--}this.aliasExpansionStack.clear(),m!==t&&(t=m)}this.ctx.state.expansionStderr=\"\";let r=await Di(this.ctx,t);if(r.error)return r.error;let n=r.tempAssignments,i=r.xtraceOutput;if(!t.name){if(t.redirections.length>0){let v=await Re(this.ctx,t.redirections);if(v)return v;let $=_(\"\",i,0);return K(this.ctx,$,t.redirections)}this.ctx.state.lastArg=\"\";let m=(this.ctx.state.expansionStderr||\"\")+i;return this.ctx.state.expansionStderr=\"\",_(\"\",m,this.ctx.state.lastExitCode)}let o=t.name&&zr(t.name,[\"local\",\"declare\",\"typeset\",\"export\",\"readonly\"]),a=Array.from(n.keys());if(a.length>0&&!o){this.ctx.state.tempExportedVars=this.ctx.state.tempExportedVars||new Set;for(let m of a)this.ctx.state.tempExportedVars.add(m)}let l=await ms(this.ctx,t.redirections);if(l){for(let[m,v]of n)v===void 0?this.ctx.state.env.delete(m):this.ctx.state.env.set(m,v);return l}let c=-1;for(let m of t.redirections){if((m.operator===\"<<\"||m.operator===\"<<-\")&&m.target.type===\"HereDoc\"){let v=m.target,$=await L(this.ctx,v.content);v.stripTabs&&($=$.split(`\n`).map(T=>T.replace(/^\\t+/,\"\")).join(`\n`)),$=Be($);let S=m.fd??0;S!==0?(this.ctx.state.fileDescriptors||(this.ctx.state.fileDescriptors=new Map),le(this.ctx),this.ctx.state.fileDescriptors.set(S,$)):s=$;continue}if(m.operator===\"<<<\"&&m.target.type===\"Word\"){s=Be(`${await L(this.ctx,m.target)}\n`);continue}if(m.operator===\"<\"&&m.target.type===\"Word\")try{let v=await L(this.ctx,m.target),$=this.ctx.fs.resolvePath(this.ctx.state.cwd,v);s=await Vt(this.ctx.fs,$)}catch{let v=await L(this.ctx,m.target);for(let[$,S]of n)S===void 0?this.ctx.state.env.delete($):this.ctx.state.env.set($,S);return A(`bash: ${v}: No such file or directory\n`)}if(m.operator===\"<&\"&&m.target.type===\"Word\"){let v=await L(this.ctx,m.target),$=Number.parseInt(v,10);if(!Number.isNaN($)&&this.ctx.state.fileDescriptors){let S=this.ctx.state.fileDescriptors.get($);if(S!==void 0)if(S.startsWith(\"__rw__:\")){let T=_i(S);T&&(s=T.content.slice(T.position),c=$)}else S.startsWith(\"__file__:\")||S.startsWith(\"__file_append__:\")||(s=S)}}}let u=await L(this.ctx,t.name),f=[],d=[];if(zr(t.name,[\"local\",\"declare\",\"typeset\",\"export\",\"readonly\"])&&(u===\"local\"||u===\"declare\"||u===\"typeset\"||u===\"export\"||u===\"readonly\"))for(let m of t.args){let v=await An(this.ctx,m);if(v)f.push(v),d.push(!0);else{let $=await kn(this.ctx,m);if($!==null)f.push($),d.push(!0);else{let S=await xe(this.ctx,m);for(let T of S.values)f.push(T),d.push(S.quoted)}}}else for(let m of t.args){let v=await xe(this.ctx,m);for(let $ of v.values)f.push($),d.push(v.quoted)}if(!u){if(t.name.parts.every(v=>v.type===\"CommandSubstitution\"||v.type===\"ParameterExpansion\"||v.type===\"ArithmeticExpansion\")){if(f.length>0){let v=f.shift();return d.shift(),await this.runCommand(v,f,d,s,!1,!1,c)}return _(\"\",\"\",this.ctx.state.lastExitCode)}return A(`bash: : command not found\n`,127)}if(u===\"exec\"&&(f.length===0||f[0]===\"--\")){for(let m of t.redirections){if(m.target.type===\"HereDoc\"||m.fdVariable)continue;let v=await L(this.ctx,m.target),$=m.fd??(m.operator===\"<\"||m.operator===\"<>\"?0:1);switch(this.ctx.state.fileDescriptors||(this.ctx.state.fileDescriptors=new Map),m.operator){case\">\":case\">|\":{let S=this.ctx.fs.resolvePath(this.ctx.state.cwd,v);await this.ctx.fs.writeFile(S,\"\",\"utf8\"),le(this.ctx),this.ctx.state.fileDescriptors.set($,`__file__:${S}`);break}case\">>\":{let S=this.ctx.fs.resolvePath(this.ctx.state.cwd,v);le(this.ctx),this.ctx.state.fileDescriptors.set($,`__file_append__:${S}`);break}case\"<\":{let S=this.ctx.fs.resolvePath(this.ctx.state.cwd,v);try{let T=await this.ctx.fs.readFile(S);le(this.ctx),this.ctx.state.fileDescriptors.set($,T)}catch{return A(`bash: ${v}: No such file or directory\n`)}break}case\"<>\":{let S=this.ctx.fs.resolvePath(this.ctx.state.cwd,v);try{let T=await this.ctx.fs.readFile(S);le(this.ctx),this.ctx.state.fileDescriptors.set($,`__rw__:${S.length}:${S}:0:${T}`)}catch{await this.ctx.fs.writeFile(S,\"\",\"utf8\"),le(this.ctx),this.ctx.state.fileDescriptors.set($,`__rw__:${S.length}:${S}:0:`)}break}case\">&\":{if(v===\"-\")this.ctx.state.fileDescriptors.delete($);else if(v.endsWith(\"-\")){let S=v.slice(0,-1),T=Number.parseInt(S,10);if(!Number.isNaN(T)){let N=this.ctx.state.fileDescriptors.get(T);N!==void 0?this.ctx.state.fileDescriptors.set($,N):this.ctx.state.fileDescriptors.set($,`__dupout__:${T}`),this.ctx.state.fileDescriptors.delete(T)}}else{let S=Number.parseInt(v,10);Number.isNaN(S)||(le(this.ctx),this.ctx.state.fileDescriptors.set($,`__dupout__:${S}`))}break}case\"<&\":{if(v===\"-\")this.ctx.state.fileDescriptors.delete($);else if(v.endsWith(\"-\")){let S=v.slice(0,-1),T=Number.parseInt(S,10);if(!Number.isNaN(T)){let N=this.ctx.state.fileDescriptors.get(T);N!==void 0?this.ctx.state.fileDescriptors.set($,N):this.ctx.state.fileDescriptors.set($,`__dupin__:${T}`),this.ctx.state.fileDescriptors.delete(T)}}else{let S=Number.parseInt(v,10);Number.isNaN(S)||(le(this.ctx),this.ctx.state.fileDescriptors.set($,`__dupin__:${S}`))}break}}}for(let[m,v]of n)v===void 0?this.ctx.state.env.delete(m):this.ctx.state.env.set(m,v);if(this.ctx.state.tempExportedVars)for(let m of n.keys())this.ctx.state.tempExportedVars.delete(m);return W}if(this.ctx.state.extraArgs){f.push(...this.ctx.state.extraArgs);for(let m=0;m<this.ctx.state.extraArgs.length;m++)d.push(!0);this.ctx.state.extraArgs=void 0}let y=await Oi(this.ctx,u,f);n.size>0&&(this.ctx.state.tempEnvBindings=this.ctx.state.tempEnvBindings||[],this.ctx.state.tempEnvBindings.push(new Map(n)));let h,w=null;try{h=await this.runCommand(u,f,d,s,!1,!1,c)}catch(m){if(m instanceof ye||m instanceof ge)w=m,h=W;else throw m}let E=i+y;if(E&&(h={...h,stderr:E+h.stderr}),h=await K(this.ctx,h,t.redirections),w)throw w;if(f.length>0){let m=f[f.length-1];if((u===\"declare\"||u===\"local\"||u===\"typeset\")&&/^[a-zA-Z_][a-zA-Z0-9_]*=\\(/.test(m)){let v=m.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\\(/);v&&(m=v[1])}this.ctx.state.lastArg=m}else this.ctx.state.lastArg=u;let g=zn(u)&&u!==\"unset\"&&u!==\"eval\";if(!this.ctx.state.options.posix||!g)for(let[m,v]of n)this.ctx.state.fullyUnsetLocals?.has(m)||(v===void 0?this.ctx.state.env.delete(m):this.ctx.state.env.set(m,v));if(this.ctx.state.tempExportedVars)for(let m of n.keys())this.ctx.state.tempExportedVars.delete(m);return n.size>0&&this.ctx.state.tempEnvBindings&&this.ctx.state.tempEnvBindings.pop(),this.ctx.state.expansionStderr&&(h={...h,stderr:this.ctx.state.expansionStderr+h.stderr},this.ctx.state.expansionStderr=\"\"),h}async runCommand(t,s,r,n,i=!1,o=!1,a=-1){let l={ctx:this.ctx,runCommand:(u,f,d,p,y,h,w)=>this.runCommand(u,f,d,p,y,h,w),buildExportedEnv:()=>this.buildExportedEnv(),executeUserScript:(u,f,d)=>this.executeUserScript(u,f,d)},c=await vi(l,t,s,r,n,i,o,a);return c!==null?c:bi(l,t,s,n,o)}aliasExpansionStack=new Set;expandAlias(t){return Ks(this.ctx.state,t,this.aliasExpansionStack)}async findCommandInPath(t){return $s(this.ctx,t)}async executeSubshell(t,s=\"\"){return Ii(this.ctx,t,s,r=>this.executeStatement(r))}async executeGroup(t,s=\"\"){return Li(this.ctx,t,s,r=>this.executeStatement(r))}async executeArithmeticCommand(t){t.line!==void 0&&(this.ctx.state.currentLine=t.line);let s=await Re(this.ctx,t.redirections);if(s)return s;try{let r=await H(this.ctx,t.expression.expression),n=Q(r!==0);return this.ctx.state.expansionStderr&&(n={...n,stderr:this.ctx.state.expansionStderr+n.stderr},this.ctx.state.expansionStderr=\"\"),K(this.ctx,n,t.redirections)}catch(r){let n=A(`bash: arithmetic expression: ${r.message}\n`);return K(this.ctx,n,t.redirections)}}async executeConditionalCommand(t){t.line!==void 0&&(this.ctx.state.currentLine=t.line);let s=await Re(this.ctx,t.redirections);if(s)return s;try{let r=await Ke(this.ctx,t.expression),n=Q(r);return this.ctx.state.expansionStderr&&(n={...n,stderr:this.ctx.state.expansionStderr+n.stderr},this.ctx.state.expansionStderr=\"\"),K(this.ctx,n,t.redirections)}catch(r){let n=r instanceof Je?1:2,i=A(`bash: conditional expression: ${r.message}\n`,n);return K(this.ctx,i,t.redirections)}}};var re={maxCallDepth:100,maxCommandCount:1e4,maxLoopIterations:1e4,maxAwkIterations:1e4,maxSedIterations:1e4,maxJqIterations:1e4,maxSqliteTimeoutMs:5e3,maxPythonTimeoutMs:1e4,maxJsTimeoutMs:1e4,maxGlobOperations:1e5,maxStringLength:10485760,maxArrayElements:1e5,maxHeredocSize:10485760,maxSubstitutionDepth:50,maxBraceExpansionResults:1e4,maxOutputSize:10485760,maxFileDescriptors:1024,maxSourceDepth:100};function Mi(e){return e?{maxCallDepth:e.maxCallDepth??re.maxCallDepth,maxCommandCount:e.maxCommandCount??re.maxCommandCount,maxLoopIterations:e.maxLoopIterations??re.maxLoopIterations,maxAwkIterations:e.maxAwkIterations??re.maxAwkIterations,maxSedIterations:e.maxSedIterations??re.maxSedIterations,maxJqIterations:e.maxJqIterations??re.maxJqIterations,maxSqliteTimeoutMs:e.maxSqliteTimeoutMs??re.maxSqliteTimeoutMs,maxPythonTimeoutMs:e.maxPythonTimeoutMs??re.maxPythonTimeoutMs,maxJsTimeoutMs:e.maxJsTimeoutMs??re.maxJsTimeoutMs,maxGlobOperations:e.maxGlobOperations??re.maxGlobOperations,maxStringLength:e.maxStringLength??re.maxStringLength,maxArrayElements:e.maxArrayElements??re.maxArrayElements,maxHeredocSize:e.maxHeredocSize??re.maxHeredocSize,maxSubstitutionDepth:e.maxSubstitutionDepth??re.maxSubstitutionDepth,maxBraceExpansionResults:e.maxBraceExpansionResults??re.maxBraceExpansionResults,maxOutputSize:e.maxOutputSize??re.maxOutputSize,maxFileDescriptors:e.maxFileDescriptors??re.maxFileDescriptors,maxSourceDepth:e.maxSourceDepth??re.maxSourceDepth}:{...re}}import{lookup as Za}from\"node:dns\";function Vr(e){try{let t=new URL(e);return{origin:t.origin,pathname:t.pathname,href:t.href}}catch{return null}}function Fa(e){let t=Vr(e);return t?{origin:t.origin,pathPrefix:t.pathname}:null}function Wi(e){if(e.includes(\"\\\\\"))return!0;let t=e.toLowerCase();return t.includes(\"%2f\")||t.includes(\"%5c\")}function Ma(e,t){return t===\"/\"||t===\"\"?!0:t.endsWith(\"/\")?e.startsWith(t):e===t||e.startsWith(`${t}/`)}function Br(e,t){let s=Vr(e);if(!s)return!1;let r=Fa(t);return!r||s.origin!==r.origin||r.pathPrefix!==\"/\"&&r.pathPrefix!==\"\"&&Wi(s.pathname)?!1:Ma(s.pathname,r.pathPrefix)}function zi(e){return typeof e==\"string\"?e:e.url}function Vi(e,t){return!t||t.length===0?!1:t.some(s=>Br(e,zi(s)))}function jr(e){let t=Wa(e);if(t===\"localhost\"||t.endsWith(\".localhost\"))return!0;let s=Bi(t);if(s)return Ps(s);let r=Va(t);return r?Ba(r):!1}function Wa(e){let t=e.trim().toLowerCase();return t.startsWith(\"[\")&&t.endsWith(\"]\")?t.slice(1,-1):t}function za(e){if(!e)return null;let t=10,s=e;if(s.startsWith(\"0x\")||s.startsWith(\"0X\")?(t=16,s=s.slice(2)):s.length>1&&s.startsWith(\"0\")&&(t=8),!s||t===16&&!/^[0-9a-fA-F]+$/.test(s)||t===10&&!/^\\d+$/.test(s)||t===8&&!/^[0-7]+$/.test(s))return null;let r=Number.parseInt(s,t);return!Number.isFinite(r)||r<0?null:r}function Bi(e){let t=e.split(\".\");if(t.length===0||t.length>4)return null;let s=t.map(l=>za(l));if(s.some(l=>l===null))return null;let r=s;if(t.length===1){let l=r[0];return l>4294967295?null:[l>>>24&255,l>>>16&255,l>>>8&255,l&255]}if(t.length===2){let[l,c]=r;return l>255||c>16777215?null:[l,c>>>16&255,c>>>8&255,c&255]}if(t.length===3){let[l,c,u]=r;return l>255||c>255||u>65535?null:[l,c,u>>>8&255,u&255]}let[n,i,o,a]=r;return n>255||i>255||o>255||a>255?null:[n,i,o,a]}function Va(e){let t=e,s=null;if(t.includes(\".\")){let h=t.lastIndexOf(\":\");if(h<0)return null;let w=t.slice(h+1),E=Bi(w);if(!E)return null;s=E,t=t.slice(0,h)}let r=t.includes(\"::\")?t.split(\"::\").length-1:0;if(r>1)return null;let[n,i]=t.split(\"::\"),o=n?n.split(\":\").filter(Boolean):[],a=i?i.split(\":\").filter(Boolean):[],l=h=>/^[0-9a-f]{1,4}$/i.test(h)?Number.parseInt(h,16):null,c=o.map(l),u=a.map(l);if(c.some(h=>h===null)||u.some(h=>h===null))return null;let f=s?2:0,d=c.length+u.length+f,p=0;if(r===1){if(p=8-d,p<0)return null}else if(d!==8)return null;let y=[...c,...new Array(p).fill(0),...u];return s&&(y.push(s[0]<<8|s[1]),y.push(s[2]<<8|s[3])),y.length===8?y:null}function Ps(e){let[t,s]=e;return t===127||t===10||t===172&&s>=16&&s<=31||t===192&&s===168||t===169&&s===254||t===0||t===100&&s>=64&&s<=127||t===198&&(s===18||s===19)||t===192&&s===0&&e[2]===0||t===192&&s===0&&e[2]===2||t===198&&s===51&&e[2]===100||t===203&&s===0&&e[2]===113||t>=240}function Ba(e){if(e.every(n=>n===0)||e.slice(0,7).every(n=>n===0)&&e[7]===1||(e[0]&65472)===65152||(e[0]&65024)===64512)return!0;if(e[0]===0&&e[1]===0&&e[2]===0&&e[3]===0&&e[4]===0&&e[5]===65535){let n=[e[6]>>>8&255,e[6]&255,e[7]>>>8&255,e[7]&255];return Ps(n)}if(e[0]===8193&&e[1]===3512)return!0;if(e[0]===100&&e[1]===65435&&e[2]===0&&e[3]===0&&e[4]===0&&e[5]===0){let n=[e[6]>>>8&255,e[6]&255,e[7]>>>8&255,e[7]&255];return Ps(n)}if(e[0]===100&&e[1]===65435&&e[2]===1)return!0;if(e[0]===8194){let n=[e[1]>>>8&255,e[1]&255,e[2]>>>8&255,e[2]&255];return Ps(n)}return!1}function ji(e){let t=[];for(let s of e){if(typeof s!=\"string\"&&(s===null||typeof s!=\"object\"||!(\"url\"in s)||typeof s.url!=\"string\")){t.push('Invalid allow-list entry: must be a string URL or an object with a \"url\" string property');continue}let r=zi(s);if(!Vr(r)){t.push(`Invalid URL in allow-list: \"${r}\" - must be a valid URL with scheme and host (e.g., \"https://example.com\")`);continue}let i=new URL(r);if(i.protocol!==\"http:\"&&i.protocol!==\"https:\"){t.push(`Only http and https URLs are allowed in allow-list: \"${r}\"`);continue}if(!i.hostname){t.push(`Allow-list entry must include a hostname: \"${r}\"`);continue}if(i.pathname!==\"/\"&&i.pathname!==\"\"&&Wi(i.pathname)){t.push(`Allow-list entry contains ambiguous path separators: \"${r}\"`);continue}(i.search||i.hash)&&t.push(`Query strings and fragments are ignored in allow-list entries: \"${r}\"`)}return t}var ja=typeof __BROWSER__<\"u\"&&__BROWSER__,wt=null,As=null,Ui=!1;function Ua(){if(wt===null&&!ja)try{let e=Is(\"node:async_hooks\");As=Is(\"node:dns\"),wt=new e.AsyncLocalStorage}catch{}}function Ha(){if(Ui||(Ua(),!wt||!As))return;Ui=!0;let e=wt,t=As.lookup;function s(...r){let n=r[0],i=e.getStore();if(typeof n!=\"string\"||!i||i.hostname.toLowerCase()!==n.toLowerCase())return t.apply(this,r);let o={},a;if(r.length===2)a=r[1];else if(r.length>=3){let c=r[1];typeof c==\"number\"?o={family:c}:c&&typeof c==\"object\"&&(o=c),a=r[2]}if(typeof a!=\"function\")return t.apply(this,r);let l=a;if(o.family!==void 0&&o.family!==0&&o.family!==i.family){let c=new Error(`ENOTFOUND ${n}`);c.code=\"ENOTFOUND\",c.errno=-3008,c.syscall=\"getaddrinfo\",c.hostname=n,process.nextTick(()=>l(c));return}process.nextTick(()=>{o.all?l(null,[{address:i.address,family:i.family}]):l(null,i.address,i.family)})}Object.defineProperty(As,\"lookup\",{value:s,writable:!0,configurable:!0})}function Hi(e,t){return Ha(),wt?wt.run(e,t):t()}var _e=class extends Error{constructor(t,s){let r=s??\"URL not in allow-list\";super(`Network access denied: ${r}: ${t}`),this.name=\"NetworkAccessDeniedError\"}},vt=class extends Error{constructor(t){super(`Too many redirects (max: ${t})`),this.name=\"TooManyRedirectsError\"}},bt=class extends Error{constructor(t){super(`Redirect target not in allow-list: ${t}`),this.name=\"RedirectNotAllowedError\"}},ks=class extends Error{constructor(t,s){super(`HTTP method '${t}' not allowed. Allowed methods: ${s.join(\", \")}`),this.name=\"MethodNotAllowedError\"}},Et=class extends Error{constructor(t){super(`Response body too large (max: ${t} bytes)`),this.name=\"ResponseTooLargeError\"}};function qa(e){return new Promise((t,s)=>{Za(e,{all:!0},(r,n)=>{r?s(r):t(n)})})}var Ga=20,Ka=3e4,Xa=10485760,Ya=[\"GET\",\"HEAD\"],Qa=new Set([\"GET\",\"HEAD\",\"OPTIONS\"]),Ja=new Set([301,302,303,307,308]);function Ur(e){let t=e.allowedUrlPrefixes??[];if(!e.dangerouslyAllowFullInternetAccess){let p=ji(t);if(p.length>0)throw new Error(`Invalid network allow-list:\n${p.join(`\n`)}`)}let s=[];for(let p of t)typeof p==\"object\"&&p.transform&&p.transform.length>0&&s.push(p);function r(p){if(s.length===0)return null;let y=null;for(let h of s)if(Br(p,h.url)&&h.transform){y||(y=new Headers);for(let w of h.transform)for(let[E,g]of Object.entries(w.headers))y.set(E,g)}return y}let n=e.maxRedirects??Ga,i=e.timeoutMs??Ka,o=e.maxResponseSize??Xa,a=e.dangerouslyAllowFullInternetAccess?[\"GET\",\"HEAD\",\"POST\",\"PUT\",\"DELETE\",\"PATCH\",\"OPTIONS\"]:e.allowedMethods??Ya,l=e.denyPrivateRanges??(typeof process<\"u\"&&process.env?.NODE_ENV===\"production\"),c=e._dnsResolve??qa;async function u(p){if(!e.dangerouslyAllowFullInternetAccess&&!Vi(p,t))throw new _e(p);if(l)try{let y=new URL(p);if(jr(y.hostname))throw new _e(p,\"private/loopback IP address blocked\");let h=y.hostname;if(/[a-zA-Z]/.test(h))try{let E=await c(h);for(let{address:b}of E)if(jr(b))throw new _e(p,\"hostname resolves to private/loopback IP address\");let g=E[0];if(g)return{hostname:h,address:g.address,family:g.family===6?6:4}}catch(E){if(E instanceof _e)throw E;let g=E?.code;if(!(g===\"ENOTFOUND\"||g===\"ENODATA\"))throw new _e(p,\"DNS resolution failed for private IP check\")}}catch(y){if(y instanceof _e)throw y}return null}function f(p){if(e.dangerouslyAllowFullInternetAccess)return;let y=p.toUpperCase();if(!a.includes(y))throw new ks(y,a)}async function d(p,y={}){let h=y.method?.toUpperCase()??\"GET\",w=await u(p);f(h);let E=p,g=0,b=y.followRedirects??!0,m=y.timeoutMs!==void 0?Math.min(y.timeoutMs,i):i;for(;;){let v=new AbortController,$=Mt(()=>v.abort(),m);try{let S=await me.runTrustedAsync(()=>{let T=r(E),N=el(y.headers,T),F={method:h,headers:N,signal:v.signal,redirect:\"manual\"};return y.body&&!Qa.has(h)&&(F.body=y.body),w?Hi(w,()=>fetch(E,F)):fetch(E,F)});if(Ja.has(S.status)&&b){let T=S.headers.get(\"location\");if(!T)return await Zi(S,E,o);let N=new URL(T,E).href;try{w=await u(N)}catch{throw new bt(N)}if(g++,g>n)throw new vt(n);E=N;continue}return await Zi(S,E,o)}finally{Wt($)}}}return d}function el(e,t){if(!e&&!t)return;if(!t)return e;let s=e instanceof Headers?new Headers(e):new Headers(e);for(let[r,n]of t)s.set(r,n);return s}async function Zi(e,t,s){let r=Object.create(null);if(e.headers.forEach((i,o)=>{r[o.toLowerCase()]=i}),s>0){let i=e.headers.get(\"content-length\");if(i){let o=parseInt(i,10);if(!Number.isNaN(o)&&o>s)throw new Et(s)}}let n;if(s>0&&e.body){let i=e.body.getReader(),o=[],a=0;for(;;){let{done:c,value:u}=await i.read();if(c)break;if(u){if(a+=u.byteLength,a>s)throw i.cancel(),new Et(s);o.push(u)}}n=new Uint8Array(a);let l=0;for(let c of o)n.set(c,l),l+=c.byteLength}else{let i=await e.arrayBuffer();if(s>0&&i.byteLength>s)throw new Et(s);n=new Uint8Array(i)}return{status:e.status,statusText:e.statusText,headers:r,body:n,url:t}}function Lt(e){return ot(e)}function ot(e){return e.statements.map(qi).join(`\n`)}function qi(e){let t=[];for(let r=0;r<e.pipelines.length;r++)t.push(tl(e.pipelines[r])),r<e.operators.length&&t.push(e.operators[r]);let s=t.join(\" \");return e.background&&(s+=\" &\"),s}function tl(e){let t=[];e.timed&&t.push(e.timePosix?\"time -p\":\"time\"),e.negated&&t.push(\"!\");let s=[];for(let n=0;n<e.commands.length;n++)if(s.push(Gi(e.commands[n])),n<e.commands.length-1){let i=e.pipeStderr?.[n];s.push(i?\"|&\":\"|\")}return(t.length>0?`${t.join(\" \")} `:\"\")+s.join(\" \")}function Gi(e){switch(e.type){case\"SimpleCommand\":return sl(e);case\"If\":return fl(e);case\"For\":return dl(e);case\"CStyleFor\":return hl(e);case\"While\":return pl(e);case\"Until\":return ml(e);case\"Case\":return yl(e);case\"Subshell\":return wl(e);case\"Group\":return vl(e);case\"ArithmeticCommand\":return bl(e);case\"ConditionalCommand\":return El(e);case\"FunctionDef\":return $l(e);default:{let t=e;throw new Error(`Unsupported command type: ${t.type}`)}}}function sl(e){let t=[];for(let s of e.assignments)t.push(rl(s));e.name&&t.push(ie(e.name));for(let s of e.args)t.push(ie(s));for(let s of e.redirections)t.push(Yi(s));return t.join(\" \")}function rl(e){let t=e.append?\"+=\":\"=\";if(e.array){let s=e.array.map(ie).join(\" \");return`${e.name}${t}(${s})`}return e.value?`${e.name}${t}${ie(e.value)}`:`${e.name}${t}`}function ie(e){return e.parts.map(t=>_s(t,!1)).join(\"\")}function Qe(e){return e.parts.map(t=>_s(t,!0)).join(\"\")}function _s(e,t){switch(e.type){case\"Literal\":return t?il(e.value):nl(e.value);case\"SingleQuoted\":return`'${e.value}'`;case\"DoubleQuoted\":return`\"${e.parts.map(s=>_s(s,!0)).join(\"\")}\"`;case\"Escaped\":return`\\\\${e.value}`;case\"ParameterExpansion\":return Ki(e);case\"CommandSubstitution\":return e.legacy?`\\`${ot(e.body)}\\``:`$(${ot(e.body)})`;case\"ArithmeticExpansion\":return`$((${Z(e.expression.expression)}))`;case\"ProcessSubstitution\":return e.direction===\"input\"?`<(${ot(e.body)})`:`>(${ot(e.body)})`;case\"BraceExpansion\":return cl(e);case\"TildeExpansion\":return e.user!==null?`~${e.user}`:\"~\";case\"Glob\":return e.pattern;default:{let s=e;throw new Error(`Unsupported word part type: ${s.type}`)}}}function nl(e){return e.replace(/[\\s\\\\'\"`!|&;()<>{}[\\]*?~#]/g,\"\\\\$&\")}function il(e){return e.replace(/[$`\"\\\\]/g,\"\\\\$&\")}function ol(e,t){return e.parts.map(s=>al(s,t)).join(\"\")}function al(e,t){switch(e.type){case\"Literal\":return t?e.value:e.value.replace(/[$`]/g,\"\\\\$&\");case\"Escaped\":return`\\\\${e.value}`;case\"ParameterExpansion\":return Ki(e);case\"CommandSubstitution\":return e.legacy?`\\`${ot(e.body)}\\``:`$(${ot(e.body)})`;case\"ArithmeticExpansion\":return`$((${Z(e.expression.expression)}))`;default:return _s(e,!1)}}function Ki(e){return e.operation?`\\${${Xi(e.parameter,e.operation)}}`:ll(e.parameter)?`\\${${e.parameter}}`:`$${e.parameter}`}function ll(e){return!(/^[?#@*$!\\-0-9]$/.test(e)||/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e))}function Xi(e,t){switch(t.type){case\"Length\":return`#${e}`;case\"LengthSliceError\":return`#${e}:`;case\"BadSubstitution\":return t.text;case\"DefaultValue\":return`${e}${t.checkEmpty?\":\":\"\"}-${Qe(t.word)}`;case\"AssignDefault\":return`${e}${t.checkEmpty?\":\":\"\"}=${Qe(t.word)}`;case\"ErrorIfUnset\":return`${e}${t.checkEmpty?\":\":\"\"}?${t.word?Qe(t.word):\"\"}`;case\"UseAlternative\":return`${e}${t.checkEmpty?\":\":\"\"}+${Qe(t.word)}`;case\"Substring\":{let s=Z(t.offset.expression);return t.length?`${e}:${s}:${Z(t.length.expression)}`:`${e}:${s}`}case\"PatternRemoval\":{let s=t.side===\"prefix\"?\"#\":\"%\",r=t.greedy?`${s}${s}`:s;return`${e}${r}${Qe(t.pattern)}`}case\"PatternReplacement\":{let s=\"/\";t.all?s=\"//\":t.anchor===\"start\"?s=\"/#\":t.anchor===\"end\"&&(s=\"/%\");let r=t.replacement?`/${Qe(t.replacement)}`:\"\";return`${e}${s}${Qe(t.pattern)}${r}`}case\"CaseModification\":{let s=t.direction===\"upper\"?\"^\":\",\",r=t.all?`${s}${s}`:s,n=t.pattern?Qe(t.pattern):\"\";return`${e}${r}${n}`}case\"Transform\":return`${e}@${t.operator}`;case\"Indirection\":return t.innerOp?`!${Xi(e,t.innerOp)}`:`!${e}`;case\"ArrayKeys\":return`!${t.array}[${t.star?\"*\":\"@\"}]`;case\"VarNamePrefix\":return`!${t.prefix}${t.star?\"*\":\"@\"}`;default:{let s=t;throw new Error(`Unsupported parameter operation type: ${s.type}`)}}}function cl(e){return`{${e.items.map(ul).join(\",\")}}`}function ul(e){if(e.type===\"Word\")return ie(e.word);let t=e.startStr??String(e.start),s=e.endStr??String(e.end);return e.step!==void 0?`${t}..${s}..${e.step}`:`${t}..${s}`}function Yi(e){let t=e.fdVariable?`{${e.fdVariable}}`:e.fd!==null?String(e.fd):\"\";if(e.operator===\"<<\"||e.operator===\"<<-\"){let s=e.target,r=s.quoted?`'${s.delimiter}'`:s.delimiter,n=ol(s.content,s.quoted);return`${t}${e.operator}${r}\n${n}${s.delimiter}`}return e.operator===\"<<<\"?`${t}<<< ${ie(e.target)}`:e.operator===\"&>\"||e.operator===\"&>>\"?`${e.operator} ${ie(e.target)}`:`${t}${e.operator} ${ie(e.target)}`}function Ce(e){return e.length===0?\"\":` ${e.map(Yi).join(\" \")}`}function $e(e){return e.map(qi).join(`\n`)}function fl(e){let t=[];for(let s=0;s<e.clauses.length;s++){let r=e.clauses[s],n=s===0?\"if\":\"elif\";t.push(`${n} ${$e(r.condition)}; then\n${$e(r.body)}`)}return e.elseBody&&t.push(`else\n${$e(e.elseBody)}`),`${t.join(`\n`)}\nfi${Ce(e.redirections)}`}function dl(e){let t;if(e.words===null)t=`for ${e.variable}`;else{let s=e.words.map(ie).join(\" \");t=`for ${e.variable} in ${s}`}return`${t}; do\n${$e(e.body)}\ndone${Ce(e.redirections)}`}function hl(e){let t=e.init?Z(e.init.expression):\"\",s=e.condition?Z(e.condition.expression):\"\",r=e.update?Z(e.update.expression):\"\";return`for ((${t}; ${s}; ${r})); do\n${$e(e.body)}\ndone${Ce(e.redirections)}`}function pl(e){return`while ${$e(e.condition)}; do\n${$e(e.body)}\ndone${Ce(e.redirections)}`}function ml(e){return`until ${$e(e.condition)}; do\n${$e(e.body)}\ndone${Ce(e.redirections)}`}function yl(e){let t=e.items.map(gl).join(`\n`);return`case ${ie(e.word)} in\n${t}\nesac${Ce(e.redirections)}`}function gl(e){let t=e.patterns.map(ie).join(\" | \"),s=$e(e.body);return s?`${t})\n${s}\n${e.terminator}`:`${t})\n${e.terminator}`}function wl(e){return`(${$e(e.body)})${Ce(e.redirections)}`}function vl(e){return`{ ${$e(e.body)}; }${Ce(e.redirections)}`}function bl(e){return`((${Z(e.expression.expression)}))${Ce(e.redirections)}`}function El(e){return`[[ ${it(e.expression)} ]]${Ce(e.redirections)}`}function $l(e){let t=Gi(e.body);return`${e.name}() ${t}${Ce(e.redirections)}`}function Z(e){switch(e.type){case\"ArithNumber\":return String(e.value);case\"ArithVariable\":return e.hasDollarPrefix?`$${e.name}`:e.name;case\"ArithSpecialVar\":return`$${e.name}`;case\"ArithBinary\":return`${Z(e.left)} ${e.operator} ${Z(e.right)}`;case\"ArithUnary\":return e.prefix?`${e.operator}${Z(e.operand)}`:`${Z(e.operand)}${e.operator}`;case\"ArithTernary\":return`${Z(e.condition)} ? ${Z(e.consequent)} : ${Z(e.alternate)}`;case\"ArithAssignment\":return`${e.subscript?`${e.variable}[${Z(e.subscript)}]`:e.stringKey!==void 0?`${e.variable}[${e.stringKey}]`:e.variable} ${e.operator} ${Z(e.value)}`;case\"ArithDynamicAssignment\":return`${e.subscript?`${Z(e.target)}[${Z(e.subscript)}]`:Z(e.target)} ${e.operator} ${Z(e.value)}`;case\"ArithDynamicElement\":return`${Z(e.nameExpr)}[${Z(e.subscript)}]`;case\"ArithGroup\":return`(${Z(e.expression)})`;case\"ArithNested\":return`$((${Z(e.expression)}))`;case\"ArithCommandSubst\":return`$(${e.command})`;case\"ArithBracedExpansion\":return`\\${${e.content}}`;case\"ArithArrayElement\":return e.stringKey!==void 0?`${e.array}[${e.stringKey}]`:e.index?`${e.array}[${Z(e.index)}]`:e.array;case\"ArithDynamicBase\":return`\\${${e.baseExpr}}#${e.value}`;case\"ArithDynamicNumber\":return`\\${${e.prefix}}${e.suffix}`;case\"ArithConcat\":return e.parts.map(Z).join(\"\");case\"ArithDoubleSubscript\":return`${e.array}[${Z(e.index)}]`;case\"ArithNumberSubscript\":return`${e.number}[${e.errorToken}]`;case\"ArithSyntaxError\":return e.errorToken;case\"ArithSingleQuote\":return`'${e.content}'`;default:{let t=e;throw new Error(`Unsupported arithmetic expression type: ${t.type}`)}}}function it(e){switch(e.type){case\"CondBinary\":return`${ie(e.left)} ${e.operator} ${ie(e.right)}`;case\"CondUnary\":return`${e.operator} ${ie(e.operand)}`;case\"CondNot\":return`! ${it(e.operand)}`;case\"CondAnd\":return`${it(e.left)} && ${it(e.right)}`;case\"CondOr\":return`${it(e.left)} || ${it(e.right)}`;case\"CondGroup\":return`( ${it(e.expression)} )`;case\"CondWord\":return ie(e.word);default:{let t=e;throw new Error(`Unsupported conditional expression type: ${t.type}`)}}}var Ft=class{fs;commands=new Map;useDefaultLayout=!1;limits;secureFetch;sleepFn;traceFn;logger;defenseInDepthConfig;coverageWriter;jsBootstrapCode;invokeToolFn;transformPlugins=[];state;constructor(t={}){let s=t.fs??new ze(t.files);this.fs=s,this.useDefaultLayout=!t.cwd&&!t.files;let r=t.cwd||(this.useDefaultLayout?\"/home/user\":\"/\"),n=new Map([[\"HOME\",this.useDefaultLayout?\"/home/user\":\"/\"],[\"PATH\",\"/usr/bin:/bin\"],[\"IFS\",` \t\n`],[\"OSTYPE\",\"linux-gnu\"],[\"MACHTYPE\",\"x86_64-pc-linux-gnu\"],[\"HOSTTYPE\",\"x86_64\"],[\"HOSTNAME\",\"localhost\"],[\"PWD\",r],[\"OLDPWD\",r],[\"OPTIND\",\"1\"],...Object.entries(t.env??{})]);if(this.limits=Mi({...t.executionLimits,...t.maxCallDepth!==void 0&&{maxCallDepth:t.maxCallDepth},...t.maxCommandCount!==void 0&&{maxCommandCount:t.maxCommandCount},...t.maxLoopIterations!==void 0&&{maxLoopIterations:t.maxLoopIterations}}),t.fetch?this.secureFetch=t.fetch:t.network&&(this.secureFetch=Ur(t.network)),this.sleepFn=t.sleep,this.traceFn=t.trace,this.logger=t.logger,this.defenseInDepthConfig=t.defenseInDepth??!0,this.coverageWriter=t.coverage,this.state={env:n,cwd:r,previousDir:\"/home/user\",functions:new Map,localScopes:[],callDepth:0,sourceDepth:0,commandCount:0,lastExitCode:0,lastArg:\"\",startTime:Date.now(),lastBackgroundPid:0,virtualPid:t.processInfo?.pid??1,virtualPpid:t.processInfo?.ppid??0,virtualUid:t.processInfo?.uid??1e3,virtualGid:t.processInfo?.gid??1e3,bashPid:t.processInfo?.pid??1,nextVirtualPid:(t.processInfo?.pid??1)+1,currentLine:1,options:{errexit:!1,pipefail:!1,nounset:!1,xtrace:!1,verbose:!1,posix:!1,allexport:!1,noclobber:!1,noglob:!1,noexec:!1,vi:!1,emacs:!1},shoptOptions:{extglob:!1,dotglob:!1,nullglob:!1,failglob:!1,globstar:!1,globskipdots:!0,nocaseglob:!1,nocasematch:!1,expand_aliases:!1,lastpipe:!1,xpg_echo:!1},inCondition:!1,loopDepth:0,exportedVars:new Set([\"HOME\",\"PATH\",\"PWD\",\"OLDPWD\",...Object.keys(t.env||{})]),readonlyVars:new Set([\"SHELLOPTS\",\"BASHOPTS\"]),hashTable:new Map},this.state.env.set(\"SHELLOPTS\",Zs(this.state.options)),this.state.env.set(\"BASHOPTS\",qs(this.state.shoptOptions)),vn(s,this.useDefaultLayout,{pid:this.state.virtualPid,ppid:this.state.virtualPpid,uid:this.state.virtualUid,gid:this.state.virtualGid}),r!==\"/\"&&s instanceof ze)try{s.mkdirSync(r,{recursive:!0})}catch{}for(let o of hn(t.commands))this.registerCommand(o);if(t.fetch||t.network)for(let o of pn())this.registerCommand(o);if(t.python)for(let o of mn())this.registerCommand(o);let i=typeof t.javascript==\"object\"?t.javascript:Object.create(null);if(t.javascript||i.invokeTool){for(let o of yn())this.registerCommand(o);i.bootstrap&&(this.jsBootstrapCode=i.bootstrap),i.invokeTool&&(this.invokeToolFn=i.invokeTool)}if(t.customCommands)for(let o of t.customCommands)gn(o)?this.registerCommand(wn(o)):this.registerCommand({...o,trusted:o.trusted??!0})}registerCommand(t){this.commands.set(t.name,t);let s=this.fs;if(typeof s.writeFileSync==\"function\"){let r=`#!/bin/bash\n# Built-in command: ${t.name}\n`;try{s.writeFileSync(`/bin/${t.name}`,r)}catch{}try{s.writeFileSync(`/usr/bin/${t.name}`,r)}catch{}}}logResult(t){return this.logger&&(t.stdout&&this.logger.debug(\"stdout\",{output:t.stdout}),t.stderr&&this.logger.info(\"stderr\",{output:t.stderr}),this.logger.info(\"exit\",{exitCode:t.exitCode})),t.stdout=Ji(t.stdout),t.stderr=Ji(t.stderr),t}async exec(t,s){if(this.state.callDepth===0&&(this.state.commandCount=0),this.state.commandCount++,this.state.commandCount>this.limits.maxCommandCount)return{stdout:\"\",stderr:`bash: maximum command count (${this.limits.maxCommandCount}) exceeded (possible infinite loop). Increase with executionLimits.maxCommandCount option.\n`,exitCode:1,env:ve(this.state.env,s?.env)};if(!t.trim())return{stdout:\"\",stderr:\"\",exitCode:0,env:ve(this.state.env,s?.env)};this.logger?.info(\"exec\",{command:t});let r=s?.cwd??this.state.cwd,n,i=r;if(s?.cwd)if(s.env&&\"PWD\"in s.env)n=s.env.PWD;else if(s?.env&&!(\"PWD\"in s.env))try{n=await this.fs.realpath(r),i=n}catch{n=r}else n=r;let o=s?.replaceEnv?new Map:new Map(this.state.env);if(s?.env)for(let[f,d]of Object.entries(s.env))o.set(f,d);n!==void 0&&o.set(\"PWD\",n);let a={...this.state,env:o,cwd:i,functions:new Map(this.state.functions),localScopes:[...this.state.localScopes],options:{...this.state.options},hashTable:this.state.hashTable,groupStdin:Pl(s?.stdin,s?.stdinKind),signal:s?.signal,extraArgs:s?.args},l=t;s?.rawScript||(l=Qi(t));let c=this.defenseInDepthConfig?me.getInstance(this.defenseInDepthConfig):null,u=c?.activate();try{let f=async()=>{let d=fe(l,{maxHeredocSize:this.limits.maxHeredocSize}),p;if(this.transformPlugins.length>0){let g=Object.create(null);for(let b of this.transformPlugins){let m=b.transform({ast:d,metadata:g});d=m.ast,m.metadata&&(g=Ct(g,m.metadata))}p=g}let y={fs:this.fs,commands:this.commands,limits:this.limits,exec:this.exec.bind(this),fetch:this.secureFetch,sleep:this.sleepFn,trace:this.traceFn,coverage:this.coverageWriter,requireDefenseContext:c?.isEnabled()===!0,jsBootstrapCode:this.jsBootstrapCode,invokeTool:this.invokeToolFn},E=await new It(y,a).executeScript(d);return p&&(E.metadata=p),this.logResult(E)};return u?await u.run(f):await f()}catch(f){if(f instanceof j)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:f.exitCode,env:ve(this.state.env,s?.env)});if(f instanceof Pe)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:f.exitCode,env:ve(this.state.env,s?.env)});if(f instanceof Je)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:1,env:ve(this.state.env,s?.env)});if(f instanceof Ht)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:124,env:ve(this.state.env,s?.env)});if(f instanceof J)return this.logResult({stdout:f.stdout,stderr:Le(f.stderr),exitCode:J.EXIT_CODE,env:ve(this.state.env,s?.env)});if(f instanceof Ve)return this.logResult({stdout:\"\",stderr:`bash: security violation: ${Le(f.message)}\n`,exitCode:1,env:ve(this.state.env,s?.env)});if(f.name===\"ParseException\")return this.logResult({stdout:\"\",stderr:`bash: syntax error: ${Le(f.message)}\n`,exitCode:2,env:ve(this.state.env,s?.env)});if(f instanceof Qr)return this.logResult({stdout:\"\",stderr:`bash: ${Le(f.message)}\n`,exitCode:2,env:ve(this.state.env,s?.env)});if(f instanceof RangeError)return this.logResult({stdout:\"\",stderr:`bash: ${Le(f.message)}\n`,exitCode:1,env:ve(this.state.env,s?.env)});throw f}finally{u?.deactivate()}}async readFile(t){return this.fs.readFile(this.fs.resolvePath(this.state.cwd,t))}async writeFile(t,s){return this.fs.writeFile(this.fs.resolvePath(this.state.cwd,t),s)}getCwd(){return this.state.cwd}getEnv(){return Ue(this.state.env)}registerTransformPlugin(t){this.transformPlugins.push(t)}transform(t){let s=Qi(t),r=fe(s,{maxHeredocSize:this.limits.maxHeredocSize}),n=Object.create(null);for(let i of this.transformPlugins){let o=i.transform({ast:r,metadata:n});r=o.ast,o.metadata&&(n=Ct(n,o.metadata))}return{script:Lt(r),ast:r,metadata:n}}};function Qi(e){let t=e.split(`\n`),s=[],r=[];for(let n=0;n<t.length;n++){let i=t[n];if(r.length>0){let l=r[r.length-1];if((l.stripTabs?i.replace(/^\\t+/,\"\"):i)===l.delimiter){s.push(i.trimStart()),r.pop();continue}s.push(i);continue}let o=i.trimStart();s.push(o);let a=/<<(-?)\\s*(['\"]?)([\\w-]+)\\2/g;for(let l of o.matchAll(a)){let c=l[1]===\"-\",u=l[3];r.push({delimiter:u,stripTabs:c})}}return s.join(`\n`)}var Sl=new TextDecoder(\"utf-8\",{fatal:!0});function Ji(e){if(!e)return e;let t=!1;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n>255)return e;n>127&&(t=!0)}if(!t)return e;let s=new Uint8Array(e.length);for(let r=0;r<e.length;r++)s[r]=e.charCodeAt(r);try{return Sl.decode(s)}catch{return e}}function Pl(e,t){if(e!==void 0)return t===\"bytes\"?e:Be(e)}var Cs=class{baseFs;mounts=new Map;constructor(t){if(this.baseFs=t?.base??new ze,t?.mounts)for(let{mountPoint:s,filesystem:r}of t.mounts)this.mount(s,r)}mount(t,s){this.validateMountPath(t);let r=O(t);this.validateMount(r),this.mounts.set(r,{mountPoint:r,filesystem:s})}unmount(t){let s=O(t);if(!this.mounts.has(s))throw new Error(`No filesystem mounted at '${t}'`);this.mounts.delete(s)}getMounts(){return Array.from(this.mounts.values()).map(t=>({mountPoint:t.mountPoint,filesystem:t.filesystem}))}isMountPoint(t){let s=O(t);return this.mounts.has(s)}validateMountPath(t){let s=t.split(\"/\");for(let r of s)if(r===\".\"||r===\"..\")throw new Error(`Invalid mount point '${t}': contains '.' or '..' segments`)}validateMount(t){if(t===\"/\")throw new Error(\"Cannot mount at root '/'\");for(let s of this.mounts.keys())if(s!==t){if(t.startsWith(`${s}/`))throw new Error(`Cannot mount at '${t}': inside existing mount '${s}'`);if(s.startsWith(`${t}/`))throw new Error(`Cannot mount at '${t}': would contain existing mount '${s}'`)}}routePath(t){x(t,\"access\");let s=O(t),r=null,n=0;for(let i of this.mounts.values()){let o=i.mountPoint;if(s===o)return{fs:i.filesystem,relativePath:\"/\"};s.startsWith(`${o}/`)&&o.length>n&&(r=i,n=o.length)}if(r){let i=s.slice(n);return{fs:r.filesystem,relativePath:i||\"/\"}}return{fs:this.baseFs,relativePath:s}}getChildMountPoints(t){let s=O(t),r=s===\"/\"?\"/\":`${s}/`,n=[];for(let i of this.mounts.keys())if(i.startsWith(r)){let a=i.slice(r.length).split(\"/\")[0];a&&!n.includes(a)&&n.push(a)}return n}async readFile(t,s){let{fs:r,relativePath:n}=this.routePath(t);return r.readFile(n,s)}async readFileBytes(t){let{fs:s,relativePath:r}=this.routePath(t);return Vt(s,r)}async readFileBuffer(t){let{fs:s,relativePath:r}=this.routePath(t);return s.readFileBuffer(r)}async writeFile(t,s,r){let{fs:n,relativePath:i}=this.routePath(t);return n.writeFile(i,s,r)}async appendFile(t,s,r){let{fs:n,relativePath:i}=this.routePath(t);return n.appendFile(i,s,r)}async exists(t){let s=O(t);if(this.mounts.has(s)||this.getChildMountPoints(s).length>0)return!0;let{fs:n,relativePath:i}=this.routePath(t);return n.exists(i)}async stat(t){let s=O(t),r=this.mounts.get(s);if(r)try{return await r.filesystem.stat(\"/\")}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}if(this.getChildMountPoints(s).length>0)try{return await this.baseFs.stat(s)}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}let{fs:i,relativePath:o}=this.routePath(t);return i.stat(o)}async lstat(t){let s=O(t),r=this.mounts.get(s);if(r)try{return await r.filesystem.lstat(\"/\")}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}if(this.getChildMountPoints(s).length>0)try{return await this.baseFs.lstat(s)}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}let{fs:i,relativePath:o}=this.routePath(t);return i.lstat(o)}async mkdir(t,s){let r=O(t);if(this.mounts.has(r)){if(s?.recursive)return;throw new Error(`EEXIST: directory already exists, mkdir '${t}'`)}if(this.getChildMountPoints(r).length>0&&s?.recursive)return;let{fs:i,relativePath:o}=this.routePath(t);return i.mkdir(o,s)}async readdir(t){let s=O(t),r=new Set,n=null,{fs:i,relativePath:o}=this.routePath(t);try{let l=await i.readdir(o);for(let c of l)r.add(c)}catch(l){let c=l.code,u=l.message||\"\";if(c!==\"ENOENT\"&&!u.includes(\"ENOENT\"))throw l;n=l}let a=this.getChildMountPoints(s);for(let l of a)r.add(l);if(r.size===0&&n&&!this.mounts.has(s))throw n;return Array.from(r).sort()}async rm(t,s){let r=O(t);if(this.mounts.has(r))throw new Error(`EBUSY: mount point, cannot remove '${t}'`);if(this.getChildMountPoints(r).length>0)throw new Error(`EBUSY: contains mount points, cannot remove '${t}'`);let{fs:i,relativePath:o}=this.routePath(t);return i.rm(o,s)}async cp(t,s,r){let n=this.routePath(t),i=this.routePath(s);return n.fs===i.fs?n.fs.cp(n.relativePath,i.relativePath,r):this.crossMountCopy(t,s,r)}async mv(t,s){let r=O(t);if(this.mounts.has(r))throw new Error(`EBUSY: mount point, cannot move '${t}'`);let n=this.routePath(t),i=this.routePath(s);if(n.fs===i.fs)return n.fs.mv(n.relativePath,i.relativePath);await this.cp(t,s,{recursive:!0}),await this.rm(t,{recursive:!0})}resolvePath(t,s){return qe(t,s)}getAllPaths(){let t=new Set;for(let s of this.baseFs.getAllPaths())t.add(s);for(let s of this.mounts.keys()){let r=s.split(\"/\").filter(Boolean),n=\"\";for(let o of r)n=`${n}/${o}`,t.add(n);let i=this.mounts.get(s);if(i)for(let o of i.filesystem.getAllPaths())o===\"/\"?t.add(s):t.add(`${s}${o}`)}return Array.from(t).sort()}async chmod(t,s){let r=O(t),n=this.mounts.get(r);if(n)return n.filesystem.chmod(\"/\",s);let{fs:i,relativePath:o}=this.routePath(t);return i.chmod(o,s)}async symlink(t,s){let{fs:r,relativePath:n}=this.routePath(s);return r.symlink(t,n)}async link(t,s){let r=this.routePath(t),n=this.routePath(s);if(r.fs!==n.fs)throw new Error(`EXDEV: cross-device link not permitted, link '${t}' -> '${s}'`);return r.fs.link(r.relativePath,n.relativePath)}async readlink(t){let{fs:s,relativePath:r}=this.routePath(t);return s.readlink(r)}async realpath(t){let s=O(t);if(this.mounts.get(s))return s;let{fs:n,relativePath:i}=this.routePath(t),o=await n.realpath(i);for(let[a,l]of this.mounts)if(s===a||s.startsWith(`${a}/`))return o===\"/\"?a:`${a}${o}`;return o}async crossMountCopy(t,s,r){let n=await this.lstat(t);if(n.isFile){let i=await this.readFileBuffer(t);await this.writeFile(s,i),await this.chmod(s,n.mode)}else if(n.isDirectory){if(!r?.recursive)throw new Error(`cp: ${t} is a directory (not copied)`);await this.mkdir(s,{recursive:!0});let i=await this.readdir(t);for(let o of i){let a=Ge(t,o),l=Ge(s,o);await this.crossMountCopy(a,l,r)}}else if(n.isSymbolicLink){let i=await this.readlink(t);await this.symlink(i,s)}}async utimes(t,s,r){let{fs:n,relativePath:i}=this.routePath(t);return n.utimes(i,s,r)}};import*as q from\"node:fs\";import*as ae from\"node:path\";import*as Se from\"node:fs\";import*as ce from\"node:path\";function Ne(e,t){if(e===t)return!0;let s=e[t.length];return(s===\"/\"||s===\"\\\\\")&&e.startsWith(t)}function at(e,t){try{let s=Se.realpathSync(e);return Ne(s,t)?s:null}catch(s){if(s.code===\"ENOENT\"){let r=ce.dirname(e);if(r===e)return null;let n=at(r,t);if(n===null)return null;try{if(Se.lstatSync(e).isSymbolicLink()){let o=Se.readlinkSync(e),a=ce.isAbsolute(o)?o:ce.resolve(ce.dirname(e),o);if(at(a,t)===null)return null}}catch{}return ce.join(n,ce.basename(e))}return null}}function Ns(e,t,s){let r=at(e,s);if(r===null)return null;let n=ce.resolve(e),i=n.slice(t.length),o=r.slice(s.length);if(i!==o)return null;try{if(Se.lstatSync(n).isSymbolicLink())return null}catch{}return r}function Os(e,t){if(!Se.existsSync(e))throw new Error(`${t} root does not exist`);if(!Se.statSync(e).isDirectory())throw new Error(`${t} root is not a directory`)}function eo(e,t){if(!ce.isAbsolute(e))return{withinRoot:!0,relativePath:e};let s;try{s=Se.realpathSync(e)}catch{s=ce.resolve(e)}return Ne(s,t)?{withinRoot:!0,relativePath:s.slice(t.length).replace(/\\\\/g,\"/\")||\"/\"}:{withinRoot:!1,safeName:ce.basename(e)}}function xs(e,t,s,r){let n=e;if(n.path===void 0){for(let o of r)if(n.message?.includes(o))throw e}let i=n.code||\"EIO\";throw new Error(`${i}: ${s} '${t}'`)}var Al=[\"ELOOP\",\"EFBIG\",\"EPERM\"],kl=\"/home/user/project\",$t=class{root;canonicalRoot;mountPoint;readOnly;maxFileReadSize;allowSymlinks;memory=new Map;deleted=new Set;constructor(t){this.root=ae.resolve(t.root);let s=t.mountPoint??kl;if(this.mountPoint=s===\"/\"?\"/\":s.replace(/\\/+$/,\"\"),!this.mountPoint.startsWith(\"/\"))throw new Error(`Mount point must be an absolute path: ${s}`);this.readOnly=t.readOnly??!1,this.maxFileReadSize=t.maxFileReadSize??10485760,this.allowSymlinks=t.allowSymlinks??!1,Os(this.root,\"OverlayFs\"),this.canonicalRoot=q.realpathSync(this.root),this.createMountPointDirs()}assertWritable(t){if(this.readOnly)throw new Error(`EROFS: read-only file system, ${t}`)}createMountPointDirs(){let t=this.mountPoint.split(\"/\").filter(Boolean),s=\"\";for(let r of t)s+=`/${r}`,this.memory.has(s)||this.memory.set(s,{type:\"directory\",mode:493,mtime:new Date});this.memory.has(\"/\")||this.memory.set(\"/\",{type:\"directory\",mode:493,mtime:new Date})}getMountPoint(){return this.mountPoint}mkdirSync(t,s){let n=O(t).split(\"/\").filter(Boolean),i=\"\";for(let o of n)i+=`/${o}`,this.memory.has(i)||this.memory.set(i,{type:\"directory\",mode:493,mtime:new Date})}writeFileSync(t,s){let r=O(t),n=this.getDirname(r);n!==\"/\"&&this.mkdirSync(n);let i=s instanceof Uint8Array?s:new TextEncoder().encode(s);this.memory.set(r,{type:\"file\",content:i,mode:420,mtime:new Date})}getDirname(t){let s=t.lastIndexOf(\"/\");return s===0?\"/\":t.slice(0,s)}getRelativeToMount(t){return this.mountPoint===\"/\"?t:t===this.mountPoint?\"/\":t.startsWith(`${this.mountPoint}/`)?t.slice(this.mountPoint.length):null}toRealPath(t){let s=O(t),r=this.getRelativeToMount(s);if(r===null)return null;let n=ae.join(this.root,r),i=ae.resolve(n);return Ne(i,this.root)?i:null}resolveRealPath_(t){return t?this.allowSymlinks?at(t,this.canonicalRoot):Ns(t,this.root,this.canonicalRoot):null}resolveRealPathParent_(t){if(!t)return null;let s=ae.dirname(t),r=this.resolveRealPath_(s);return r===null?null:ae.join(r,ae.basename(t))}sanitizeError(t,s,r){xs(t,s,r,Al)}ensureParentDirs(t){let s=st(t);s!==\"/\"&&(this.memory.has(s)||(this.ensureParentDirs(s),this.memory.set(s,{type:\"directory\",mode:493,mtime:new Date})),this.deleted.delete(s))}async existsInOverlay(t){let s=O(t);if(this.deleted.has(s))return!1;if(this.memory.has(s))return!0;let r=this.resolveRealPathParent_(this.toRealPath(s));if(!r)return!1;try{return await q.promises.lstat(r),!0}catch{return!1}}async readFile(t,s){let r=await this.readFileBuffer(t),n=be(s);return Me(r,n)}async readFileBytes(t){let s=await this.readFileBuffer(t);return Me(s,\"binary\")}async readFileBuffer(t,s=new Set){x(t,\"open\");let r=O(t);if(s.has(r))throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`);if(s.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, open '${t}'`);let n=this.memory.get(r);if(n){if(n.type===\"symlink\"){let o=this.resolveSymlink(r,n.target);return this.readFileBuffer(o,s)}if(n.type!==\"file\")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);return n.content}let i=this.resolveRealPath_(this.toRealPath(r));if(!i)throw new Error(`ENOENT: no such file or directory, open '${t}'`);try{let o=await q.promises.lstat(i);if(o.isSymbolicLink()){if(!this.allowSymlinks)throw new Error(`ENOENT: no such file or directory, open '${t}'`);let c=await q.promises.readlink(i),u=this.realTargetToVirtual(r,c),f=this.resolveSymlink(r,u);return this.readFileBuffer(f,s)}if(o.isDirectory())throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);if(this.maxFileReadSize>0&&o.size>this.maxFileReadSize)throw new Error(`EFBIG: file too large, read '${t}' (${o.size} bytes, max ${this.maxFileReadSize})`);let a=this.allowSymlinks?q.constants.O_RDONLY:q.constants.O_RDONLY|q.constants.O_NOFOLLOW,l=await q.promises.open(i,a);try{let c=await l.readFile();return new Uint8Array(c)}finally{await l.close()}}catch(o){let a=o.code;if(a===\"ENOENT\")throw new Error(`ENOENT: no such file or directory, open '${t}'`);if(a===\"ELOOP\")throw new Error(`ENOENT: no such file or directory, open '${t}'`);this.sanitizeError(o,t,\"open\")}}async writeFile(t,s,r){x(t,\"write\"),this.assertWritable(`write '${t}'`);let n=O(t);this.ensureParentDirs(n);let i=be(r),o=Fe(s,i);this.memory.set(n,{type:\"file\",content:o,mode:420,mtime:new Date}),this.deleted.delete(n)}async appendFile(t,s,r){x(t,\"append\"),this.assertWritable(`append '${t}'`);let n=O(t),i=be(r),o=Fe(s,i),a;try{a=await this.readFileBuffer(n)}catch{a=new Uint8Array(0)}let l=new Uint8Array(a.length+o.length);l.set(a),l.set(o,a.length),this.ensureParentDirs(n),this.memory.set(n,{type:\"file\",content:l,mode:420,mtime:new Date}),this.deleted.delete(n)}async exists(t){return t.includes(\"\\0\")?!1:this.existsInOverlay(t)}async stat(t,s=new Set){x(t,\"stat\");let r=O(t);if(s.has(r))throw new Error(`ELOOP: too many levels of symbolic links, stat '${t}'`);if(s.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, stat '${t}'`);let n=this.memory.get(r);if(n){if(n.type===\"symlink\"){let a=this.resolveSymlink(r,n.target);return this.stat(a,s)}let o=0;return n.type===\"file\"&&(o=n.content.length),{isFile:n.type===\"file\",isDirectory:n.type===\"directory\",isSymbolicLink:!1,mode:n.mode,size:o,mtime:n.mtime}}let i=this.resolveRealPath_(this.toRealPath(r));if(!i)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);try{let o=await q.promises.lstat(i);if(o.isSymbolicLink()){if(!this.allowSymlinks)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);let a=await q.promises.readlink(i),l=this.realTargetToVirtual(r,a),c=this.resolveSymlink(r,l);return this.stat(c,s)}return{isFile:o.isFile(),isDirectory:o.isDirectory(),isSymbolicLink:!1,mode:o.mode,size:o.size,mtime:o.mtime}}catch(o){if(o.code===\"ENOENT\")throw new Error(`ENOENT: no such file or directory, stat '${t}'`);this.sanitizeError(o,t,\"stat\")}}async lstat(t){x(t,\"lstat\");let s=O(t);if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);let r=this.memory.get(s);if(r){if(r.type===\"symlink\")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:r.mode,size:r.target.length,mtime:r.mtime};let i=0;return r.type===\"file\"&&(i=r.content.length),{isFile:r.type===\"file\",isDirectory:r.type===\"directory\",isSymbolicLink:!1,mode:r.mode,size:i,mtime:r.mtime}}let n=this.resolveRealPathParent_(this.toRealPath(s));if(!n)throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);try{let i=await q.promises.lstat(n);return{isFile:i.isFile(),isDirectory:i.isDirectory(),isSymbolicLink:i.isSymbolicLink(),mode:i.mode,size:i.size,mtime:i.mtime}}catch(i){if(i.code===\"ENOENT\")throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);this.sanitizeError(i,t,\"lstat\")}}resolveSymlink(t,s){return ct(t,s)}realTargetToVirtual(t,s){let r=eo(s,this.canonicalRoot);if(r.withinRoot){if(!ae.isAbsolute(s))return s;let n=r.relativePath;return this.mountPoint===\"/\"?n:`${this.mountPoint}${n}`}return r.safeName}async mkdir(t,s){x(t,\"mkdir\"),this.assertWritable(`mkdir '${t}'`);let r=O(t);if(await this.existsInOverlay(r)){if(!s?.recursive)throw new Error(`EEXIST: file already exists, mkdir '${t}'`);return}let i=st(r);if(i!==\"/\"&&!await this.existsInOverlay(i))if(s?.recursive)await this.mkdir(i,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${t}'`);this.memory.set(r,{type:\"directory\",mode:493,mtime:new Date}),this.deleted.delete(r)}async readdirCore(t,s){if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);let r=new Map,n=new Set,i=s===\"/\"?\"/\":`${s}/`;for(let a of this.deleted)if(a.startsWith(i)){let l=a.slice(i.length),c=l.split(\"/\")[0];c&&!l.includes(\"/\",c.length)&&n.add(c)}for(let[a,l]of this.memory)if(a!==s&&a.startsWith(i)){let c=a.slice(i.length),u=c.split(\"/\")[0];u&&!n.has(u)&&!c.includes(\"/\",1)&&r.set(u,{name:u,isFile:l.type===\"file\",isDirectory:l.type===\"directory\",isSymbolicLink:l.type===\"symlink\"})}let o=this.resolveRealPath_(this.toRealPath(s));if(o)try{if(!this.allowSymlinks&&(await q.promises.lstat(o)).isSymbolicLink()){if(!this.memory.has(s))throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);return r}let a=await q.promises.readdir(o,{withFileTypes:!0});for(let l of a)!n.has(l.name)&&!r.has(l.name)&&r.set(l.name,{name:l.name,isFile:l.isFile(),isDirectory:l.isDirectory(),isSymbolicLink:l.isSymbolicLink()})}catch(a){if(a.code===\"ENOENT\"){if(!this.memory.has(s))throw new Error(`ENOENT: no such file or directory, scandir '${t}'`)}else a.code!==\"ENOTDIR\"&&this.sanitizeError(a,t,\"scandir\")}return r}async resolveForReaddir(t,s=!1){let r=O(t),n=new Set,i=s,o=this.memory.get(r);for(;o&&o.type===\"symlink\";){if(n.has(r))throw new Error(`ELOOP: too many levels of symbolic links, scandir '${t}'`);n.add(r),i=!0,r=this.resolveSymlink(r,o.target),o=this.memory.get(r)}if(o)return{normalized:r,outsideOverlay:!1};if(this.getRelativeToMount(r)===null)return{normalized:r,outsideOverlay:!0};let l=this.resolveRealPath_(this.toRealPath(r));if(!l)return{normalized:r,outsideOverlay:!0};try{if((await q.promises.lstat(l)).isSymbolicLink()){if(!this.allowSymlinks)return{normalized:r,outsideOverlay:!0};let u=await q.promises.readlink(l),f=this.realTargetToVirtual(r,u),d=this.resolveSymlink(r,f);return this.resolveForReaddir(d,!0)}return{normalized:r,outsideOverlay:!1}}catch{return i?{normalized:r,outsideOverlay:!0}:{normalized:r,outsideOverlay:!1}}}async readdir(t){x(t,\"scandir\");let{normalized:s,outsideOverlay:r}=await this.resolveForReaddir(t);if(r)return[];let n=await this.readdirCore(t,s);return Array.from(n.keys()).sort((i,o)=>i<o?-1:i>o?1:0)}async readdirWithFileTypes(t){x(t,\"scandir\");let{normalized:s,outsideOverlay:r}=await this.resolveForReaddir(t);if(r)return[];let n=await this.readdirCore(t,s);return Array.from(n.values()).sort((i,o)=>i.name<o.name?-1:i.name>o.name?1:0)}async rm(t,s){x(t,\"rm\"),this.assertWritable(`rm '${t}'`);let r=O(t);if(!await this.existsInOverlay(r)){if(s?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${t}'`)}try{if((await this.stat(r)).isDirectory){let o=await this.readdir(r);if(o.length>0){if(!s?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${t}'`);for(let a of o){let l=r===\"/\"?`/${a}`:`${r}/${a}`;await this.rm(l,s)}}}}catch(i){if(i instanceof Error&&(i.message.includes(\"ENOTEMPTY\")||i.message.includes(\"EISDIR\")))throw i}this.memory.delete(r),this.existsOnRealFs(r)&&this.deleted.add(r)}existsOnRealFs(t){let s=this.toRealPath(t),r=this.resolveRealPathParent_(s);if(!r)return!1;try{return q.lstatSync(r),!0}catch{return!1}}async cp(t,s,r){x(t,\"cp\"),x(s,\"cp\"),this.assertWritable(`cp '${s}'`);let n=O(t),i=O(s);if(!await this.existsInOverlay(n))throw new Error(`ENOENT: no such file or directory, cp '${t}'`);let a=await this.stat(n);if(a.isFile){let l=await this.readFileBuffer(n);await this.writeFile(i,l)}else if(a.isDirectory){if(!r?.recursive)throw new Error(`EISDIR: is a directory, cp '${t}'`);await this.mkdir(i,{recursive:!0});let l=await this.readdir(n);for(let c of l){let u=n===\"/\"?`/${c}`:`${n}/${c}`,f=i===\"/\"?`/${c}`:`${i}/${c}`;await this.cp(u,f,r)}}}async mv(t,s){this.assertWritable(`mv '${s}'`),await this.cp(t,s,{recursive:!0}),await this.rm(t,{recursive:!0})}resolvePath(t,s){return qe(t,s)}getAllPaths(){let t=new Set(this.memory.keys());for(let s of this.deleted)t.delete(s);return this.scanRealFs(\"/\",t),Array.from(t)}scanRealFs(t,s){if(this.deleted.has(t))return;let r=this.resolveRealPath_(this.toRealPath(t));if(r)try{let n=q.readdirSync(r);for(let i of n){let o=t===\"/\"?`/${i}`:`${t}/${i}`;if(this.deleted.has(o))continue;s.add(o);let a=ae.join(r,i);q.lstatSync(a).isDirectory()&&this.scanRealFs(o,s)}}catch{}}async chmod(t,s){x(t,\"chmod\"),this.assertWritable(`chmod '${t}'`);let r=O(t);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, chmod '${t}'`);let i=this.memory.get(r);if(i){i.mode=s;return}let o=await this.stat(r);if(o.isFile){let a=await this.readFileBuffer(r);this.memory.set(r,{type:\"file\",content:a,mode:s,mtime:new Date})}else o.isDirectory&&this.memory.set(r,{type:\"directory\",mode:s,mtime:new Date})}async symlink(t,s){if(!this.allowSymlinks)throw new Error(`EPERM: operation not permitted, symlink '${s}'`);x(s,\"symlink\"),this.assertWritable(`symlink '${s}'`);let r=O(s);if(await this.existsInOverlay(r))throw new Error(`EEXIST: file already exists, symlink '${s}'`);this.ensureParentDirs(r),this.memory.set(r,{type:\"symlink\",target:t,mode:511,mtime:new Date}),this.deleted.delete(r)}async link(t,s){x(t,\"link\"),x(s,\"link\"),this.assertWritable(`link '${s}'`);let r=O(t),n=O(s);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, link '${t}'`);let o=await this.stat(r);if(!o.isFile)throw new Error(`EPERM: operation not permitted, link '${t}'`);if(await this.existsInOverlay(n))throw new Error(`EEXIST: file already exists, link '${s}'`);let l=await this.readFileBuffer(r);this.ensureParentDirs(n),this.memory.set(n,{type:\"file\",content:l,mode:o.mode,mtime:new Date}),this.deleted.delete(n)}async readlink(t){x(t,\"readlink\");let s=O(t);if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);let r=this.memory.get(s);if(r){if(r.type!==\"symlink\")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);return r.target}let n=this.resolveRealPathParent_(this.toRealPath(s));if(!n)throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);try{let i=await q.promises.readlink(n);if(!ae.isAbsolute(i)){let o=ae.resolve(ae.dirname(n),i),a;try{a=q.realpathSync(o)}catch{a=o}if(!Ne(a,this.canonicalRoot))return ae.basename(i)}return this.realTargetToVirtual(s,i)}catch(i){if(i.code===\"ENOENT\")throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);if(i.code===\"EINVAL\")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);this.sanitizeError(i,t,\"readlink\")}}async realpath(t){x(t,\"realpath\");let s=O(t),r=new Set,n=async a=>{let l=a===\"/\"?[]:a.slice(1).split(\"/\"),c=\"\";for(let u of l){if(c=`${c}/${u}`,r.has(c))throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(this.deleted.has(c))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);let f=this.memory.get(c),d=0,p=40;for(;f&&f.type===\"symlink\"&&d<p;){if(r.add(c),c=this.resolveSymlink(c,f.target),d++,r.has(c))throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(this.deleted.has(c))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);f=this.memory.get(c)}if(d>=p)throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(!f){let y=this.toRealPath(c),h=this.resolveRealPath_(y);if(h)try{if((await q.promises.lstat(h)).isSymbolicLink()){if(!this.allowSymlinks)throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);let E=await q.promises.readlink(h),g=this.realTargetToVirtual(c,E);return r.add(c),c=this.resolveSymlink(c,g),n(c)}}catch(w){if(w.code===\"ENOENT\")throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);this.sanitizeError(w,t,\"realpath\")}else if(!this.allowSymlinks){let w=this.resolveRealPathParent_(y);if(w)try{if((await q.promises.lstat(w)).isSymbolicLink())throw new Error(`ENOENT: no such file or directory, realpath '${t}'`)}catch(E){if(E.message?.includes(\"ENOENT\")||E.message?.includes(\"ELOOP\"))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);this.sanitizeError(E,t,\"realpath\")}}}}return c||\"/\"},i=await n(s);if(!await this.existsInOverlay(i))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);return i}async utimes(t,s,r){x(t,\"utimes\"),this.assertWritable(`utimes '${t}'`);let n=O(t);if(!await this.existsInOverlay(n))throw new Error(`ENOENT: no such file or directory, utimes '${t}'`);let o=this.memory.get(n);if(o){o.mtime=r;return}let a=await this.stat(n);if(a.isFile){let l=await this.readFileBuffer(n);this.memory.set(n,{type:\"file\",content:l,mode:a.mode,mtime:r})}else a.isDirectory&&this.memory.set(n,{type:\"directory\",mode:a.mode,mtime:r})}};import*as I from\"node:fs\";import*as U from\"node:path\";var _l=[\"EACCES\",\"escaping sandbox\",\"EFBIG\"],Ts=class{root;canonicalRoot;maxFileReadSize;allowSymlinks;constructor(t){this.root=U.resolve(t.root),this.maxFileReadSize=t.maxFileReadSize??10485760,this.allowSymlinks=t.allowSymlinks??!1,Os(this.root,\"ReadWriteFs\"),this.canonicalRoot=I.realpathSync(this.root)}resolveAndValidate(t,s){let r=this.allowSymlinks?at(t,this.canonicalRoot):Ns(t,this.root,this.canonicalRoot);if(r===null)throw new Error(`EACCES: permission denied, '${s}' resolves outside sandbox`);return r}validateParent(t,s){let r=U.dirname(t),n=this.resolveAndValidate(r,s);return U.join(n,U.basename(t))}toRealPath(t){let s=O(t),r=U.join(this.root,s);return U.resolve(r)}async readFile(t,s){let r=await this.readFileBuffer(t),n=be(s);return Me(r,n)}async readFileBytes(t){let s=await this.readFileBuffer(t);return Me(s,\"binary\")}async readFileBuffer(t){x(t,\"open\");let s=this.toRealPath(t),r=this.resolveAndValidate(s,t);try{let n=this.allowSymlinks?I.constants.O_RDONLY:I.constants.O_RDONLY|I.constants.O_NOFOLLOW,i=await I.promises.open(r,n);try{if(this.maxFileReadSize>0){let a=await i.stat();if(a.size>this.maxFileReadSize)throw new Error(`EFBIG: file too large, read '${t}' (${a.size} bytes, max ${this.maxFileReadSize})`)}let o=await i.readFile();return new Uint8Array(o)}finally{await i.close()}}catch(n){let i=n;if(i.code===\"ENOENT\")throw new Error(`ENOENT: no such file or directory, open '${t}'`);if(i.code===\"EISDIR\")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);if(i.code===\"ELOOP\")throw new Error(`EACCES: permission denied, '${t}' is a symlink`);this.sanitizeError(n,t,\"open\")}}async writeFile(t,s,r){x(t,\"write\");let n=this.toRealPath(t),i=this.resolveAndValidate(n,t),o=be(r),a=Fe(s,o),l=U.dirname(i);try{await I.promises.mkdir(l,{recursive:!0}),i=this.resolveAndValidate(n,t);let c=this.allowSymlinks?0:I.constants.O_NOFOLLOW,u=I.constants.O_WRONLY|I.constants.O_CREAT|I.constants.O_TRUNC|c,f=await I.promises.open(i,u,438);try{await f.writeFile(a)}finally{await f.close()}}catch(c){if(c.code===\"ELOOP\")throw new Error(`EACCES: permission denied, '${t}' is a symlink`);this.sanitizeError(c,t,\"write\")}}async appendFile(t,s,r){x(t,\"append\");let n=this.toRealPath(t),i=this.resolveAndValidate(n,t),o=be(r),a=Fe(s,o),l=U.dirname(i);try{await I.promises.mkdir(l,{recursive:!0}),i=this.resolveAndValidate(n,t);let c=this.allowSymlinks?0:I.constants.O_NOFOLLOW,u=I.constants.O_WRONLY|I.constants.O_CREAT|I.constants.O_APPEND|c,f=await I.promises.open(i,u,438);try{await f.writeFile(a)}finally{await f.close()}}catch(c){if(c.code===\"ELOOP\")throw new Error(`EACCES: permission denied, '${t}' is a symlink`);this.sanitizeError(c,t,\"append\")}}async exists(t){if(t.includes(\"\\0\"))return!1;let s=this.toRealPath(t);try{let r=this.resolveAndValidate(s,t);return await I.promises.access(r),!0}catch{return!1}}async stat(t){x(t,\"stat\");let s=this.toRealPath(t),r=this.resolveAndValidate(s,t);try{let n=await I.promises.lstat(r);if(!this.allowSymlinks&&n.isSymbolicLink())throw new Error(`EACCES: permission denied, '${t}' is a symlink`);return{isFile:n.isFile(),isDirectory:n.isDirectory(),isSymbolicLink:n.isSymbolicLink(),mode:n.mode,size:n.size,mtime:n.mtime}}catch(n){if(n.code===\"ENOENT\")throw new Error(`ENOENT: no such file or directory, stat '${t}'`);this.sanitizeError(n,t,\"stat\")}}async lstat(t){x(t,\"lstat\");let s=this.toRealPath(t),r=this.validateParent(s,t);try{let n=await I.promises.lstat(r);return{isFile:n.isFile(),isDirectory:n.isDirectory(),isSymbolicLink:n.isSymbolicLink(),mode:n.mode,size:n.size,mtime:n.mtime}}catch(n){if(n.code===\"ENOENT\")throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);this.sanitizeError(n,t,\"lstat\")}}async mkdir(t,s){x(t,\"mkdir\");let r=this.toRealPath(t),n=this.resolveAndValidate(r,t);try{await I.promises.mkdir(n,{recursive:s?.recursive})}catch(i){let o=i;if(o.code===\"EEXIST\")throw new Error(`EEXIST: file already exists, mkdir '${t}'`);if(o.code===\"ENOENT\")throw new Error(`ENOENT: no such file or directory, mkdir '${t}'`);this.sanitizeError(i,t,\"mkdir\")}}async readdir(t){return(await this.readdirWithFileTypes(t)).map(r=>r.name)}async readdirWithFileTypes(t){x(t,\"scandir\");let s=this.toRealPath(t),r=this.resolveAndValidate(s,t);try{if(!this.allowSymlinks&&(await I.promises.lstat(r)).isSymbolicLink())throw new Error(`EACCES: permission denied, '${t}' is a symlink`);return(await I.promises.readdir(r,{withFileTypes:!0})).map(i=>({name:i.name,isFile:i.isFile(),isDirectory:i.isDirectory(),isSymbolicLink:i.isSymbolicLink()})).sort((i,o)=>i.name<o.name?-1:i.name>o.name?1:0)}catch(n){let i=n;if(i.code===\"ENOENT\")throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);if(i.code===\"ENOTDIR\")throw new Error(`ENOTDIR: not a directory, scandir '${t}'`);this.sanitizeError(n,t,\"scandir\")}}async rm(t,s){x(t,\"rm\");let r=this.toRealPath(t),n=this.resolveAndValidate(r,t);try{await I.promises.rm(n,{recursive:s?.recursive??!1,force:s?.force??!1})}catch(i){let o=i;if(o.code===\"ENOENT\"&&!s?.force)throw new Error(`ENOENT: no such file or directory, rm '${t}'`);if(o.code===\"ENOTEMPTY\")throw new Error(`ENOTEMPTY: directory not empty, rm '${t}'`);this.sanitizeError(i,t,\"rm\")}}async cp(t,s,r){x(t,\"cp\"),x(s,\"cp\");let n=this.toRealPath(t),i=this.toRealPath(s),o=this.resolveAndValidate(n,t),a=this.resolveAndValidate(i,s);try{await I.promises.cp(o,a,{recursive:r?.recursive??!1,filter:async l=>{try{if(I.lstatSync(l).isSymbolicLink()){let u=await I.promises.realpath(l).catch(()=>null);return u===null?!1:Ne(u,this.canonicalRoot)}return!0}catch(c){return c.code===\"ENOENT\"}}})}catch(l){let c=l;if(c.code===\"ENOENT\")throw new Error(`ENOENT: no such file or directory, cp '${t}'`);if(c.code===\"EISDIR\")throw new Error(`EISDIR: is a directory, cp '${t}'`);this.sanitizeError(l,t,\"cp\")}}async mv(t,s){x(t,\"mv\"),x(s,\"mv\");let r=this.toRealPath(t),n=this.toRealPath(s),i=this.validateParent(r,t),o=this.validateParent(n,s);try{if((await I.promises.lstat(i)).isSymbolicLink()){let c=await I.promises.readlink(i),u=U.resolve(U.dirname(o),c),f=await I.promises.realpath(u).catch(()=>u);if(!Ne(f,this.canonicalRoot))throw new Error(`EACCES: permission denied, mv '${t}' -> '${s}' would create symlink escaping sandbox`)}}catch(l){let c=l;if(c.code===\"ENOENT\")throw new Error(`ENOENT: no such file or directory, mv '${t}'`);if(c.message?.includes(\"EACCES\")||c.message?.includes(\"escaping sandbox\"))throw l}let a=U.dirname(o);try{await I.promises.mkdir(a,{recursive:!0})}catch(l){this.sanitizeError(l,s,\"mv\")}try{await I.promises.rename(i,o)}catch(l){let c=l;if(c.code===\"ENOENT\")throw new Error(`ENOENT: no such file or directory, mv '${t}'`);if(c.code===\"EXDEV\"){await this.cp(t,s,{recursive:!0}),await this.rm(t,{recursive:!0});return}this.sanitizeError(l,t,\"mv\")}try{if(I.lstatSync(o).isDirectory()&&this.findEscapingSymlinks(o).length>0)throw await I.promises.rename(o,i),new Error(`EACCES: permission denied, mv '${t}' -> '${s}' would create symlinks escaping sandbox`)}catch(l){if(l.message?.includes(\"EACCES\")||l.message?.includes(\"escaping sandbox\"))throw l}}resolvePath(t,s){return qe(t,s)}getAllPaths(){let t=[];return this.scanDir(\"/\",t),t}sanitizeError(t,s,r){xs(t,s,r,_l)}findEscapingSymlinks(t){let s=[];try{let r=I.readdirSync(t);for(let n of r){let i=U.join(t,n);try{let o=I.lstatSync(i);if(o.isSymbolicLink()){let a=I.readlinkSync(i),l=U.resolve(t,a),c;try{c=I.realpathSync(l)}catch{c=l}Ne(c,this.canonicalRoot)||s.push(i)}else o.isDirectory()&&s.push(...this.findEscapingSymlinks(i))}catch{}}}catch{}return s}scanDir(t,s){let r=this.toRealPath(t),n;try{n=this.resolveAndValidate(r,t)}catch{return}try{let i=I.readdirSync(n);for(let o of i){let a=t===\"/\"?`/${o}`:`${t}/${o}`;s.push(a);let l=U.join(n,o);I.lstatSync(l).isDirectory()&&this.scanDir(a,s)}}catch{}}async chmod(t,s){x(t,\"chmod\");let r=this.toRealPath(t),n=this.resolveAndValidate(r,t);try{let i=this.allowSymlinks?I.constants.O_RDONLY:I.constants.O_RDONLY|I.constants.O_NOFOLLOW,o=await I.promises.open(n,i);try{await o.chmod(s)}finally{await o.close()}}catch(i){let o=i;if(o.code===\"ENOENT\")throw new Error(`ENOENT: no such file or directory, chmod '${t}'`);if(o.code===\"ELOOP\")throw new Error(`EACCES: permission denied, '${t}' is a symlink`);this.sanitizeError(i,t,\"chmod\")}}async symlink(t,s){if(!this.allowSymlinks)throw new Error(`EPERM: operation not permitted, symlink '${s}'`);x(s,\"symlink\");let r=this.toRealPath(s),n=this.validateParent(r,s),i=O(s),o=O(U.dirname(i)),a=t.startsWith(\"/\")?O(t):O(o===\"/\"?`/${t}`:`${o}/${t}`),l=U.join(this.canonicalRoot,a),c=U.dirname(n),u=t.startsWith(\"/\")?l:U.relative(c,l)||\".\";try{await I.promises.symlink(u,n)}catch(f){if(f.code===\"EEXIST\")throw new Error(`EEXIST: file already exists, symlink '${s}'`);this.sanitizeError(f,s,\"symlink\")}}async link(t,s){x(t,\"link\"),x(s,\"link\");let r=this.toRealPath(t),n=this.toRealPath(s),i=this.resolveAndValidate(r,t),o=this.resolveAndValidate(n,s);try{await I.promises.link(i,o)}catch(a){let l=a;if(l.code===\"ENOENT\")throw new Error(`ENOENT: no such file or directory, link '${t}'`);if(l.code===\"EEXIST\")throw new Error(`EEXIST: file already exists, link '${s}'`);if(l.code===\"EPERM\")throw new Error(`EPERM: operation not permitted, link '${t}'`);this.sanitizeError(a,t,\"link\")}}async readlink(t){x(t,\"readlink\");let s=this.toRealPath(t),r=this.validateParent(s,t);try{let n=await I.promises.readlink(r),i=O(t),o=U.dirname(i),a=U.isAbsolute(n)?n:U.resolve(U.dirname(r),n),l=await I.promises.realpath(a).catch(()=>a);if(Ne(l,this.canonicalRoot)){let c=l.slice(this.canonicalRoot.length)||\"/\";return o===\"/\"?c.startsWith(\"/\")?c.slice(1)||\".\":c:U.relative(o,c)}return U.basename(n)}catch(n){let i=n;if(i.code===\"ENOENT\")throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);if(i.code===\"EINVAL\")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);this.sanitizeError(n,t,\"readlink\")}}async realpath(t){x(t,\"realpath\");let s=this.toRealPath(t);try{this.resolveAndValidate(s,t)}catch{throw new Error(`ENOENT: no such file or directory, realpath '${t}'`)}let r;try{r=await I.promises.realpath(s)}catch(n){let i=n;if(i.code===\"ENOENT\")throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);if(i.code===\"ELOOP\")throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);this.sanitizeError(n,t,\"realpath\")}if(Ne(r,this.canonicalRoot))return r.slice(this.canonicalRoot.length)||\"/\";throw new Error(`ENOENT: no such file or directory, realpath '${t}'`)}async utimes(t,s,r){x(t,\"utimes\");let n=this.toRealPath(t),i=this.resolveAndValidate(n,t);try{let o=this.allowSymlinks?I.constants.O_RDONLY:I.constants.O_RDONLY|I.constants.O_NOFOLLOW,a=await I.promises.open(i,o);try{await a.utimes(s,r)}finally{await a.close()}}catch(o){let a=o;if(a.code===\"ENOENT\")throw new Error(`ENOENT: no such file or directory, utimes '${t}'`);if(a.code===\"ELOOP\")throw new Error(`EACCES: permission denied, '${t}' is a symlink`);this.sanitizeError(o,t,\"utimes\")}}};var St=class{cmdId;cwd;startedAt;exitCode;bashEnv;cmdLine;env;explicitCwd;signal;timeoutMs;abortController=new AbortController;timeoutId;externalAbortListener;resultPromise;constructor(t,s,r,n,i=!1,o,a){this.cmdId=crypto.randomUUID(),this.cwd=r,this.startedAt=new Date,this.bashEnv=t,this.cmdLine=s,this.env=n,this.explicitCwd=i,this.signal=o,this.timeoutMs=a,this.setupCancellation(),this.resultPromise=this.execute()}setupCancellation(){if(this.signal&&(this.signal.aborted?this.abortController.abort(this.signal.reason):(this.externalAbortListener=()=>{this.abortController.abort(this.signal?.reason)},this.signal.addEventListener(\"abort\",this.externalAbortListener,{once:!0}))),this.timeoutMs!==void 0){let t=Math.max(0,this.timeoutMs);this.timeoutId=Mt(()=>{this.abortController.abort(new Error(`sandbox command timeout after ${t}ms`))},t)}}cleanupCancellation(){this.timeoutId!==void 0&&(Wt(this.timeoutId),this.timeoutId=void 0),this.signal&&this.externalAbortListener&&(this.signal.removeEventListener(\"abort\",this.externalAbortListener),this.externalAbortListener=void 0)}async execute(){let t={cwd:this.explicitCwd?this.cwd:void 0,env:this.env,signal:this.abortController.signal};try{let s=await this.bashEnv.exec(this.cmdLine,t);return this.exitCode=s.exitCode,s}finally{this.cleanupCancellation()}}async*logs(){let t=await this.resultPromise;t.stdout&&(yield{type:\"stdout\",data:t.stdout,timestamp:new Date}),t.stderr&&(yield{type:\"stderr\",data:t.stderr,timestamp:new Date})}async wait(){return await this.resultPromise,this}async output(){let t=await this.resultPromise;return t.stdout+t.stderr}async stdout(){return(await this.resultPromise).stdout}async stderr(){return(await this.resultPromise).stderr}async kill(){this.abortController.abort(new Error(\"command killed\"))}};var Ds=class e{bashEnv;timeoutMs;constructor(t,s){this.bashEnv=t,this.timeoutMs=s}static async create(t){let s=t?.fs;if(t?.overlayRoot){if(t?.fs)throw new Error(\"Cannot specify both 'fs' and 'overlayRoot' options\");s=new $t({root:t.overlayRoot})}let r=new Ft({env:t?.env,cwd:t?.cwd,fs:s,maxCallDepth:t?.maxCallDepth,maxCommandCount:t?.maxCommandCount,maxLoopIterations:t?.maxLoopIterations,network:t?.network,defenseInDepth:t?.defenseInDepth});return new e(r,t?.timeoutMs)}async runCommand(t,s,r){let n,i,o,a,l=!1,c,u;if(typeof t==\"object\"){let h=t,w=[h.cmd,...h.args??[]];n=Ls(w),i=h.cwd,o=h.env,a=h.signal,l=h.detached??!1,c=h.stdout,u=h.stderr}else if(Array.isArray(s)){let h=r;n=Ls([t,...s]),a=h?.signal}else{n=t;let h=s;i=h?.cwd,o=h?.env}let f=i??this.bashEnv.getCwd(),d=i!==void 0,p=new St(this.bashEnv,n,f,o,d,a,this.timeoutMs);if(l)return p;let y=await p.wait();if(c){let h=await p.stdout();h&&c.write(h)}if(u){let h=await p.stderr();h&&u.write(h)}return y}async writeFiles(t){let s=this.bashEnv.getCwd();for(let[r,n]of Object.entries(t)){let i;typeof n==\"string\"?i=n:n.encoding===\"base64\"?i=Buffer.from(n.content,\"base64\").toString(\"utf-8\"):i=n.content;let o=this.bashEnv.fs.resolvePath(s,r),a=o.substring(0,o.lastIndexOf(\"/\"))||\"/\";a!==\"/\"&&await this.bashEnv.fs.mkdir(a,{recursive:!0}),await this.bashEnv.writeFile(o,i)}}async readFile(t,s){let r=await this.bashEnv.readFile(t);return s===\"base64\"?Buffer.from(r).toString(\"base64\"):r}async mkDir(t,s){let r=this.bashEnv.fs.resolvePath(this.bashEnv.getCwd(),t);await this.bashEnv.fs.mkdir(r,{recursive:s?.recursive??!1})}async stop(){}async extendTimeout(t){}get domain(){}get bashEnvInstance(){return this.bashEnv}};var Rs=class{violations=[];violationsByType=new Map;options;constructor(t={}){this.options={maxViolationsPerType:t.maxViolationsPerType??100,maxViolationsTotal:t.maxViolationsTotal??1e3,includeStackTraces:t.includeStackTraces??!0,onViolation:t.onViolation??(()=>{}),logToConsole:t.logToConsole??!1}}record(t){let s=this.options.includeStackTraces?t:{...t,stack:void 0};this.violations.unshift(s),this.violations.length>this.options.maxViolationsTotal&&(this.violations.length=this.options.maxViolationsTotal);let r=this.violationsByType.get(t.type);r||(r=[],this.violationsByType.set(t.type,r)),r.length<this.options.maxViolationsPerType&&r.push(s),this.options.logToConsole&&console.warn(`[SecurityViolation] ${t.type}: ${t.message}`,t.path),this.options.onViolation(s)}getViolations(){return[...this.violations]}getViolationsByType(t){return[...this.violationsByType.get(t)??[]]}getSummary(){let t=[];for(let[s,r]of this.violationsByType){if(r.length===0)continue;let n=new Set,i=Number.POSITIVE_INFINITY,o=0;for(let a of r)n.add(a.path),i=Math.min(i,a.timestamp),o=Math.max(o,a.timestamp);t.push({type:s,count:r.length,firstSeen:i,lastSeen:o,paths:Array.from(n)})}return t.sort((s,r)=>r.count-s.count),t}getTotalCount(){return this.violations.length}hasViolations(){return this.violations.length>0}clear(){this.violations=[],this.violationsByType.clear()}createCallback(){return t=>this.record(t)}};function to(){return e=>{console.warn(\"[DefenseInDepth] Security violation detected:\",`\n Type: ${e.type}`,`\n Path: ${e.path}`,`\n Message: ${e.message}`,e.executionId?`\n ExecutionId: ${e.executionId}`:\"\")}}var Hr=class{plugins=[];use(t){return this.plugins.push(t),this}transform(t){let s=fe(t),r=Object.create(null);for(let n of this.plugins){let i=n.transform({ast:s,metadata:r});s=i.ast,i.metadata&&(r=Ct(r,i.metadata))}return{script:Lt(s),ast:s,metadata:r}}};var Zr=class{name=\"command-collector\";transform(t){let s=new Set;return this.walkScript(t.ast,s),{ast:t.ast,metadata:{commands:[...s].sort()}}}walkScript(t,s){for(let r of t.statements)this.walkStatement(r,s)}walkStatement(t,s){for(let r of t.pipelines)this.walkPipeline(r,s)}walkPipeline(t,s){for(let r of t.commands)this.walkCommand(r,s)}walkCommand(t,s){switch(t.type){case\"SimpleCommand\":if(t.name){let r=this.extractName(t.name);r&&s.add(r)}t.name&&this.walkWordParts(t.name.parts,s);for(let r of t.args)this.walkWordParts(r.parts,s);for(let r of t.assignments)if(r.value&&this.walkWordParts(r.value.parts,s),r.array)for(let n of r.array)this.walkWordParts(n.parts,s);break;case\"If\":for(let r of t.clauses){for(let n of r.condition)this.walkStatement(n,s);for(let n of r.body)this.walkStatement(n,s)}if(t.elseBody)for(let r of t.elseBody)this.walkStatement(r,s);break;case\"For\":if(t.words)for(let r of t.words)this.walkWordParts(r.parts,s);for(let r of t.body)this.walkStatement(r,s);break;case\"CStyleFor\":for(let r of t.body)this.walkStatement(r,s);break;case\"While\":case\"Until\":for(let r of t.condition)this.walkStatement(r,s);for(let r of t.body)this.walkStatement(r,s);break;case\"Case\":this.walkWordParts(t.word.parts,s);for(let r of t.items)for(let n of r.body)this.walkStatement(n,s);break;case\"Subshell\":case\"Group\":for(let r of t.body)this.walkStatement(r,s);break;case\"ArithmeticCommand\":case\"ConditionalCommand\":break;case\"FunctionDef\":this.walkCommand(t.body,s);break}}walkWordParts(t,s){for(let r of t)switch(r.type){case\"CommandSubstitution\":this.walkScript(r.body,s);break;case\"ProcessSubstitution\":this.walkScript(r.body,s);break;case\"DoubleQuoted\":this.walkWordParts(r.parts,s);break;case\"ParameterExpansion\":r.operation&&this.walkParameterOp(r.operation,s);break}}walkParameterOp(t,s){switch(t.type){case\"DefaultValue\":case\"AssignDefault\":case\"UseAlternative\":this.walkWordParts(t.word.parts,s);break;case\"ErrorIfUnset\":t.word&&this.walkWordParts(t.word.parts,s);break;case\"PatternRemoval\":this.walkWordParts(t.pattern.parts,s);break;case\"PatternReplacement\":this.walkWordParts(t.pattern.parts,s),t.replacement&&this.walkWordParts(t.replacement.parts,s);break;case\"CaseModification\":t.pattern&&this.walkWordParts(t.pattern.parts,s);break;case\"Indirection\":t.innerOp&&this.walkParameterOp(t.innerOp,s);break}}extractName(t){return t.parts.length===1&&t.parts[0].type===\"Literal\"?t.parts[0].value:null}};var qr=class{name=\"tee\";options;counter=0;constructor(t){this.options=t}transform(t){let s=[],r=this.options.timestamp??new Date;return{ast:this.transformScript(t.ast,s,r),metadata:{teeFiles:s}}}formatTimestamp(t){return t.toISOString().replace(/:/g,\"-\")}generateStdoutPath(t,s,r){let n=this.formatTimestamp(r),i=String(t).padStart(3,\"0\");return`${this.options.outputDir}/${n}-${i}-${s}.stdout.txt`}transformScript(t,s,r){return{...t,statements:t.statements.map(n=>this.transformStatement(n,s,r))}}transformStatement(t,s,r){let n=[],i=[];for(let o=0;o<t.pipelines.length;o++){let a=t.pipelines[o];o>0&&i.push(t.operators[o-1]);let l=this.transformPipeline(a,s,r);if(n.push(l.pipeline),l.origCmdNewIndices!==null){let c=l.origCmdNewIndices;i.push(\";\"),n.push(this.makePipestatusSave(c)),i.push(\";\"),n.push(this.makePipestatusRestore(c.length,l.negated))}}return{...t,pipelines:n,operators:i}}transformPipeline(t,s,r){if(t.commands.length<=1)return{pipeline:t,origCmdNewIndices:null,negated:!1};let n=[],i=[],o=[],a=!1;for(let l=0;l<t.commands.length;l++){let c=t.commands[l],u=l===t.commands.length-1;if(c.type!==\"SimpleCommand\"||!c.name||!this.shouldTarget(c)){o.push(n.length),n.push(c),u||i.push(t.pipeStderr?.[l]??!1);continue}let f=this.getCommandName(c.name)??\"unknown\",d=this.counter++,p=this.generateStdoutPath(d,f,r),y=this.makeTeeCommand(p),h=this.serializeCommand(c);s.push({commandIndex:d,commandName:f,command:h,stdoutFile:p}),o.push(n.length),n.push(c),i.push(t.pipeStderr?.[l]??!1),n.push(y),u||i.push(!1),a=!0}return a?{pipeline:{...t,negated:!1,commands:n,pipeStderr:i.length>0?i:void 0},origCmdNewIndices:o,negated:t.negated}:{pipeline:t,origCmdNewIndices:null,negated:!1}}makePipestatusSave(t){return{type:\"Pipeline\",commands:[{type:\"SimpleCommand\",assignments:t.map((s,r)=>({type:\"Assignment\",name:`__tps${r}`,value:{type:\"Word\",parts:[{type:\"ParameterExpansion\",parameter:`PIPESTATUS[${s}]`,operation:null}]},append:!1,array:null})),name:null,args:[],redirections:[]}],negated:!1}}makePipestatusRestore(t,s){let r=[];for(let n=0;n<t;n++)r.push({type:\"Subshell\",body:[{type:\"Statement\",pipelines:[{type:\"Pipeline\",commands:[{type:\"SimpleCommand\",assignments:[],name:{type:\"Word\",parts:[{type:\"Literal\",value:\"exit\"}]},args:[{type:\"Word\",parts:[{type:\"ParameterExpansion\",parameter:`__tps${n}`,operation:null}]}],redirections:[]}],negated:!1}],operators:[],background:!1}],redirections:[]});return{type:\"Pipeline\",commands:r,negated:s}}shouldTarget(t){if(!this.options.targetCommandPattern)return!0;let s=this.getCommandName(t.name);return s!==null&&this.options.targetCommandPattern.test(s)}getCommandName(t){return t&&t.parts.length===1&&t.parts[0].type===\"Literal\"?t.parts[0].value:null}serializeCommand(t){let s=[];t.name&&s.push(ie(t.name));for(let r of t.args)s.push(ie(r));return s.join(\" \")}makeTeeCommand(t){return{type:\"SimpleCommand\",assignments:[],name:{type:\"Word\",parts:[{type:\"Literal\",value:\"tee\"}]},args:[{type:\"Word\",parts:[{type:\"Literal\",value:t}]}],redirections:[]}}};export{Ft as Bash,Hr as BashTransformPipeline,Zr as CommandCollectorPlugin,me as DefenseInDepthBox,oo as EMPTY_BYTES,ze as InMemoryFs,Cs as MountableFs,_e as NetworkAccessDeniedError,$t as OverlayFs,Ts as ReadWriteFs,bt as RedirectNotAllowedError,Ds as Sandbox,St as SandboxCommand,Ve as SecurityViolationError,Rs as SecurityViolationLogger,qr as TeePlugin,vt as TooManyRedirectsError,co as bytesOutput,to as createConsoleViolationCallback,io as decodeBytesToUtf8,mo as defineCommand,Be as encodeUtf8ToBytes,uo as getCommandNames,po as getJavaScriptCommandNames,fo as getNetworkCommandNames,ho as getPythonCommandNames,zt as latin1FromBytes,fe as parse,Lt as serialize,Bt as stdoutAsBytes,ao as stdoutKind,lo as textOutput,At as unsafeBytesFromLatin1};\n","export const TIMEOUT_MAX = 2147483647; // 2^31-1\n/**\n * Creates a new timeout, which can exceed the max timeout limit of 2^31-1.\n * Since multiple timeouts are used internally, the timeoutId used to clear the timeout\n * is returned as a handle (object) and changes whenever the max timeout limit is exceeded.\n * The handle parameter can be ignored, it is used internally for updating the timeoutId\n * in the handle after creating the next timeout.\n */\nexport function longTimeout(fn, timeout, previousHandle) {\n let nextTimeout = timeout;\n let remainingTimeout = 0;\n if (nextTimeout > TIMEOUT_MAX) {\n remainingTimeout = nextTimeout - TIMEOUT_MAX;\n nextTimeout = TIMEOUT_MAX;\n }\n const handle = previousHandle !== null && previousHandle !== void 0 ? previousHandle : {\n timeoutId: undefined,\n };\n handle.timeoutId = setTimeout(() => {\n if (remainingTimeout > 0) {\n longTimeout(fn, remainingTimeout, previousHandle);\n }\n else {\n fn();\n }\n }, nextTimeout);\n return handle;\n}\n/* Extracts second, minute, hour, date, month and the weekday from a date. */\nexport function extractDateElements(date) {\n return {\n second: date.getSeconds(),\n minute: date.getMinutes(),\n hour: date.getHours(),\n day: date.getDate(),\n month: date.getMonth(),\n weekday: date.getDay(),\n year: date.getFullYear(),\n };\n}\n/* Gets the amount of days in the given month (indexed by 0) of the given year. */\nexport function getDaysInMonth(year, month) {\n return new Date(year, month + 1, 0).getDate();\n}\n/* Gets the amount of days from weekday1 to weekday2. */\nexport function getDaysBetweenWeekdays(weekday1, weekday2) {\n if (weekday1 <= weekday2) {\n return weekday2 - weekday1;\n }\n return 6 - weekday1 + weekday2 + 1;\n}\nexport function wrapFunction(fn, errorHandler) {\n return () => {\n try {\n const res = fn();\n if (res instanceof Promise) {\n res.catch((err) => {\n if (errorHandler) {\n errorHandler(err);\n }\n });\n }\n }\n catch (err) {\n if (errorHandler) {\n errorHandler(err);\n }\n }\n };\n}\n//# sourceMappingURL=utils.js.map","import { extractDateElements, getDaysBetweenWeekdays, getDaysInMonth, } from './utils.js';\nexport class Cron {\n constructor({ seconds, minutes, hours, days, months, weekdays, }) {\n // Validate that there are values provided.\n if (!seconds || seconds.size === 0)\n throw new Error('There must be at least one allowed second.');\n if (!minutes || minutes.size === 0)\n throw new Error('There must be at least one allowed minute.');\n if (!hours || hours.size === 0)\n throw new Error('There must be at least one allowed hour.');\n if (!months || months.size === 0)\n throw new Error('There must be at least one allowed month.');\n if ((!weekdays || weekdays.size === 0) && (!days || days.size === 0))\n throw new Error('There must be at least one allowed day or weekday.');\n // Convert set to array and sort in ascending order.\n this.seconds = Array.from(seconds).sort((a, b) => a - b);\n this.minutes = Array.from(minutes).sort((a, b) => a - b);\n this.hours = Array.from(hours).sort((a, b) => a - b);\n this.days = Array.from(days).sort((a, b) => a - b);\n this.months = Array.from(months).sort((a, b) => a - b);\n this.weekdays = Array.from(weekdays).sort((a, b) => a - b);\n // Validate that all values are integers within the constraint.\n const validateData = (name, data, constraint) => {\n if (data.some((x) => typeof x !== 'number' ||\n x % 1 !== 0 ||\n x < constraint.min ||\n x > constraint.max)) {\n throw new Error(`${name} must only consist of integers which are within the range of ${constraint.min} and ${constraint.max}`);\n }\n };\n validateData('seconds', this.seconds, { min: 0, max: 59 });\n validateData('minutes', this.minutes, { min: 0, max: 59 });\n validateData('hours', this.hours, { min: 0, max: 23 });\n validateData('days', this.days, { min: 1, max: 31 });\n validateData('months', this.months, { min: 0, max: 11 });\n validateData('weekdays', this.weekdays, { min: 0, max: 6 });\n // For each element, store a reversed copy in the reversed attribute for finding prev dates.\n this.reversed = {\n seconds: this.seconds.map((x) => x).reverse(),\n minutes: this.minutes.map((x) => x).reverse(),\n hours: this.hours.map((x) => x).reverse(),\n days: this.days.map((x) => x).reverse(),\n months: this.months.map((x) => x).reverse(),\n weekdays: this.weekdays.map((x) => x).reverse(),\n };\n }\n /**\n * Find the next or previous hour, starting from the given start hour that matches the hour constraint.\n * startHour itself might also be allowed.\n */\n findAllowedHour(dir, startHour) {\n return dir === 'next'\n ? this.hours.find((x) => x >= startHour)\n : this.reversed.hours.find((x) => x <= startHour);\n }\n /**\n * Find the next or previous minute, starting from the given start minute that matches the minute constraint.\n * startMinute itself might also be allowed.\n */\n findAllowedMinute(dir, startMinute) {\n return dir === 'next'\n ? this.minutes.find((x) => x >= startMinute)\n : this.reversed.minutes.find((x) => x <= startMinute);\n }\n /**\n * Find the next or previous second, starting from the given start second that matches the second constraint.\n * startSecond itself IS NOT allowed.\n */\n findAllowedSecond(dir, startSecond) {\n return dir === 'next'\n ? this.seconds.find((x) => x > startSecond)\n : this.reversed.seconds.find((x) => x < startSecond);\n }\n /**\n * Find the next or previous time, starting from the given start time that matches the hour, minute\n * and second constraints. startTime itself might also be allowed.\n */\n findAllowedTime(dir, startTime) {\n // Try to find an allowed hour.\n let hour = this.findAllowedHour(dir, startTime.hour);\n if (hour !== undefined) {\n if (hour === startTime.hour) {\n // We found an hour that is the start hour. Try to find an allowed minute.\n let minute = this.findAllowedMinute(dir, startTime.minute);\n if (minute !== undefined) {\n if (minute === startTime.minute) {\n // We found a minute that is the start minute. Try to find an allowed second.\n const second = this.findAllowedSecond(dir, startTime.second);\n if (second !== undefined) {\n // We found a second within the start hour and minute.\n return { hour, minute, second };\n }\n // We did not find a valid second within the start minute. Try to find another minute.\n minute = this.findAllowedMinute(dir, dir === 'next' ? startTime.minute + 1 : startTime.minute - 1);\n if (minute !== undefined) {\n // We found a minute which is not the start minute. Return that minute together with the hour and the first / last allowed second.\n return {\n hour,\n minute,\n second: dir === 'next' ? this.seconds[0] : this.reversed.seconds[0],\n };\n }\n }\n else {\n // We found a minute which is not the start minute. Return that minute together with the hour and the first / last allowed second.\n return {\n hour,\n minute,\n second: dir === 'next' ? this.seconds[0] : this.reversed.seconds[0],\n };\n }\n }\n // We did not find an allowed minute / second combination inside the start hour. Try to find the next / previous allowed hour.\n hour = this.findAllowedHour(dir, dir === 'next' ? startTime.hour + 1 : startTime.hour - 1);\n if (hour !== undefined) {\n // We found an allowed hour which is not the start hour. Return that hour together with the first / last allowed minutes / seconds.\n return {\n hour,\n minute: dir === 'next' ? this.minutes[0] : this.reversed.minutes[0],\n second: dir === 'next' ? this.seconds[0] : this.reversed.seconds[0],\n };\n }\n }\n else {\n // We found an allowed hour which is not the start hour. Return that hour together with the first / last allowed minutes / seconds.\n return {\n hour,\n minute: dir === 'next' ? this.minutes[0] : this.reversed.minutes[0],\n second: dir === 'next' ? this.seconds[0] : this.reversed.seconds[0],\n };\n }\n }\n // No allowed time found.\n return undefined;\n }\n /**\n * Find the next or previous day in the given month, starting from the given startDay\n * that matches either the day or the weekday constraint. startDay itself might also be allowed.\n */\n findAllowedDayInMonth(dir, year, month, startDay) {\n var _a, _b;\n if (startDay < 1)\n throw new Error('startDay must not be smaller than 1.');\n // If only days are restricted: allow day based on day constraint only.\n // If only weekdays are restricted: allow day based on weekday constraint only.\n // If both are restricted: allow day based on both day and weekday constraint. pick day that is closer to startDay.\n // If none are restricted: return the day closest to startDay (respecting dir) that is allowed (or startDay itself).\n const daysInMonth = getDaysInMonth(year, month);\n const daysRestricted = this.days.length !== 31;\n const weekdaysRestricted = this.weekdays.length !== 7;\n if (!daysRestricted && !weekdaysRestricted) {\n if (startDay > daysInMonth) {\n return dir === 'next' ? undefined : daysInMonth;\n }\n return startDay;\n }\n // Try to find a day based on the days constraint.\n let allowedDayByDays;\n if (daysRestricted) {\n allowedDayByDays =\n dir === 'next'\n ? this.days.find((x) => x >= startDay)\n : this.reversed.days.find((x) => x <= startDay);\n // Make sure the day does not exceed the amount of days in month.\n if (allowedDayByDays !== undefined && allowedDayByDays > daysInMonth) {\n allowedDayByDays = undefined;\n }\n }\n // Try to find a day based on the weekday constraint.\n let allowedDayByWeekdays;\n if (weekdaysRestricted) {\n const startWeekday = new Date(year, month, startDay).getDay();\n const nearestAllowedWeekday = dir === 'next'\n ? ((_a = this.weekdays.find((x) => x >= startWeekday)) !== null && _a !== void 0 ? _a : this.weekdays[0])\n : ((_b = this.reversed.weekdays.find((x) => x <= startWeekday)) !== null && _b !== void 0 ? _b : this.reversed.weekdays[0]);\n if (nearestAllowedWeekday !== undefined) {\n const daysBetweenWeekdays = dir === 'next'\n ? getDaysBetweenWeekdays(startWeekday, nearestAllowedWeekday)\n : getDaysBetweenWeekdays(nearestAllowedWeekday, startWeekday);\n allowedDayByWeekdays =\n dir === 'next'\n ? startDay + daysBetweenWeekdays\n : startDay - daysBetweenWeekdays;\n // Make sure the day does not exceed the month boundaries.\n if (allowedDayByWeekdays > daysInMonth || allowedDayByWeekdays < 1) {\n allowedDayByWeekdays = undefined;\n }\n }\n }\n if (allowedDayByDays !== undefined && allowedDayByWeekdays !== undefined) {\n // If a day is found both via the days and the weekdays constraint, pick the day\n // that is closer to start date.\n return dir === 'next'\n ? Math.min(allowedDayByDays, allowedDayByWeekdays)\n : Math.max(allowedDayByDays, allowedDayByWeekdays);\n }\n if (allowedDayByDays !== undefined) {\n return allowedDayByDays;\n }\n if (allowedDayByWeekdays !== undefined) {\n return allowedDayByWeekdays;\n }\n return undefined;\n }\n /** Gets the next date starting from the given start date or now. */\n getNextDate(startDate = new Date()) {\n const startDateElements = extractDateElements(startDate);\n let minYear = startDateElements.year;\n let startIndexMonth = this.months.findIndex((x) => x >= startDateElements.month);\n if (startIndexMonth === -1) {\n startIndexMonth = 0;\n minYear++;\n }\n // We try every month within the next 5 years to make sure that we tried to\n // find a matching date insidde a whole leap year.\n const maxIterations = this.months.length * 5;\n for (let i = 0; i < maxIterations; i++) {\n // Get the next year and month.\n const year = minYear + Math.floor((startIndexMonth + i) / this.months.length);\n const month = this.months[(startIndexMonth + i) % this.months.length];\n const isStartMonth = year === startDateElements.year && month === startDateElements.month;\n // Find the next day.\n let day = this.findAllowedDayInMonth('next', year, month, isStartMonth ? startDateElements.day : 1);\n let isStartDay = isStartMonth && day === startDateElements.day;\n // If we found a day and it is the start day, try to find a valid time beginning from the start date time.\n if (day !== undefined && isStartDay) {\n const nextTime = this.findAllowedTime('next', startDateElements);\n if (nextTime !== undefined) {\n return new Date(year, month, day, nextTime.hour, nextTime.minute, nextTime.second);\n }\n // If no valid time has been found for the start date, try the next day.\n day = this.findAllowedDayInMonth('next', year, month, day + 1);\n isStartDay = false;\n }\n // If we found a next day and it is not the start day, just use the next day with the first allowed values\n // for hours, minutes and seconds.\n if (day !== undefined && !isStartDay) {\n return new Date(year, month, day, this.hours[0], this.minutes[0], this.seconds[0]);\n }\n // No allowed day has been found for this month. Continue to search in next month.\n }\n throw new Error('No valid next date was found.');\n }\n /** Gets the specified amount of future dates starting from the given start date or now. */\n getNextDates(amount, startDate) {\n const dates = [];\n let nextDate;\n for (let i = 0; i < amount; i++) {\n nextDate = this.getNextDate(nextDate !== null && nextDate !== void 0 ? nextDate : startDate);\n dates.push(nextDate);\n }\n return dates;\n }\n /**\n * Get an ES6 compatible iterator which iterates over the next dates starting from startDate or now.\n * The iterator runs until the optional endDate is reached or forever.\n */\n *getNextDatesIterator(startDate, endDate) {\n let nextDate;\n while (true) {\n nextDate = this.getNextDate(nextDate !== null && nextDate !== void 0 ? nextDate : startDate);\n if (endDate && endDate.getTime() < nextDate.getTime()) {\n return;\n }\n yield nextDate;\n }\n }\n /** Gets the previous date starting from the given start date or now. */\n getPrevDate(startDate = new Date()) {\n const startDateElements = extractDateElements(startDate);\n let maxYear = startDateElements.year;\n let startIndexMonth = this.reversed.months.findIndex((x) => x <= startDateElements.month);\n if (startIndexMonth === -1) {\n startIndexMonth = 0;\n maxYear--;\n }\n // We try every month within the past 5 years to make sure that we tried to\n // find a matching date inside a whole leap year.\n const maxIterations = this.reversed.months.length * 5;\n for (let i = 0; i < maxIterations; i++) {\n // Get the next year and month.\n const year = maxYear -\n Math.floor((startIndexMonth + i) / this.reversed.months.length);\n const month = this.reversed.months[(startIndexMonth + i) % this.reversed.months.length];\n const isStartMonth = year === startDateElements.year && month === startDateElements.month;\n // Find the previous day.\n let day = this.findAllowedDayInMonth('prev', year, month, isStartMonth\n ? startDateElements.day\n : // Start searching from the last day of the month.\n getDaysInMonth(year, month));\n let isStartDay = isStartMonth && day === startDateElements.day;\n // If we found a day and it is the start day, try to find a valid time beginning from the start date time.\n if (day !== undefined && isStartDay) {\n const prevTime = this.findAllowedTime('prev', startDateElements);\n if (prevTime !== undefined) {\n return new Date(year, month, day, prevTime.hour, prevTime.minute, prevTime.second);\n }\n // If no valid time has been found for the start date, try the previous day.\n if (day > 1) {\n day = this.findAllowedDayInMonth('prev', year, month, day - 1);\n isStartDay = false;\n }\n }\n // If we found a previous day and it is not the start day, just use the previous day with the first allowed values\n // for hours, minutes and seconds (which will be the latest time due to using the reversed array).\n if (day !== undefined && !isStartDay) {\n return new Date(year, month, day, this.reversed.hours[0], this.reversed.minutes[0], this.reversed.seconds[0]);\n }\n // No allowed day has been found for this month. Continue to search in previous month.\n }\n throw new Error('No valid previous date was found.');\n }\n /** Gets the specified amount of previous dates starting from the given start date or now. */\n getPrevDates(amount, startDate) {\n const dates = [];\n let prevDate;\n for (let i = 0; i < amount; i++) {\n prevDate = this.getPrevDate(prevDate !== null && prevDate !== void 0 ? prevDate : startDate);\n dates.push(prevDate);\n }\n return dates;\n }\n /**\n * Get an ES6 compatible iterator which iterates over the previous dates starting from startDate or now.\n * The iterator runs until the optional endDate is reached or forever.\n */\n *getPrevDatesIterator(startDate, endDate) {\n let prevDate;\n while (true) {\n prevDate = this.getPrevDate(prevDate !== null && prevDate !== void 0 ? prevDate : startDate);\n if (endDate && endDate.getTime() > prevDate.getTime()) {\n return;\n }\n yield prevDate;\n }\n }\n /** Returns true when there is a cron date at the given date. */\n matchDate(date) {\n const { second, minute, hour, day, month, weekday } = extractDateElements(date);\n if (this.seconds.indexOf(second) === -1 ||\n this.minutes.indexOf(minute) === -1 ||\n this.hours.indexOf(hour) === -1 ||\n this.months.indexOf(month) === -1) {\n return false;\n }\n if (this.days.length !== 31 && this.weekdays.length !== 7) {\n return (this.days.indexOf(day) !== -1 || this.weekdays.indexOf(weekday) !== -1);\n }\n return (this.days.indexOf(day) !== -1 && this.weekdays.indexOf(weekday) !== -1);\n }\n}\n//# sourceMappingURL=cron.js.map","import { Cron } from './cron.js';\nconst secondConstraint = {\n min: 0,\n max: 59,\n};\nconst minuteConstraint = {\n min: 0,\n max: 59,\n};\nconst hourConstraint = {\n min: 0,\n max: 23,\n};\nconst dayConstraint = {\n min: 1,\n max: 31,\n};\nconst monthConstraint = {\n min: 1,\n max: 12,\n aliases: {\n jan: '1',\n feb: '2',\n mar: '3',\n apr: '4',\n may: '5',\n jun: '6',\n jul: '7',\n aug: '8',\n sep: '9',\n oct: '10',\n nov: '11',\n dec: '12',\n },\n};\nconst weekdayConstraint = {\n min: 0,\n max: 7,\n aliases: {\n mon: '1',\n tue: '2',\n wed: '3',\n thu: '4',\n fri: '5',\n sat: '6',\n sun: '7',\n },\n};\nconst timeNicknames = {\n '@yearly': '0 0 1 1 *',\n '@annually': '0 0 1 1 *',\n '@monthly': '0 0 1 * *',\n '@weekly': '0 0 * * 0',\n '@daily': '0 0 * * *',\n '@hourly': '0 * * * *',\n '@minutely': '* * * * *',\n};\nfunction parseElement(element, constraint) {\n const result = new Set();\n // If returned set of numbers is empty, the scheduler class interpretes the emtpy set of numbers as all valid values of the constraint\n if (element === '*') {\n for (let i = constraint.min; i <= constraint.max; i = i + 1) {\n result.add(i);\n }\n return result;\n }\n // If the element is a list, parse each element in the list.\n const listElements = element.split(',');\n if (listElements.length > 1) {\n for (const listElement of listElements) {\n const parsedListElement = parseElement(listElement, constraint);\n for (const x of parsedListElement) {\n result.add(x);\n }\n }\n return result;\n }\n // Helper function to parse a single element, which includes checking for alias, valid number and constraint min and max.\n const parseSingleElement = (singleElement) => {\n var _a, _b;\n singleElement =\n (_b = (_a = constraint.aliases) === null || _a === void 0 ? void 0 : _a[singleElement.toLowerCase()]) !== null && _b !== void 0 ? _b : singleElement;\n const parsedElement = Number.parseInt(singleElement, 10);\n if (Number.isNaN(parsedElement)) {\n throw new Error(`Failed to parse ${element}: ${singleElement} is NaN.`);\n }\n if (parsedElement < constraint.min || parsedElement > constraint.max) {\n throw new Error(`Failed to parse ${element}: ${singleElement} is outside of constraint range of ${constraint.min} - ${constraint.max}.`);\n }\n return parsedElement;\n };\n // Detect if the element is a range.\n // Possible range formats: 'start-end', 'start-end/step', '*', '*/step'.\n // Where start and end can be numbers or aliases.\n // Capture groups: 1: start-end, 2: start, 3: end, 4: /step, 5: step.\n const rangeSegments = /^(([0-9a-zA-Z]+)-([0-9a-zA-Z]+)|\\*)(\\/([0-9]+))?$/.exec(element);\n // If not, it must be a single element.\n if (rangeSegments === null) {\n result.add(parseSingleElement(element));\n return result;\n }\n // If it is a range, get start and end of the range.\n let parsedStart = rangeSegments[1] === '*'\n ? constraint.min\n : parseSingleElement(rangeSegments[2]);\n const parsedEnd = rangeSegments[1] === '*'\n ? constraint.max\n : parseSingleElement(rangeSegments[3]);\n // need to catch Sunday, which gets parsed here as 7, but is also legitimate at the start of a range as 0, to avoid the out of order error\n if (constraint === weekdayConstraint &&\n parsedStart === 7 &&\n // this check ensures that sun-sun is not incorrectly parsed as [0,1,2,3,4,5,6]\n parsedEnd !== 7) {\n parsedStart = 0;\n }\n if (parsedStart > parsedEnd) {\n throw new Error(`Failed to parse ${element}: Invalid range (start: ${parsedStart}, end: ${parsedEnd}).`);\n }\n // Check whether there is a custom step defined for the range, defaulting to 1.\n const step = rangeSegments[5];\n let parsedStep = 1;\n if (step !== undefined) {\n parsedStep = Number.parseInt(step, 10);\n if (Number.isNaN(parsedStep)) {\n throw new Error(`Failed to parse step: ${step} is NaN.`);\n }\n if (parsedStep < 1) {\n throw new Error(`Failed to parse step: Expected ${step} to be greater than 0.`);\n }\n }\n // Go from start to end of the range by the given steps.\n for (let i = parsedStart; i <= parsedEnd; i = i + parsedStep) {\n result.add(i);\n }\n return result;\n}\n/** Parses a cron expression into a Cron instance. */\nexport function parseCronExpression(cronExpression) {\n var _a;\n if (typeof cronExpression !== 'string') {\n throw new TypeError('Invalid cron expression: must be of type string.');\n }\n // Convert time nicknames.\n cronExpression = (_a = timeNicknames[cronExpression.toLowerCase()]) !== null && _a !== void 0 ? _a : cronExpression;\n // Split the cron expression into its elements, removing empty elements (extra whitespaces).\n const elements = cronExpression.split(' ').filter((elem) => elem.length > 0);\n if (elements.length < 5 || elements.length > 6) {\n throw new Error('Invalid cron expression: expected 5 or 6 elements.');\n }\n const rawSeconds = elements.length === 6 ? elements[0] : '0';\n const rawMinutes = elements.length === 6 ? elements[1] : elements[0];\n const rawHours = elements.length === 6 ? elements[2] : elements[1];\n const rawDays = elements.length === 6 ? elements[3] : elements[2];\n const rawMonths = elements.length === 6 ? elements[4] : elements[3];\n const rawWeekdays = elements.length === 6 ? elements[5] : elements[4];\n return new Cron({\n seconds: parseElement(rawSeconds, secondConstraint),\n minutes: parseElement(rawMinutes, minuteConstraint),\n hours: parseElement(rawHours, hourConstraint),\n days: parseElement(rawDays, dayConstraint),\n // months in cron are indexed by 1, but Cron expects indexes by 0, so we need to reduce all set values by one.\n months: new Set(Array.from(parseElement(rawMonths, monthConstraint)).map((x) => x - 1)),\n weekdays: new Set(Array.from(parseElement(rawWeekdays, weekdayConstraint)).map((x) => x % 7)),\n });\n}\n//# sourceMappingURL=cron-parser.js.map","import { z } from \"zod\";\nimport { CREDENTIAL_SCOPE_TYPES, credential, credentialInputSchema, defineCredential, isCredentialInput, normalizeCredentialList, toCredentialRequirement, toolParameters } from \"@keystrokehq/shared\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n//#region src/action-definition.ts\nconst zodSchema = z.custom((v) => v instanceof z.ZodType, \"must be a Zod schema\");\n/** Runtime validation for an unbranded action definition. */\nconst actionCoreSchema = z.object({\n\tslug: z.string().trim().min(1),\n\tname: z.string().optional(),\n\tdescription: z.string().optional(),\n\tinput: zodSchema,\n\toutput: zodSchema,\n\tcredentials: z.array(credentialInputSchema).optional(),\n\trun: z.function()\n});\nconst ACTION = Symbol.for(\"keystroke.action\");\n/**\n* Validates brand + shape via `actionCoreSchema` so discovery and guards reject\n* malformed definitions.\n*/\nfunction isAction(value) {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tif (!(ACTION in value) || value[ACTION] !== true) return false;\n\treturn actionCoreSchema.safeParse(value).success;\n}\nfunction getActionCredentialRequirements(action) {\n\treturn action.credentials;\n}\n//#endregion\n//#region src/action-execution-context.ts\n/**\n* Tracks the action whose `run` is currently executing. Actions are leaf units:\n* orchestration belongs in workflows, not inside another action. We use this to\n* reject an action that tries to invoke another action's `run` (directly or as a\n* step) while one is already on the stack.\n*/\nconst executingAction = new AsyncLocalStorage();\n/**\n* Runs an action's `run` body. Throws if another action is already executing in\n* the current async context — that means an action called another action.\n*/\nfunction runWithinActionExecution(actionKey, run) {\n\tconst parentKey = executingAction.getStore();\n\tif (parentKey !== void 0) throw new Error(`Action \"${actionKey}\" was invoked from inside action \"${parentKey}\". Actions are leaf units — an action must not call another action. Orchestrate actions in a workflow (src/workflows/), or attach the action directly as an agent tool (src/agents/).`);\n\treturn executingAction.run(actionKey, run);\n}\n/**\n* Resets the action-execution context for the duration of `fn`. Agent tool calls\n* are fresh top-level executions even when the agent was prompted from inside an\n* action, so calling actions as agent tools must not trip the guard.\n*/\nfunction runOutsideActionExecution(fn) {\n\treturn executingAction.exit(fn);\n}\n/** True while an action's `run` body is executing (agent steps are suppressed). */\nfunction isWithinActionExecution() {\n\treturn executingAction.getStore() !== void 0;\n}\n//#endregion\n//#region src/run-signal-context.ts\nconst runSignalStorage = new AsyncLocalStorage();\n/** Never-aborting signal used outside a cancellable run (direct calls, tests). */\nconst NEVER_ABORT = new AbortController().signal;\n/**\n* Runs `fn` with `signal` as the ambient run-cancellation signal. The worker\n* wires this once per queued run so every nested action/agent/workflow can read\n* it via {@link getRunSignal} without threading a parameter — cancellation stays\n* invisible to authoring SDKs.\n*/\nfunction runWithRunSignal(signal, fn) {\n\treturn runSignalStorage.run(signal, fn);\n}\n/** The current run's cancellation signal; never aborts outside a run. */\nfunction getRunSignal() {\n\treturn runSignalStorage.getStore() ?? NEVER_ABORT;\n}\n//#endregion\n//#region src/workflow-run-registry.ts\nconst REGISTRY_KEY$2 = Symbol.for(\"keystroke.workflowRunGetter\");\nfunction registry$1() {\n\tconst globalScope = globalThis;\n\tif (!globalScope[REGISTRY_KEY$2]) globalScope[REGISTRY_KEY$2] = {};\n\treturn globalScope[REGISTRY_KEY$2];\n}\nfunction registerWorkflowRunGetter(fn) {\n\tregistry$1().getter = fn;\n}\nfunction getWorkflowRunHandle() {\n\treturn registry$1().getter?.();\n}\n//#endregion\n//#region src/step-invocation.ts\nfunction executeStep(state) {\n\tif (state.input === void 0) throw new Error(`Step \"${state.action.slug}\" has no input. Call .run(input) before awaiting or chaining .scope().`);\n\tconst handle = getWorkflowRunHandle();\n\tif (!handle) throw new Error(`Step \"${state.action.slug}\" must run inside a workflow or be called as .run(input, credentials) in tests.`);\n\treturn handle.actionRunner(state.action, state.input, {\n\t\tid: state.id,\n\t\tcredentialScope: state.scope\n\t});\n}\nfunction isStepInvocation(value) {\n\treturn typeof value === \"object\" && value !== null && \"then\" in value && typeof value.then === \"function\" && \"scope\" in value && typeof value.scope === \"function\";\n}\nfunction createStepInvocation(state) {\n\treturn {\n\t\tscope(scope) {\n\t\t\treturn createStepInvocation({\n\t\t\t\t...state,\n\t\t\t\tscope\n\t\t\t});\n\t\t},\n\t\trun(input) {\n\t\t\treturn createStepInvocation({\n\t\t\t\t...state,\n\t\t\t\tinput\n\t\t\t});\n\t\t},\n\t\tstepId(id) {\n\t\t\treturn createStepInvocation({\n\t\t\t\t...state,\n\t\t\t\tid\n\t\t\t});\n\t\t},\n\t\tthen(onfulfilled, onrejected) {\n\t\t\treturn executeStep(state).then(onfulfilled, onrejected);\n\t\t}\n\t};\n}\n//#endregion\n//#region src/define-action.ts\nfunction attachStepApi(action) {\n\tconst execute = action.run.bind(action);\n\tconst stepAction = action;\n\treturn {\n\t\t...action,\n\t\trun(input, credentials) {\n\t\t\tif (credentials !== void 0) return execute(input, credentials);\n\t\t\treturn createStepInvocation({\n\t\t\t\taction: stepAction,\n\t\t\t\tinput\n\t\t\t});\n\t\t},\n\t\tscope(scope) {\n\t\t\tif (!action.credentials) return attachStepApi(action);\n\t\t\tconst credentials = normalizeCredentialList(action.credentials).map((requirement) => ({\n\t\t\t\t...requirement,\n\t\t\t\tscope\n\t\t\t}));\n\t\t\treturn attachStepApi({\n\t\t\t\t...action,\n\t\t\t\tcredentials\n\t\t\t});\n\t\t}\n\t};\n}\nfunction defineAction(def) {\n\tconst result = actionCoreSchema.safeParse(def);\n\tif (!result.success) throw new Error(`Invalid action definition: ${formatIssues(result.error.issues)}`);\n\tconst guardedRun = (input, credentials) => runWithinActionExecution(result.data.slug, () => def.run(input, credentials, { signal: getRunSignal() }));\n\treturn attachStepApi({\n\t\t...result.data,\n\t\trun: guardedRun,\n\t\tcredentials: def.credentials,\n\t\t[ACTION]: true\n\t});\n}\nfunction formatIssues(issues) {\n\treturn issues.map((issue) => {\n\t\treturn `${issue.path.length > 0 ? `${issue.path.join(\".\")}: ` : \"\"}${issue.message}`;\n\t}).join(\"; \");\n}\n//#endregion\n//#region src/execute-action.ts\nasync function executeAction(action, input, credentials = {}) {\n\tconst validatedInput = action.input.parse(input);\n\tconst result = await action.run(validatedInput, credentials);\n\treturn action.output.parse(result);\n}\n//#endregion\n//#region src/mcp-credential-context-registry.ts\n/**\n* The store lives in a global `Symbol.for` slot rather than a module-level `const` so a single\n* `AsyncLocalStorage` instance is shared even when the bundled `@keystrokehq/keystroke` facade\n* ships its own copy of this module: the worker sets context via `runWithMcpCredentialContext`\n* and the facade reads it via `getRegisteredMcpCredentialContext` against the same instance.\n*/\nconst REGISTRY_KEY$1 = Symbol.for(\"keystroke.mcpCredentialContextStore\");\nfunction store() {\n\tconst globalScope = globalThis;\n\tif (!globalScope[REGISTRY_KEY$1]) globalScope[REGISTRY_KEY$1] = new AsyncLocalStorage();\n\treturn globalScope[REGISTRY_KEY$1];\n}\nfunction getRegisteredMcpCredentialContext() {\n\treturn store().getStore();\n}\n/**\n* Run `fn` with MCP credential context active for its entire async execution. Nested calls merge\n* over the enclosing context, so an agent's assignment target and a per-tool consumer id compose.\n*/\nfunction runWithMcpCredentialContext(context, fn) {\n\tconst als = store();\n\treturn als.run({\n\t\t...als.getStore(),\n\t\t...context\n\t}, fn);\n}\n//#endregion\n//#region src/resolve-action-tool.ts\nfunction resolveActionTool(action, options) {\n\tconst consumer = options?.consumer ?? {\n\t\tkind: \"tool\",\n\t\tname: action.slug\n\t};\n\treturn {\n\t\tname: action.slug,\n\t\tlabel: action.name ?? action.slug,\n\t\tdescription: action.description ?? action.name ?? action.slug,\n\t\tparameters: toolParameters(action.input),\n\t\tasync execute(_toolCallId, params) {\n\t\t\tconst requirements = getActionCredentialRequirements(action);\n\t\t\tlet credentials = {};\n\t\t\tif (requirements?.length) {\n\t\t\t\tif (!options?.resolveCredentials) throw new Error(`Missing credential resolver for action \"${action.slug}\"`);\n\t\t\t\tcredentials = await options.resolveCredentials(requirements, consumer, options.contextOverride);\n\t\t\t}\n\t\t\tconst output = await runWithMcpCredentialContext({\n\t\t\t\t...options?.mcpCredentialContext,\n\t\t\t\tconsumerId: consumer.id ?? consumer.name\n\t\t\t}, () => runOutsideActionExecution(() => executeAction(action, params, credentials)));\n\t\t\treturn {\n\t\t\t\tcontent: [{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: JSON.stringify(output)\n\t\t\t\t}],\n\t\t\t\tdetails: output\n\t\t\t};\n\t\t}\n\t};\n}\n//#endregion\n//#region src/project-scope-registry.ts\n/**\n* Cross-module bridge for the bound project scope. The runtime registers the database-backed\n* getter (reading the per-job `runWithProjectScope` async context); the bundled keystroke facade\n* reads it without importing `@keystrokehq/database`. Keyed by a global `Symbol.for` so a single\n* slot is shared even when the facade ships its own bundled copy of this module.\n*/\nconst REGISTRY_KEY = Symbol.for(\"keystroke.projectScopeGetter\");\nfunction registry() {\n\tconst globalScope = globalThis;\n\tif (!globalScope[REGISTRY_KEY]) globalScope[REGISTRY_KEY] = {};\n\treturn globalScope[REGISTRY_KEY];\n}\nfunction registerProjectScopeGetter(fn) {\n\tregistry().getter = fn;\n}\nfunction getRegisteredProjectScopeId() {\n\treturn registry().getter?.();\n}\n//#endregion\nexport { CREDENTIAL_SCOPE_TYPES, actionCoreSchema, createStepInvocation, credential, credentialInputSchema, defineAction, defineCredential, executeAction, getActionCredentialRequirements, getRegisteredMcpCredentialContext, getRegisteredProjectScopeId, getRunSignal, getWorkflowRunHandle, isAction, isCredentialInput, isStepInvocation, isWithinActionExecution, normalizeCredentialList, registerProjectScopeGetter, registerWorkflowRunGetter, resolveActionTool, runOutsideActionExecution, runWithMcpCredentialContext, runWithRunSignal, runWithinActionExecution, toCredentialRequirement };\n\n//# sourceMappingURL=index.mjs.map","import { AsyncLocalStorage } from \"node:async_hooks\";\n//#region src/config.ts\nlet sink;\nfunction configureTracing(options) {\n\tsink = options.sink;\n}\nfunction getTracingSink() {\n\treturn sink;\n}\nfunction resetTracingForTests() {\n\tsink = void 0;\n}\n//#endregion\n//#region src/context.ts\nconst traceContextStorage = new AsyncLocalStorage();\nfunction getTraceContext() {\n\treturn traceContextStorage.getStore();\n}\nfunction runWithTraceContext(context, fn) {\n\treturn traceContextStorage.run(context, fn);\n}\n//#endregion\n//#region src/serialize.ts\nfunction formatConsoleArg(value) {\n\tif (typeof value === \"string\") return value;\n\tif (value instanceof Error) return value.stack ?? value.message;\n\ttry {\n\t\treturn JSON.stringify(value);\n\t} catch {\n\t\treturn String(value);\n\t}\n}\nfunction serializeConsoleArgs(args) {\n\tif (args.length === 0) return { message: \"\" };\n\tconst [first, ...rest] = args;\n\tconst message = formatConsoleArg(first);\n\tif (rest.length === 0) return { message };\n\tif (rest.length === 1) return {\n\t\tmessage,\n\t\tdata: rest[0]\n\t};\n\treturn {\n\t\tmessage,\n\t\tdata: rest\n\t};\n}\nfunction summarizePayload(payload) {\n\tif (payload === void 0) return;\n\ttry {\n\t\tconst serialized = JSON.stringify(payload);\n\t\tif (serialized.length <= 500) return payload;\n\t\treturn {\n\t\t\ttruncated: true,\n\t\t\tlength: serialized.length,\n\t\t\tpreview: serialized.slice(0, 500)\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\ttruncated: true,\n\t\t\tpreview: String(payload).slice(0, 500)\n\t\t};\n\t}\n}\n//#endregion\n//#region src/console.ts\nconst CONSOLE_LEVELS = [\n\t\"log\",\n\t\"debug\",\n\t\"info\",\n\t\"warn\",\n\t\"error\"\n];\nfunction mapConsoleLevel(level) {\n\tif (level === \"log\") return \"info\";\n\treturn level;\n}\nasync function captureConsole(fn) {\n\tconst originals = /* @__PURE__ */ new Map();\n\tfor (const level of CONSOLE_LEVELS) {\n\t\toriginals.set(level, console[level].bind(console));\n\t\tconsole[level] = (...args) => {\n\t\t\toriginals.get(level)?.(...args);\n\t\t\tconst sink = getTracingSink();\n\t\t\tconst context = getTraceContext();\n\t\t\tif (!sink || !context) return;\n\t\t\tconst { message, data } = serializeConsoleArgs(args);\n\t\t\tsink.appendLog({\n\t\t\t\ttraceId: context.traceId,\n\t\t\t\tspanId: context.spanId,\n\t\t\t\tlevel: mapConsoleLevel(level),\n\t\t\t\tmessage,\n\t\t\t\tdata,\n\t\t\t\tsource: \"console\",\n\t\t\t\tcreatedAt: /* @__PURE__ */ new Date()\n\t\t\t});\n\t\t};\n\t}\n\ttry {\n\t\treturn await fn();\n\t} finally {\n\t\tfor (const level of CONSOLE_LEVELS) {\n\t\t\tconst original = originals.get(level);\n\t\t\tif (original) console[level] = original;\n\t\t}\n\t}\n}\n//#endregion\n//#region src/log.ts\nasync function logSystem(level, message, data) {\n\tconst sink = getTracingSink();\n\tconst context = getTraceContext();\n\tif (!sink || !context) return;\n\tawait sink.appendLog({\n\t\ttraceId: context.traceId,\n\t\tspanId: context.spanId,\n\t\tlevel,\n\t\tmessage,\n\t\tdata,\n\t\tsource: \"system\",\n\t\tcreatedAt: /* @__PURE__ */ new Date()\n\t});\n}\n//#endregion\n//#region src/span.ts\nfunction serializeSpanError(error) {\n\tif (error instanceof Error) return {\n\t\tname: error.name,\n\t\tmessage: error.message\n\t};\n\treturn { message: String(error) };\n}\nasync function withSpan(input, fn) {\n\tconst sink = getTracingSink();\n\tif (!sink) return await fn();\n\tconst parent = getTraceContext();\n\tconst spanId = input.spanId ?? crypto.randomUUID();\n\tconst traceId = input.traceId ?? parent?.traceId ?? spanId;\n\tconst parentSpanId = input.parentSpanId ?? parent?.spanId;\n\tconst startedAt = /* @__PURE__ */ new Date();\n\tawait sink.openSpan({\n\t\tid: spanId,\n\t\ttraceId,\n\t\tparentSpanId,\n\t\tkind: input.kind,\n\t\trefId: input.refId,\n\t\tname: input.name,\n\t\tmetadata: input.metadata,\n\t\tstartedAt\n\t});\n\tconst context = {\n\t\ttraceId,\n\t\tspanId,\n\t\tparentSpanId\n\t};\n\ttry {\n\t\tconst result = await runWithTraceContext(context, () => fn());\n\t\tawait sink.closeSpan(spanId, \"ok\", /* @__PURE__ */ new Date());\n\t\treturn result;\n\t} catch (error) {\n\t\tawait sink.closeSpan(spanId, \"error\", /* @__PURE__ */ new Date(), serializeSpanError(error));\n\t\tthrow error;\n\t}\n}\nfunction isSpanActive() {\n\treturn getTraceContext() !== void 0;\n}\n//#endregion\nexport { captureConsole, configureTracing, getTraceContext, isSpanActive, logSystem, resetTracingForTests, runWithTraceContext, summarizePayload, withSpan };\n\n//# sourceMappingURL=index.mjs.map","import { createRequire } from \"node:module\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { doublePrecision, index, integer, jsonb, pgTable, text, timestamp, uniqueIndex } from \"drizzle-orm/pg-core\";\nimport { index as index$1, integer as integer$1, real, sqliteTable, text as text$1, uniqueIndex as uniqueIndex$1 } from \"drizzle-orm/sqlite-core\";\nimport { and, and as and$1, asc, count, desc, eq, eq as eq$1, gt, inArray, inArray as inArray$1, isNotNull, isNull, lt, lte, max, max as max$1, ne, notInArray, or, sql, sql as sql$1 } from \"drizzle-orm\";\nimport { existsSync, mkdirSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport SqliteClient from \"better-sqlite3\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\nimport { readMigrationFiles } from \"drizzle-orm/migrator\";\nimport { fileURLToPath } from \"node:url\";\nimport { migrate } from \"drizzle-orm/better-sqlite3/migrator\";\nimport { getTraceContext } from \"@keystrokehq/tracing\";\nimport { createCipheriv, createDecipheriv, createHash, randomBytes } from \"node:crypto\";\nimport { buildCredentialInstanceLabel, deriveCredentialInstanceSlug, displayCredentialAppName, resolveUniqueCredentialInstanceLabel } from \"@keystrokehq/shared\";\n//#region \\0rolldown/runtime.js\nvar __defProp = Object.defineProperty;\nvar __exportAll = (all, no_symbols) => {\n\tlet target = {};\n\tfor (var name in all) __defProp(target, name, {\n\t\tget: all[name],\n\t\tenumerable: true\n\t});\n\tif (!no_symbols) __defProp(target, Symbol.toStringTag, { value: \"Module\" });\n\treturn target;\n};\n//#endregion\n//#region src/config/constants.ts\n/** Used when `DATABASE_URL` is unset and `initDatabase({ url })` is omitted. */\nconst DEFAULT_DATABASE_URL = \"file:./data/dev.db\";\nconst tenantScopeStorage = new AsyncLocalStorage();\nfunction runWithTenantScope(tenantId, fn) {\n\treturn tenantScopeStorage.run(tenantId, fn);\n}\nfunction getServerTenantScopeId() {\n\treturn tenantScopeStorage.getStore() ?? process.env.TENANT_ID?.trim() ?? \"default\";\n}\n//#endregion\n//#region src/config/project-scope.ts\n/** Default project id for local single-project dev. */\nconst DEFAULT_PROJECT_ID = \"default\";\nconst projectScopeStorage = new AsyncLocalStorage();\nfunction runWithProjectScope(projectId, fn) {\n\treturn projectScopeStorage.run(projectId, fn);\n}\nfunction getBoundProjectScopeId() {\n\treturn projectScopeStorage.getStore();\n}\nfunction getProjectScopeId() {\n\treturn getBoundProjectScopeId() ?? \"default\";\n}\n//#endregion\n//#region src/config/postgres-url.ts\nconst POSTGRES_ENV_KEYS = [\n\t\"POSTGRES_HOST\",\n\t\"POSTGRES_PORT\",\n\t\"POSTGRES_DB\",\n\t\"POSTGRES_USER\",\n\t\"POSTGRES_PASSWORD\"\n];\nfunction readEnv(env, key) {\n\treturn env[key]?.trim() || void 0;\n}\nfunction readPostgresSsl(env) {\n\tconst value = readEnv(env, \"POSTGRES_SSL\")?.toLowerCase();\n\treturn value === \"true\" || value === \"1\" || value === \"yes\";\n}\nfunction readPostgresSslFromUrl(url) {\n\ttry {\n\t\tconst sslmode = new URL(url.replace(/^postgresql:/i, \"postgres:\")).searchParams.get(\"sslmode\")?.toLowerCase();\n\t\treturn sslmode === \"require\" || sslmode === \"verify-ca\" || sslmode === \"verify-full\";\n\t} catch {\n\t\treturn false;\n\t}\n}\nfunction resolvePostgresSsl(env, url) {\n\treturn readPostgresSsl(env) || (url ? readPostgresSslFromUrl(url) : false);\n}\nfunction resolvePostgresBranch(env) {\n\tconst explicit = env.POSTGRES_BRANCH?.trim();\n\tif (explicit) return explicit;\n\tconst platformUser = readEnv(env, \"POSTGRES_USER\") ?? readPostgresUserFromDatabaseUrl(readEnv(env, \"DATABASE_URL\"));\n\tif (!platformUser?.includes(\".\")) return;\n\treturn platformUser.slice(platformUser.lastIndexOf(\".\") + 1) || void 0;\n}\nfunction readPostgresUserFromDatabaseUrl(url) {\n\tif (!url || !/^postgres(ql)?:\\/\\//i.test(url)) return;\n\ttry {\n\t\tconst parsed = new URL(url.replace(/^postgresql:/i, \"postgres:\"));\n\t\treturn decodeURIComponent(parsed.username);\n\t} catch {\n\t\treturn;\n\t}\n}\nfunction applyPostgresSslMode(url) {\n\tconst parsed = new URL(url.replace(/^postgresql:/i, \"postgres:\"));\n\tif (!parsed.searchParams.has(\"sslmode\")) parsed.searchParams.set(\"sslmode\", \"require\");\n\treturn parsed.toString().replace(/^postgres:/i, \"postgresql:\");\n}\nfunction missingPostgresEnvKeys(env) {\n\treturn POSTGRES_ENV_KEYS.filter((key) => readEnv(env, key) === void 0);\n}\n/** Append POSTGRES_BRANCH to bare role names for providers that use user.branch connections. */\nfunction qualifyConnectionUser(user, env = process.env) {\n\tif (user.includes(\".\")) return user;\n\tconst branch = resolvePostgresBranch(env);\n\tif (!branch) return user;\n\treturn `${user}.${branch}`;\n}\nfunction buildPostgresUrl(config) {\n\tconst user = encodeURIComponent(config.user);\n\tconst password = encodeURIComponent(config.password);\n\tconst auth = config.password ? `${user}:${password}` : user;\n\tconst database = encodeURIComponent(config.database).replace(/%2F/g, \"/\");\n\tconst url = `postgresql://${auth}@${config.host}:${config.port}/${database}`;\n\treturn config.ssl ? applyPostgresSslMode(url) : url;\n}\nfunction parsePostgresUrl(url) {\n\tconst parsed = new URL(url.replace(/^postgresql:/i, \"postgres:\"));\n\tconst database = decodeURIComponent(parsed.pathname.replace(/^\\//, \"\"));\n\tif (!database) throw new Error(`Postgres URL is missing database name: ${url}`);\n\treturn {\n\t\thost: parsed.hostname,\n\t\tport: parsed.port ? Number(parsed.port) : 5432,\n\t\tdatabase,\n\t\tuser: decodeURIComponent(parsed.username),\n\t\tpassword: decodeURIComponent(parsed.password)\n\t};\n}\nfunction resolvePostgresConfigFromPostgresEnv(env) {\n\tif (missingPostgresEnvKeys(env).length > 0) return;\n\tconst port = Number(readEnv(env, \"POSTGRES_PORT\"));\n\tif (!Number.isFinite(port)) throw new Error(`Invalid POSTGRES_PORT: ${env.POSTGRES_PORT}`);\n\treturn {\n\t\thost: readEnv(env, \"POSTGRES_HOST\"),\n\t\tport,\n\t\tdatabase: readEnv(env, \"POSTGRES_DB\"),\n\t\tuser: readEnv(env, \"POSTGRES_USER\"),\n\t\tpassword: readEnv(env, \"POSTGRES_PASSWORD\"),\n\t\tssl: readPostgresSsl(env)\n\t};\n}\n/** Requires POSTGRES_* env vars or a postgres DATABASE_URL. */\nfunction resolvePostgresConfigFromEnv(env = process.env) {\n\tconst direct = readEnv(env, \"DATABASE_URL\");\n\tif (direct && /^postgres(ql)?:\\/\\//i.test(direct)) return {\n\t\t...parsePostgresUrl(direct),\n\t\tssl: resolvePostgresSsl(env, direct)\n\t};\n\tconst config = resolvePostgresConfigFromPostgresEnv(env);\n\tif (!config) throw new Error(`Missing required Postgres env vars: ${missingPostgresEnvKeys(env).join(\", \")}`);\n\treturn config;\n}\n/** Requires POSTGRES_* env vars or a postgres DATABASE_URL. */\nfunction resolvePostgresUrlFromEnv(env = process.env) {\n\tconst ssl = readPostgresSsl(env);\n\tconst direct = readEnv(env, \"DATABASE_URL\");\n\tif (direct && /^postgres(ql)?:\\/\\//i.test(direct)) return ssl ? applyPostgresSslMode(direct) : direct;\n\treturn buildPostgresUrl(resolvePostgresConfigFromEnv(env));\n}\n/**\n* Project runtime — POSTGRES_* only (same env shape as hosted workers).\n* Returns undefined when unset; initDatabase falls back to sqlite DEFAULT_DATABASE_URL.\n* Optional DATABASE_SEARCH_PATH sets the tenant schema search_path.\n*/\nfunction resolveProjectDatabaseUrlFromEnv(env = process.env) {\n\tconst config = resolvePostgresConfigFromPostgresEnv(env);\n\treturn config ? buildPostgresUrl(config) : void 0;\n}\n/** @deprecated Prefer resolveProjectDatabaseUrlFromEnv (project) or resolvePostgresUrlFromEnv (platform). */\nfunction resolveDatabaseUrlFromEnv(env = process.env) {\n\treturn resolveProjectDatabaseUrlFromEnv(env);\n}\n//#endregion\n//#region src/client/request-context.ts\nconst requestHandle = new AsyncLocalStorage();\nfunction getRequestDatabaseHandle() {\n\treturn requestHandle.getStore();\n}\nfunction runWithRequestDatabaseHandle(handle, fn) {\n\treturn requestHandle.run(handle, fn);\n}\n//#endregion\n//#region src/client/context.ts\nlet handle;\nfunction isDatabaseInitialized() {\n\treturn getRequestDatabaseHandle() !== void 0 || handle !== void 0;\n}\nfunction getDatabaseHandle() {\n\tconst scoped = getRequestDatabaseHandle();\n\tif (scoped) return scoped;\n\tif (!handle) throw new Error(\"Database not initialized. Call initDatabase() before getDb().\");\n\treturn handle;\n}\nfunction setDatabaseHandle(next) {\n\thandle = next;\n}\nfunction getDefaultDatabaseHandle() {\n\treturn handle;\n}\nfunction getDbFromContext() {\n\treturn getDatabaseHandle().db;\n}\n//#endregion\n//#region src/connection/pg/driver.ts\nconst require = createRequire(import.meta.url);\n/**\n* Lazily load the native `pg` driver. Keeping this off the module's static import\n* graph means consumers that only reference database helpers/types (e.g. the CLI,\n* which never opens a Postgres pool) never force `pg` into their bundle — it\n* resolves from the runtime image only when a connection is actually created.\n*/\nfunction loadPg() {\n\treturn require(\"pg\");\n}\n/** Lazily load drizzle's node-postgres adapter — it statically imports `pg`. */\nfunction loadDrizzlePg() {\n\treturn require(\"drizzle-orm/node-postgres\");\n}\n//#endregion\n//#region src/schema/bundle.ts\nfunction buildPgSchema(registry) {\n\treturn Object.fromEntries(Object.entries(registry).map(([name, { pg }]) => [name, pg]));\n}\nfunction buildSqliteSchema(registry) {\n\treturn Object.fromEntries(Object.entries(registry).map(([name, { sqlite }]) => [name, sqlite]));\n}\n//#endregion\n//#region src/schema/tables/agents.ts\nconst agents = pgTable(\"agents\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\tslug: text(\"slug\").notNull(),\n\tname: text(\"name\"),\n\tdescription: text(\"description\"),\n\troute: text(\"route\").notNull(),\n\tmoduleFile: text(\"module_file\").notNull(),\n\tmodel: text(\"model\").notNull(),\n\tsystemPrompt: text(\"system_prompt\").notNull(),\n\ttoolCount: integer(\"tool_count\"),\n\tcredentialCount: integer(\"credential_count\"),\n\tappSlugs: jsonb(\"app_slugs\").$type(),\n\tregisteredAt: timestamp(\"registered_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tdeletedAt: timestamp(\"deleted_at\", { withTimezone: true })\n}, (table) => [uniqueIndex(\"agents_project_id_slug_idx\").on(table.projectId, table.slug), uniqueIndex(\"agents_project_id_route_idx\").on(table.projectId, table.route)]);\nconst agentsSqlite = sqliteTable(\"agents\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\tslug: text$1(\"slug\").notNull(),\n\tname: text$1(\"name\"),\n\tdescription: text$1(\"description\"),\n\troute: text$1(\"route\").notNull(),\n\tmoduleFile: text$1(\"module_file\").notNull(),\n\tmodel: text$1(\"model\").notNull(),\n\tsystemPrompt: text$1(\"system_prompt\").notNull(),\n\ttoolCount: integer$1(\"tool_count\"),\n\tcredentialCount: integer$1(\"credential_count\"),\n\tappSlugs: text$1(\"app_slugs\", { mode: \"json\" }).$type(),\n\tregisteredAt: integer$1(\"registered_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tdeletedAt: integer$1(\"deleted_at\", { mode: \"timestamp_ms\" })\n}, (table) => [uniqueIndex$1(\"agents_project_id_slug_idx\").on(table.projectId, table.slug), uniqueIndex$1(\"agents_project_id_route_idx\").on(table.projectId, table.route)]);\n//#endregion\n//#region src/schema/tables/agent-sessions.ts\nconst agentSessions = pgTable(\"agent_sessions\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\tagentId: text(\"agent_id\").notNull().references(() => agents.id),\n\tsourceKind: text(\"source_kind\").$type().notNull().default(\"api\"),\n\tsourceId: text(\"source_id\"),\n\tparentSpanId: text(\"parent_span_id\"),\n\tranByUserId: text(\"ran_by_user_id\"),\n\ttitle: text(\"title\"),\n\tcanceledAt: timestamp(\"canceled_at\", { withTimezone: true }),\n\ttotalDurationMs: integer(\"total_duration_ms\").notNull().default(0),\n\tliveMessage: jsonb(\"live_message\"),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tdeletedAt: timestamp(\"deleted_at\", { withTimezone: true })\n}, (table) => [index(\"agent_sessions_agent_updated_idx\").on(table.agentId, table.updatedAt)]);\nconst agentSessionsSqlite = sqliteTable(\"agent_sessions\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\tagentId: text$1(\"agent_id\").notNull().references(() => agentsSqlite.id),\n\tsourceKind: text$1(\"source_kind\").$type().notNull().default(\"api\"),\n\tsourceId: text$1(\"source_id\"),\n\tparentSpanId: text$1(\"parent_span_id\"),\n\tranByUserId: text$1(\"ran_by_user_id\"),\n\ttitle: text$1(\"title\"),\n\tcanceledAt: integer$1(\"canceled_at\", { mode: \"timestamp_ms\" }),\n\ttotalDurationMs: integer$1(\"total_duration_ms\").notNull().default(0),\n\tliveMessage: text$1(\"live_message\", { mode: \"json\" }),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tdeletedAt: integer$1(\"deleted_at\", { mode: \"timestamp_ms\" })\n}, (table) => [index$1(\"agent_sessions_agent_updated_idx\").on(table.agentId, table.updatedAt)]);\n//#endregion\n//#region src/schema/tables/agent-events.ts\nconst agentEvents = pgTable(\"agent_events\", {\n\tid: text(\"id\").primaryKey(),\n\tsessionId: text(\"session_id\").notNull().references(() => agentSessions.id),\n\tseq: integer(\"seq\").notNull(),\n\teventType: text(\"event_type\").notNull(),\n\tpayload: jsonb(\"payload\").notNull(),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tdeletedAt: timestamp(\"deleted_at\", { withTimezone: true })\n});\nconst agentEventsSqlite = sqliteTable(\"agent_events\", {\n\tid: text$1(\"id\").primaryKey(),\n\tsessionId: text$1(\"session_id\").notNull().references(() => agentSessionsSqlite.id),\n\tseq: integer$1(\"seq\").notNull(),\n\teventType: text$1(\"event_type\").notNull(),\n\tpayload: text$1(\"payload\", { mode: \"json\" }).notNull(),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tdeletedAt: integer$1(\"deleted_at\", { mode: \"timestamp_ms\" })\n});\n//#endregion\n//#region src/schema/tables/usage-records.ts\nconst usageRecords = pgTable(\"usage_records\", {\n\tid: text(\"id\").primaryKey(),\n\trunId: text(\"run_id\").notNull(),\n\trunKind: text(\"run_kind\").$type().notNull(),\n\tkind: text(\"kind\").notNull(),\n\tlabel: text(\"label\").notNull(),\n\tquantity: integer(\"quantity\"),\n\tunit: text(\"unit\"),\n\tamount: doublePrecision(\"amount\").notNull(),\n\tmetadata: jsonb(\"metadata\"),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull()\n}, (table) => [index(\"usage_records_run_run_kind_idx\").on(table.runId, table.runKind), index(\"usage_records_kind_idx\").on(table.kind)]);\nconst usageRecordsSqlite = sqliteTable(\"usage_records\", {\n\tid: text$1(\"id\").primaryKey(),\n\trunId: text$1(\"run_id\").notNull(),\n\trunKind: text$1(\"run_kind\").$type().notNull(),\n\tkind: text$1(\"kind\").notNull(),\n\tlabel: text$1(\"label\").notNull(),\n\tquantity: integer$1(\"quantity\"),\n\tunit: text$1(\"unit\"),\n\tamount: real(\"amount\").notNull(),\n\tmetadata: text$1(\"metadata\", { mode: \"json\" }),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [index$1(\"usage_records_run_run_kind_idx\").on(table.runId, table.runKind), index$1(\"usage_records_kind_idx\").on(table.kind)]);\n//#endregion\n//#region src/schema/tables/triggers.ts\nconst triggers = pgTable(\"triggers\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\tslug: text(\"slug\").notNull(),\n\tkind: text(\"kind\").$type().notNull(),\n\tname: text(\"name\"),\n\tdescription: text(\"description\"),\n\tmoduleFile: text(\"module_file\").notNull(),\n\torigin: text(\"origin\").$type().notNull().default(\"project\"),\n\tconfig: jsonb(\"config\").$type(),\n\tschedule: text(\"schedule\"),\n\tnextRunAt: timestamp(\"next_run_at\", { withTimezone: true }),\n\tenabled: integer(\"enabled\").notNull().default(1),\n\tlifecycle: jsonb(\"lifecycle\").$type(),\n\tcreatedBySessionId: text(\"created_by_session_id\"),\n\ttriggerHash: text(\"trigger_hash\"),\n\toverviewMarkdown: text(\"overview_markdown\"),\n\toverviewHash: text(\"overview_hash\"),\n\toverviewModel: text(\"overview_model\"),\n\toverviewStatus: text(\"overview_status\").$type().notNull().default(\"idle\"),\n\toverviewGeneratedAt: timestamp(\"overview_generated_at\", { withTimezone: true }),\n\tregisteredAt: timestamp(\"registered_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tdeletedAt: timestamp(\"deleted_at\", { withTimezone: true })\n}, (table) => [uniqueIndex(\"triggers_project_id_slug_idx\").on(table.projectId, table.slug), index(\"triggers_next_run_at_enabled_idx\").on(table.nextRunAt, table.enabled)]);\nconst triggersSqlite = sqliteTable(\"triggers\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\tslug: text$1(\"slug\").notNull(),\n\tkind: text$1(\"kind\").$type().notNull(),\n\tname: text$1(\"name\"),\n\tdescription: text$1(\"description\"),\n\tmoduleFile: text$1(\"module_file\").notNull(),\n\torigin: text$1(\"origin\").$type().notNull().default(\"project\"),\n\tconfig: text$1(\"config\", { mode: \"json\" }).$type(),\n\tschedule: text$1(\"schedule\"),\n\tnextRunAt: integer$1(\"next_run_at\", { mode: \"timestamp_ms\" }),\n\tenabled: integer$1(\"enabled\").notNull().default(1),\n\tlifecycle: text$1(\"lifecycle\", { mode: \"json\" }).$type(),\n\tcreatedBySessionId: text$1(\"created_by_session_id\"),\n\ttriggerHash: text$1(\"trigger_hash\"),\n\toverviewMarkdown: text$1(\"overview_markdown\"),\n\toverviewHash: text$1(\"overview_hash\"),\n\toverviewModel: text$1(\"overview_model\"),\n\toverviewStatus: text$1(\"overview_status\").$type().notNull().default(\"idle\"),\n\toverviewGeneratedAt: integer$1(\"overview_generated_at\", { mode: \"timestamp_ms\" }),\n\tregisteredAt: integer$1(\"registered_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tdeletedAt: integer$1(\"deleted_at\", { mode: \"timestamp_ms\" })\n}, (table) => [uniqueIndex$1(\"triggers_project_id_slug_idx\").on(table.projectId, table.slug), index$1(\"triggers_next_run_at_enabled_idx\").on(table.nextRunAt, table.enabled)]);\n//#endregion\n//#region src/schema/tables/trigger-attachments.ts\nconst triggerAttachments = pgTable(\"trigger_attachments\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\ttriggerId: text(\"trigger_id\").notNull().references(() => triggers.id),\n\tslug: text(\"slug\").notNull(),\n\ttargetKind: text(\"target_kind\").$type().notNull().default(\"workflow\"),\n\tworkflowSlug: text(\"workflow_slug\"),\n\tagentSlug: text(\"agent_slug\"),\n\tprompt: text(\"prompt\"),\n\tregisteredAt: timestamp(\"registered_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tdeletedAt: timestamp(\"deleted_at\", { withTimezone: true })\n}, (table) => [uniqueIndex(\"trigger_attachments_project_id_slug_idx\").on(table.projectId, table.slug)]);\nconst triggerAttachmentsSqlite = sqliteTable(\"trigger_attachments\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\ttriggerId: text$1(\"trigger_id\").notNull().references(() => triggersSqlite.id),\n\tslug: text$1(\"slug\").notNull(),\n\ttargetKind: text$1(\"target_kind\").$type().notNull().default(\"workflow\"),\n\tworkflowSlug: text$1(\"workflow_slug\"),\n\tagentSlug: text$1(\"agent_slug\"),\n\tprompt: text$1(\"prompt\"),\n\tregisteredAt: integer$1(\"registered_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tdeletedAt: integer$1(\"deleted_at\", { mode: \"timestamp_ms\" })\n}, (table) => [uniqueIndex$1(\"trigger_attachments_project_id_slug_idx\").on(table.projectId, table.slug)]);\n//#endregion\n//#region src/schema/tables/trigger-runs.ts\nconst triggerRuns = pgTable(\"trigger_runs\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\ttriggerId: text(\"trigger_id\").notNull().references(() => triggers.id),\n\tsourcePath: text(\"source_path\"),\n\ttriggerType: text(\"trigger_type\").$type().notNull(),\n\toutcome: text(\"outcome\").$type().notNull().default(\"dispatched\"),\n\treason: text(\"reason\").$type(),\n\tdetail: text(\"detail\"),\n\tpayload: jsonb(\"payload\"),\n\ttriggeredAt: timestamp(\"triggered_at\", { withTimezone: true }).notNull()\n}, (table) => [index(\"trigger_runs_project_trigger_triggered_idx\").on(table.projectId, table.triggerId, table.triggeredAt), index(\"trigger_runs_project_triggered_idx\").on(table.projectId, table.triggeredAt)]);\nconst triggerRunsSqlite = sqliteTable(\"trigger_runs\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\ttriggerId: text$1(\"trigger_id\").notNull().references(() => triggersSqlite.id),\n\tsourcePath: text$1(\"source_path\"),\n\ttriggerType: text$1(\"trigger_type\").$type().notNull(),\n\toutcome: text$1(\"outcome\").$type().notNull().default(\"dispatched\"),\n\treason: text$1(\"reason\").$type(),\n\tdetail: text$1(\"detail\"),\n\tpayload: text$1(\"payload\", { mode: \"json\" }),\n\ttriggeredAt: integer$1(\"triggered_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [index$1(\"trigger_runs_project_trigger_triggered_idx\").on(table.projectId, table.triggerId, table.triggeredAt), index$1(\"trigger_runs_project_triggered_idx\").on(table.projectId, table.triggeredAt)]);\n//#endregion\n//#region src/schema/tables/workflow-subscriptions.ts\nconst workflowSubscriptions = pgTable(\"workflow_subscriptions\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\tworkflowSlug: text(\"workflow_slug\").notNull(),\n\tuserId: text(\"user_id\").notNull(),\n\tenabled: integer(\"enabled\").notNull(),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [uniqueIndex(\"workflow_subscriptions_project_workflow_user\").on(table.projectId, table.workflowSlug, table.userId)]);\nconst workflowSubscriptionsSqlite = sqliteTable(\"workflow_subscriptions\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\tworkflowSlug: text$1(\"workflow_slug\").notNull(),\n\tuserId: text$1(\"user_id\").notNull(),\n\tenabled: integer$1(\"enabled\", { mode: \"boolean\" }).notNull(),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [uniqueIndex$1(\"workflow_subscriptions_project_workflow_user\").on(table.projectId, table.workflowSlug, table.userId)]);\n//#endregion\n//#region src/schema/tables/workflow-runs.ts\nconst workflowRuns = pgTable(\"workflow_runs\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\tworkflowSlug: text(\"workflow_slug\").notNull(),\n\tattachmentId: text(\"attachment_id\").references(() => triggerAttachments.id),\n\tsubscriptionId: text(\"subscription_id\").references(() => workflowSubscriptions.id),\n\ttriggerRunId: text(\"trigger_run_id\").references(() => triggerRuns.id),\n\tparentWorkflowRunId: text(\"parent_workflow_run_id\"),\n\tparentSpanId: text(\"parent_span_id\"),\n\tsourceKind: text(\"source_kind\").$type().notNull().default(\"api\"),\n\tsourceId: text(\"source_id\"),\n\tranByUserId: text(\"ran_by_user_id\"),\n\tstatus: text(\"status\").$type().notNull(),\n\ttrigger: text(\"trigger\").$type().notNull(),\n\ttriggeredAt: timestamp(\"triggered_at\", { withTimezone: true }).notNull(),\n\tstartedAt: timestamp(\"started_at\", { withTimezone: true }),\n\tfinishedAt: timestamp(\"finished_at\", { withTimezone: true }),\n\tinput: jsonb(\"input\"),\n\toutput: jsonb(\"output\"),\n\terror: jsonb(\"error\")\n}, (table) => [index(\"workflow_runs_project_workflow_triggered_idx\").on(table.projectId, table.workflowSlug, table.triggeredAt)]);\nconst workflowRunsSqlite = sqliteTable(\"workflow_runs\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\tworkflowSlug: text$1(\"workflow_slug\").notNull(),\n\tattachmentId: text$1(\"attachment_id\").references(() => triggerAttachmentsSqlite.id),\n\tsubscriptionId: text$1(\"subscription_id\").references(() => workflowSubscriptionsSqlite.id),\n\ttriggerRunId: text$1(\"trigger_run_id\").references(() => triggerRunsSqlite.id),\n\tparentWorkflowRunId: text$1(\"parent_workflow_run_id\"),\n\tparentSpanId: text$1(\"parent_span_id\"),\n\tsourceKind: text$1(\"source_kind\").$type().notNull().default(\"api\"),\n\tsourceId: text$1(\"source_id\"),\n\tranByUserId: text$1(\"ran_by_user_id\"),\n\tstatus: text$1(\"status\").$type().notNull(),\n\ttrigger: text$1(\"trigger\").$type().notNull(),\n\ttriggeredAt: integer$1(\"triggered_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tstartedAt: integer$1(\"started_at\", { mode: \"timestamp_ms\" }),\n\tfinishedAt: integer$1(\"finished_at\", { mode: \"timestamp_ms\" }),\n\tinput: text$1(\"input\", { mode: \"json\" }),\n\toutput: text$1(\"output\", { mode: \"json\" }),\n\terror: text$1(\"error\", { mode: \"json\" })\n}, (table) => [index$1(\"workflow_runs_project_workflow_triggered_idx\").on(table.projectId, table.workflowSlug, table.triggeredAt)]);\n//#endregion\n//#region src/schema/tables/workflow-events.ts\n/**\n* Append-only durable execution log. One row per workflow lifecycle transition.\n* Replay reads these in `seq` order and short-circuits already-completed primitives.\n*/\nconst workflowEvents = pgTable(\"workflow_events\", {\n\tid: text(\"id\").primaryKey(),\n\trunId: text(\"run_id\").notNull().references(() => workflowRuns.id),\n\tprojectId: text(\"project_id\").notNull(),\n\tseq: integer(\"seq\").notNull(),\n\ttype: text(\"type\").$type().notNull(),\n\tcorrelationId: text(\"correlation_id\"),\n\tdata: jsonb(\"data\"),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull()\n}, (table) => [\n\tuniqueIndex(\"workflow_events_run_id_seq_unique\").on(table.runId, table.seq),\n\tindex(\"workflow_events_run_id_type_idx\").on(table.runId, table.type),\n\tindex(\"workflow_events_correlation_id_idx\").on(table.correlationId)\n]);\nconst workflowEventsSqlite = sqliteTable(\"workflow_events\", {\n\tid: text$1(\"id\").primaryKey(),\n\trunId: text$1(\"run_id\").notNull().references(() => workflowRunsSqlite.id),\n\tprojectId: text$1(\"project_id\").notNull(),\n\tseq: integer$1(\"seq\").notNull(),\n\ttype: text$1(\"type\").$type().notNull(),\n\tcorrelationId: text$1(\"correlation_id\"),\n\tdata: text$1(\"data\", { mode: \"json\" }),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [\n\tuniqueIndex$1(\"workflow_events_run_id_seq_unique\").on(table.runId, table.seq),\n\tindex$1(\"workflow_events_run_id_type_idx\").on(table.runId, table.type),\n\tindex$1(\"workflow_events_correlation_id_idx\").on(table.correlationId)\n]);\n//#endregion\n//#region src/schema/tables/workflow-hooks.ts\nconst workflowHooks = pgTable(\"workflow_hooks\", {\n\thookId: text(\"hook_id\").primaryKey(),\n\trunId: text(\"run_id\").notNull().references(() => workflowRuns.id),\n\tprojectId: text(\"project_id\").notNull(),\n\ttoken: text(\"token\").notNull(),\n\tcorrelationId: text(\"correlation_id\").notNull(),\n\tstatus: text(\"status\").$type().notNull(),\n\tpayload: jsonb(\"payload\"),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tresumedAt: timestamp(\"resumed_at\", { withTimezone: true })\n}, (table) => [uniqueIndex(\"workflow_hooks_token_unique\").on(table.token), index(\"workflow_hooks_run_id_idx\").on(table.runId)]);\nconst workflowHooksSqlite = sqliteTable(\"workflow_hooks\", {\n\thookId: text$1(\"hook_id\").primaryKey(),\n\trunId: text$1(\"run_id\").notNull().references(() => workflowRunsSqlite.id),\n\tprojectId: text$1(\"project_id\").notNull(),\n\ttoken: text$1(\"token\").notNull(),\n\tcorrelationId: text$1(\"correlation_id\").notNull(),\n\tstatus: text$1(\"status\").$type().notNull(),\n\tpayload: text$1(\"payload\", { mode: \"json\" }),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tresumedAt: integer$1(\"resumed_at\", { mode: \"timestamp_ms\" })\n}, (table) => [uniqueIndex$1(\"workflow_hooks_token_unique\").on(table.token), index$1(\"workflow_hooks_run_id_idx\").on(table.runId)]);\n//#endregion\n//#region src/schema/tables/credential-instances.ts\nconst credentialInstances = pgTable(\"credential_instances\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\tappSlug: text(\"app_slug\").notNull(),\n\tslug: text(\"slug\").notNull(),\n\tname: text(\"name\"),\n\tscopeType: text(\"scope_type\").$type().notNull(),\n\tscopeId: text(\"scope_id\"),\n\tlabel: text(\"label\"),\n\tisDefault: integer(\"is_default\").notNull(),\n\tauthKind: text(\"auth_kind\").$type().notNull(),\n\tciphertext: text(\"ciphertext\"),\n\tconnectionId: text(\"connection_id\"),\n\t/** MCP entity id that owns connection_id when multiple scopes share one connection. */\n\tsharedConnectionId: text(\"shared_connection_id\"),\n\tgrantedScopes: jsonb(\"granted_scopes\").$type(),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tlastUsedAt: timestamp(\"last_used_at\", { withTimezone: true })\n}, (table) => [uniqueIndex(\"credential_instances_project_scope_slug_unique\").on(table.projectId, table.scopeType, table.scopeId, table.slug), index(\"credential_instances_project_app_slug_scope_idx\").on(table.projectId, table.appSlug, table.scopeType, table.scopeId)]);\nconst credentialInstancesSqlite = sqliteTable(\"credential_instances\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\tappSlug: text$1(\"app_slug\").notNull(),\n\tslug: text$1(\"slug\").notNull(),\n\tname: text$1(\"name\"),\n\tscopeType: text$1(\"scope_type\").$type().notNull(),\n\tscopeId: text$1(\"scope_id\"),\n\tlabel: text$1(\"label\"),\n\tisDefault: integer$1(\"is_default\", { mode: \"boolean\" }).notNull(),\n\tauthKind: text$1(\"auth_kind\").$type().notNull(),\n\tciphertext: text$1(\"ciphertext\"),\n\tconnectionId: text$1(\"connection_id\"),\n\t/** MCP entity id that owns connection_id when multiple scopes share one connection. */\n\tsharedConnectionId: text$1(\"shared_connection_id\"),\n\tgrantedScopes: text$1(\"granted_scopes\", { mode: \"json\" }).$type(),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tlastUsedAt: integer$1(\"last_used_at\", { mode: \"timestamp_ms\" })\n}, (table) => [uniqueIndex$1(\"credential_instances_project_scope_slug_unique\").on(table.projectId, table.scopeType, table.scopeId, table.slug), index$1(\"credential_instances_project_app_slug_scope_idx\").on(table.projectId, table.appSlug, table.scopeType, table.scopeId)]);\n//#endregion\n//#region src/schema/tables/credential-assignments.ts\nconst credentialAssignments = pgTable(\"credential_assignments\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\ttargetType: text(\"target_type\").$type().notNull(),\n\ttargetKey: text(\"target_key\").notNull(),\n\t/** '*' = wildcard; else runtime consumer id (step correlation id or tool slug). */\n\tconsumerId: text(\"consumer_id\").notNull(),\n\tcredentialSlug: text(\"credential_slug\").notNull(),\n\tinstanceId: text(\"instance_id\").notNull(),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [uniqueIndex(\"credential_assignments_project_target_consumer_slug\").on(table.projectId, table.targetType, table.targetKey, table.consumerId, table.credentialSlug), index(\"credential_assignments_project_target_idx\").on(table.projectId, table.targetType, table.targetKey)]);\nconst credentialAssignmentsSqlite = sqliteTable(\"credential_assignments\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\ttargetType: text$1(\"target_type\").$type().notNull(),\n\ttargetKey: text$1(\"target_key\").notNull(),\n\tconsumerId: text$1(\"consumer_id\").notNull(),\n\tcredentialSlug: text$1(\"credential_slug\").notNull(),\n\tinstanceId: text$1(\"instance_id\").notNull(),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [uniqueIndex$1(\"credential_assignments_project_target_consumer_slug\").on(table.projectId, table.targetType, table.targetKey, table.consumerId, table.credentialSlug), index$1(\"credential_assignments_project_target_idx\").on(table.projectId, table.targetType, table.targetKey)]);\n//#endregion\n//#region src/schema/tables/jobs.ts\nconst jobs = pgTable(\"jobs\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\tkind: text(\"kind\").$type().notNull(),\n\ttargetId: text(\"target_id\").notNull(),\n\trunId: text(\"run_id\").notNull(),\n\ttrigger: text(\"trigger\").$type().notNull(),\n\tpayload: jsonb(\"payload\"),\n\tstatus: text(\"status\").$type().notNull(),\n\tscheduledAt: timestamp(\"scheduled_at\", { withTimezone: true }).notNull(),\n\tattempt: integer(\"attempt\").notNull(),\n\tmaxAttempts: integer(\"max_attempts\").notNull(),\n\tleasedBy: text(\"leased_by\"),\n\tleaseExpiresAt: timestamp(\"lease_expires_at\", { withTimezone: true }),\n\tcompletedAt: timestamp(\"completed_at\", { withTimezone: true }),\n\terror: jsonb(\"error\")\n});\nconst jobsSqlite = sqliteTable(\"jobs\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\tkind: text$1(\"kind\").$type().notNull(),\n\ttargetId: text$1(\"target_id\").notNull(),\n\trunId: text$1(\"run_id\").notNull(),\n\ttrigger: text$1(\"trigger\").$type().notNull(),\n\tpayload: text$1(\"payload\", { mode: \"json\" }),\n\tstatus: text$1(\"status\").$type().notNull(),\n\tscheduledAt: integer$1(\"scheduled_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tattempt: integer$1(\"attempt\").notNull(),\n\tmaxAttempts: integer$1(\"max_attempts\").notNull(),\n\tleasedBy: text$1(\"leased_by\"),\n\tleaseExpiresAt: integer$1(\"lease_expires_at\", { mode: \"timestamp_ms\" }),\n\tcompletedAt: integer$1(\"completed_at\", { mode: \"timestamp_ms\" }),\n\terror: text$1(\"error\", { mode: \"json\" })\n});\n//#endregion\n//#region src/schema/tables/gateway-attachments.ts\nconst gatewayAttachments = pgTable(\"gateway_attachments\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\tslug: text(\"slug\").notNull(),\n\tagentSlug: text(\"agent_slug\").notNull(),\n\tmoduleFile: text(\"module_file\"),\n\tplatform: text(\"platform\").notNull(),\n\tteamId: text(\"team_id\"),\n\tchannelId: text(\"channel_id\").notNull(),\n\tsource: jsonb(\"source\").$type().notNull(),\n\tregisteredAt: timestamp(\"registered_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tdeletedAt: timestamp(\"deleted_at\", { withTimezone: true })\n}, (table) => [uniqueIndex(\"gateway_attachments_project_id_slug_idx\").on(table.projectId, table.slug), uniqueIndex(\"gateway_attachments_project_platform_channel_active\").on(table.projectId, table.platform, table.channelId).where(sql`${table.deletedAt} is null`)]);\nconst gatewayAttachmentsSqlite = sqliteTable(\"gateway_attachments\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\tslug: text$1(\"slug\").notNull(),\n\tagentSlug: text$1(\"agent_slug\").notNull(),\n\tmoduleFile: text$1(\"module_file\"),\n\tplatform: text$1(\"platform\").notNull(),\n\tteamId: text$1(\"team_id\"),\n\tchannelId: text$1(\"channel_id\").notNull(),\n\tsource: text$1(\"source\", { mode: \"json\" }).$type().notNull(),\n\tregisteredAt: integer$1(\"registered_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tdeletedAt: integer$1(\"deleted_at\", { mode: \"timestamp_ms\" })\n}, (table) => [uniqueIndex$1(\"gateway_attachments_project_id_slug_idx\").on(table.projectId, table.slug), uniqueIndex$1(\"gateway_attachments_project_platform_channel_active\").on(table.projectId, table.platform, table.channelId).where(sql`${table.deletedAt} is null`)]);\nfunction gatewayAttachmentKeyForChannel(platform, channelId) {\n\treturn `${platform}:${channelId}`;\n}\n//#endregion\n//#region src/schema/tables/gateway-thread-sessions.ts\nconst gatewayThreadSessions = pgTable(\"gateway_thread_sessions\", {\n\tthreadId: text(\"thread_id\").primaryKey(),\n\tagentId: text(\"agent_id\").notNull().references(() => agents.id),\n\tsessionId: text(\"session_id\").notNull().references(() => agentSessions.id),\n\tattachmentId: text(\"attachment_id\").notNull().references(() => gatewayAttachments.id),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n});\nconst gatewayThreadSessionsSqlite = sqliteTable(\"gateway_thread_sessions\", {\n\tthreadId: text$1(\"thread_id\").primaryKey(),\n\tagentId: text$1(\"agent_id\").notNull().references(() => agentsSqlite.id),\n\tsessionId: text$1(\"session_id\").notNull().references(() => agentSessionsSqlite.id),\n\tattachmentId: text$1(\"attachment_id\").notNull().references(() => gatewayAttachmentsSqlite.id),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n});\n//#endregion\n//#region src/schema/tables/trace-spans.ts\nconst traceSpans = pgTable(\"trace_spans\", {\n\tid: text(\"id\").primaryKey(),\n\ttraceId: text(\"trace_id\").notNull(),\n\tparentSpanId: text(\"parent_span_id\"),\n\tkind: text(\"kind\").$type().notNull(),\n\trefId: text(\"ref_id\").notNull(),\n\tname: text(\"name\").notNull(),\n\tstatus: text(\"status\").$type().notNull(),\n\tstartedAt: timestamp(\"started_at\", { withTimezone: true }).notNull(),\n\tfinishedAt: timestamp(\"finished_at\", { withTimezone: true }),\n\tmetadata: jsonb(\"metadata\"),\n\terror: jsonb(\"error\")\n});\nconst traceSpansSqlite = sqliteTable(\"trace_spans\", {\n\tid: text$1(\"id\").primaryKey(),\n\ttraceId: text$1(\"trace_id\").notNull(),\n\tparentSpanId: text$1(\"parent_span_id\"),\n\tkind: text$1(\"kind\").$type().notNull(),\n\trefId: text$1(\"ref_id\").notNull(),\n\tname: text$1(\"name\").notNull(),\n\tstatus: text$1(\"status\").$type().notNull(),\n\tstartedAt: integer$1(\"started_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tfinishedAt: integer$1(\"finished_at\", { mode: \"timestamp_ms\" }),\n\tmetadata: text$1(\"metadata\", { mode: \"json\" }),\n\terror: text$1(\"error\", { mode: \"json\" })\n});\n//#endregion\n//#region src/schema/tables/trace-logs.ts\nconst traceLogs = pgTable(\"trace_logs\", {\n\tid: text(\"id\").primaryKey(),\n\ttraceId: text(\"trace_id\").notNull(),\n\tspanId: text(\"span_id\").notNull().references(() => traceSpans.id),\n\tseq: integer(\"seq\").notNull(),\n\tlevel: text(\"level\").$type().notNull(),\n\tmessage: text(\"message\").notNull(),\n\tdata: jsonb(\"data\"),\n\tsource: text(\"source\").$type().notNull(),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull()\n}, (table) => [index(\"trace_logs_trace_id_seq_idx\").on(table.traceId, table.seq), index(\"trace_logs_span_id_seq_idx\").on(table.spanId, table.seq)]);\nconst traceLogsSqlite = sqliteTable(\"trace_logs\", {\n\tid: text$1(\"id\").primaryKey(),\n\ttraceId: text$1(\"trace_id\").notNull(),\n\tspanId: text$1(\"span_id\").notNull().references(() => traceSpansSqlite.id),\n\tseq: integer$1(\"seq\").notNull(),\n\tlevel: text$1(\"level\").$type().notNull(),\n\tmessage: text$1(\"message\").notNull(),\n\tdata: text$1(\"data\", { mode: \"json\" }),\n\tsource: text$1(\"source\").$type().notNull(),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [index$1(\"trace_logs_trace_id_seq_idx\").on(table.traceId, table.seq), index$1(\"trace_logs_span_id_seq_idx\").on(table.spanId, table.seq)]);\n//#endregion\n//#region src/schema/tables/skills.ts\nconst skills = pgTable(\"skills\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\tslug: text(\"slug\").notNull(),\n\tname: text(\"name\"),\n\tdescription: text(\"description\"),\n\tmoduleFile: text(\"module_file\").notNull(),\n\tregisteredAt: timestamp(\"registered_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tdeletedAt: timestamp(\"deleted_at\", { withTimezone: true })\n}, (table) => [uniqueIndex(\"skills_project_id_slug_idx\").on(table.projectId, table.slug)]);\nconst skillsSqlite = sqliteTable(\"skills\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\tslug: text$1(\"slug\").notNull(),\n\tname: text$1(\"name\"),\n\tdescription: text$1(\"description\"),\n\tmoduleFile: text$1(\"module_file\").notNull(),\n\tregisteredAt: integer$1(\"registered_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tdeletedAt: integer$1(\"deleted_at\", { mode: \"timestamp_ms\" })\n}, (table) => [uniqueIndex$1(\"skills_project_id_slug_idx\").on(table.projectId, table.slug)]);\n//#endregion\n//#region src/schema/tables/workflows.ts\nconst workflows = pgTable(\"workflows\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\tslug: text(\"slug\").notNull(),\n\tname: text(\"name\"),\n\tdescription: text(\"description\"),\n\tmoduleFile: text(\"module_file\").notNull(),\n\tsubscribable: integer(\"subscribable\").notNull(),\n\tregisteredAt: timestamp(\"registered_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tdeletedAt: timestamp(\"deleted_at\", { withTimezone: true })\n}, (table) => [uniqueIndex(\"workflows_project_id_slug_idx\").on(table.projectId, table.slug)]);\nconst workflowsSqlite = sqliteTable(\"workflows\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\tslug: text$1(\"slug\").notNull(),\n\tname: text$1(\"name\"),\n\tdescription: text$1(\"description\"),\n\tmoduleFile: text$1(\"module_file\").notNull(),\n\tsubscribable: integer$1(\"subscribable\", { mode: \"boolean\" }).notNull(),\n\tregisteredAt: integer$1(\"registered_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tdeletedAt: integer$1(\"deleted_at\", { mode: \"timestamp_ms\" })\n}, (table) => [uniqueIndex$1(\"workflows_project_id_slug_idx\").on(table.projectId, table.slug)]);\n//#endregion\n//#region src/schema/tables/resource-activity.ts\nconst resourceActivity = pgTable(\"resource_activity\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\tuserId: text(\"user_id\").notNull(),\n\tresourceKind: text(\"resource_kind\").notNull(),\n\tresourceId: text(\"resource_id\").notNull(),\n\tlastOpenedAt: timestamp(\"last_opened_at\", { withTimezone: true }).notNull()\n}, (table) => [uniqueIndex(\"resource_activity_project_user_kind_resource\").on(table.projectId, table.userId, table.resourceKind, table.resourceId), index(\"resource_activity_user_last_opened_at\").on(table.userId, table.lastOpenedAt)]);\nconst resourceActivitySqlite = sqliteTable(\"resource_activity\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\tuserId: text$1(\"user_id\").notNull(),\n\tresourceKind: text$1(\"resource_kind\").notNull(),\n\tresourceId: text$1(\"resource_id\").notNull(),\n\tlastOpenedAt: integer$1(\"last_opened_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [uniqueIndex$1(\"resource_activity_project_user_kind_resource\").on(table.projectId, table.userId, table.resourceKind, table.resourceId), index$1(\"resource_activity_user_last_opened_at\").on(table.userId, table.lastOpenedAt)]);\n//#endregion\n//#region src/schema/registrations.ts\n/**\n* Project server tables — Postgres (hosted) or SQLite (local dev).\n*/\nconst tableRegistry = {\n\tagents: {\n\t\tpg: agents,\n\t\tsqlite: agentsSqlite\n\t},\n\tagentSessions: {\n\t\tpg: agentSessions,\n\t\tsqlite: agentSessionsSqlite\n\t},\n\tagentEvents: {\n\t\tpg: agentEvents,\n\t\tsqlite: agentEventsSqlite\n\t},\n\tusageRecords: {\n\t\tpg: usageRecords,\n\t\tsqlite: usageRecordsSqlite\n\t},\n\ttriggers: {\n\t\tpg: triggers,\n\t\tsqlite: triggersSqlite\n\t},\n\ttriggerAttachments: {\n\t\tpg: triggerAttachments,\n\t\tsqlite: triggerAttachmentsSqlite\n\t},\n\ttriggerRuns: {\n\t\tpg: triggerRuns,\n\t\tsqlite: triggerRunsSqlite\n\t},\n\tworkflowRuns: {\n\t\tpg: workflowRuns,\n\t\tsqlite: workflowRunsSqlite\n\t},\n\tworkflowEvents: {\n\t\tpg: workflowEvents,\n\t\tsqlite: workflowEventsSqlite\n\t},\n\tworkflowHooks: {\n\t\tpg: workflowHooks,\n\t\tsqlite: workflowHooksSqlite\n\t},\n\tcredentialInstances: {\n\t\tpg: credentialInstances,\n\t\tsqlite: credentialInstancesSqlite\n\t},\n\tcredentialAssignments: {\n\t\tpg: credentialAssignments,\n\t\tsqlite: credentialAssignmentsSqlite\n\t},\n\tjobs: {\n\t\tpg: jobs,\n\t\tsqlite: jobsSqlite\n\t},\n\tgatewayAttachments: {\n\t\tpg: gatewayAttachments,\n\t\tsqlite: gatewayAttachmentsSqlite\n\t},\n\tgatewayThreadSessions: {\n\t\tpg: gatewayThreadSessions,\n\t\tsqlite: gatewayThreadSessionsSqlite\n\t},\n\ttraceSpans: {\n\t\tpg: traceSpans,\n\t\tsqlite: traceSpansSqlite\n\t},\n\ttraceLogs: {\n\t\tpg: traceLogs,\n\t\tsqlite: traceLogsSqlite\n\t},\n\tskills: {\n\t\tpg: skills,\n\t\tsqlite: skillsSqlite\n\t},\n\tworkflows: {\n\t\tpg: workflows,\n\t\tsqlite: workflowsSqlite\n\t},\n\tworkflowSubscriptions: {\n\t\tpg: workflowSubscriptions,\n\t\tsqlite: workflowSubscriptionsSqlite\n\t},\n\tresourceActivity: {\n\t\tpg: resourceActivity,\n\t\tsqlite: resourceActivitySqlite\n\t}\n};\nconst schema = buildPgSchema(tableRegistry);\nbuildSqliteSchema(tableRegistry);\n//#endregion\n//#region src/schema/pg.ts\nvar pg_exports = /* @__PURE__ */ __exportAll({\n\tagentEvents: () => agentEvents,\n\tagentSessions: () => agentSessions,\n\tagents: () => agents,\n\tcredentialAssignments: () => credentialAssignments,\n\tcredentialInstances: () => credentialInstances,\n\tgatewayAttachments: () => gatewayAttachments,\n\tgatewayThreadSessions: () => gatewayThreadSessions,\n\tjobs: () => jobs,\n\tresourceActivity: () => resourceActivity,\n\tschema: () => schema,\n\tskills: () => skills,\n\ttraceLogs: () => traceLogs,\n\ttraceSpans: () => traceSpans,\n\ttriggerAttachments: () => triggerAttachments,\n\ttriggerRuns: () => triggerRuns,\n\ttriggers: () => triggers,\n\tusageRecords: () => usageRecords,\n\tworkflowEvents: () => workflowEvents,\n\tworkflowHooks: () => workflowHooks,\n\tworkflowRuns: () => workflowRuns,\n\tworkflowSubscriptions: () => workflowSubscriptions,\n\tworkflows: () => workflows\n});\n//#endregion\n//#region src/connection/pg/db.ts\n/** Inferred from `schema` — `getDb()` and query files use this type. */\nfunction createPgDb(pool) {\n\treturn loadDrizzlePg().drizzle(pool, { schema });\n}\n//#endregion\n//#region src/connection/pg/search-path.ts\nconst SCHEMA_IDENT = /^[a-zA-Z_][a-zA-Z0-9_]*$/;\n/** Drizzle __drizzle_migrations schema — tenant path when set, else public (platform). */\nfunction resolveMigrationsSchema(searchPath) {\n\treturn searchPath ? primarySearchPathSchema(searchPath) : \"public\";\n}\n/** First schema in a comma-separated search_path (the tenant / app schema). */\nfunction primarySearchPathSchema(searchPath) {\n\tconst schema = searchPath.split(\",\")[0]?.trim();\n\tif (!schema || !SCHEMA_IDENT.test(schema)) throw new Error(`Invalid search_path: ${searchPath}`);\n\treturn schema;\n}\nfunction parseSearchPathFromUrl(url) {\n\ttry {\n\t\tconst parsed = new URL(url.replace(/^postgresql:/, \"postgres:\"));\n\t\tconst direct = parsed.searchParams.get(\"search_path\");\n\t\tif (direct) return direct;\n\t\tconst options = parsed.searchParams.get(\"options\");\n\t\tif (!options) return;\n\t\treturn decodeURIComponent(options).match(/search_path[= ]([^,\\s]+(?:,\\s*[^,\\s]+)*)/i)?.[1]?.trim();\n\t} catch {\n\t\treturn;\n\t}\n}\nfunction urlHasSearchPath(url) {\n\treturn parseSearchPathFromUrl(url) !== void 0;\n}\nfunction resolveSearchPath(url, override) {\n\tconst explicit = override?.trim() || process.env.DATABASE_SEARCH_PATH?.trim();\n\tif (explicit) {\n\t\tprimarySearchPathSchema(explicit);\n\t\treturn explicit;\n\t}\n\treturn parseSearchPathFromUrl(url);\n}\n/** Ensures libpq sets search_path at connect time (avoids pool connect-handler races). */\nfunction appendSearchPathToUrl(url, searchPath) {\n\tif (urlHasSearchPath(url)) return url;\n\tprimarySearchPathSchema(searchPath);\n\tconst option = encodeURIComponent(`-c search_path=${searchPath}`);\n\treturn `${url}${url.includes(\"?\") ? \"&\" : \"?\"}options=${option}`;\n}\n//#endregion\n//#region src/connection/pg/index.ts\nfunction createPgConnection(options) {\n\tconst searchPath = resolveSearchPath(options.url, options.searchPath);\n\tconst { Pool } = loadPg();\n\tconst pool = new Pool({\n\t\tconnectionString: options.url,\n\t\tmax: options.max ?? 10,\n\t\tconnectionTimeoutMillis: 5e3,\n\t\tidleTimeoutMillis: 3e4,\n\t\tkeepAlive: true\n\t});\n\treturn {\n\t\tdialect: \"postgres\",\n\t\tdb: createPgDb(pool),\n\t\tpool,\n\t\tsearchPath,\n\t\tclose: () => pool.end()\n\t};\n}\n//#endregion\n//#region src/connection/sqlite/configure.ts\n/** Pragmas for on-disk sqlite (WAL, FKs, busy timeout). No-op for `:memory:`. */\nfunction configureSqlite(client, path) {\n\tif (path === \":memory:\" || path.startsWith(\":memory:\")) {\n\t\tclient.pragma(\"foreign_keys = ON\");\n\t\treturn;\n\t}\n\tclient.pragma(\"journal_mode = WAL\");\n\tclient.pragma(\"synchronous = NORMAL\");\n\tclient.pragma(\"foreign_keys = ON\");\n\tclient.pragma(\"busy_timeout = 5000\");\n}\n//#endregion\n//#region src/connection/sqlite/resolve-path.ts\nfunction resolveSqlitePath(url) {\n\tif (url === \":memory:\" || url.startsWith(\":memory:\")) return url;\n\tif (url.startsWith(\"file:\")) return url.slice(5);\n\tif (url.startsWith(\"sqlite:\")) return url.slice(7);\n\treturn url;\n}\n//#endregion\n//#region src/connection/sqlite/index.ts\nfunction createSqliteConnection(options) {\n\tconst path = resolveSqlitePath(options.url);\n\tif (path !== \":memory:\" && !path.startsWith(\":memory:\")) mkdirSync(dirname(path), { recursive: true });\n\tconst client = new SqliteClient(path);\n\tconfigureSqlite(client, path);\n\treturn {\n\t\tdialect: \"sqlite\",\n\t\tdb: drizzle(client, { schema: pg_exports }),\n\t\tclose: () => client.close()\n\t};\n}\n//#endregion\n//#region src/connection/pg/cancel-channel.ts\n/** Postgres LISTEN/NOTIFY pub/sub for a single cancel channel (lowercase identifier, max 63 chars). */\nfunction createPostgresCancelChannel(connectionString, channel) {\n\tconst { Client } = loadPg();\n\treturn {\n\t\tasync publishCancel(runId) {\n\t\t\tconst client = new Client({ connectionString });\n\t\t\tawait client.connect();\n\t\t\ttry {\n\t\t\t\tawait client.query(\"SELECT pg_notify($1, $2)\", [channel, runId]);\n\t\t\t} finally {\n\t\t\t\tawait client.end();\n\t\t\t}\n\t\t},\n\t\tasync subscribeCancel(handler) {\n\t\t\tconst client = new Client({ connectionString });\n\t\t\tawait client.connect();\n\t\t\tawait client.query(`LISTEN ${channel}`);\n\t\t\tconst onNotification = (message) => {\n\t\t\t\tif (message.payload) handler(message.payload);\n\t\t\t};\n\t\t\tclient.on(\"notification\", onNotification);\n\t\t\treturn async () => {\n\t\t\t\tclient.off(\"notification\", onNotification);\n\t\t\t\tawait client.query(`UNLISTEN ${channel}`);\n\t\t\t\tawait client.end();\n\t\t\t};\n\t\t}\n\t};\n}\n//#endregion\n//#region src/connection/index.ts\nfunction createConnection(options) {\n\tif (options.dialect === \"postgres\") return createPgConnection({\n\t\turl: options.url,\n\t\tmax: options.max,\n\t\tsearchPath: options.searchPath\n\t});\n\treturn createSqliteConnection({ url: options.url });\n}\n//#endregion\n//#region src/dialect/infer.ts\nfunction inferDialect(url, override) {\n\tif (override) return override;\n\tconst lower = url.toLowerCase();\n\tif (lower.startsWith(\"postgres://\") || lower.startsWith(\"postgresql://\")) return \"postgres\";\n\tif (lower.startsWith(\"file:\") || lower.startsWith(\"sqlite:\") || lower === \":memory:\" || lower.startsWith(\":memory:\")) return \"sqlite\";\n\tif (!url.includes(\"://\")) return \"sqlite\";\n\tthrow new Error(`Could not infer database dialect from DATABASE_URL. Set dialect explicitly (got: ${url})`);\n}\n//#endregion\n//#region src/client/pool-cache.ts\nconst MAX_CACHED_POOLS = 20;\nconst IDLE_EVICT_MS = 6e4;\nconst EVICT_INTERVAL_MS = 3e4;\nconst cache = /* @__PURE__ */ new Map();\nlet evictTimer;\nfunction cacheKey(url, searchPath, max) {\n\treturn `${url}\\0${searchPath ?? \"\"}\\0${max ?? \"\"}`;\n}\nfunction touch(entry) {\n\tentry.lastUsedAt = Date.now();\n}\nfunction ensureEvictTimer() {\n\tif (evictTimer) return;\n\tevictTimer = setInterval(() => {\n\t\tevictIdlePools();\n\t}, EVICT_INTERVAL_MS);\n\tevictTimer.unref?.();\n}\nasync function closeEntry(key, entry) {\n\tcache.delete(key);\n\tawait entry.handle.close();\n}\nasync function evictIdlePools() {\n\tconst now = Date.now();\n\tfor (const [key, entry] of cache) if (entry.refs === 0 && now - entry.lastUsedAt >= IDLE_EVICT_MS) await closeEntry(key, entry);\n}\nasync function evictLeastRecentlyUsedIdle() {\n\tlet oldestKey;\n\tlet oldestUsedAt = Number.POSITIVE_INFINITY;\n\tfor (const [key, entry] of cache) if (entry.refs === 0 && entry.lastUsedAt < oldestUsedAt) {\n\t\toldestKey = key;\n\t\toldestUsedAt = entry.lastUsedAt;\n\t}\n\tif (!oldestKey) return false;\n\tconst entry = cache.get(oldestKey);\n\tif (!entry) return false;\n\tawait closeEntry(oldestKey, entry);\n\treturn true;\n}\nasync function acquireProjectDatabasePool(options) {\n\tconst dialect = inferDialect(options.url);\n\tif (dialect !== \"postgres\") {\n\t\tconst searchPath = resolveSearchPath(options.url, options.searchPath);\n\t\treturn createConnection({\n\t\t\turl: options.url,\n\t\t\tdialect,\n\t\t\tmax: options.max,\n\t\t\tsearchPath\n\t\t});\n\t}\n\tconst searchPath = resolveSearchPath(options.url, options.searchPath);\n\tconst max = options.max ?? 5;\n\tconst key = cacheKey(options.url, searchPath, max);\n\tlet entry = cache.get(key);\n\tif (!entry) {\n\t\twhile (cache.size >= MAX_CACHED_POOLS) if (!await evictLeastRecentlyUsedIdle()) break;\n\t\tentry = {\n\t\t\thandle: createConnection({\n\t\t\t\turl: options.url,\n\t\t\t\tdialect,\n\t\t\t\tmax,\n\t\t\t\tsearchPath\n\t\t\t}),\n\t\t\trefs: 0,\n\t\t\tlastUsedAt: Date.now()\n\t\t};\n\t\tcache.set(key, entry);\n\t\tensureEvictTimer();\n\t}\n\tentry.refs += 1;\n\ttouch(entry);\n\treturn entry.handle;\n}\nfunction releaseProjectDatabasePool(options) {\n\tif (inferDialect(options.url) !== \"postgres\") return;\n\tconst searchPath = resolveSearchPath(options.url, options.searchPath);\n\tconst max = options.max ?? 5;\n\tconst key = cacheKey(options.url, searchPath, max);\n\tconst entry = cache.get(key);\n\tif (!entry) return;\n\tentry.refs = Math.max(0, entry.refs - 1);\n\ttouch(entry);\n}\nasync function closeAllProjectDatabasePools() {\n\tconst entries = [...cache.entries()];\n\tcache.clear();\n\tif (evictTimer) {\n\t\tclearInterval(evictTimer);\n\t\tevictTimer = void 0;\n\t}\n\tawait Promise.all(entries.map(([, entry]) => entry.handle.close()));\n}\n//#endregion\n//#region src/client/close.ts\nasync function closeDatabase() {\n\tif (getRequestDatabaseHandle()) throw new Error(\"closeDatabase() cannot be called inside runWithProjectDatabase()\");\n\tawait closeAllProjectDatabasePools();\n\tconst handle = getDefaultDatabaseHandle();\n\tif (!handle) return;\n\tawait handle.close();\n\tsetDatabaseHandle(void 0);\n}\n//#endregion\n//#region src/migrate/adapt-pg-migrations.ts\n/** Drizzle-kit emits REFERENCES \"public\".\"table\" — strip public so search_path applies. */\nfunction adaptPgMigrationsForSearchPath(migrations) {\n\treturn migrations.map((migration) => ({\n\t\t...migration,\n\t\tsql: migration.sql.map((statement) => statement.replace(/REFERENCES \"public\"\\./gi, \"REFERENCES \"))\n\t}));\n}\n//#endregion\n//#region src/migrate/load-migrations.ts\nfunction loadMigrations(migrationsFolder, embedded) {\n\tif (existsSync(join(migrationsFolder, \"meta\", \"_journal.json\"))) return readMigrationFiles({ migrationsFolder });\n\treturn embedded.map((migration) => ({\n\t\t...migration,\n\t\tsql: [...migration.sql]\n\t}));\n}\n//#endregion\n//#region src/migrate/migrate-pg.ts\nasync function migratePgDatabase(db, config, migrations) {\n\tconst migrator = db;\n\tawait migrator.dialect.migrate(migrations, migrator.session, config);\n}\n//#endregion\n//#region src/migrate/resolve-folder.ts\nfunction resolvePackageRoot() {\n\tlet dir = dirname(fileURLToPath(import.meta.url));\n\tfor (;;) {\n\t\tif (existsSync(join(dir, \"drizzle\", \"sqlite\", \"meta\", \"_journal.json\")) || existsSync(join(dir, \"drizzle\", \"pg\", \"meta\", \"_journal.json\"))) return dir;\n\t\tconst parent = dirname(dir);\n\t\tif (parent === dir) break;\n\t\tdir = parent;\n\t}\n\tthrow new Error(\"Could not resolve @keystrokehq/database package root for migrations\");\n}\nfunction fallbackFolder(...segments) {\n\treturn join(dirname(fileURLToPath(import.meta.url)), ...segments);\n}\nfunction resolveMigrationsFolder(dialect, override) {\n\tif (override) return override;\n\ttry {\n\t\treturn join(resolvePackageRoot(), \"drizzle\", dialect === \"postgres\" ? \"pg\" : \"sqlite\");\n\t} catch {\n\t\treturn fallbackFolder(\"drizzle\", dialect === \"postgres\" ? \"pg\" : \"sqlite\");\n\t}\n}\n//#endregion\n//#region src/migrate/migrations.pg.generated.ts\nconst pgMigrations = [\n\t{\n\t\t\"sql\": [\n\t\t\t\"CREATE TABLE \\\"agent_events\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"session_id\\\" text NOT NULL,\\n\t\\\"seq\\\" integer NOT NULL,\\n\t\\\"event_type\\\" text NOT NULL,\\n\t\\\"payload\\\" jsonb NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"deleted_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"agent_sessions\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"agent_id\\\" text NOT NULL,\\n\t\\\"source_kind\\\" text DEFAULT 'api' NOT NULL,\\n\t\\\"source_id\\\" text,\\n\t\\\"parent_span_id\\\" text,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"deleted_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"agents\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"name\\\" text,\\n\t\\\"description\\\" text,\\n\t\\\"route\\\" text NOT NULL,\\n\t\\\"module_file\\\" text NOT NULL,\\n\t\\\"model\\\" text NOT NULL,\\n\t\\\"system_prompt\\\" text NOT NULL,\\n\t\\\"tool_count\\\" integer,\\n\t\\\"credential_count\\\" integer,\\n\t\\\"registered_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"deleted_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"credential_instances\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"scope_type\\\" text NOT NULL,\\n\t\\\"scope_id\\\" text,\\n\t\\\"label\\\" text,\\n\t\\\"is_default\\\" integer NOT NULL,\\n\t\\\"auth_kind\\\" text NOT NULL,\\n\t\\\"ciphertext\\\" text,\\n\t\\\"connection_id\\\" text,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"gateway_attachments\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"agent_slug\\\" text NOT NULL,\\n\t\\\"module_file\\\" text,\\n\t\\\"platform\\\" text NOT NULL,\\n\t\\\"team_id\\\" text,\\n\t\\\"channel_id\\\" text NOT NULL,\\n\t\\\"source\\\" jsonb NOT NULL,\\n\t\\\"registered_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"deleted_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"gateway_thread_sessions\\\" (\\n\t\\\"thread_id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"agent_id\\\" text NOT NULL,\\n\t\\\"session_id\\\" text NOT NULL,\\n\t\\\"attachment_id\\\" text NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"jobs\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"kind\\\" text NOT NULL,\\n\t\\\"target_id\\\" text NOT NULL,\\n\t\\\"run_id\\\" text NOT NULL,\\n\t\\\"trigger\\\" text NOT NULL,\\n\t\\\"payload\\\" jsonb,\\n\t\\\"status\\\" text NOT NULL,\\n\t\\\"scheduled_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"attempt\\\" integer NOT NULL,\\n\t\\\"max_attempts\\\" integer NOT NULL,\\n\t\\\"leased_by\\\" text,\\n\t\\\"lease_expires_at\\\" timestamp with time zone,\\n\t\\\"completed_at\\\" timestamp with time zone,\\n\t\\\"error\\\" jsonb\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"oauth_apps\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"provider\\\" text NOT NULL,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"token_strategy\\\" text NOT NULL,\\n\t\\\"client_id_ciphertext\\\" text NOT NULL,\\n\t\\\"client_secret_ciphertext\\\" text NOT NULL,\\n\t\\\"signing_secret_ciphertext\\\" text,\\n\t\\\"redirect_uri\\\" text,\\n\t\\\"metadata\\\" jsonb,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"oauth_connections\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"app_id\\\" text NOT NULL,\\n\t\\\"external_id\\\" text NOT NULL,\\n\t\\\"access_token_ciphertext\\\" text NOT NULL,\\n\t\\\"refresh_token_ciphertext\\\" text,\\n\t\\\"access_token_expires_at\\\" timestamp with time zone,\\n\t\\\"granted_scopes\\\" jsonb,\\n\t\\\"metadata\\\" jsonb,\\n\t\\\"connected_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"resource_activity\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"user_id\\\" text NOT NULL,\\n\t\\\"resource_kind\\\" text NOT NULL,\\n\t\\\"resource_id\\\" text NOT NULL,\\n\t\\\"last_opened_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"secret_values\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"ref_kind\\\" text NOT NULL,\\n\t\\\"ref_id\\\" text NOT NULL,\\n\t\\\"field\\\" text NOT NULL,\\n\t\\\"ciphertext\\\" text NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"skills\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"name\\\" text,\\n\t\\\"description\\\" text,\\n\t\\\"module_file\\\" text NOT NULL,\\n\t\\\"registered_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"deleted_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"trace_logs\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"trace_id\\\" text NOT NULL,\\n\t\\\"span_id\\\" text NOT NULL,\\n\t\\\"seq\\\" integer NOT NULL,\\n\t\\\"level\\\" text NOT NULL,\\n\t\\\"message\\\" text NOT NULL,\\n\t\\\"data\\\" jsonb,\\n\t\\\"source\\\" text NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"trace_spans\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"trace_id\\\" text NOT NULL,\\n\t\\\"parent_span_id\\\" text,\\n\t\\\"kind\\\" text NOT NULL,\\n\t\\\"ref_id\\\" text NOT NULL,\\n\t\\\"name\\\" text NOT NULL,\\n\t\\\"status\\\" text NOT NULL,\\n\t\\\"started_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"finished_at\\\" timestamp with time zone,\\n\t\\\"metadata\\\" jsonb,\\n\t\\\"error\\\" jsonb\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"trigger_attachments\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"target_kind\\\" text DEFAULT 'workflow' NOT NULL,\\n\t\\\"workflow_slug\\\" text,\\n\t\\\"agent_slug\\\" text,\\n\t\\\"module_file\\\" text NOT NULL,\\n\t\\\"source\\\" jsonb NOT NULL,\\n\t\\\"origin\\\" text DEFAULT 'project' NOT NULL,\\n\t\\\"prompt\\\" text,\\n\t\\\"lifecycle\\\" jsonb,\\n\t\\\"created_by_session_id\\\" text,\\n\t\\\"registered_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"deleted_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"trigger_runs\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"attachment_id\\\" text NOT NULL,\\n\t\\\"source_path\\\" text,\\n\t\\\"trigger_type\\\" text NOT NULL,\\n\t\\\"payload\\\" jsonb,\\n\t\\\"triggered_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"trigger_schedules\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"attachment_slug\\\" text NOT NULL,\\n\t\\\"kind\\\" text NOT NULL,\\n\t\\\"schedule\\\" text NOT NULL,\\n\t\\\"next_run_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"enabled\\\" integer NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"workflow_events\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"run_id\\\" text NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"seq\\\" integer NOT NULL,\\n\t\\\"type\\\" text NOT NULL,\\n\t\\\"correlation_id\\\" text,\\n\t\\\"data\\\" jsonb,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"workflow_hooks\\\" (\\n\t\\\"hook_id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"run_id\\\" text NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"token\\\" text NOT NULL,\\n\t\\\"correlation_id\\\" text NOT NULL,\\n\t\\\"status\\\" text NOT NULL,\\n\t\\\"payload\\\" jsonb,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"resumed_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"workflow_runs\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"workflow_slug\\\" text NOT NULL,\\n\t\\\"attachment_id\\\" text,\\n\t\\\"subscription_id\\\" text,\\n\t\\\"trigger_run_id\\\" text,\\n\t\\\"parent_workflow_run_id\\\" text,\\n\t\\\"parent_span_id\\\" text,\\n\t\\\"source_kind\\\" text DEFAULT 'api' NOT NULL,\\n\t\\\"source_id\\\" text,\\n\t\\\"status\\\" text NOT NULL,\\n\t\\\"trigger\\\" text NOT NULL,\\n\t\\\"triggered_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"started_at\\\" timestamp with time zone,\\n\t\\\"finished_at\\\" timestamp with time zone,\\n\t\\\"input\\\" jsonb,\\n\t\\\"output\\\" jsonb,\\n\t\\\"error\\\" jsonb\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"workflow_subscriptions\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"workflow_slug\\\" text NOT NULL,\\n\t\\\"user_id\\\" text NOT NULL,\\n\t\\\"enabled\\\" integer NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"workflows\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"name\\\" text,\\n\t\\\"description\\\" text,\\n\t\\\"module_file\\\" text NOT NULL,\\n\t\\\"subscribable\\\" integer NOT NULL,\\n\t\\\"registered_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"deleted_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nALTER TABLE \\\"agent_events\\\" ADD CONSTRAINT \\\"agent_events_session_id_agent_sessions_id_fk\\\" FOREIGN KEY (\\\"session_id\\\") REFERENCES \\\"public\\\".\\\"agent_sessions\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"agent_sessions\\\" ADD CONSTRAINT \\\"agent_sessions_agent_id_agents_id_fk\\\" FOREIGN KEY (\\\"agent_id\\\") REFERENCES \\\"public\\\".\\\"agents\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"gateway_thread_sessions\\\" ADD CONSTRAINT \\\"gateway_thread_sessions_agent_id_agents_id_fk\\\" FOREIGN KEY (\\\"agent_id\\\") REFERENCES \\\"public\\\".\\\"agents\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"gateway_thread_sessions\\\" ADD CONSTRAINT \\\"gateway_thread_sessions_session_id_agent_sessions_id_fk\\\" FOREIGN KEY (\\\"session_id\\\") REFERENCES \\\"public\\\".\\\"agent_sessions\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"gateway_thread_sessions\\\" ADD CONSTRAINT \\\"gateway_thread_sessions_attachment_id_gateway_attachments_id_fk\\\" FOREIGN KEY (\\\"attachment_id\\\") REFERENCES \\\"public\\\".\\\"gateway_attachments\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"oauth_connections\\\" ADD CONSTRAINT \\\"oauth_connections_app_id_oauth_apps_id_fk\\\" FOREIGN KEY (\\\"app_id\\\") REFERENCES \\\"public\\\".\\\"oauth_apps\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"trace_logs\\\" ADD CONSTRAINT \\\"trace_logs_span_id_trace_spans_id_fk\\\" FOREIGN KEY (\\\"span_id\\\") REFERENCES \\\"public\\\".\\\"trace_spans\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_runs\\\" ADD CONSTRAINT \\\"trigger_runs_attachment_id_trigger_attachments_id_fk\\\" FOREIGN KEY (\\\"attachment_id\\\") REFERENCES \\\"public\\\".\\\"trigger_attachments\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"workflow_events\\\" ADD CONSTRAINT \\\"workflow_events_run_id_workflow_runs_id_fk\\\" FOREIGN KEY (\\\"run_id\\\") REFERENCES \\\"public\\\".\\\"workflow_runs\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"workflow_hooks\\\" ADD CONSTRAINT \\\"workflow_hooks_run_id_workflow_runs_id_fk\\\" FOREIGN KEY (\\\"run_id\\\") REFERENCES \\\"public\\\".\\\"workflow_runs\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"workflow_runs\\\" ADD CONSTRAINT \\\"workflow_runs_attachment_id_trigger_attachments_id_fk\\\" FOREIGN KEY (\\\"attachment_id\\\") REFERENCES \\\"public\\\".\\\"trigger_attachments\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"workflow_runs\\\" ADD CONSTRAINT \\\"workflow_runs_subscription_id_workflow_subscriptions_id_fk\\\" FOREIGN KEY (\\\"subscription_id\\\") REFERENCES \\\"public\\\".\\\"workflow_subscriptions\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"workflow_runs\\\" ADD CONSTRAINT \\\"workflow_runs_trigger_run_id_trigger_runs_id_fk\\\" FOREIGN KEY (\\\"trigger_run_id\\\") REFERENCES \\\"public\\\".\\\"trigger_runs\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nCREATE INDEX \\\"agent_sessions_agent_updated_idx\\\" ON \\\"agent_sessions\\\" USING btree (\\\"agent_id\\\",\\\"updated_at\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"agents_project_id_slug_idx\\\" ON \\\"agents\\\" USING btree (\\\"project_id\\\",\\\"slug\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"agents_project_id_route_idx\\\" ON \\\"agents\\\" USING btree (\\\"project_id\\\",\\\"route\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"credential_instances_project_slug_scope_label_unique\\\" ON \\\"credential_instances\\\" USING btree (\\\"project_id\\\",\\\"slug\\\",\\\"scope_type\\\",\\\"scope_id\\\",\\\"label\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"credential_instances_project_slug_scope_idx\\\" ON \\\"credential_instances\\\" USING btree (\\\"project_id\\\",\\\"slug\\\",\\\"scope_type\\\",\\\"scope_id\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"gateway_attachments_project_id_slug_idx\\\" ON \\\"gateway_attachments\\\" USING btree (\\\"project_id\\\",\\\"slug\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"gateway_attachments_project_platform_channel_active\\\" ON \\\"gateway_attachments\\\" USING btree (\\\"project_id\\\",\\\"platform\\\",\\\"channel_id\\\") WHERE \\\"gateway_attachments\\\".\\\"deleted_at\\\" is null;\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"oauth_apps_project_id_slug_idx\\\" ON \\\"oauth_apps\\\" USING btree (\\\"project_id\\\",\\\"slug\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"oauth_connections_app_external_unique\\\" ON \\\"oauth_connections\\\" USING btree (\\\"app_id\\\",\\\"external_id\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"resource_activity_project_user_kind_resource\\\" ON \\\"resource_activity\\\" USING btree (\\\"project_id\\\",\\\"user_id\\\",\\\"resource_kind\\\",\\\"resource_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"resource_activity_user_last_opened_at\\\" ON \\\"resource_activity\\\" USING btree (\\\"user_id\\\",\\\"last_opened_at\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"secret_values_ref_unique\\\" ON \\\"secret_values\\\" USING btree (\\\"project_id\\\",\\\"ref_kind\\\",\\\"ref_id\\\",\\\"field\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"secret_values_ref_idx\\\" ON \\\"secret_values\\\" USING btree (\\\"project_id\\\",\\\"ref_kind\\\",\\\"ref_id\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"skills_project_id_slug_idx\\\" ON \\\"skills\\\" USING btree (\\\"project_id\\\",\\\"slug\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"trace_logs_trace_id_seq_idx\\\" ON \\\"trace_logs\\\" USING btree (\\\"trace_id\\\",\\\"seq\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"trace_logs_span_id_seq_idx\\\" ON \\\"trace_logs\\\" USING btree (\\\"span_id\\\",\\\"seq\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"trigger_attachments_project_id_slug_idx\\\" ON \\\"trigger_attachments\\\" USING btree (\\\"project_id\\\",\\\"slug\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"trigger_schedules_project_id_attachment_slug_idx\\\" ON \\\"trigger_schedules\\\" USING btree (\\\"project_id\\\",\\\"attachment_slug\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"trigger_schedules_next_run_at_idx\\\" ON \\\"trigger_schedules\\\" USING btree (\\\"next_run_at\\\",\\\"enabled\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"workflow_events_run_id_seq_unique\\\" ON \\\"workflow_events\\\" USING btree (\\\"run_id\\\",\\\"seq\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"workflow_events_run_id_type_idx\\\" ON \\\"workflow_events\\\" USING btree (\\\"run_id\\\",\\\"type\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"workflow_events_correlation_id_idx\\\" ON \\\"workflow_events\\\" USING btree (\\\"correlation_id\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"workflow_hooks_token_unique\\\" ON \\\"workflow_hooks\\\" USING btree (\\\"token\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"workflow_hooks_run_id_idx\\\" ON \\\"workflow_hooks\\\" USING btree (\\\"run_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"workflow_runs_project_workflow_triggered_idx\\\" ON \\\"workflow_runs\\\" USING btree (\\\"project_id\\\",\\\"workflow_slug\\\",\\\"triggered_at\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"workflow_subscriptions_project_workflow_user\\\" ON \\\"workflow_subscriptions\\\" USING btree (\\\"project_id\\\",\\\"workflow_slug\\\",\\\"user_id\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"workflows_project_id_slug_idx\\\" ON \\\"workflows\\\" USING btree (\\\"project_id\\\",\\\"slug\\\");\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1781213647873,\n\t\t\"hash\": \"03d99ea3c47d7b7f9a3b73a9b767c82a29394e5b2c53868e55061bf0bed93e0b\"\n\t},\n\t{\n\t\t\"sql\": [\"ALTER TABLE \\\"agent_sessions\\\" ADD COLUMN \\\"ran_by_user_id\\\" text;\", \"\\nALTER TABLE \\\"workflow_runs\\\" ADD COLUMN \\\"ran_by_user_id\\\" text;\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1781243850513,\n\t\t\"hash\": \"3f3eb52271a724ca488bfd6b2aba9095265455c55dee2a5d76d16c8698801906\"\n\t},\n\t{\n\t\t\"sql\": [\"ALTER TABLE \\\"agent_sessions\\\" ADD COLUMN \\\"canceled_at\\\" timestamp with time zone;\\n\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 17813e8,\n\t\t\"hash\": \"3dbe010bde8652bd58886b33d5d8c449e7213ef66a6235c365598dc978802d71\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"CREATE TABLE \\\"agent_runs\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"session_id\\\" text NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"agent_id\\\" text NOT NULL,\\n\t\\\"run_index\\\" integer NOT NULL,\\n\t\\\"source_kind\\\" text DEFAULT 'api' NOT NULL,\\n\t\\\"source_id\\\" text,\\n\t\\\"ran_by_user_id\\\" text,\\n\t\\\"status\\\" text NOT NULL,\\n\t\\\"error\\\" jsonb,\\n\t\\\"started_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"finished_at\\\" timestamp with time zone,\\n\t\\\"total_cost_usd\\\" double precision,\\n\t\\\"total_tokens\\\" integer,\\n\t\\\"models_used\\\" jsonb,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"deleted_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"usage_records\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"run_id\\\" text NOT NULL,\\n\t\\\"run_kind\\\" text NOT NULL,\\n\t\\\"kind\\\" text NOT NULL,\\n\t\\\"label\\\" text NOT NULL,\\n\t\\\"quantity\\\" integer,\\n\t\\\"unit\\\" text,\\n\t\\\"amount\\\" double precision NOT NULL,\\n\t\\\"metadata\\\" jsonb,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nALTER TABLE \\\"agent_events\\\" ADD COLUMN \\\"run_id\\\" text;\",\n\t\t\t\"\\nALTER TABLE \\\"agent_runs\\\" ADD CONSTRAINT \\\"agent_runs_session_id_agent_sessions_id_fk\\\" FOREIGN KEY (\\\"session_id\\\") REFERENCES \\\"public\\\".\\\"agent_sessions\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"agent_runs\\\" ADD CONSTRAINT \\\"agent_runs_agent_id_agents_id_fk\\\" FOREIGN KEY (\\\"agent_id\\\") REFERENCES \\\"public\\\".\\\"agents\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nCREATE INDEX \\\"agent_runs_session_run_index_idx\\\" ON \\\"agent_runs\\\" USING btree (\\\"session_id\\\",\\\"run_index\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"agent_runs_agent_started_idx\\\" ON \\\"agent_runs\\\" USING btree (\\\"agent_id\\\",\\\"started_at\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"agent_runs_project_started_idx\\\" ON \\\"agent_runs\\\" USING btree (\\\"project_id\\\",\\\"started_at\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"usage_records_run_run_kind_idx\\\" ON \\\"usage_records\\\" USING btree (\\\"run_id\\\",\\\"run_kind\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"usage_records_kind_idx\\\" ON \\\"usage_records\\\" USING btree (\\\"kind\\\");\",\n\t\t\t\"\\nALTER TABLE \\\"agent_events\\\" ADD CONSTRAINT \\\"agent_events_run_id_agent_runs_id_fk\\\" FOREIGN KEY (\\\"run_id\\\") REFERENCES \\\"public\\\".\\\"agent_runs\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1781568153484,\n\t\t\"hash\": \"e40c228590351e229ed0fb39e8e3045e2b68368363675b2f147a694c6437a80e\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"ALTER TABLE IF EXISTS \\\"agent_runs\\\" DISABLE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nDROP TABLE IF EXISTS \\\"agent_runs\\\" CASCADE;\",\n\t\t\t\"\\nALTER TABLE \\\"agent_sessions\\\" ADD COLUMN IF NOT EXISTS \\\"total_duration_ms\\\" integer DEFAULT 0 NOT NULL;\",\n\t\t\t\"\\nALTER TABLE \\\"agent_events\\\" DROP COLUMN IF EXISTS \\\"run_id\\\";\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1781630388181,\n\t\t\"hash\": \"b995f6f4e5f1147c20ea90cd26877d7154ff1b1625adba277507268c2a8c35f6\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"DROP TABLE \\\"oauth_apps\\\" CASCADE;\",\n\t\t\t\"\\nDROP TABLE \\\"oauth_connections\\\" CASCADE;\",\n\t\t\t\"\\nDROP TABLE \\\"secret_values\\\" CASCADE;\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1781941661795,\n\t\t\"hash\": \"3816998a2a2c7ead79cacfb64281fd415220473dee9512192b05b8cb57516f74\"\n\t},\n\t{\n\t\t\"sql\": [\"ALTER TABLE \\\"credential_instances\\\" ADD COLUMN \\\"shared_connection_id\\\" text;\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1782243320892,\n\t\t\"hash\": \"ec36b70bcd148a39ac4f55789348aee32315070e7d8b75aff61a9cee1d245721\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"ALTER TABLE \\\"agent_sessions\\\" ADD COLUMN \\\"title\\\" text;\",\n\t\t\t\"\\nALTER TABLE \\\"agent_sessions\\\" ADD COLUMN \\\"live_message\\\" jsonb;\",\n\t\t\t\"\\nALTER TABLE \\\"agents\\\" ADD COLUMN \\\"credential_keys\\\" jsonb;\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1782280074442,\n\t\t\"hash\": \"6174d3625965c6921bc20d51f67cc841b3e96b0d1c3777508a6969a2f2622f25\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"ALTER TABLE \\\"agents\\\" RENAME COLUMN \\\"credential_keys\\\" TO \\\"app_slugs\\\";\",\n\t\t\t\"\\nCREATE TABLE \\\"credential_assignments\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"target_type\\\" text NOT NULL,\\n\t\\\"target_key\\\" text NOT NULL,\\n\t\\\"consumer_id\\\" text NOT NULL,\\n\t\\\"credential_slug\\\" text NOT NULL,\\n\t\\\"instance_id\\\" text NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"credential_assignments_project_target_consumer_slug\\\" ON \\\"credential_assignments\\\" USING btree (\\\"project_id\\\",\\\"target_type\\\",\\\"target_key\\\",\\\"consumer_id\\\",\\\"credential_slug\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"credential_assignments_project_target_idx\\\" ON \\\"credential_assignments\\\" USING btree (\\\"project_id\\\",\\\"target_type\\\",\\\"target_key\\\");\",\n\t\t\t\"\\nALTER TABLE \\\"credential_instances\\\" RENAME COLUMN \\\"slug\\\" TO \\\"app_slug\\\";\",\n\t\t\t\"\\nALTER TABLE \\\"credential_instances\\\" ADD COLUMN \\\"slug\\\" text;\",\n\t\t\t\"\\nALTER TABLE \\\"credential_instances\\\" ADD COLUMN \\\"name\\\" text;\",\n\t\t\t\"\\nUPDATE \\\"credential_instances\\\" SET \\\"name\\\" = \\\"label\\\";\",\n\t\t\t\"\\nUPDATE \\\"credential_instances\\\" SET \\\"slug\\\" = CASE WHEN \\\"is_default\\\" = 1 THEN \\\"app_slug\\\" ELSE \\\"app_slug\\\" || '-' || substr(\\\"id\\\", 1, 8) END;\",\n\t\t\t\"\\nALTER TABLE \\\"credential_instances\\\" ALTER COLUMN \\\"slug\\\" SET NOT NULL;\",\n\t\t\t\"\\nDROP INDEX \\\"credential_instances_project_slug_scope_label_unique\\\";\",\n\t\t\t\"\\nDROP INDEX \\\"credential_instances_project_slug_scope_idx\\\";\",\n\t\t\t\"\\nCREATE INDEX \\\"credential_instances_project_app_slug_scope_idx\\\" ON \\\"credential_instances\\\" USING btree (\\\"project_id\\\",\\\"app_slug\\\",\\\"scope_type\\\",\\\"scope_id\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"credential_instances_project_scope_slug_unique\\\" ON \\\"credential_instances\\\" USING btree (\\\"project_id\\\",\\\"scope_type\\\",\\\"scope_id\\\",\\\"slug\\\");\\n\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 17826e8,\n\t\t\"hash\": \"ee310c8ce64fdc1b17cff8f138fee267eb1b1676262e58dae6e4c7e505295b4a\"\n\t},\n\t{\n\t\t\"sql\": [\"ALTER TABLE \\\"trigger_attachments\\\" ADD COLUMN \\\"name\\\" text;\", \"\\nALTER TABLE \\\"trigger_attachments\\\" ADD COLUMN \\\"description\\\" text;\\n\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 17827e8,\n\t\t\"hash\": \"5ce9dbb84f2eaae456389abaca578d65e148ade609bf7f4e3debe55041163dd6\"\n\t},\n\t{\n\t\t\"sql\": [\"ALTER TABLE \\\"credential_instances\\\" ADD COLUMN \\\"granted_scopes\\\" jsonb;\\n\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 17828e8,\n\t\t\"hash\": \"643bd06059078751d2c1d03c61a21f56313a8feb89cf69ed97a8fb6fac66ea19\"\n\t},\n\t{\n\t\t\"sql\": [\"ALTER TABLE \\\"credential_instances\\\" ADD COLUMN \\\"last_used_at\\\" timestamp with time zone;\\n\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 17829e8,\n\t\t\"hash\": \"eb8a691e801cb24a2e6a41a1472bd61c838b6ecea23341dff7fa5d48414a9b05\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"CREATE TABLE \\\"triggers\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"kind\\\" text NOT NULL,\\n\t\\\"name\\\" text,\\n\t\\\"description\\\" text,\\n\t\\\"module_file\\\" text NOT NULL,\\n\t\\\"origin\\\" text DEFAULT 'project' NOT NULL,\\n\t\\\"config\\\" jsonb,\\n\t\\\"schedule\\\" text,\\n\t\\\"next_run_at\\\" timestamp with time zone,\\n\t\\\"enabled\\\" integer DEFAULT 1 NOT NULL,\\n\t\\\"lifecycle\\\" jsonb,\\n\t\\\"created_by_session_id\\\" text,\\n\t\\\"registered_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"deleted_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"triggers_project_id_slug_idx\\\" ON \\\"triggers\\\" USING btree (\\\"project_id\\\",\\\"slug\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"triggers_next_run_at_enabled_idx\\\" ON \\\"triggers\\\" USING btree (\\\"next_run_at\\\",\\\"enabled\\\");\",\n\t\t\t\"\\nINSERT INTO \\\"triggers\\\" (\\n\t\\\"id\\\",\\n\t\\\"project_id\\\",\\n\t\\\"slug\\\",\\n\t\\\"kind\\\",\\n\t\\\"name\\\",\\n\t\\\"description\\\",\\n\t\\\"module_file\\\",\\n\t\\\"origin\\\",\\n\t\\\"config\\\",\\n\t\\\"schedule\\\",\\n\t\\\"next_run_at\\\",\\n\t\\\"enabled\\\",\\n\t\\\"lifecycle\\\",\\n\t\\\"created_by_session_id\\\",\\n\t\\\"registered_at\\\",\\n\t\\\"updated_at\\\",\\n\t\\\"deleted_at\\\"\\n)\\nSELECT\\n\tgen_random_uuid()::text,\\n\tg.project_id,\\n\tg.slug,\\n\tg.kind,\\n\tg.name,\\n\tg.description,\\n\tg.module_file,\\n\tg.origin,\\n\tg.config,\\n\tg.schedule,\\n\tg.next_run_at,\\n\tg.enabled,\\n\tg.lifecycle,\\n\tg.created_by_session_id,\\n\tg.registered_at,\\n\tg.updated_at,\\n\tg.deleted_at\\nFROM (\\n\tSELECT DISTINCT ON (ta.project_id, g.group_key)\\n\t\tta.project_id,\\n\t\tCASE\\n\t\t\tWHEN ta.origin = 'ephemeral' THEN ta.slug\\n\t\t\tELSE COALESCE(NULLIF(ta.source->>'slug', ''), NULLIF(ta.source->>'key', ''))\\n\t\tEND AS slug,\\n\t\t(ta.source->>'kind') AS kind,\\n\t\tta.name,\\n\t\tta.description,\\n\t\tta.module_file,\\n\t\tta.origin,\\n\t\tCASE\\n\t\t\tWHEN ta.source->>'kind' = 'webhook' THEN jsonb_strip_nulls(\\n\t\t\t\tjsonb_build_object(\\n\t\t\t\t\t'endpoint', ta.source->>'endpoint',\\n\t\t\t\t\t'requestSchema', ta.source->'requestSchema',\\n\t\t\t\t\t'filterSchema', ta.source->'filterSchema'\\n\t\t\t\t)\\n\t\t\t)\\n\t\t\tWHEN ta.source->>'kind' = 'poll' THEN jsonb_strip_nulls(\\n\t\t\t\tjsonb_build_object('code', ta.source->>'code', 'id', ta.source->>'id')\\n\t\t\t)\\n\t\t\tELSE NULL\\n\t\tEND AS config,\\n\t\tCASE\\n\t\t\tWHEN ta.source->>'kind' IN ('cron', 'poll') THEN ta.source->>'schedule'\\n\t\t\tELSE NULL\\n\t\tEND AS schedule,\\n\t\ts.next_run_at,\\n\t\tCOALESCE(s.enabled, 1) AS enabled,\\n\t\tta.lifecycle,\\n\t\tta.created_by_session_id,\\n\t\tta.registered_at,\\n\t\tta.updated_at,\\n\t\tta.deleted_at,\\n\t\tg.group_key\\n\tFROM trigger_attachments ta\\n\tINNER JOIN (\\n\t\tSELECT\\n\t\t\tid,\\n\t\t\tCASE\\n\t\t\t\tWHEN origin = 'ephemeral' THEN id\\n\t\t\t\tWHEN source->>'kind' = 'poll' AND source->>'id' IS NOT NULL THEN 'poll:' || (source->>'id')\\n\t\t\t\tELSE (source->>'kind') || ':' || COALESCE(NULLIF(source->>'slug', ''), NULLIF(source->>'key', ''))\\n\t\t\tEND AS group_key\\n\t\tFROM trigger_attachments\\n\t) g ON g.id = ta.id\\n\tLEFT JOIN LATERAL (\\n\t\tSELECT ts.next_run_at, ts.enabled\\n\t\tFROM trigger_schedules ts\\n\t\tWHERE ts.project_id = ta.project_id AND ts.attachment_slug = ta.slug\\n\t\tORDER BY ts.enabled DESC, ts.next_run_at ASC NULLS LAST\\n\t\tLIMIT 1\\n\t) s ON true\\n\tORDER BY ta.project_id, g.group_key, ta.registered_at ASC\\n) g;\\n\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_attachments\\\" ADD COLUMN \\\"trigger_id\\\" text;\",\n\t\t\t\"\\nUPDATE trigger_attachments ta\\nSET trigger_id = t.id\\nFROM triggers t\\nWHERE t.project_id = ta.project_id\\n\tAND t.kind = (ta.source->>'kind')\\n\tAND (\\n\t\t(ta.origin = 'ephemeral' AND t.origin = 'ephemeral' AND t.slug = ta.slug)\\n\t\tOR (\\n\t\t\tta.origin <> 'ephemeral'\\n\t\t\tAND t.origin = 'project'\\n\t\t\tAND t.slug = COALESCE(NULLIF(ta.source->>'slug', ''), NULLIF(ta.source->>'key', ''))\\n\t\t)\\n\t);\\n\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_runs\\\" ADD COLUMN IF NOT EXISTS \\\"outcome\\\" text DEFAULT 'dispatched' NOT NULL;\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_runs\\\" ADD COLUMN IF NOT EXISTS \\\"reason\\\" text;\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_runs\\\" ADD COLUMN IF NOT EXISTS \\\"detail\\\" text;\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_runs\\\" ADD COLUMN \\\"trigger_id\\\" text;\",\n\t\t\t\"\\nUPDATE trigger_runs tr\\nSET trigger_id = ta.trigger_id\\nFROM trigger_attachments ta\\nWHERE tr.attachment_id = ta.id;\\n\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_runs\\\" DROP CONSTRAINT \\\"trigger_runs_attachment_id_trigger_attachments_id_fk\\\";\",\n\t\t\t\"\\nDROP INDEX IF EXISTS \\\"trigger_runs_project_attachment_triggered_idx\\\";\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_runs\\\" DROP COLUMN \\\"attachment_id\\\";\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_runs\\\" ALTER COLUMN \\\"trigger_id\\\" SET NOT NULL;\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_runs\\\" ADD CONSTRAINT \\\"trigger_runs_trigger_id_triggers_id_fk\\\" FOREIGN KEY (\\\"trigger_id\\\") REFERENCES \\\"public\\\".\\\"triggers\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nCREATE INDEX \\\"trigger_runs_project_trigger_triggered_idx\\\" ON \\\"trigger_runs\\\" USING btree (\\\"project_id\\\",\\\"trigger_id\\\",\\\"triggered_at\\\");\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_attachments\\\" DROP COLUMN \\\"name\\\";\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_attachments\\\" DROP COLUMN \\\"description\\\";\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_attachments\\\" DROP COLUMN \\\"module_file\\\";\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_attachments\\\" DROP COLUMN \\\"source\\\";\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_attachments\\\" DROP COLUMN \\\"origin\\\";\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_attachments\\\" DROP COLUMN \\\"lifecycle\\\";\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_attachments\\\" DROP COLUMN \\\"created_by_session_id\\\";\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_attachments\\\" ALTER COLUMN \\\"trigger_id\\\" SET NOT NULL;\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_attachments\\\" ADD CONSTRAINT \\\"trigger_attachments_trigger_id_triggers_id_fk\\\" FOREIGN KEY (\\\"trigger_id\\\") REFERENCES \\\"public\\\".\\\"triggers\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nDROP TABLE \\\"trigger_schedules\\\";\\n\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1783e9,\n\t\t\"hash\": \"1413969c71976435768a9ade921f6da3e6e974a3b1c1dbaf9644536bd47f6507\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"ALTER TABLE \\\"triggers\\\" ADD COLUMN \\\"trigger_hash\\\" text;\",\n\t\t\t\"\\nALTER TABLE \\\"triggers\\\" ADD COLUMN \\\"overview_markdown\\\" text;\",\n\t\t\t\"\\nALTER TABLE \\\"triggers\\\" ADD COLUMN \\\"overview_hash\\\" text;\",\n\t\t\t\"\\nALTER TABLE \\\"triggers\\\" ADD COLUMN \\\"overview_model\\\" text;\",\n\t\t\t\"\\nALTER TABLE \\\"triggers\\\" ADD COLUMN \\\"overview_status\\\" text DEFAULT 'idle' NOT NULL;\",\n\t\t\t\"\\nALTER TABLE \\\"triggers\\\" ADD COLUMN \\\"overview_generated_at\\\" timestamp with time zone;\\n\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 17831e8,\n\t\t\"hash\": \"6bfdc822c7dffa912d818b7c46dfed152e15b0baa37c8117da0dd1f2123a8613\"\n\t}\n];\n//#endregion\n//#region src/migrate/run.ts\nasync function runMigrations(handle, migrationsFolder) {\n\tif (handle.dialect === \"postgres\") {\n\t\tconst config = {\n\t\t\tmigrationsFolder,\n\t\t\tmigrationsSchema: resolveMigrationsSchema(handle.searchPath)\n\t\t};\n\t\tconst loaded = loadMigrations(migrationsFolder, pgMigrations);\n\t\tconst migrations = handle.searchPath ? adaptPgMigrationsForSearchPath(loaded) : loaded;\n\t\tawait migratePgDatabase(handle.db, config, migrations);\n\t\treturn;\n\t}\n\tmigrate(handle.db, { migrationsFolder });\n}\n//#endregion\n//#region src/client/init.ts\nfunction resolveUrl(url) {\n\tif (url) return url;\n\tconst envUrl = process.env.DATABASE_URL?.trim();\n\tif (envUrl && inferDialect(envUrl) === \"sqlite\") return envUrl;\n\treturn resolveProjectDatabaseUrlFromEnv(process.env) ?? \"file:./data/dev.db\";\n}\nasync function initDatabase(options = {}) {\n\tif (isDatabaseInitialized()) return;\n\tconst url = resolveUrl(options.url);\n\tconst dialect = inferDialect(url, options.dialect);\n\tconst searchPath = resolveSearchPath(url, options.searchPath);\n\tconst next = createConnection({\n\t\turl,\n\t\tdialect,\n\t\tmax: options.max,\n\t\tsearchPath\n\t});\n\tsetDatabaseHandle(next);\n\tif (options.migrate ?? true) await runMigrations(next, resolveMigrationsFolder(dialect, options.migrationsFolder));\n}\n//#endregion\n//#region src/client/project-database.ts\n/** Bind a Postgres handle for the org's shared runtime schema (all projects in the org). */\nasync function runWithProjectDatabase(options, fn) {\n\tconst poolOptions = {\n\t\turl: options.url,\n\t\tsearchPath: options.searchPath,\n\t\tmax: options.max\n\t};\n\tconst handle = await acquireProjectDatabasePool(poolOptions);\n\tconst closeOnRelease = inferDialect(options.url) !== \"postgres\";\n\treturn runWithRequestDatabaseHandle(handle, async () => {\n\t\ttry {\n\t\t\treturn await fn();\n\t\t} finally {\n\t\t\tif (closeOnRelease) await handle.close();\n\t\t\telse releaseProjectDatabasePool(poolOptions);\n\t\t}\n\t});\n}\n//#endregion\n//#region src/queries/_internal.ts\n/** Internal: only `queries/**` may call this. */\nfunction getDb() {\n\treturn getDbFromContext();\n}\n//#endregion\n//#region src/queries/agents/list-active.ts\n/**\n* List every active agent in the bound org schema (all projects). Not project\n* scoped — the org database schema is itself the tenant boundary.\n*/\nasync function listActiveAgents(options) {\n\tconst db = getDb();\n\tif (options?.projectIds !== void 0 && options.projectIds.length === 0) return [];\n\tconst conditions = [isNull(agents.deletedAt)];\n\tif (options?.projectIds !== void 0) conditions.push(inArray$1(agents.projectId, options.projectIds));\n\treturn db.select().from(agents).where(and$1(...conditions)).orderBy(desc(agents.updatedAt));\n}\n//#endregion\n//#region src/queries/_internal/project-scope.ts\nfunction eqProjectScope(table) {\n\treturn eq$1(table.projectId, getProjectScopeId());\n}\nfunction scopedAnd(table, ...conditions) {\n\treturn and$1(eqProjectScope(table), ...conditions);\n}\nfunction projectScopeId() {\n\treturn getProjectScopeId();\n}\n/** Use with left joins on workflowRuns/triggerRuns/agentSessions keyed by trace or ref id. */\nfunction traceRootProjectScopeFilter() {\n\treturn or(eq$1(workflowRuns.projectId, getProjectScopeId()), eq$1(triggerRuns.projectId, getProjectScopeId()), eq$1(agentSessions.projectId, getProjectScopeId()));\n}\n//#endregion\n//#region src/queries/agents/select.ts\nasync function selectAgentBySlug(slug) {\n\treturn (await getDb().select().from(agents).where(scopedAnd(agents, eq$1(agents.slug, slug))).limit(1))[0];\n}\nasync function selectActiveAgentByRoute(route) {\n\treturn (await getDb().select({\n\t\tid: agents.id,\n\t\tslug: agents.slug\n\t}).from(agents).where(scopedAnd(agents, eq$1(agents.route, route), isNull(agents.deletedAt))).limit(1))[0];\n}\n/** Fetch active agents by id from the bound org schema (all projects). */\nasync function selectActiveAgentsByIds(ids) {\n\tif (ids.length === 0) return [];\n\treturn getDb().select().from(agents).where(and$1(inArray$1(agents.id, ids), isNull(agents.deletedAt)));\n}\n/** Fetch a single active agent by id from the bound org schema (all projects). */\nasync function selectActiveAgentById(id) {\n\treturn (await getDb().select().from(agents).where(and$1(eq$1(agents.id, id), isNull(agents.deletedAt))).limit(1))[0];\n}\n//#endregion\n//#region src/queries/agents/resolve-project-id.ts\n/** The agent row is the source of truth for which project it belongs to. */\nasync function resolveAgentProjectId(agentId) {\n\tconst agent = await selectActiveAgentById(agentId);\n\tif (!agent) throw new Error(`Agent not found: ${agentId}`);\n\treturn agent.projectId;\n}\n//#endregion\n//#region src/queries/agents/write.ts\nasync function insertAgent(values) {\n\tawait getDb().insert(agents).values({\n\t\t...values,\n\t\tprojectId: projectScopeId()\n\t});\n}\nasync function updateAgentById(id, values) {\n\tawait getDb().update(agents).set(values).where(scopedAnd(agents, eq$1(agents.id, id)));\n}\nasync function softDeleteAllAgents(now) {\n\tawait getDb().update(agents).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(agents, isNull(agents.deletedAt)));\n}\nasync function softDeleteAgentsNotInSlugs(slugs, now) {\n\tawait getDb().update(agents).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(agents, isNull(agents.deletedAt), notInArray(agents.slug, slugs)));\n}\n//#endregion\n//#region src/agents/cursor.ts\nfunction encodeAgentSessionCursor(cursor) {\n\treturn Buffer.from(JSON.stringify({\n\t\tupdatedAt: cursor.updatedAt.toISOString(),\n\t\tid: cursor.id\n\t})).toString(\"base64url\");\n}\nfunction decodeAgentSessionCursor(value) {\n\ttry {\n\t\tconst parsed = JSON.parse(Buffer.from(value, \"base64url\").toString(\"utf8\"));\n\t\tif (typeof parsed.updatedAt !== \"string\" || typeof parsed.id !== \"string\") return null;\n\t\tconst updatedAt = new Date(parsed.updatedAt);\n\t\tif (Number.isNaN(updatedAt.getTime())) return null;\n\t\treturn {\n\t\t\tupdatedAt,\n\t\t\tid: parsed.id\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\n//#endregion\n//#region src/queries/agent-sessions/index.ts\nasync function insertAgentSession(values) {\n\tawait getDb().insert(agentSessions).values({\n\t\t...values,\n\t\tsourceKind: values.sourceKind ?? \"api\",\n\t\tsourceId: values.sourceId ?? null,\n\t\tranByUserId: values.ranByUserId ?? null,\n\t\tprojectId: projectScopeId()\n\t});\n}\nasync function selectActiveAgentSession(sessionId) {\n\treturn (await getDb().select().from(agentSessions).where(scopedAnd(agentSessions, eq$1(agentSessions.id, sessionId), isNull(agentSessions.deletedAt))).limit(1))[0];\n}\nasync function selectAgentSessionById(sessionId) {\n\treturn selectActiveAgentSession(sessionId);\n}\nasync function listAgentSessionsBySourceIds(options) {\n\tif (options.sourceIds.length === 0) return /* @__PURE__ */ new Map();\n\tconst rows = await getDb().select().from(agentSessions).where(scopedAnd(agentSessions, eq$1(agentSessions.sourceKind, options.sourceKind), inArray$1(agentSessions.sourceId, options.sourceIds), isNull(agentSessions.deletedAt)));\n\tconst bySourceId = /* @__PURE__ */ new Map();\n\tfor (const row of rows) if (row.sourceId) {\n\t\tconst bucket = bySourceId.get(row.sourceId) ?? [];\n\t\tbucket.push(row);\n\t\tbySourceId.set(row.sourceId, bucket);\n\t}\n\treturn bySourceId;\n}\nasync function selectAgentSessionForAgent(agentSlug, sessionId) {\n\treturn (await getDb().select({ session: agentSessions }).from(agentSessions).innerJoin(agents, eq$1(agents.id, agentSessions.agentId)).where(and$1(eq$1(agents.slug, agentSlug), eq$1(agents.projectId, projectScopeId()), eq$1(agentSessions.id, sessionId), isNull(agentSessions.deletedAt))).limit(1))[0]?.session;\n}\nasync function touchAgentSession(sessionId, updatedAt) {\n\tawait getDb().update(agentSessions).set({ updatedAt }).where(scopedAnd(agentSessions, eq$1(agentSessions.id, sessionId), isNull(agentSessions.deletedAt)));\n}\nasync function updateAgentSessionTitle(sessionId, title) {\n\tawait getDb().update(agentSessions).set({ title }).where(scopedAnd(agentSessions, eq$1(agentSessions.id, sessionId), isNull(agentSessions.deletedAt)));\n}\nasync function addAgentSessionDuration(sessionId, deltaMs) {\n\tif (deltaMs <= 0) return;\n\tawait getDb().update(agentSessions).set({ totalDurationMs: sql$1`${agentSessions.totalDurationMs} + ${deltaMs}` }).where(scopedAnd(agentSessions, eq$1(agentSessions.id, sessionId), isNull(agentSessions.deletedAt)));\n}\nfunction cursorBefore$2(cursor) {\n\treturn or(lt(agentSessions.updatedAt, cursor.updatedAt), and$1(eq$1(agentSessions.updatedAt, cursor.updatedAt), lt(agentSessions.id, cursor.id)));\n}\nasync function listAgentSessionRowsPaginated(options) {\n\tconst db = getDb();\n\tconst conditions = [\n\t\teq$1(agents.slug, options.agentSlug),\n\t\teq$1(agents.projectId, projectScopeId()),\n\t\tisNull(agentSessions.deletedAt)\n\t];\n\tif (options.source) conditions.push(eq$1(agentSessions.sourceKind, options.source));\n\tif (options.cursor) {\n\t\tconst decoded = decodeAgentSessionCursor(options.cursor);\n\t\tif (!decoded) throw new Error(\"Invalid cursor\");\n\t\tconditions.push(cursorBefore$2(decoded));\n\t}\n\tconst limit = options.limit + 1;\n\tconst sessions = (await db.select({ session: agentSessions }).from(agentSessions).innerJoin(agents, eq$1(agents.id, agentSessions.agentId)).where(and$1(...conditions)).orderBy(desc(agentSessions.updatedAt), desc(agentSessions.id)).limit(limit)).map((row) => row.session);\n\tconst hasMore = sessions.length > options.limit;\n\tconst page = hasMore ? sessions.slice(0, options.limit) : sessions;\n\tconst last = page.at(-1);\n\treturn {\n\t\trows: page,\n\t\tnextCursor: hasMore && last ? encodeAgentSessionCursor({\n\t\t\tupdatedAt: last.updatedAt,\n\t\t\tid: last.id\n\t\t}) : null\n\t};\n}\nasync function cancelAgentSessionRow(sessionId, canceledAt) {\n\treturn (await getDb().update(agentSessions).set({\n\t\tcanceledAt,\n\t\tupdatedAt: canceledAt\n\t}).where(scopedAnd(agentSessions, eq$1(agentSessions.id, sessionId), isNull(agentSessions.deletedAt), isNull(agentSessions.canceledAt))).returning())[0];\n}\n/**\n* Reactivates a session for a new run by clearing a prior cancellation. Cancellation\n* is per-run: a session is a multi-turn conversation, so a new prompt must not be blocked\n* (or perpetually shown as \"canceled\") just because an earlier turn was canceled. No-ops\n* when the session was not canceled.\n*/\nasync function clearAgentSessionCancellation(sessionId) {\n\tawait getDb().update(agentSessions).set({ canceledAt: null }).where(scopedAnd(agentSessions, eq$1(agentSessions.id, sessionId), isNull(agentSessions.deletedAt), isNotNull(agentSessions.canceledAt)));\n}\nasync function updateSessionLiveMessage(sessionId, message) {\n\tawait getDb().update(agentSessions).set({ liveMessage: message }).where(scopedAnd(agentSessions, eq$1(agentSessions.id, sessionId), isNull(agentSessions.deletedAt)));\n}\nasync function clearSessionLiveMessage(sessionId) {\n\tawait getDb().update(agentSessions).set({ liveMessage: null }).where(scopedAnd(agentSessions, eq$1(agentSessions.id, sessionId), isNull(agentSessions.deletedAt)));\n}\nasync function selectSessionLiveMessage(sessionId) {\n\treturn (await getDb().select({ liveMessage: agentSessions.liveMessage }).from(agentSessions).where(scopedAnd(agentSessions, eq$1(agentSessions.id, sessionId), isNull(agentSessions.deletedAt))).limit(1))[0]?.liveMessage;\n}\n//#endregion\n//#region src/queries/agent-events/index.ts\nasync function maxSeqForSession(sessionId) {\n\treturn (await getDb().select({ value: max$1(agentEvents.seq) }).from(agentEvents).innerJoin(agentSessions, eq$1(agentSessions.id, agentEvents.sessionId)).where(scopedAnd(agentSessions, eq$1(agentEvents.sessionId, sessionId), isNull(agentEvents.deletedAt))))[0]?.value ?? 0;\n}\nasync function insertAgentEvent(values) {\n\tawait getDb().insert(agentEvents).values(values);\n}\nasync function listMessagePayloads(sessionId, messageEventType) {\n\treturn (await listMessageEventsForSession(sessionId, messageEventType)).map((row) => row.payload);\n}\nasync function listMessageEventsForSession(sessionId, messageEventType, options) {\n\tconst db = getDb();\n\tconst sinceSeq = options?.sinceSeq;\n\treturn await db.select({\n\t\tpayload: agentEvents.payload,\n\t\tcreatedAt: agentEvents.createdAt,\n\t\tseq: agentEvents.seq\n\t}).from(agentEvents).innerJoin(agentSessions, eq$1(agentSessions.id, agentEvents.sessionId)).where(scopedAnd(agentSessions, eq$1(agentEvents.sessionId, sessionId), eq$1(agentEvents.eventType, messageEventType), isNull(agentEvents.deletedAt), sinceSeq != null && sinceSeq > 0 ? gt(agentEvents.seq, sinceSeq) : void 0)).orderBy(asc(agentEvents.seq));\n}\nasync function countMessageEventsForSession(sessionId, messageEventType) {\n\tconst rows = await getDb().select({ count: sql$1`count(*)` }).from(agentEvents).innerJoin(agentSessions, eq$1(agentSessions.id, agentEvents.sessionId)).where(scopedAnd(agentSessions, eq$1(agentEvents.sessionId, sessionId), eq$1(agentEvents.eventType, messageEventType), isNull(agentEvents.deletedAt)));\n\treturn Number(rows[0]?.count ?? 0);\n}\nasync function listAgentEventsForSession(sessionId) {\n\treturn (await getDb().select({ event: agentEvents }).from(agentEvents).innerJoin(agentSessions, eq$1(agentSessions.id, agentEvents.sessionId)).where(scopedAnd(agentSessions, eq$1(agentEvents.sessionId, sessionId), isNull(agentEvents.deletedAt))).orderBy(asc(agentEvents.seq))).map((row) => row.event);\n}\n//#endregion\n//#region src/queries/usage-records/index.ts\nasync function insertUsageRecord(values) {\n\tawait getDb().insert(usageRecords).values({\n\t\t...values,\n\t\tquantity: values.quantity ?? null,\n\t\tunit: values.unit ?? null,\n\t\tmetadata: values.metadata ?? null\n\t});\n}\nasync function listUsageRecordsForRun(runId, runKind) {\n\treturn getDb().select().from(usageRecords).where(and$1(eq$1(usageRecords.runId, runId), eq$1(usageRecords.runKind, runKind))).orderBy(asc(usageRecords.createdAt), asc(usageRecords.id));\n}\nasync function listUsageRecordsForRuns(runIds, runKind) {\n\tif (runIds.length === 0) return [];\n\treturn getDb().select().from(usageRecords).where(and$1(inArray$1(usageRecords.runId, runIds), eq$1(usageRecords.runKind, runKind))).orderBy(asc(usageRecords.createdAt), asc(usageRecords.id));\n}\n//#endregion\n//#region src/queries/triggers/index.ts\nasync function selectTriggerBySlug(slug) {\n\treturn (await getDb().select().from(triggers).where(scopedAnd(triggers, eq$1(triggers.slug, slug))).limit(1))[0];\n}\nasync function selectTriggerById(id) {\n\treturn (await getDb().select().from(triggers).where(scopedAnd(triggers, eq$1(triggers.id, id))).limit(1))[0];\n}\nasync function insertTrigger(values) {\n\tawait getDb().insert(triggers).values({\n\t\t...values,\n\t\tprojectId: projectScopeId(),\n\t\torigin: values.origin ?? \"project\",\n\t\tenabled: values.enabled ?? 1\n\t});\n}\nasync function updateTriggerById(id, values) {\n\tawait getDb().update(triggers).set(values).where(scopedAnd(triggers, eq$1(triggers.id, id)));\n}\nasync function setTriggerOverviewGenerating(id, hash, now = /* @__PURE__ */ new Date()) {\n\tawait getDb().update(triggers).set({\n\t\toverviewStatus: \"generating\",\n\t\toverviewHash: hash,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(triggers, eq$1(triggers.id, id)));\n}\nasync function updateTriggerOverview(id, values, now = /* @__PURE__ */ new Date()) {\n\tconst db = getDb();\n\tconst set = {\n\t\toverviewStatus: values.status,\n\t\tupdatedAt: now\n\t};\n\tif (values.markdown !== void 0) {\n\t\tset.overviewMarkdown = values.markdown;\n\t\tset.overviewGeneratedAt = now;\n\t}\n\tif (values.hash !== void 0) set.overviewHash = values.hash;\n\tif (values.model !== void 0) set.overviewModel = values.model;\n\tawait db.update(triggers).set(set).where(scopedAnd(triggers, eq$1(triggers.id, id)));\n}\nasync function softDeleteAllProjectTriggers(now) {\n\tawait getDb().update(triggers).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(triggers, isNull(triggers.deletedAt), eq$1(triggers.origin, \"project\")));\n}\nasync function softDeleteProjectTriggersNotInSlugs(slugs, now) {\n\tawait getDb().update(triggers).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(triggers, isNull(triggers.deletedAt), eq$1(triggers.origin, \"project\"), notInArray(triggers.slug, slugs)));\n}\nasync function listActiveTriggersByProjectIds(projectIds) {\n\tconst db = getDb();\n\tif (projectIds !== void 0 && projectIds.length === 0) return [];\n\tconst conditions = [isNull(triggers.deletedAt), eq$1(triggers.origin, \"project\")];\n\tif (projectIds !== void 0) conditions.push(inArray$1(triggers.projectId, projectIds));\n\treturn db.select().from(triggers).where(and$1(...conditions));\n}\nasync function listActiveEphemeralTriggers() {\n\treturn getDb().select().from(triggers).where(scopedAnd(triggers, isNull(triggers.deletedAt), eq$1(triggers.origin, \"ephemeral\")));\n}\nasync function selectWebhookTriggers() {\n\treturn (await getDb().select().from(triggers).where(scopedAnd(triggers, isNull(triggers.deletedAt)))).filter((row) => row.kind === \"webhook\");\n}\nasync function setTriggerScheduleEnabled(triggerSlug, enabled, now) {\n\tawait getDb().update(triggers).set({\n\t\tenabled: enabled ? 1 : 0,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(triggers, eq$1(triggers.slug, triggerSlug)));\n}\nasync function disableAllTriggerSchedules(now) {\n\tawait getDb().update(triggers).set({\n\t\tenabled: 0,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(triggers, eq$1(triggers.enabled, 1), inArray$1(triggers.kind, [\"cron\", \"poll\"])));\n}\nasync function disableTriggerSchedulesNotInSlugs(triggerSlugs, now) {\n\tawait getDb().update(triggers).set({\n\t\tenabled: 0,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(triggers, eq$1(triggers.enabled, 1), inArray$1(triggers.kind, [\"cron\", \"poll\"]), notInArray(triggers.slug, triggerSlugs)));\n}\nasync function listEnabledScheduledTriggers() {\n\treturn getDb().select().from(triggers).where(scopedAnd(triggers, eq$1(triggers.enabled, 1), inArray$1(triggers.kind, [\"cron\", \"poll\"]), isNull(triggers.deletedAt))).orderBy(asc(triggers.slug));\n}\nasync function claimDueTriggers(now, resolveNextRunAt, limit = 10) {\n\tconst db = getDb();\n\tif (getDatabaseHandle().dialect === \"postgres\") return db.transaction(async (tx) => {\n\t\tconst due = await tx.select().from(triggers).where(scopedAnd(triggers, eq$1(triggers.enabled, 1), inArray$1(triggers.kind, [\"cron\", \"poll\"]), isNull(triggers.deletedAt), lte(triggers.nextRunAt, now))).orderBy(asc(triggers.nextRunAt)).limit(limit);\n\t\tconst claimed = [];\n\t\tfor (const row of due) {\n\t\t\tif (!row.schedule) continue;\n\t\t\tconst nextRunAt = resolveNextRunAt(row.schedule);\n\t\t\tconst [updated] = await tx.update(triggers).set({\n\t\t\t\tnextRunAt,\n\t\t\t\tupdatedAt: now\n\t\t\t}).where(scopedAnd(triggers, eq$1(triggers.id, row.id), lte(triggers.nextRunAt, now))).returning();\n\t\t\tif (updated) claimed.push(updated);\n\t\t}\n\t\treturn claimed;\n\t});\n\tconst due = await db.select().from(triggers).where(scopedAnd(triggers, eq$1(triggers.enabled, 1), inArray$1(triggers.kind, [\"cron\", \"poll\"]), isNull(triggers.deletedAt), lte(triggers.nextRunAt, now))).orderBy(asc(triggers.nextRunAt)).limit(limit);\n\tconst claimed = [];\n\tfor (const row of due) {\n\t\tif (!row.schedule) continue;\n\t\tconst nextRunAt = resolveNextRunAt(row.schedule);\n\t\tawait db.update(triggers).set({\n\t\t\tnextRunAt,\n\t\t\tupdatedAt: now\n\t\t}).where(scopedAnd(triggers, eq$1(triggers.id, row.id), lte(triggers.nextRunAt, now)));\n\t\tconst updated = await selectTriggerById(row.id);\n\t\tif (updated && updated.nextRunAt?.getTime() === nextRunAt.getTime()) claimed.push(updated);\n\t}\n\treturn claimed;\n}\nasync function claimDueTriggersForOrg(now, resolveNextRunAt, limit = 10) {\n\tconst db = getDb();\n\tif (getDatabaseHandle().dialect === \"postgres\") return db.transaction(async (tx) => {\n\t\tconst due = await tx.select().from(triggers).where(and$1(eq$1(triggers.enabled, 1), inArray$1(triggers.kind, [\"cron\", \"poll\"]), isNull(triggers.deletedAt), lte(triggers.nextRunAt, now))).orderBy(asc(triggers.nextRunAt)).limit(limit);\n\t\tconst claimed = [];\n\t\tfor (const row of due) {\n\t\t\tif (!row.schedule) continue;\n\t\t\tconst nextRunAt = resolveNextRunAt(row.schedule);\n\t\t\tconst [updated] = await tx.update(triggers).set({\n\t\t\t\tnextRunAt,\n\t\t\t\tupdatedAt: now\n\t\t\t}).where(and$1(eq$1(triggers.id, row.id), eq$1(triggers.projectId, row.projectId), lte(triggers.nextRunAt, now))).returning();\n\t\t\tif (updated) claimed.push(updated);\n\t\t}\n\t\treturn claimed;\n\t});\n\tconst due = await db.select().from(triggers).where(and$1(eq$1(triggers.enabled, 1), inArray$1(triggers.kind, [\"cron\", \"poll\"]), isNull(triggers.deletedAt), lte(triggers.nextRunAt, now))).orderBy(asc(triggers.nextRunAt)).limit(limit);\n\tconst claimed = [];\n\tfor (const row of due) {\n\t\tif (!row.schedule) continue;\n\t\tconst nextRunAt = resolveNextRunAt(row.schedule);\n\t\tawait db.update(triggers).set({\n\t\t\tnextRunAt,\n\t\t\tupdatedAt: now\n\t\t}).where(and$1(eq$1(triggers.id, row.id), eq$1(triggers.projectId, row.projectId), lte(triggers.nextRunAt, now)));\n\t\tconst trigger = (await db.select().from(triggers).where(and$1(eq$1(triggers.id, row.id), eq$1(triggers.projectId, row.projectId))).limit(1))[0];\n\t\tif (trigger && trigger.nextRunAt?.getTime() === nextRunAt.getTime()) claimed.push(trigger);\n\t}\n\treturn claimed;\n}\nasync function upsertTriggerScheduleFields(options) {\n\tawait getDb().update(triggers).set({\n\t\tschedule: options.schedule,\n\t\tnextRunAt: options.nextRunAt,\n\t\tenabled: options.enabled ? 1 : 0,\n\t\tupdatedAt: options.updatedAt\n\t}).where(scopedAnd(triggers, eq$1(triggers.slug, options.triggerSlug)));\n}\nasync function listTriggersByIds(ids) {\n\tif (ids.length === 0) return [];\n\treturn getDb().select().from(triggers).where(scopedAnd(triggers, inArray$1(triggers.id, ids)));\n}\n//#endregion\n//#region src/queries/trigger-attachments/index.ts\nasync function selectTriggerAttachmentBySlug(slug) {\n\treturn (await getDb().select().from(triggerAttachments).where(scopedAnd(triggerAttachments, eq$1(triggerAttachments.slug, slug))).limit(1))[0];\n}\nasync function selectTriggerAttachmentById(id) {\n\treturn (await getDb().select().from(triggerAttachments).where(scopedAnd(triggerAttachments, eq$1(triggerAttachments.id, id))).limit(1))[0];\n}\nasync function insertTriggerAttachment(values) {\n\tawait getDb().insert(triggerAttachments).values({\n\t\t...values,\n\t\tprojectId: projectScopeId()\n\t});\n}\nasync function updateTriggerAttachmentById(id, values) {\n\tawait getDb().update(triggerAttachments).set(values).where(scopedAnd(triggerAttachments, eq$1(triggerAttachments.id, id)));\n}\nasync function softDeleteAllTriggerAttachments(now) {\n\tconst db = getDb();\n\tconst { triggers } = await Promise.resolve().then(() => pg_exports);\n\tconst ids = (await db.select({ id: triggers.id }).from(triggers).where(scopedAnd(triggers, isNull(triggers.deletedAt), eq$1(triggers.origin, \"project\")))).map((row) => row.id);\n\tif (ids.length === 0) return;\n\tawait db.update(triggerAttachments).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(triggerAttachments, isNull(triggerAttachments.deletedAt), inArray$1(triggerAttachments.triggerId, ids)));\n}\nasync function softDeleteTriggerAttachmentsNotInSlugs(slugs, now) {\n\tconst db = getDb();\n\tconst { triggers } = await Promise.resolve().then(() => pg_exports);\n\tconst projectTriggerIds = (await db.select({ id: triggers.id }).from(triggers).where(scopedAnd(triggers, isNull(triggers.deletedAt), eq$1(triggers.origin, \"project\")))).map((row) => row.id);\n\tif (projectTriggerIds.length === 0) return;\n\tawait db.update(triggerAttachments).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(triggerAttachments, isNull(triggerAttachments.deletedAt), notInArray(triggerAttachments.slug, slugs), inArray$1(triggerAttachments.triggerId, projectTriggerIds)));\n}\nasync function getTriggerAttachmentBySlug(slug) {\n\treturn selectTriggerAttachmentBySlug(slug);\n}\nasync function listActiveTriggerAttachments() {\n\tconst db = getDb();\n\tconst { triggers } = await Promise.resolve().then(() => pg_exports);\n\treturn (await db.select({ attachment: triggerAttachments }).from(triggerAttachments).innerJoin(triggers, eq$1(triggerAttachments.triggerId, triggers.id)).where(scopedAnd(triggerAttachments, isNull(triggerAttachments.deletedAt), isNull(triggers.deletedAt), eq$1(triggers.origin, \"project\")))).map((row) => row.attachment);\n}\nasync function listAttachmentsByTriggerIds(triggerIds) {\n\tif (triggerIds.length === 0) return [];\n\treturn getDb().select().from(triggerAttachments).where(and$1(isNull(triggerAttachments.deletedAt), inArray$1(triggerAttachments.triggerId, triggerIds)));\n}\nasync function selectEphemeralTriggerAttachmentsByAgentSlug(agentSlug) {\n\tconst db = getDb();\n\tconst { triggers } = await Promise.resolve().then(() => pg_exports);\n\treturn db.select({ attachment: triggerAttachments }).from(triggerAttachments).innerJoin(triggers, eq$1(triggerAttachments.triggerId, triggers.id)).where(scopedAnd(triggerAttachments, isNull(triggerAttachments.deletedAt), isNull(triggers.deletedAt), eq$1(triggers.origin, \"ephemeral\"), eq$1(triggerAttachments.agentSlug, agentSlug))).then((rows) => rows.map((row) => row.attachment));\n}\nasync function selectTriggerAttachmentsByAgentSlug(agentSlug) {\n\treturn getDb().select().from(triggerAttachments).where(scopedAnd(triggerAttachments, isNull(triggerAttachments.deletedAt), eq$1(triggerAttachments.agentSlug, agentSlug)));\n}\nasync function selectEphemeralTriggerAttachments() {\n\tconst db = getDb();\n\tconst { triggers } = await Promise.resolve().then(() => pg_exports);\n\treturn db.select({ attachment: triggerAttachments }).from(triggerAttachments).innerJoin(triggers, eq$1(triggerAttachments.triggerId, triggers.id)).where(scopedAnd(triggerAttachments, isNull(triggerAttachments.deletedAt), isNull(triggers.deletedAt), eq$1(triggers.origin, \"ephemeral\"))).then((rows) => rows.map((row) => row.attachment));\n}\n/** @deprecated Use selectWebhookTriggers + listAttachmentsByTriggerIds */\nasync function selectWebhookTriggerAttachments() {\n\tconst db = getDb();\n\tconst { triggers } = await Promise.resolve().then(() => pg_exports);\n\treturn db.select({ attachment: triggerAttachments }).from(triggerAttachments).innerJoin(triggers, eq$1(triggerAttachments.triggerId, triggers.id)).where(scopedAnd(triggerAttachments, isNull(triggerAttachments.deletedAt), isNull(triggers.deletedAt), eq$1(triggers.kind, \"webhook\"))).then((rows) => rows.map((row) => row.attachment));\n}\n//#endregion\n//#region src/workflows/cursor.ts\nfunction encodeWorkflowRunCursor(cursor) {\n\treturn Buffer.from(JSON.stringify({\n\t\ttriggeredAt: cursor.triggeredAt.toISOString(),\n\t\tid: cursor.id\n\t})).toString(\"base64url\");\n}\nfunction decodeWorkflowRunCursor(value) {\n\ttry {\n\t\tconst parsed = JSON.parse(Buffer.from(value, \"base64url\").toString(\"utf8\"));\n\t\tif (typeof parsed.triggeredAt !== \"string\" || typeof parsed.id !== \"string\") return null;\n\t\tconst triggeredAt = new Date(parsed.triggeredAt);\n\t\tif (Number.isNaN(triggeredAt.getTime())) return null;\n\t\treturn {\n\t\t\ttriggeredAt,\n\t\t\tid: parsed.id\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\n//#endregion\n//#region src/workflows/serialize.ts\nfunction toIso(value) {\n\tif (!value) return null;\n\treturn value.toISOString();\n}\nfunction workflowRunSummaryFromRow(row) {\n\treturn {\n\t\tid: row.id,\n\t\tstatus: row.status,\n\t\ttrigger: row.trigger,\n\t\ttriggeredAt: row.triggeredAt.toISOString(),\n\t\tstartedAt: toIso(row.startedAt),\n\t\tfinishedAt: toIso(row.finishedAt),\n\t\ttriggerRunId: row.triggerRunId ?? null,\n\t\tattachmentId: row.attachmentId ?? null,\n\t\tsourceKind: row.sourceKind,\n\t\tsourceId: row.sourceId ?? null\n\t};\n}\nfunction workflowRunRecordFromRow(row) {\n\treturn {\n\t\tid: row.id,\n\t\tworkflowSlug: row.workflowSlug,\n\t\tstatus: row.status,\n\t\ttrigger: row.trigger,\n\t\ttriggeredAt: row.triggeredAt.toISOString(),\n\t\tstartedAt: toIso(row.startedAt),\n\t\tfinishedAt: toIso(row.finishedAt),\n\t\tsourceKind: row.sourceKind,\n\t\tsourceId: row.sourceId ?? null,\n\t\ttriggerRunId: row.triggerRunId ?? null,\n\t\tattachmentId: row.attachmentId ?? null,\n\t\tparentWorkflowRunId: row.parentWorkflowRunId ?? null,\n\t\tparentSpanId: row.parentSpanId ?? null,\n\t\tinput: row.input ?? null,\n\t\toutput: row.output ?? null,\n\t\terror: row.error ?? null\n\t};\n}\nfunction triggerRunDetailFromRow(row, attachmentSlug) {\n\treturn {\n\t\tid: row.id,\n\t\ttriggerId: row.triggerId,\n\t\tattachmentSlug,\n\t\ttriggerType: row.triggerType,\n\t\tsourcePath: row.sourcePath ?? null,\n\t\tpayload: row.payload ?? null,\n\t\ttriggeredAt: row.triggeredAt.toISOString()\n\t};\n}\nfunction workflowStepRunFromEvent(row) {\n\treturn {\n\t\tid: row.id,\n\t\tactionKey: row.correlationId ?? row.id,\n\t\toutput: row.data ?? null,\n\t\tcompletedAt: row.createdAt.toISOString()\n\t};\n}\nfunction traceSpanToJson(span) {\n\treturn {\n\t\t...span,\n\t\tstartedAt: span.startedAt.toISOString(),\n\t\tfinishedAt: toIso(span.finishedAt)\n\t};\n}\nfunction traceLogToJson(log) {\n\treturn {\n\t\t...log,\n\t\tcreatedAt: log.createdAt.toISOString()\n\t};\n}\nfunction traceResponseToJson(trace) {\n\treturn {\n\t\ttraceId: trace.traceId,\n\t\ttrigger: trace.trigger,\n\t\tgateway: trace.gateway,\n\t\tspans: trace.spans.map(traceSpanToJson),\n\t\tlogs: trace.logs.map(traceLogToJson)\n\t};\n}\n//#endregion\n//#region src/queries/workflow-runs/index.ts\nasync function insertWorkflowRun(values) {\n\tawait getDb().insert(workflowRuns).values({\n\t\t...values,\n\t\tsourceKind: values.sourceKind ?? \"api\",\n\t\tsourceId: values.sourceId ?? null,\n\t\tranByUserId: values.ranByUserId ?? null,\n\t\tprojectId: projectScopeId()\n\t});\n}\nasync function markWorkflowRunRunningRow(id, startedAt) {\n\tawait getDb().update(workflowRuns).set({\n\t\tstatus: \"running\",\n\t\tstartedAt,\n\t\terror: null,\n\t\tfinishedAt: null\n\t}).where(scopedAnd(workflowRuns, eq$1(workflowRuns.id, id)));\n}\nasync function setWorkflowRunStatusRow(id, status) {\n\tawait getDb().update(workflowRuns).set({ status }).where(scopedAnd(workflowRuns, eq$1(workflowRuns.id, id)));\n}\nasync function selectWorkflowRunById(id) {\n\treturn (await getDb().select().from(workflowRuns).where(scopedAnd(workflowRuns, eq$1(workflowRuns.id, id))).limit(1))[0];\n}\n/** Resolve the owning project for a run id across the whole org schema. */\nasync function resolveWorkflowRunProjectId(runId) {\n\tconst rows = await getDb().select({ projectId: workflowRuns.projectId }).from(workflowRuns).where(eq$1(workflowRuns.id, runId)).limit(1);\n\tif (!rows[0]) throw new Error(`Workflow run not found: ${runId}`);\n\treturn rows[0].projectId;\n}\nasync function completeWorkflowRunRow(id, output, finishedAt) {\n\tawait getDb().update(workflowRuns).set({\n\t\tstatus: \"completed\",\n\t\toutput,\n\t\tfinishedAt,\n\t\terror: null\n\t}).where(scopedAnd(workflowRuns, eq$1(workflowRuns.id, id), ne(workflowRuns.status, \"canceled\")));\n}\nasync function failWorkflowRunRow(id, error, finishedAt) {\n\tawait getDb().update(workflowRuns).set({\n\t\tstatus: \"failed\",\n\t\terror,\n\t\tfinishedAt\n\t}).where(scopedAnd(workflowRuns, eq$1(workflowRuns.id, id), ne(workflowRuns.status, \"canceled\")));\n}\nconst CANCELABLE_WORKFLOW_STATUSES = [\n\t\"pending\",\n\t\"running\",\n\t\"sleeping\",\n\t\"waiting_hook\"\n];\nasync function cancelWorkflowRunRow(id, finishedAt) {\n\treturn (await getDb().update(workflowRuns).set({\n\t\tstatus: \"canceled\",\n\t\tfinishedAt\n\t}).where(scopedAnd(workflowRuns, eq$1(workflowRuns.id, id), inArray$1(workflowRuns.status, CANCELABLE_WORKFLOW_STATUSES))).returning())[0];\n}\nasync function listWorkflowRunsByWorkflowSlug(workflowSlug) {\n\treturn getDb().select().from(workflowRuns).where(scopedAnd(workflowRuns, eq$1(workflowRuns.workflowSlug, workflowSlug)));\n}\nasync function listWorkflowRunsByTriggerRunId(triggerRunId) {\n\treturn getDb().select().from(workflowRuns).where(scopedAnd(workflowRuns, eq$1(workflowRuns.triggerRunId, triggerRunId)));\n}\nasync function listWorkflowRunsByTriggerRunIds(triggerRunIds) {\n\tif (triggerRunIds.length === 0) return /* @__PURE__ */ new Map();\n\tconst rows = await getDb().select().from(workflowRuns).where(scopedAnd(workflowRuns, inArray$1(workflowRuns.triggerRunId, triggerRunIds)));\n\tconst byTriggerRunId = /* @__PURE__ */ new Map();\n\tfor (const row of rows) if (row.triggerRunId) {\n\t\tconst bucket = byTriggerRunId.get(row.triggerRunId) ?? [];\n\t\tbucket.push(row);\n\t\tbyTriggerRunId.set(row.triggerRunId, bucket);\n\t}\n\treturn byTriggerRunId;\n}\nasync function selectWorkflowRunForWorkflow(workflowSlug, runId) {\n\treturn (await getDb().select().from(workflowRuns).where(scopedAnd(workflowRuns, eq$1(workflowRuns.id, runId), eq$1(workflowRuns.workflowSlug, workflowSlug))).limit(1))[0];\n}\nfunction cursorBefore$1(cursor) {\n\treturn or(lt(workflowRuns.triggeredAt, cursor.triggeredAt), and$1(eq$1(workflowRuns.triggeredAt, cursor.triggeredAt), lt(workflowRuns.id, cursor.id)));\n}\nasync function listWorkflowRunsPaginated(options) {\n\tconst db = getDb();\n\tconst conditions = [eq$1(workflowRuns.workflowSlug, options.workflowSlug)];\n\tif (options.status) conditions.push(eq$1(workflowRuns.status, options.status));\n\tif (options.trigger) conditions.push(eq$1(workflowRuns.trigger, options.trigger));\n\tif (options.cursor) {\n\t\tconst decoded = decodeWorkflowRunCursor(options.cursor);\n\t\tif (!decoded) throw new Error(\"Invalid cursor\");\n\t\tconditions.push(cursorBefore$1(decoded));\n\t}\n\tconst limit = options.limit + 1;\n\tconst rows = await db.select().from(workflowRuns).where(scopedAnd(workflowRuns, ...conditions)).orderBy(desc(workflowRuns.triggeredAt), desc(workflowRuns.id)).limit(limit);\n\tconst hasMore = rows.length > options.limit;\n\tconst page = hasMore ? rows.slice(0, options.limit) : rows;\n\tconst last = page.at(-1);\n\treturn {\n\t\titems: page.map(workflowRunSummaryFromRow),\n\t\tnextCursor: hasMore && last ? encodeWorkflowRunCursor({\n\t\t\ttriggeredAt: last.triggeredAt,\n\t\t\tid: last.id\n\t\t}) : null\n\t};\n}\n//#endregion\n//#region src/queries/workflow-events/index.ts\nasync function selectMaxEventSeq(runId) {\n\tconst rows = await getDb().select({ value: max$1(workflowEvents.seq) }).from(workflowEvents).where(scopedAnd(workflowEvents, eq$1(workflowEvents.runId, runId)));\n\treturn Number(rows[0]?.value ?? -1);\n}\n/**\n* Append one event. Allocates the next per-run `seq` (max+1) and is idempotent\n* when an explicit `id` is supplied. Returns true when a row was inserted.\n*/\nasync function appendWorkflowEvent(values) {\n\tconst db = getDb();\n\tconst id = values.id ?? crypto.randomUUID();\n\tconst seq = await selectMaxEventSeq(values.runId) + 1;\n\treturn (await db.insert(workflowEvents).values({\n\t\tid,\n\t\trunId: values.runId,\n\t\tprojectId: projectScopeId(),\n\t\tseq,\n\t\ttype: values.type,\n\t\tcorrelationId: values.correlationId ?? null,\n\t\tdata: values.data ?? null,\n\t\tcreatedAt: /* @__PURE__ */ new Date()\n\t}).onConflictDoNothing({ target: workflowEvents.id }).returning({ id: workflowEvents.id })).length > 0;\n}\nasync function listReplayEvents(runId) {\n\treturn getDb().select().from(workflowEvents).where(scopedAnd(workflowEvents, eq$1(workflowEvents.runId, runId))).orderBy(asc(workflowEvents.seq));\n}\n/** Completed step events for a run, in execution order — backs the run-detail steps view. */\nasync function listStepCompletedEvents(runId) {\n\treturn getDb().select().from(workflowEvents).where(scopedAnd(workflowEvents, eq$1(workflowEvents.runId, runId), eq$1(workflowEvents.type, \"step_completed\"))).orderBy(asc(workflowEvents.seq));\n}\n//#endregion\n//#region src/queries/workflow-hooks/index.ts\n/** Idempotent on `token` so replays don't create duplicate hook rows. */\nasync function insertWorkflowHook(values) {\n\tawait getDb().insert(workflowHooks).values({\n\t\thookId: values.hookId,\n\t\trunId: values.runId,\n\t\tprojectId: projectScopeId(),\n\t\ttoken: values.token,\n\t\tcorrelationId: values.correlationId,\n\t\tstatus: \"waiting\",\n\t\tpayload: values.payload ?? null,\n\t\tcreatedAt: /* @__PURE__ */ new Date(),\n\t\tresumedAt: null\n\t}).onConflictDoNothing({ target: workflowHooks.token });\n}\nasync function selectWorkflowHookByToken(token) {\n\treturn (await getDb().select().from(workflowHooks).where(scopedAnd(workflowHooks, eq$1(workflowHooks.token, token))).limit(1))[0];\n}\nasync function markWorkflowHookResumed(hookId, payload) {\n\tawait getDb().update(workflowHooks).set({\n\t\tstatus: \"resumed\",\n\t\tpayload,\n\t\tresumedAt: /* @__PURE__ */ new Date()\n\t}).where(scopedAnd(workflowHooks, eq$1(workflowHooks.hookId, hookId)));\n}\n//#endregion\n//#region src/triggers/cursor.ts\nfunction encodeTriggerRunCursor(cursor) {\n\treturn Buffer.from(JSON.stringify({\n\t\ttriggeredAt: cursor.triggeredAt.toISOString(),\n\t\tid: cursor.id\n\t})).toString(\"base64url\");\n}\nfunction decodeTriggerRunCursor(value) {\n\ttry {\n\t\tconst parsed = JSON.parse(Buffer.from(value, \"base64url\").toString(\"utf8\"));\n\t\tif (typeof parsed.triggeredAt !== \"string\" || typeof parsed.id !== \"string\") return null;\n\t\tconst triggeredAt = new Date(parsed.triggeredAt);\n\t\tif (Number.isNaN(triggeredAt.getTime())) return null;\n\t\treturn {\n\t\t\ttriggeredAt,\n\t\t\tid: parsed.id\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\n//#endregion\n//#region src/triggers/serialize.ts\nfunction triggerRunSummaryFromRow(row, options) {\n\treturn {\n\t\tid: row.id,\n\t\ttriggerType: row.triggerType,\n\t\ttriggeredAt: row.triggeredAt.toISOString(),\n\t\tsourcePath: row.sourcePath ?? null,\n\t\toutcome: row.outcome,\n\t\treason: row.reason ?? null,\n\t\tdetail: row.detail ?? null,\n\t\tworkflowRuns: (options?.workflowRuns ?? []).map((workflowRun) => ({\n\t\t\tid: workflowRun.id,\n\t\t\tstatus: workflowRun.status,\n\t\t\tworkflowSlug: workflowRun.workflowSlug\n\t\t})),\n\t\tagentSessions: (options?.agentSessions ?? []).map((session) => ({\n\t\t\tid: session.id,\n\t\t\tagentSlug: session.agentSlug\n\t\t}))\n\t};\n}\nfunction triggerRunRecordFromRow(row, attachmentSlug, triggerId = row.triggerId) {\n\treturn {\n\t\tid: row.id,\n\t\ttriggerId,\n\t\tattachmentSlug,\n\t\ttriggerType: row.triggerType,\n\t\tsourcePath: row.sourcePath ?? null,\n\t\toutcome: row.outcome,\n\t\treason: row.reason ?? null,\n\t\tdetail: row.detail ?? null,\n\t\tpayload: row.payload ?? null,\n\t\ttriggeredAt: row.triggeredAt.toISOString()\n\t};\n}\n//#endregion\n//#region src/queries/trigger-runs/index.ts\nasync function insertTriggerRun(values) {\n\tawait getDb().insert(triggerRuns).values({\n\t\t...values,\n\t\toutcome: values.outcome ?? \"dispatched\",\n\t\treason: values.reason ?? null,\n\t\tdetail: values.detail ?? null,\n\t\tprojectId: projectScopeId()\n\t});\n}\nasync function selectTriggerRunById(id) {\n\treturn (await getDb().select().from(triggerRuns).where(scopedAnd(triggerRuns, eq$1(triggerRuns.id, id))).limit(1))[0];\n}\nasync function selectTriggerRunForTrigger(triggerId, runId) {\n\treturn (await getDb().select().from(triggerRuns).where(scopedAnd(triggerRuns, eq$1(triggerRuns.id, runId), eq$1(triggerRuns.triggerId, triggerId))).limit(1))[0];\n}\nfunction cursorBefore(cursor) {\n\treturn or(lt(triggerRuns.triggeredAt, cursor.triggeredAt), and$1(eq$1(triggerRuns.triggeredAt, cursor.triggeredAt), lt(triggerRuns.id, cursor.id)));\n}\nasync function listTriggerRunRowsPaginated(options) {\n\tif (options.triggerIds.length === 0) return {\n\t\titems: [],\n\t\tnextCursor: null\n\t};\n\tconst db = getDb();\n\tconst conditions = [inArray$1(triggerRuns.triggerId, options.triggerIds)];\n\tif (options.triggerType) conditions.push(eq$1(triggerRuns.triggerType, options.triggerType));\n\tif (options.cursor) {\n\t\tconst decoded = decodeTriggerRunCursor(options.cursor);\n\t\tif (!decoded) throw new Error(\"Invalid cursor\");\n\t\tconditions.push(cursorBefore(decoded));\n\t}\n\tconst limit = options.limit + 1;\n\tconst rows = await db.select().from(triggerRuns).where(scopedAnd(triggerRuns, ...conditions)).orderBy(desc(triggerRuns.triggeredAt), desc(triggerRuns.id)).limit(limit);\n\tconst hasMore = rows.length > options.limit;\n\tconst page = hasMore ? rows.slice(0, options.limit) : rows;\n\tconst last = page.at(-1);\n\tconst workflowRunsByTriggerRunId = await listWorkflowRunsByTriggerRunIds(page.map((row) => row.id));\n\treturn {\n\t\titems: page.map((row) => triggerRunSummaryFromRow(row, { workflowRuns: workflowRunsByTriggerRunId.get(row.id) ?? [] })),\n\t\tnextCursor: hasMore && last ? encodeTriggerRunCursor({\n\t\t\ttriggeredAt: last.triggeredAt,\n\t\t\tid: last.id\n\t\t}) : null\n\t};\n}\nasync function selectTriggerLastFiredAtByTriggerIds(triggerIds) {\n\tif (triggerIds.length === 0) return /* @__PURE__ */ new Map();\n\tconst rows = await getDb().select({\n\t\ttriggerId: triggerRuns.triggerId,\n\t\tlastFiredAt: max$1(triggerRuns.triggeredAt)\n\t}).from(triggerRuns).where(inArray$1(triggerRuns.triggerId, triggerIds)).groupBy(triggerRuns.triggerId);\n\tconst result = /* @__PURE__ */ new Map();\n\tfor (const row of rows) if (row.lastFiredAt) result.set(row.triggerId, row.lastFiredAt);\n\treturn result;\n}\nasync function selectTriggerFireCountByTriggerIds(triggerIds) {\n\tif (triggerIds.length === 0) return /* @__PURE__ */ new Map();\n\tconst rows = await getDb().select({\n\t\ttriggerId: triggerRuns.triggerId,\n\t\tfireCount: count()\n\t}).from(triggerRuns).where(inArray$1(triggerRuns.triggerId, triggerIds)).groupBy(triggerRuns.triggerId);\n\tconst result = /* @__PURE__ */ new Map();\n\tfor (const row of rows) result.set(row.triggerId, Number(row.fireCount));\n\treturn result;\n}\n//#endregion\n//#region src/queries/jobs/index.ts\nconst DEFAULT_LEASE_MS = 300 * 1e3;\nasync function insertJob(values) {\n\tawait getDb().insert(jobs).values({\n\t\t...values,\n\t\tprojectId: projectScopeId()\n\t});\n}\nasync function claimPendingJob(workerId, leaseExpiresAt, now) {\n\tconst db = getDb();\n\tconst job = (await db.select().from(jobs).where(scopedAnd(jobs, eq$1(jobs.status, \"pending\"), lte(jobs.scheduledAt, now))).orderBy(asc(jobs.scheduledAt)).limit(1))[0];\n\tif (!job) return;\n\tawait db.update(jobs).set({\n\t\tstatus: \"leased\",\n\t\tleasedBy: workerId,\n\t\tleaseExpiresAt\n\t}).where(scopedAnd(jobs, eq$1(jobs.id, job.id), eq$1(jobs.status, \"pending\")));\n\tconst claimed = await selectJobById(job.id);\n\tif (claimed?.status !== \"leased\" || claimed.leasedBy !== workerId) return;\n\treturn claimed;\n}\nasync function claimNextJobRow(workerId, leaseMs = DEFAULT_LEASE_MS) {\n\tconst db = getDb();\n\tconst dialect = getDatabaseHandle().dialect;\n\tconst now = /* @__PURE__ */ new Date();\n\tconst leaseExpiresAt = new Date(now.getTime() + leaseMs);\n\tif (dialect === \"postgres\") return db.transaction(async (tx) => {\n\t\tconst job = (await tx.select().from(jobs).where(scopedAnd(jobs, eq$1(jobs.status, \"pending\"), lte(jobs.scheduledAt, now))).orderBy(asc(jobs.scheduledAt)).limit(1))[0];\n\t\tif (!job) return;\n\t\tawait tx.update(jobs).set({\n\t\t\tstatus: \"leased\",\n\t\t\tleasedBy: workerId,\n\t\t\tleaseExpiresAt\n\t\t}).where(scopedAnd(jobs, eq$1(jobs.id, job.id)));\n\t\treturn {\n\t\t\t...job,\n\t\t\tstatus: \"leased\",\n\t\t\tleasedBy: workerId,\n\t\t\tleaseExpiresAt\n\t\t};\n\t});\n\treturn claimPendingJob(workerId, leaseExpiresAt, now);\n}\nasync function markJobRunning(id) {\n\tawait getDb().update(jobs).set({ status: \"running\" }).where(scopedAnd(jobs, eq$1(jobs.id, id)));\n}\nasync function completeJobRow(id, completedAt) {\n\tawait getDb().update(jobs).set({\n\t\tstatus: \"completed\",\n\t\tcompletedAt,\n\t\terror: null\n\t}).where(scopedAnd(jobs, eq$1(jobs.id, id)));\n}\nasync function failJobRow(id, error, completedAt) {\n\tawait getDb().update(jobs).set({\n\t\tstatus: \"failed\",\n\t\terror,\n\t\tcompletedAt\n\t}).where(scopedAnd(jobs, eq$1(jobs.id, id)));\n}\nasync function requeueExpiredLeases(now = /* @__PURE__ */ new Date()) {\n\tconst db = getDb();\n\tconst expired = await db.select({ id: jobs.id }).from(jobs).where(scopedAnd(jobs, inArray$1(jobs.status, [\"leased\", \"running\"]), isNotNull(jobs.leaseExpiresAt), lt(jobs.leaseExpiresAt, now)));\n\tif (expired.length === 0) return 0;\n\tawait db.update(jobs).set({\n\t\tstatus: \"pending\",\n\t\tleasedBy: null,\n\t\tleaseExpiresAt: null\n\t}).where(scopedAnd(jobs, inArray$1(jobs.id, expired.map((row) => row.id))));\n\treturn expired.length;\n}\nasync function selectJobById(id) {\n\treturn (await getDb().select().from(jobs).where(scopedAnd(jobs, eq$1(jobs.id, id))).limit(1))[0];\n}\nasync function selectJobByRunId(runId) {\n\treturn (await getDb().select().from(jobs).where(scopedAnd(jobs, eq$1(jobs.runId, runId))).limit(1))[0];\n}\nasync function resetJobForRetry(id, scheduledAt, attempt) {\n\tawait getDb().update(jobs).set({\n\t\tstatus: \"pending\",\n\t\tscheduledAt,\n\t\tattempt,\n\t\tleasedBy: null,\n\t\tleaseExpiresAt: null,\n\t\tcompletedAt: null,\n\t\terror: null\n\t}).where(scopedAnd(jobs, eq$1(jobs.id, id)));\n}\n//#endregion\n//#region src/queries/gateway-attachments/index.ts\nasync function selectGatewayAttachmentBySlug(slug) {\n\treturn (await getDb().select().from(gatewayAttachments).where(scopedAnd(gatewayAttachments, eq$1(gatewayAttachments.slug, slug))).limit(1))[0];\n}\nasync function selectGatewayAttachmentById(id) {\n\treturn (await getDb().select().from(gatewayAttachments).where(scopedAnd(gatewayAttachments, eq$1(gatewayAttachments.id, id))).limit(1))[0];\n}\n/** Thrown when a channel is already bound by a different project in the same organization. */\nvar GatewayChannelConflictError = class extends Error {\n\tplatform;\n\tchannelId;\n\townerProjectId;\n\tconstructor(platform, channelId, ownerProjectId) {\n\t\tsuper(`Channel ${channelId} is already bound to another project in this organization`);\n\t\tthis.platform = platform;\n\t\tthis.channelId = channelId;\n\t\tthis.ownerProjectId = ownerProjectId;\n\t\tthis.name = \"GatewayChannelConflictError\";\n\t}\n};\n/** Project-unscoped active binding for a channel — used to enforce org-unique channel ownership. */\nasync function getActiveOrgGatewayAttachmentByChannel(platform, channelId) {\n\treturn (await getDb().select().from(gatewayAttachments).where(and$1(eq$1(gatewayAttachments.platform, platform), eq$1(gatewayAttachments.channelId, channelId), isNull(gatewayAttachments.deletedAt))).limit(1))[0];\n}\n/** Project-unscoped binding for a Slack workspace channel. */\nasync function getActiveOrgGatewayAttachmentByTeamAndChannel(platform, teamId, channelId) {\n\treturn (await getDb().select().from(gatewayAttachments).where(and$1(eq$1(gatewayAttachments.platform, platform), eq$1(gatewayAttachments.teamId, teamId), eq$1(gatewayAttachments.channelId, channelId), isNull(gatewayAttachments.deletedAt))).limit(1))[0];\n}\nasync function getActiveGatewayAttachmentByChannel(platform, channelId) {\n\treturn (await getDb().select().from(gatewayAttachments).where(scopedAnd(gatewayAttachments, eq$1(gatewayAttachments.platform, platform), eq$1(gatewayAttachments.channelId, channelId), isNull(gatewayAttachments.deletedAt))).limit(1))[0];\n}\nasync function listActiveGatewayAttachments() {\n\treturn getDb().select().from(gatewayAttachments).where(scopedAnd(gatewayAttachments, isNull(gatewayAttachments.deletedAt)));\n}\n/**\n* Project-unscoped: every active attachment for a platform across all projects in the current org\n* schema, joined to its agent's registry id. Used by the platform ingress, which routes by channel\n* before a project scope is known. A single query avoids per-attachment agent lookups.\n*/\nasync function listActiveOrgGatewayBindingsByPlatform(platform) {\n\treturn getDb().select({\n\t\tattachmentId: gatewayAttachments.id,\n\t\tslug: gatewayAttachments.slug,\n\t\tagentSlug: gatewayAttachments.agentSlug,\n\t\tagentId: agents.id,\n\t\tchannelId: gatewayAttachments.channelId,\n\t\tteamId: gatewayAttachments.teamId,\n\t\tsource: gatewayAttachments.source,\n\t\tprojectId: gatewayAttachments.projectId\n\t}).from(gatewayAttachments).innerJoin(agents, and$1(eq$1(agents.projectId, gatewayAttachments.projectId), eq$1(agents.slug, gatewayAttachments.agentSlug), isNull(agents.deletedAt))).where(and$1(eq$1(gatewayAttachments.platform, platform), isNull(gatewayAttachments.deletedAt)));\n}\nasync function listActiveGatewayAttachmentsByAgentSlug(agentSlug) {\n\treturn getDb().select().from(gatewayAttachments).where(scopedAnd(gatewayAttachments, eq$1(gatewayAttachments.agentSlug, agentSlug), isNull(gatewayAttachments.deletedAt)));\n}\nasync function softDeleteGatewayAttachmentsForAgentPlatformTeam(agentSlug, platform, teamId, now) {\n\tconst db = getDb();\n\tconst targets = (await listActiveGatewayAttachmentsByAgentSlug(agentSlug)).filter((row) => row.platform === platform && (teamId === null ? row.teamId == null : row.teamId === teamId));\n\tif (targets.length === 0) return 0;\n\tfor (const row of targets) await db.update(gatewayAttachments).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(gatewayAttachments, eq$1(gatewayAttachments.id, row.id)));\n\treturn targets.length;\n}\nasync function listActiveGatewayAttachmentsByPlatform(platform) {\n\treturn getDb().select().from(gatewayAttachments).where(scopedAnd(gatewayAttachments, eq$1(gatewayAttachments.platform, platform), isNull(gatewayAttachments.deletedAt)));\n}\nasync function insertGatewayAttachment(values) {\n\tawait getDb().insert(gatewayAttachments).values({\n\t\t...values,\n\t\tprojectId: projectScopeId()\n\t});\n}\nasync function updateGatewayAttachmentById(id, values) {\n\tawait getDb().update(gatewayAttachments).set(values).where(scopedAnd(gatewayAttachments, eq$1(gatewayAttachments.id, id)));\n}\nasync function softDeleteGatewayAttachmentByChannel(platform, channelId, now) {\n\tconst existing = await getActiveGatewayAttachmentByChannel(platform, channelId);\n\tif (!existing) return false;\n\tawait getDb().update(gatewayAttachments).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(gatewayAttachments, eq$1(gatewayAttachments.id, existing.id)));\n\treturn true;\n}\nasync function upsertGatewayAttachmentByChannel(options) {\n\tconst now = /* @__PURE__ */ new Date();\n\tconst slug = gatewayAttachmentKeyForChannel(options.platform, options.channelId);\n\tconst existing = await getActiveGatewayAttachmentByChannel(options.platform, options.channelId);\n\tif (existing) {\n\t\tawait updateGatewayAttachmentById(existing.id, {\n\t\t\tagentSlug: options.agentSlug,\n\t\t\tmoduleFile: \"\",\n\t\t\tplatform: options.platform,\n\t\t\tteamId: options.teamId ?? existing.teamId,\n\t\t\tchannelId: options.channelId,\n\t\t\tsource: options.source,\n\t\t\tupdatedAt: now,\n\t\t\tdeletedAt: null\n\t\t});\n\t\tconst updated = await selectGatewayAttachmentById(existing.id);\n\t\tif (!updated) throw new Error(\"Failed to load gateway attachment after update\");\n\t\treturn updated;\n\t}\n\tconst orgOwned = await getActiveOrgGatewayAttachmentByChannel(options.platform, options.channelId);\n\tif (orgOwned && orgOwned.projectId !== projectScopeId()) throw new GatewayChannelConflictError(options.platform, options.channelId, orgOwned.projectId);\n\tconst softDeleted = await selectGatewayAttachmentBySlug(slug);\n\tif (softDeleted && softDeleted.deletedAt) {\n\t\tawait updateGatewayAttachmentById(softDeleted.id, {\n\t\t\tagentSlug: options.agentSlug,\n\t\t\tmoduleFile: \"\",\n\t\t\tplatform: options.platform,\n\t\t\tteamId: options.teamId ?? softDeleted.teamId,\n\t\t\tchannelId: options.channelId,\n\t\t\tsource: options.source,\n\t\t\tupdatedAt: now,\n\t\t\tdeletedAt: null\n\t\t});\n\t\tconst revived = await selectGatewayAttachmentById(softDeleted.id);\n\t\tif (!revived) throw new Error(\"Failed to load gateway attachment after revive\");\n\t\treturn revived;\n\t}\n\tconst id = crypto.randomUUID();\n\tawait insertGatewayAttachment({\n\t\tid,\n\t\tslug,\n\t\tagentSlug: options.agentSlug,\n\t\tmoduleFile: \"\",\n\t\tplatform: options.platform,\n\t\tteamId: options.teamId ?? null,\n\t\tchannelId: options.channelId,\n\t\tsource: options.source,\n\t\tregisteredAt: now,\n\t\tupdatedAt: now,\n\t\tdeletedAt: null\n\t});\n\tconst inserted = await selectGatewayAttachmentById(id);\n\tif (!inserted) throw new Error(\"Failed to load gateway attachment after insert\");\n\treturn inserted;\n}\nasync function getGatewayAttachmentBySlug(slug) {\n\treturn selectGatewayAttachmentBySlug(slug);\n}\n//#endregion\n//#region src/queries/gateway-thread-sessions/index.ts\nasync function selectGatewayThreadSessionByThreadId(threadId) {\n\treturn (await getDb().select({ session: gatewayThreadSessions }).from(gatewayThreadSessions).innerJoin(gatewayAttachments, eq$1(gatewayAttachments.id, gatewayThreadSessions.attachmentId)).where(scopedAnd(gatewayAttachments, eq$1(gatewayThreadSessions.threadId, threadId))).limit(1))[0]?.session;\n}\nasync function selectGatewayThreadSessionBySessionId(sessionId) {\n\treturn (await getDb().select({ session: gatewayThreadSessions }).from(gatewayThreadSessions).innerJoin(gatewayAttachments, eq$1(gatewayAttachments.id, gatewayThreadSessions.attachmentId)).where(scopedAnd(gatewayAttachments, eq$1(gatewayThreadSessions.sessionId, sessionId))).limit(1))[0]?.session;\n}\nasync function upsertGatewayThreadSession(values) {\n\tawait getDb().insert(gatewayThreadSessions).values(values).onConflictDoUpdate({\n\t\ttarget: gatewayThreadSessions.threadId,\n\t\tset: {\n\t\t\tagentId: values.agentId,\n\t\t\tsessionId: values.sessionId,\n\t\t\tattachmentId: values.attachmentId,\n\t\t\tupdatedAt: values.updatedAt\n\t\t}\n\t});\n}\n//#endregion\n//#region src/queries/workflows/list-active.ts\n/**\n* List every active workflow in the bound org schema (all projects). Not project\n* scoped — the org database schema is itself the tenant boundary.\n*/\nasync function listActiveWorkflows(options) {\n\tconst db = getDb();\n\tif (options?.projectIds !== void 0 && options.projectIds.length === 0) return [];\n\tconst conditions = [isNull(workflows.deletedAt)];\n\tif (options?.projectIds !== void 0) conditions.push(inArray$1(workflows.projectId, options.projectIds));\n\treturn db.select().from(workflows).where(and$1(...conditions)).orderBy(desc(workflows.updatedAt));\n}\n//#endregion\n//#region src/queries/workflows/select.ts\nasync function selectWorkflowBySlug(slug) {\n\treturn (await getDb().select().from(workflows).where(scopedAnd(workflows, eq$1(workflows.slug, slug))).limit(1))[0];\n}\nasync function selectActiveWorkflowBySlug(slug) {\n\treturn (await getDb().select().from(workflows).where(scopedAnd(workflows, eq$1(workflows.slug, slug), isNull(workflows.deletedAt))).limit(1))[0];\n}\n/** Fetch active workflows by id from the bound org schema (all projects). */\nasync function selectActiveWorkflowsByIds(ids) {\n\tif (ids.length === 0) return [];\n\treturn getDb().select().from(workflows).where(and$1(inArray$1(workflows.id, ids), isNull(workflows.deletedAt)));\n}\n/** Fetch a single active workflow by id from the bound org schema (all projects). */\nasync function selectActiveWorkflowById(id) {\n\treturn (await getDb().select().from(workflows).where(and$1(eq$1(workflows.id, id), isNull(workflows.deletedAt))).limit(1))[0];\n}\n//#endregion\n//#region src/queries/workflows/write.ts\nasync function insertWorkflow(values) {\n\tawait getDb().insert(workflows).values({\n\t\t...values,\n\t\tprojectId: projectScopeId(),\n\t\tsubscribable: values.subscribable ? 1 : 0\n\t});\n}\nasync function updateWorkflowById(id, values) {\n\tawait getDb().update(workflows).set({\n\t\tname: values.name,\n\t\tdescription: values.description,\n\t\tmoduleFile: values.moduleFile,\n\t\tsubscribable: values.subscribable ? 1 : 0,\n\t\tupdatedAt: values.updatedAt,\n\t\tdeletedAt: values.deletedAt\n\t}).where(scopedAnd(workflows, eq$1(workflows.id, id)));\n}\nasync function softDeleteAllWorkflows(now) {\n\tawait getDb().update(workflows).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(workflows, isNull(workflows.deletedAt)));\n}\nasync function softDeleteWorkflowsNotInSlugs(slugs, now) {\n\tawait getDb().update(workflows).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(workflows, isNull(workflows.deletedAt), notInArray(workflows.slug, slugs)));\n}\n//#endregion\n//#region src/queries/skills/list-active.ts\n/**\n* List every active skill in the bound org schema (all projects). Not project\n* scoped — the org database schema is itself the tenant boundary.\n*/\nasync function listActiveSkills(options) {\n\tconst db = getDb();\n\tif (options?.projectIds !== void 0 && options.projectIds.length === 0) return [];\n\tconst conditions = [isNull(skills.deletedAt)];\n\tif (options?.projectIds !== void 0) conditions.push(inArray$1(skills.projectId, options.projectIds));\n\treturn db.select().from(skills).where(and$1(...conditions)).orderBy(desc(skills.updatedAt));\n}\n//#endregion\n//#region src/queries/skills/select.ts\nasync function selectSkillBySlug(slug) {\n\treturn (await getDb().select().from(skills).where(scopedAnd(skills, eq$1(skills.slug, slug))).limit(1))[0];\n}\n/** Fetch active skills by id from the bound org schema (all projects). */\nasync function selectActiveSkillsByIds(ids) {\n\tif (ids.length === 0) return [];\n\treturn getDb().select().from(skills).where(and$1(inArray$1(skills.id, ids), isNull(skills.deletedAt)));\n}\n/** Fetch a single active skill by id from the bound org schema (all projects). */\nasync function selectActiveSkillById(id) {\n\treturn (await getDb().select().from(skills).where(and$1(eq$1(skills.id, id), isNull(skills.deletedAt))).limit(1))[0];\n}\n//#endregion\n//#region src/queries/skills/write.ts\nasync function insertSkill(values) {\n\tawait getDb().insert(skills).values({\n\t\t...values,\n\t\tprojectId: projectScopeId()\n\t});\n}\nasync function updateSkillById(id, values) {\n\tawait getDb().update(skills).set({\n\t\tname: values.name,\n\t\tdescription: values.description,\n\t\tmoduleFile: values.moduleFile,\n\t\tupdatedAt: values.updatedAt,\n\t\tdeletedAt: values.deletedAt\n\t}).where(scopedAnd(skills, eq$1(skills.id, id)));\n}\nasync function softDeleteAllSkills(now) {\n\tawait getDb().update(skills).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(skills, isNull(skills.deletedAt)));\n}\nasync function softDeleteSkillsNotInSlugs(slugs, now) {\n\tawait getDb().update(skills).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(skills, isNull(skills.deletedAt), notInArray(skills.slug, slugs)));\n}\n//#endregion\n//#region src/queries/workflow-subscriptions/index.ts\nasync function selectWorkflowSubscriptionById(id) {\n\treturn (await getDb().select().from(workflowSubscriptions).where(scopedAnd(workflowSubscriptions, eq$1(workflowSubscriptions.id, id))).limit(1))[0];\n}\nasync function selectWorkflowSubscriptionByWorkflowAndUser(workflowSlug, userId) {\n\treturn (await getDb().select().from(workflowSubscriptions).where(scopedAnd(workflowSubscriptions, eq$1(workflowSubscriptions.workflowSlug, workflowSlug), eq$1(workflowSubscriptions.userId, userId))).limit(1))[0];\n}\nasync function listWorkflowSubscriptionsByWorkflowSlug(workflowSlug) {\n\treturn getDb().select().from(workflowSubscriptions).where(scopedAnd(workflowSubscriptions, eq$1(workflowSubscriptions.workflowSlug, workflowSlug)));\n}\nasync function listEnabledWorkflowSubscriptionsByWorkflowSlug(workflowSlug) {\n\treturn getDb().select().from(workflowSubscriptions).where(scopedAnd(workflowSubscriptions, eq$1(workflowSubscriptions.workflowSlug, workflowSlug), eq$1(workflowSubscriptions.enabled, 1)));\n}\nasync function insertWorkflowSubscription(values) {\n\tawait getDb().insert(workflowSubscriptions).values({\n\t\t...values,\n\t\tprojectId: projectScopeId(),\n\t\tenabled: values.enabled ? 1 : 0\n\t});\n}\nasync function updateWorkflowSubscriptionById(id, values) {\n\tawait getDb().update(workflowSubscriptions).set({\n\t\tenabled: values.enabled ? 1 : 0,\n\t\tupdatedAt: values.updatedAt\n\t}).where(scopedAnd(workflowSubscriptions, eq$1(workflowSubscriptions.id, id)));\n}\nasync function deleteWorkflowSubscriptionById(id) {\n\tif (!await selectWorkflowSubscriptionById(id)) return false;\n\tawait getDb().delete(workflowSubscriptions).where(scopedAnd(workflowSubscriptions, eq$1(workflowSubscriptions.id, id)));\n\treturn true;\n}\n//#endregion\n//#region src/queries/resource-activity/index.ts\nasync function selectResourceActivityByUserAndResource(input) {\n\treturn (await getDb().select().from(resourceActivity).where(and$1(eq$1(resourceActivity.projectId, input.projectId), eq$1(resourceActivity.userId, input.userId), eq$1(resourceActivity.resourceKind, input.resourceKind), eq$1(resourceActivity.resourceId, input.resourceId))).limit(1))[0];\n}\nasync function touchResourceActivity(input) {\n\tconst now = /* @__PURE__ */ new Date();\n\tconst existing = await selectResourceActivityByUserAndResource(input);\n\tconst db = getDb();\n\tif (existing) {\n\t\tawait db.update(resourceActivity).set({ lastOpenedAt: now }).where(eq$1(resourceActivity.id, existing.id));\n\t\treturn;\n\t}\n\tawait db.insert(resourceActivity).values({\n\t\tid: crypto.randomUUID(),\n\t\tprojectId: input.projectId,\n\t\tuserId: input.userId,\n\t\tresourceKind: input.resourceKind,\n\t\tresourceId: input.resourceId,\n\t\tlastOpenedAt: now\n\t});\n}\nasync function listRecentResourceActivity(userId, limit) {\n\treturn getDb().select().from(resourceActivity).where(eq$1(resourceActivity.userId, userId)).orderBy(desc(resourceActivity.lastOpenedAt)).limit(limit);\n}\n//#endregion\n//#region src/queries/resource-last-run/index.ts\n/**\n* Last run per workflow id from the bound org schema.\n*\n* Runs are keyed by (projectId, workflowSlug), so join onto the workflows\n* registry to resolve ids. Account pages span all projects in the org, so this\n* intentionally does not use the ALS project scope — the join already matches\n* each run to its own project's workflow row.\n*/\nasync function selectWorkflowLastRunAtByIds(workflowIds) {\n\tif (workflowIds.length === 0) return /* @__PURE__ */ new Map();\n\tconst rows = await getDb().select({\n\t\tworkflowId: workflows.id,\n\t\tlastRunAt: max(workflowRuns.triggeredAt)\n\t}).from(workflowRuns).innerJoin(workflows, and(eq(workflows.projectId, workflowRuns.projectId), eq(workflows.slug, workflowRuns.workflowSlug))).where(inArray(workflows.id, workflowIds)).groupBy(workflows.id);\n\tconst result = /* @__PURE__ */ new Map();\n\tfor (const row of rows) if (row.lastRunAt) result.set(row.workflowId, row.lastRunAt);\n\treturn result;\n}\n/**\n* Last session activity per agent id from the bound org schema.\n*\n* Agent ids are unique within the org schema, so no project scope filter is\n* needed (and the ALS scope is not bound on account routes anyway).\n*/\nasync function selectAgentLastRunAtByIds(agentIds) {\n\tif (agentIds.length === 0) return /* @__PURE__ */ new Map();\n\tconst rows = await getDb().select({\n\t\tagentId: agentSessions.agentId,\n\t\tlastRunAt: max(agentSessions.updatedAt)\n\t}).from(agentSessions).where(inArray(agentSessions.agentId, agentIds)).groupBy(agentSessions.agentId);\n\tconst result = /* @__PURE__ */ new Map();\n\tfor (const row of rows) if (row.lastRunAt) result.set(row.agentId, row.lastRunAt);\n\treturn result;\n}\n//#endregion\n//#region src/queries/project-metrics/select-resource-counts.ts\n/**\n* Active resource counts grouped by project id across the bound org schema. Not\n* project scoped — the org database schema is itself the tenant boundary.\n*/\nasync function selectProjectResourceCounts(options) {\n\tif (options?.projectIds !== void 0 && options.projectIds.length === 0) return {};\n\tconst db = getDb();\n\tconst projectIds = options?.projectIds;\n\tconst agentConditions = [isNull(agents.deletedAt)];\n\tconst workflowConditions = [isNull(workflows.deletedAt)];\n\tconst skillConditions = [isNull(skills.deletedAt)];\n\tconst credentialConditions = [eq$1(credentialInstances.scopeType, \"project\")];\n\tif (projectIds !== void 0) {\n\t\tagentConditions.push(inArray$1(agents.projectId, projectIds));\n\t\tworkflowConditions.push(inArray$1(workflows.projectId, projectIds));\n\t\tskillConditions.push(inArray$1(skills.projectId, projectIds));\n\t\tcredentialConditions.push(inArray$1(credentialInstances.projectId, projectIds));\n\t}\n\tconst [agentRows, workflowRows, skillRows, credentialRows] = await Promise.all([\n\t\tdb.select({\n\t\t\tprojectId: agents.projectId,\n\t\t\tcount: count()\n\t\t}).from(agents).where(and$1(...agentConditions)).groupBy(agents.projectId),\n\t\tdb.select({\n\t\t\tprojectId: workflows.projectId,\n\t\t\tcount: count()\n\t\t}).from(workflows).where(and$1(...workflowConditions)).groupBy(workflows.projectId),\n\t\tdb.select({\n\t\t\tprojectId: skills.projectId,\n\t\t\tcount: count()\n\t\t}).from(skills).where(and$1(...skillConditions)).groupBy(skills.projectId),\n\t\tdb.select({\n\t\t\tprojectId: credentialInstances.projectId,\n\t\t\tcount: count()\n\t\t}).from(credentialInstances).where(and$1(...credentialConditions)).groupBy(credentialInstances.projectId)\n\t]);\n\tconst metrics = {};\n\tconst ensure = (projectId) => {\n\t\tlet entry = metrics[projectId];\n\t\tif (!entry) {\n\t\t\tentry = {\n\t\t\t\tagentCount: 0,\n\t\t\t\tworkflowCount: 0,\n\t\t\t\tskillCount: 0,\n\t\t\t\tcredentialCount: 0\n\t\t\t};\n\t\t\tmetrics[projectId] = entry;\n\t\t}\n\t\treturn entry;\n\t};\n\tfor (const row of agentRows) ensure(row.projectId).agentCount = Number(row.count);\n\tfor (const row of workflowRows) ensure(row.projectId).workflowCount = Number(row.count);\n\tfor (const row of skillRows) ensure(row.projectId).skillCount = Number(row.count);\n\tfor (const row of credentialRows) ensure(row.projectId).credentialCount = Number(row.count);\n\treturn metrics;\n}\n//#endregion\n//#region src/agents/serialize.ts\nfunction agentSessionStatusFromSpan(span, messageCount, canceledAt) {\n\tif (canceledAt) return \"canceled\";\n\tif (span) {\n\t\tif (span.status === \"running\") return \"running\";\n\t\tif (span.status === \"error\") return \"failed\";\n\t\treturn \"completed\";\n\t}\n\treturn messageCount > 0 ? \"completed\" : \"running\";\n}\nfunction agentSessionSummaryFromParts(options) {\n\treturn {\n\t\tid: options.row.id,\n\t\tstatus: options.status,\n\t\tsource: options.row.sourceKind,\n\t\tsourceId: options.row.sourceId ?? null,\n\t\ttitle: options.row.title ?? null,\n\t\tranByUserName: options.ranByUserName ?? null,\n\t\tgatewayPlatform: options.gatewayPlatform ?? null,\n\t\ttriggerType: options.triggerType ?? null,\n\t\tcreatedAt: options.row.createdAt.toISOString(),\n\t\tupdatedAt: options.row.updatedAt.toISOString(),\n\t\tmessageCount: options.messageCount\n\t};\n}\nfunction agentSessionRecordFromParts(options) {\n\treturn {\n\t\tid: options.row.id,\n\t\tagentSlug: options.agentSlug,\n\t\tstatus: options.status,\n\t\tsource: options.row.sourceKind,\n\t\tsourceId: options.row.sourceId ?? null,\n\t\tcreatedAt: options.row.createdAt.toISOString(),\n\t\tupdatedAt: options.row.updatedAt.toISOString(),\n\t\tparentSpanId: options.row.parentSpanId ?? null,\n\t\tmessageCount: options.messageCount,\n\t\terror: options.error,\n\t\ttotalDurationMs: options.row.totalDurationMs\n\t};\n}\nfunction gatewaySessionDetailFromParts(gateway, attachmentSlug) {\n\treturn {\n\t\tthreadId: gateway.threadId,\n\t\tattachmentId: gateway.attachmentId,\n\t\tattachmentSlug\n\t};\n}\nfunction agentEventFromRow(row) {\n\treturn {\n\t\tid: row.id,\n\t\tsessionId: row.sessionId,\n\t\tseq: row.seq,\n\t\teventType: row.eventType,\n\t\tpayload: row.payload,\n\t\tcreatedAt: row.createdAt.toISOString()\n\t};\n}\nfunction sessionErrorFromSpan(span) {\n\tif (!span || span.status !== \"error\") return null;\n\treturn span.error ?? null;\n}\n//#endregion\n//#region src/agents/types.ts\nconst MESSAGE_EVENT_TYPE = \"message\";\n//#endregion\n//#region src/tracing/sink.ts\nconst FLUSH_INTERVAL_MS = 50;\nconst FLUSH_BATCH_SIZE = 100;\nfunction createDatabaseTracingSink() {\n\tconst pending = [];\n\tconst seqByTrace = /* @__PURE__ */ new Map();\n\tlet flushTimer;\n\tasync function flushNow() {\n\t\tif (flushTimer) {\n\t\t\tclearTimeout(flushTimer);\n\t\t\tflushTimer = void 0;\n\t\t}\n\t\tif (pending.length === 0) return;\n\t\tawait insertTraceLogs(pending.splice(0, pending.length));\n\t}\n\tfunction scheduleFlush() {\n\t\tif (flushTimer) return;\n\t\tflushTimer = setTimeout(() => {\n\t\t\tflushTimer = void 0;\n\t\t\tflushNow().catch((error) => {\n\t\t\t\tconsole.error(\"[tracing] failed to flush logs:\", error);\n\t\t\t});\n\t\t}, FLUSH_INTERVAL_MS);\n\t}\n\tasync function nextSeq(traceId) {\n\t\tconst cached = seqByTrace.get(traceId);\n\t\tif (cached !== void 0) {\n\t\t\tconst next = cached + 1;\n\t\t\tseqByTrace.set(traceId, next);\n\t\t\treturn next;\n\t\t}\n\t\tconst next = await maxTraceLogSeq(traceId) + 1;\n\t\tseqByTrace.set(traceId, next);\n\t\treturn next;\n\t}\n\treturn {\n\t\tasync openSpan(span) {\n\t\t\tawait insertTraceSpan({\n\t\t\t\tid: span.id,\n\t\t\t\ttraceId: span.traceId,\n\t\t\t\tparentSpanId: span.parentSpanId ?? null,\n\t\t\t\tkind: span.kind,\n\t\t\t\trefId: span.refId,\n\t\t\t\tname: span.name,\n\t\t\t\tstatus: \"running\",\n\t\t\t\tstartedAt: span.startedAt,\n\t\t\t\tmetadata: span.metadata ?? null\n\t\t\t});\n\t\t},\n\t\tasync closeSpan(spanId, status, finishedAt, error) {\n\t\t\tawait updateTraceSpanStatus(spanId, status, finishedAt, error);\n\t\t\tawait flushNow();\n\t\t},\n\t\tasync appendLog(entry) {\n\t\t\tconst seq = await nextSeq(entry.traceId);\n\t\t\tpending.push({\n\t\t\t\tid: crypto.randomUUID(),\n\t\t\t\ttraceId: entry.traceId,\n\t\t\t\tspanId: entry.spanId,\n\t\t\t\tseq,\n\t\t\t\tlevel: entry.level,\n\t\t\t\tmessage: entry.message,\n\t\t\t\tdata: entry.data,\n\t\t\t\tsource: entry.source,\n\t\t\t\tcreatedAt: entry.createdAt\n\t\t\t});\n\t\t\tif (pending.length >= FLUSH_BATCH_SIZE) {\n\t\t\t\tawait flushNow();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tscheduleFlush();\n\t\t},\n\t\tflushNow\n\t};\n}\n//#endregion\n//#region src/tracing/index.ts\nfunction triggerFromSpans(spans) {\n\tconst triggerSpan = spans.find((span) => span.kind === \"trigger_run\");\n\tif (!triggerSpan?.metadata || typeof triggerSpan.metadata !== \"object\") return null;\n\tconst metadata = triggerSpan.metadata;\n\treturn {\n\t\ttriggerType: String(metadata.triggerType ?? \"unknown\"),\n\t\ttriggerRunId: triggerSpan.refId,\n\t\tworkflowSlug: typeof metadata.workflowSlug === \"string\" ? metadata.workflowSlug : void 0,\n\t\tagentSlug: typeof metadata.agentSlug === \"string\" ? metadata.agentSlug : void 0,\n\t\tattachmentId: typeof metadata.attachmentId === \"string\" ? metadata.attachmentId : null,\n\t\tattachmentSlug: typeof metadata.attachmentSlug === \"string\" ? metadata.attachmentSlug : null,\n\t\troute: typeof metadata.route === \"string\" ? metadata.route : void 0,\n\t\tsourcePath: typeof metadata.sourcePath === \"string\" ? metadata.sourcePath : null\n\t};\n}\nfunction gatewayFromSpans(spans) {\n\tconst gatewaySpan = spans.find((span) => span.kind === \"gateway_event\");\n\tif (!gatewaySpan?.metadata || typeof gatewaySpan.metadata !== \"object\") return null;\n\tconst metadata = gatewaySpan.metadata;\n\tif (typeof metadata.gatewayAttachmentId !== \"string\" || typeof metadata.gatewayAttachmentKey !== \"string\") return null;\n\treturn {\n\t\tgatewayAttachmentId: metadata.gatewayAttachmentId,\n\t\tgatewayAttachmentKey: metadata.gatewayAttachmentKey,\n\t\tthreadId: typeof metadata.threadId === \"string\" ? metadata.threadId : void 0,\n\t\tchannelId: typeof metadata.channelId === \"string\" ? metadata.channelId : void 0,\n\t\tmode: typeof metadata.mode === \"string\" ? metadata.mode : void 0\n\t};\n}\nasync function getTraceForWorkflowRun(workflowRunId) {\n\tconst run = await selectWorkflowRunById(workflowRunId);\n\tif (!run) return null;\n\tlet traceId = workflowRunId;\n\tif (run.triggerRunId) traceId = run.triggerRunId;\n\telse {\n\t\tconst workflowSpan = await selectTraceSpanByRefId(workflowRunId);\n\t\tif (workflowSpan) traceId = workflowSpan.traceId;\n\t}\n\tconst spans = await listTraceSpansByTraceId(traceId);\n\tconst logs = await listTraceLogsByTraceId(traceId);\n\treturn {\n\t\ttraceId,\n\t\ttrigger: triggerFromSpans(spans),\n\t\tgateway: gatewayFromSpans(spans),\n\t\tspans,\n\t\tlogs\n\t};\n}\nasync function getTraceForTriggerRun(triggerRunId) {\n\tconst spans = await listTraceSpansByTraceId(triggerRunId);\n\tif (spans.length === 0) return null;\n\tconst logs = await listTraceLogsByTraceId(triggerRunId);\n\treturn {\n\t\ttraceId: triggerRunId,\n\t\ttrigger: triggerFromSpans(spans),\n\t\tgateway: gatewayFromSpans(spans),\n\t\tspans,\n\t\tlogs\n\t};\n}\nasync function getTraceForAgentSession(sessionId) {\n\tconst traceId = (await selectTraceSpanByRefId(sessionId))?.traceId ?? sessionId;\n\tconst spans = await listTraceSpansByTraceId(traceId);\n\tconst logs = await listTraceLogsByTraceId(traceId);\n\tif (spans.length === 0 && logs.length === 0) return null;\n\treturn {\n\t\ttraceId,\n\t\ttrigger: triggerFromSpans(spans),\n\t\tgateway: gatewayFromSpans(spans),\n\t\tspans,\n\t\tlogs\n\t};\n}\n//#endregion\n//#region src/agents/session-api.ts\nasync function resolveGatewayPlatform(row) {\n\tif (row.sourceKind !== \"gateway\" || !row.sourceId) return null;\n\treturn (await selectGatewayAttachmentById(row.sourceId))?.platform ?? null;\n}\nasync function resolveTriggerType(row) {\n\tif (row.sourceKind !== \"trigger\" || !row.sourceId) return null;\n\treturn (await selectTriggerRunById(row.sourceId))?.triggerType ?? null;\n}\nasync function enrichSessionRow(row) {\n\tconst [span, gateway, messageCount] = await Promise.all([\n\t\tselectLatestAgentSessionSpanByRefId(row.id),\n\t\tselectGatewayThreadSessionBySessionId(row.id),\n\t\tcountMessageEventsForSession(row.id, MESSAGE_EVENT_TYPE)\n\t]);\n\treturn {\n\t\tspan,\n\t\tgateway,\n\t\tmessageCount,\n\t\tstatus: agentSessionStatusFromSpan(span, messageCount, row.canceledAt)\n\t};\n}\nasync function buildAgentSessionSummary(row, options) {\n\tconst enriched = await enrichSessionRow(row);\n\tconst [gatewayPlatform, triggerType, ranByUserName] = await Promise.all([\n\t\tresolveGatewayPlatform(row),\n\t\tresolveTriggerType(row),\n\t\trow.ranByUserId && options?.resolveUserName ? options.resolveUserName(row.ranByUserId) : Promise.resolve(null)\n\t]);\n\treturn agentSessionSummaryFromParts({\n\t\trow,\n\t\tstatus: enriched.status,\n\t\tmessageCount: enriched.messageCount,\n\t\tgatewayPlatform,\n\t\ttriggerType,\n\t\tranByUserName\n\t});\n}\nasync function listAgentSessionsPaginated(options) {\n\tconst items = [];\n\tlet cursor = options.cursor;\n\tlet nextCursor = null;\n\twhile (items.length < options.limit) {\n\t\tconst page = await listAgentSessionRowsPaginated({\n\t\t\tagentSlug: options.agentSlug,\n\t\t\tlimit: options.limit,\n\t\t\tcursor,\n\t\t\tsource: options.source\n\t\t});\n\t\tfor (const row of page.rows) {\n\t\t\tconst summary = await buildAgentSessionSummary(row, { resolveUserName: options.resolveUserName });\n\t\t\tif (options.status && summary.status !== options.status) continue;\n\t\t\titems.push(summary);\n\t\t\tif (items.length >= options.limit) {\n\t\t\t\tnextCursor = page.nextCursor;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (items.length >= options.limit || !page.nextCursor) {\n\t\t\tif (items.length < options.limit) nextCursor = null;\n\t\t\tbreak;\n\t\t}\n\t\tcursor = page.nextCursor;\n\t}\n\treturn {\n\t\titems,\n\t\tnextCursor\n\t};\n}\nasync function buildAgentSessionDetail(options) {\n\tconst row = await selectAgentSessionForAgent(options.agentSlug, options.sessionId);\n\tif (!row) return null;\n\tconst enriched = await enrichSessionRow(row);\n\tconst includeGateway = options.include.includes(\"gateway\");\n\tconst includeMessages = options.include.includes(\"messages\");\n\tconst includeEvents = options.include.includes(\"events\");\n\tconst includeTrace = options.include.includes(\"trace\");\n\tlet gateway = null;\n\tif (includeGateway && enriched.gateway) {\n\t\tconst attachment = await selectGatewayAttachmentById(enriched.gateway.attachmentId);\n\t\tgateway = gatewaySessionDetailFromParts(enriched.gateway, attachment?.slug ?? null);\n\t}\n\tconst messages = includeMessages ? await listMessagePayloads(row.id, MESSAGE_EVENT_TYPE) : [];\n\tconst events = includeEvents ? (await listAgentEventsForSession(row.id)).map(agentEventFromRow) : [];\n\tlet trace = null;\n\tif (includeTrace) {\n\t\tconst traceData = await getTraceForAgentSession(row.id);\n\t\ttrace = traceData ? traceResponseToJson(traceData) : null;\n\t}\n\treturn {\n\t\tsession: agentSessionRecordFromParts({\n\t\t\trow,\n\t\t\tagentSlug: options.agentSlug,\n\t\t\tstatus: enriched.status,\n\t\t\tmessageCount: enriched.messageCount,\n\t\t\terror: sessionErrorFromSpan(enriched.span)\n\t\t}),\n\t\tgateway,\n\t\tmessages,\n\t\tevents,\n\t\ttrace\n\t};\n}\nfunction messagePayloadWithSentAt(payload, createdAt, seq) {\n\treturn {\n\t\t...typeof payload === \"object\" && payload !== null && !Array.isArray(payload) ? payload : { content: payload },\n\t\tsentAt: createdAt.toISOString(),\n\t\tseq\n\t};\n}\n/**\n* Returns the persisted chat state for a session. `messages` is the full\n* transcript by default, or only events with `seq > sinceSeq` when a cursor is\n* supplied — the chat UI polls with its highest seen seq so each poll ships only\n* new turns plus the (separate, transient) `live` streaming message. Each\n* message carries its `seq` so the client can advance the cursor and key the row.\n*/\nasync function buildAgentSessionChatState(sessionId, options) {\n\tconst row = await selectActiveAgentSession(sessionId);\n\tif (!row) return null;\n\tconst enriched = await enrichSessionRow(row);\n\tconst [messageEvents, live] = await Promise.all([listMessageEventsForSession(row.id, MESSAGE_EVENT_TYPE, { sinceSeq: options?.sinceSeq }), selectSessionLiveMessage(row.id)]);\n\tconst messages = messageEvents.map(({ payload, createdAt, seq }) => messagePayloadWithSentAt(payload, createdAt, seq));\n\treturn {\n\t\tstatus: enriched.status,\n\t\tmessages,\n\t\tlive: live ?? null\n\t};\n}\n//#endregion\n//#region src/workflows/run-detail.ts\nasync function buildWorkflowRunDetail(options) {\n\tconst row = await selectWorkflowRunForWorkflow(options.workflowSlug, options.runId);\n\tif (!row) return null;\n\tconst includeTrigger = options.include.includes(\"trigger\");\n\tconst includeSteps = options.include.includes(\"steps\");\n\tconst includeTrace = options.include.includes(\"trace\");\n\tlet trigger = null;\n\tif (includeTrigger && row.triggerRunId) {\n\t\tconst triggerRun = await selectTriggerRunById(row.triggerRunId);\n\t\tif (triggerRun) {\n\t\t\tlet attachmentSlug = null;\n\t\t\tif (row.attachmentId) attachmentSlug = (await selectTriggerAttachmentById(row.attachmentId))?.slug ?? null;\n\t\t\ttrigger = triggerRunDetailFromRow(triggerRun, attachmentSlug);\n\t\t}\n\t}\n\tconst steps = includeSteps ? (await listStepCompletedEvents(row.id)).map(workflowStepRunFromEvent) : [];\n\tlet trace = null;\n\tif (includeTrace) {\n\t\tconst traceData = await getTraceForWorkflowRun(row.id);\n\t\ttrace = traceData ? traceResponseToJson(traceData) : null;\n\t}\n\treturn {\n\t\trun: workflowRunRecordFromRow(row),\n\t\ttrigger,\n\t\tsteps,\n\t\ttrace\n\t};\n}\n//#endregion\n//#region src/history/helpers.ts\nfunction titleCaseResourceName(slug, explicitName) {\n\tif (explicitName?.trim()) return explicitName.trim();\n\tconst normalized = slug.split(/[/_-]+/).filter(Boolean).join(\" \");\n\tif (!normalized) return slug;\n\treturn normalized.replace(/\\b\\w/g, (char) => char.toUpperCase());\n}\nfunction triggerLabelFromRaw(raw) {\n\tif (raw === \"api\") return \"API\";\n\treturn raw.charAt(0).toUpperCase() + raw.slice(1);\n}\nfunction timeInQueueMsBetween(triggeredAt, startedAt) {\n\tif (!startedAt) return null;\n\treturn Math.max(0, startedAt.getTime() - triggeredAt.getTime());\n}\nfunction buildHistoryUsage(records, durationMs) {\n\tconst grouped = /* @__PURE__ */ new Map();\n\tfor (const record of records) {\n\t\tconst key = `${record.kind}:${record.label}`;\n\t\tconst existing = grouped.get(key);\n\t\tif (existing) existing.amountUsd += record.amountUsd;\n\t\telse grouped.set(key, {\n\t\t\tlabel: record.label,\n\t\t\tamountUsd: record.amountUsd\n\t\t});\n\t}\n\tconst lineItems = [...grouped.entries()].map(([id, item]) => ({\n\t\tid,\n\t\tlabel: item.label,\n\t\tamountUsd: item.amountUsd\n\t}));\n\treturn {\n\t\trunDurationMs: durationMs,\n\t\tlineItems,\n\t\ttotalExcludingDurationUsd: lineItems.reduce((sum, item) => sum + item.amountUsd, 0)\n\t};\n}\n//#endregion\n//#region src/history/trace-messages.ts\nfunction metadataRecord(metadata) {\n\tif (metadata && typeof metadata === \"object\" && !Array.isArray(metadata)) return metadata;\n\treturn {};\n}\nfunction attachMessagesToAgentSessionSpans(spans, messages) {\n\tconst sessionSpans = spans.filter((span) => span.kind === \"agent_session\").sort((left, right) => Date.parse(left.startedAt) - Date.parse(right.startedAt));\n\tif (sessionSpans.length === 0) return spans;\n\tconst sortedMessages = [...messages].sort((left, right) => left.createdAt.getTime() - right.createdAt.getTime());\n\tconst messagesBySpanId = /* @__PURE__ */ new Map();\n\tfor (let index = 0; index < sessionSpans.length; index += 1) {\n\t\tconst span = sessionSpans[index];\n\t\tconst windowStartMs = Date.parse(span.startedAt);\n\t\tconst windowEndMs = index + 1 < sessionSpans.length ? Date.parse(sessionSpans[index + 1].startedAt) : Number.POSITIVE_INFINITY;\n\t\tconst slice = sortedMessages.filter((message) => {\n\t\t\tconst createdAtMs = message.createdAt.getTime();\n\t\t\treturn createdAtMs >= windowStartMs && createdAtMs < windowEndMs;\n\t\t}).map((message) => message.payload);\n\t\tmessagesBySpanId.set(span.id, slice);\n\t}\n\treturn spans.map((span) => {\n\t\tif (span.kind !== \"agent_session\") return span;\n\t\tconst { messages: _stale, ...rest } = metadataRecord(span.metadata);\n\t\treturn {\n\t\t\t...span,\n\t\t\tmetadata: {\n\t\t\t\t...rest,\n\t\t\t\tmessages: messagesBySpanId.get(span.id) ?? []\n\t\t\t}\n\t\t};\n\t});\n}\n//#endregion\n//#region src/history/serialize.ts\nfunction workflowTriggerRaw(run) {\n\tif (run.sourceKind === \"gateway\") return \"gateway\";\n\treturn run.trigger;\n}\nfunction agentTriggerRaw(session) {\n\treturn session.sourceKind;\n}\nfunction workflowTriggerRawFromParts(run, override) {\n\treturn override ?? workflowTriggerRaw(run);\n}\nfunction agentTriggerRawFromParts(session, override) {\n\treturn override ?? agentTriggerRaw(session);\n}\nfunction durationMsBetween(startedAt, finishedAt) {\n\tif (!startedAt || !finishedAt) return null;\n\treturn Math.max(0, finishedAt.getTime() - startedAt.getTime());\n}\nfunction historyRunFromWorkflow(parts) {\n\tconst { run, workflow, stepCount } = parts;\n\tconst resourceKey = run.workflowSlug;\n\tconst resourceId = workflow?.id ?? run.workflowSlug;\n\tconst resourceName = titleCaseResourceName(resourceKey, workflow?.name);\n\tconst status = run.status;\n\tconst startedAt = run.startedAt ?? run.triggeredAt;\n\tconst triggerRaw = workflowTriggerRawFromParts(run, parts.triggerRaw);\n\treturn {\n\t\tid: run.id,\n\t\tkind: \"workflow\",\n\t\ttraceId: run.triggerRunId ?? run.id,\n\t\tprojectId: run.projectId,\n\t\tresourceKey,\n\t\tresourceId,\n\t\tresourceName,\n\t\tstatus,\n\t\ttriggeredAt: run.triggeredAt.toISOString(),\n\t\ttimeInQueueMs: timeInQueueMsBetween(run.triggeredAt, run.startedAt),\n\t\tstartedAt: startedAt.toISOString(),\n\t\tfinishedAt: run.finishedAt?.toISOString() ?? null,\n\t\tdurationMs: durationMsBetween(startedAt, run.finishedAt),\n\t\ttriggerLabel: triggerLabelFromRaw(triggerRaw),\n\t\ttriggerRaw,\n\t\tranByUserId: run.ranByUserId ?? null,\n\t\tmodelsUsed: parts.modelsUsed ?? [],\n\t\totherServicesUsed: parts.otherServicesUsed ?? [],\n\t\ttotalCostUsd: parts.totalCostUsd ?? 0,\n\t\tstepCount\n\t};\n}\nfunction historyRunFromAgent(parts) {\n\tconst { session, agent, status, messageCount } = parts;\n\tconst resourceKey = agent.slug;\n\tconst triggerRaw = agentTriggerRawFromParts(session, parts.triggerRaw);\n\tconst startedAt = session.createdAt;\n\tconst finishedAt = status === \"running\" ? null : session.canceledAt ?? session.updatedAt;\n\treturn {\n\t\tid: session.id,\n\t\tkind: \"agent\",\n\t\ttraceId: session.id,\n\t\tprojectId: session.projectId,\n\t\tresourceKey,\n\t\tresourceId: agent.id,\n\t\tresourceName: titleCaseResourceName(resourceKey, agent.name),\n\t\tstatus,\n\t\ttriggeredAt: session.createdAt.toISOString(),\n\t\ttimeInQueueMs: null,\n\t\tstartedAt: startedAt.toISOString(),\n\t\tfinishedAt: finishedAt?.toISOString() ?? null,\n\t\tdurationMs: parts.totalDurationMs ?? 0,\n\t\ttriggerLabel: triggerLabelFromRaw(triggerRaw),\n\t\ttriggerRaw,\n\t\tranByUserId: session.ranByUserId ?? null,\n\t\tmodelsUsed: parts.modelsUsed ?? [],\n\t\totherServicesUsed: parts.otherServicesUsed ?? [],\n\t\ttotalCostUsd: parts.totalCostUsd ?? 0,\n\t\tmessageCount\n\t};\n}\nfunction mapTrace(trace, messageEvents = []) {\n\treturn {\n\t\ttraceId: trace.traceId,\n\t\ttrigger: trace.trigger ? {\n\t\t\ttriggerType: trace.trigger.triggerType,\n\t\t\ttriggerRunId: trace.trigger.triggerRunId,\n\t\t\t...trace.trigger.workflowSlug ? { workflowKey: trace.trigger.workflowSlug } : {},\n\t\t\t...trace.trigger.agentSlug ? { agentKey: trace.trigger.agentSlug } : {},\n\t\t\tattachmentId: trace.trigger.attachmentId ?? null,\n\t\t\tattachmentSlug: trace.trigger.attachmentSlug ?? null,\n\t\t\troute: trace.trigger.route,\n\t\t\tsourcePath: trace.trigger.sourcePath ?? null\n\t\t} : null,\n\t\tgateway: trace.gateway,\n\t\tspans: attachMessagesToAgentSessionSpans(trace.spans, messageEvents),\n\t\tlogs: trace.logs\n\t};\n}\nasync function buildHistoryWorkflowRunDetail(workflowSlug, runId) {\n\tconst detail = await buildWorkflowRunDetail({\n\t\tworkflowSlug,\n\t\trunId,\n\t\tinclude: [\n\t\t\t\"trigger\",\n\t\t\t\"steps\",\n\t\t\t\"trace\"\n\t\t]\n\t});\n\tif (!detail) return null;\n\tconst durationMs = durationMsBetween(detail.run.startedAt ? new Date(detail.run.startedAt) : null, detail.run.finishedAt ? new Date(detail.run.finishedAt) : null);\n\tconst usageRecords = await listUsageRecordsForRun(runId, \"workflow\");\n\treturn {\n\t\tkind: \"workflow\",\n\t\trun: {\n\t\t\tid: detail.run.id,\n\t\t\tworkflowKey: detail.run.workflowSlug,\n\t\t\tstatus: detail.run.status,\n\t\t\ttrigger: detail.run.trigger,\n\t\t\ttriggeredAt: detail.run.triggeredAt,\n\t\t\tstartedAt: detail.run.startedAt,\n\t\t\tfinishedAt: detail.run.finishedAt,\n\t\t\tinput: detail.run.input,\n\t\t\toutput: detail.run.output,\n\t\t\terror: detail.run.error\n\t\t},\n\t\ttrigger: detail.trigger ? {\n\t\t\tid: detail.trigger.id,\n\t\t\tattachmentSlug: detail.trigger.attachmentSlug,\n\t\t\ttriggerType: detail.trigger.triggerType,\n\t\t\tsourcePath: detail.trigger.sourcePath,\n\t\t\tpayload: detail.trigger.payload,\n\t\t\ttriggeredAt: detail.trigger.triggeredAt\n\t\t} : null,\n\t\tsteps: detail.steps,\n\t\ttrace: detail.trace ? mapTrace(detail.trace) : null,\n\t\tusage: buildHistoryUsage(usageRecords.map((record) => ({\n\t\t\tkind: record.kind,\n\t\t\tlabel: record.label,\n\t\t\tamountUsd: record.amount\n\t\t})), durationMs)\n\t};\n}\nasync function buildHistoryAgentSessionDetail(agentSlug, sessionId) {\n\tconst [detail, messageEvents] = await Promise.all([buildAgentSessionDetail({\n\t\tagentSlug,\n\t\tsessionId,\n\t\tinclude: [\"gateway\", \"trace\"]\n\t}), listMessageEventsForSession(sessionId, MESSAGE_EVENT_TYPE)]);\n\tif (!detail) return null;\n\tconst usageRecords = await listUsageRecordsForRun(sessionId, \"agent\");\n\treturn {\n\t\tkind: \"agent\",\n\t\trunId: detail.session.id,\n\t\tsession: {\n\t\t\tid: detail.session.id,\n\t\t\tagentKey: detail.session.agentSlug,\n\t\t\tstatus: detail.session.status,\n\t\t\tsource: detail.session.source,\n\t\t\tsourceId: detail.session.sourceId,\n\t\t\tcreatedAt: detail.session.createdAt,\n\t\t\tupdatedAt: detail.session.updatedAt,\n\t\t\tmessageCount: detail.session.messageCount,\n\t\t\terror: detail.session.error\n\t\t},\n\t\tgateway: detail.gateway ? {\n\t\t\tthreadId: detail.gateway.threadId,\n\t\t\tattachmentSlug: detail.gateway.attachmentSlug\n\t\t} : null,\n\t\tmessages: messageEvents.map((event) => event.payload),\n\t\ttrace: detail.trace ? mapTrace(detail.trace, messageEvents) : null,\n\t\tusage: buildHistoryUsage(usageRecords.map((record) => ({\n\t\t\tkind: record.kind,\n\t\t\tlabel: record.label,\n\t\t\tamountUsd: record.amount\n\t\t})), detail.session.totalDurationMs ?? null)\n\t};\n}\n//#endregion\n//#region src/queries/history/internal.ts\nasync function countStepCompletedEventsByRunIds(runIds) {\n\tif (runIds.length === 0) return /* @__PURE__ */ new Map();\n\tconst rows = await getDb().select({\n\t\trunId: workflowEvents.runId,\n\t\tcount: sql$1`count(*)`\n\t}).from(workflowEvents).where(and$1(inArray$1(workflowEvents.runId, runIds), eq$1(workflowEvents.type, \"step_completed\"))).groupBy(workflowEvents.runId);\n\treturn new Map(rows.map((row) => [row.runId, Number(row.count ?? 0)]));\n}\nasync function countStepCompletedEvents(runId) {\n\treturn (await countStepCompletedEventsByRunIds([runId])).get(runId) ?? 0;\n}\nasync function countMessageEventsBySessionIds(sessionIds, messageEventType) {\n\tif (sessionIds.length === 0) return /* @__PURE__ */ new Map();\n\tconst rows = await getDb().select({\n\t\tsessionId: agentEvents.sessionId,\n\t\tcount: sql$1`count(*)`\n\t}).from(agentEvents).innerJoin(agentSessions, eq$1(agentSessions.id, agentEvents.sessionId)).where(and$1(inArray$1(agentEvents.sessionId, sessionIds), eq$1(agentEvents.eventType, messageEventType), isNull(agentEvents.deletedAt))).groupBy(agentEvents.sessionId);\n\treturn new Map(rows.map((row) => [row.sessionId, Number(row.count ?? 0)]));\n}\nasync function selectTriggerTypesByIds(ids) {\n\tif (ids.length === 0) return /* @__PURE__ */ new Map();\n\tconst rows = await getDb().select({\n\t\tid: triggerRuns.id,\n\t\ttriggerType: triggerRuns.triggerType\n\t}).from(triggerRuns).where(inArray$1(triggerRuns.id, ids));\n\treturn new Map(rows.map((row) => [row.id, row.triggerType]));\n}\nfunction resolveWorkflowTriggerRaw(run, triggerTypes) {\n\tif (run.sourceKind === \"gateway\") return \"gateway\";\n\tif (run.sourceKind === \"trigger\" && run.triggerRunId) {\n\t\tconst triggerType = triggerTypes.get(run.triggerRunId);\n\t\tif (triggerType) return triggerType;\n\t}\n\treturn run.trigger;\n}\nfunction resolveAgentTriggerRaw(session, triggerTypes) {\n\tif (session.sourceKind === \"trigger\" && session.sourceId) {\n\t\tconst triggerType = triggerTypes.get(session.sourceId);\n\t\tif (triggerType) return triggerType;\n\t}\n\tif (session.sourceKind === \"gateway\") return \"gateway\";\n\treturn session.sourceKind;\n}\nfunction otherServicesUsedByRunId(records) {\n\tconst byRunId = /* @__PURE__ */ new Map();\n\tfor (const record of records) {\n\t\tif (record.kind === \"llm\") continue;\n\t\tconst kinds = byRunId.get(record.runId) ?? /* @__PURE__ */ new Set();\n\t\tkinds.add(record.kind);\n\t\tbyRunId.set(record.runId, kinds);\n\t}\n\treturn new Map([...byRunId.entries()].map(([runId, kinds]) => [runId, [...kinds]]));\n}\nfunction workflowUsageRollupsByRunId(records) {\n\tconst byRunId = /* @__PURE__ */ new Map();\n\tfor (const record of records) {\n\t\tconst entry = byRunId.get(record.runId) ?? {\n\t\t\ttotalCostUsd: 0,\n\t\t\tmodelsUsed: /* @__PURE__ */ new Set()\n\t\t};\n\t\tentry.totalCostUsd += record.amount;\n\t\tif (record.kind === \"llm\") entry.modelsUsed.add(record.label);\n\t\tbyRunId.set(record.runId, entry);\n\t}\n\treturn new Map([...byRunId.entries()].map(([runId, entry]) => [runId, {\n\t\ttotalCostUsd: entry.totalCostUsd,\n\t\tmodelsUsed: [...entry.modelsUsed]\n\t}]));\n}\nasync function selectLatestAgentSessionSpansByRefIds(sessionIds) {\n\tif (sessionIds.length === 0) return /* @__PURE__ */ new Map();\n\tconst rows = await getDb().select({\n\t\tspan: traceSpans,\n\t\trefId: traceSpans.refId\n\t}).from(traceSpans).innerJoin(agentSessions, eq$1(agentSessions.id, traceSpans.refId)).where(and$1(inArray$1(traceSpans.refId, sessionIds), eq$1(traceSpans.kind, \"agent_session\"), isNull(agentSessions.deletedAt))).orderBy(desc(traceSpans.startedAt));\n\tconst latestByRefId = /* @__PURE__ */ new Map();\n\tfor (const row of rows) if (!latestByRefId.has(row.refId)) latestByRefId.set(row.refId, row.span);\n\treturn latestByRefId;\n}\nfunction historyProjectConditions(column, filter) {\n\tif (filter?.projectIds !== void 0) {\n\t\tif (filter.projectIds.length === 0) return [];\n\t\treturn [inArray$1(column, filter.projectIds)];\n\t}\n\treturn [];\n}\nfunction resolveFetchLimit(limit, status) {\n\tif (!status) return limit;\n\treturn Math.min(limit * 5, 500);\n}\nfunction matchesStatusFilter(actual, filter) {\n\tif (filter === \"running\") return actual === \"running\" || actual === \"pending\";\n\treturn actual === filter;\n}\n//#endregion\n//#region src/queries/history/list-runs.ts\nasync function listWorkflowHistoryRuns(filter, fetchLimit) {\n\tconst conditions = historyProjectConditions(workflowRuns.projectId, filter);\n\tif (filter?.projectIds !== void 0 && filter.projectIds.length === 0) return [];\n\tconst db = getDb();\n\tconst rows = await (conditions.length > 0 ? db.select({\n\t\trun: workflowRuns,\n\t\tworkflow: workflows\n\t}).from(workflowRuns).leftJoin(workflows, and$1(eq$1(workflows.projectId, workflowRuns.projectId), eq$1(workflows.slug, workflowRuns.workflowSlug), isNull(workflows.deletedAt))).where(and$1(...conditions)) : db.select({\n\t\trun: workflowRuns,\n\t\tworkflow: workflows\n\t}).from(workflowRuns).leftJoin(workflows, and$1(eq$1(workflows.projectId, workflowRuns.projectId), eq$1(workflows.slug, workflowRuns.workflowSlug), isNull(workflows.deletedAt)))).orderBy(desc(workflowRuns.triggeredAt), desc(workflowRuns.id)).limit(fetchLimit);\n\tconst runIds = rows.map((row) => row.run.id);\n\tconst triggerRunIds = rows.map((row) => row.run.sourceKind === \"trigger\" ? row.run.triggerRunId : null).filter((id) => Boolean(id));\n\tconst [stepCounts, triggerTypes, usageRecords] = await Promise.all([\n\t\tcountStepCompletedEventsByRunIds(runIds),\n\t\tselectTriggerTypesByIds(triggerRunIds),\n\t\tlistUsageRecordsForRuns(runIds, \"workflow\")\n\t]);\n\tconst usageRollups = workflowUsageRollupsByRunId(usageRecords);\n\tconst otherServicesUsed = otherServicesUsedByRunId(usageRecords);\n\treturn rows.map((row) => {\n\t\tconst rollups = usageRollups.get(row.run.id);\n\t\treturn historyRunFromWorkflow({\n\t\t\trun: row.run,\n\t\t\tworkflow: row.workflow,\n\t\t\tstepCount: stepCounts.get(row.run.id) ?? 0,\n\t\t\ttriggerRaw: resolveWorkflowTriggerRaw(row.run, triggerTypes),\n\t\t\ttotalCostUsd: rollups?.totalCostUsd ?? 0,\n\t\t\tmodelsUsed: rollups?.modelsUsed ?? [],\n\t\t\totherServicesUsed: otherServicesUsed.get(row.run.id) ?? []\n\t\t});\n\t});\n}\nasync function listAgentHistoryRuns(filter, fetchLimit) {\n\tif (filter?.projectIds !== void 0 && filter.projectIds.length === 0) return [];\n\tconst db = getDb();\n\tconst conditions = [isNull(agentSessions.deletedAt), isNull(agents.deletedAt)];\n\tif (filter?.projectIds !== void 0) conditions.push(inArray$1(agentSessions.projectId, filter.projectIds));\n\tconst rows = await db.select({\n\t\tsession: agentSessions,\n\t\tagent: agents\n\t}).from(agentSessions).innerJoin(agents, eq$1(agents.id, agentSessions.agentId)).where(and$1(...conditions)).orderBy(desc(agentSessions.updatedAt), desc(agentSessions.id)).limit(fetchLimit);\n\tconst sessionIds = rows.map((row) => row.session.id);\n\tconst triggerRunIds = rows.map((row) => row.session.sourceKind === \"trigger\" ? row.session.sourceId : null).filter((id) => Boolean(id));\n\tconst [messageCounts, triggerTypes, spansBySessionId, usageRecords] = await Promise.all([\n\t\tcountMessageEventsBySessionIds(sessionIds, MESSAGE_EVENT_TYPE),\n\t\tselectTriggerTypesByIds(triggerRunIds),\n\t\tselectLatestAgentSessionSpansByRefIds(sessionIds),\n\t\tlistUsageRecordsForRuns(sessionIds, \"agent\")\n\t]);\n\tconst usageRollups = workflowUsageRollupsByRunId(usageRecords);\n\tconst otherServicesUsed = otherServicesUsedByRunId(usageRecords);\n\treturn rows.map((row) => {\n\t\tconst messageCount = messageCounts.get(row.session.id) ?? 0;\n\t\tconst span = spansBySessionId.get(row.session.id);\n\t\tconst rollups = usageRollups.get(row.session.id);\n\t\treturn historyRunFromAgent({\n\t\t\tsession: row.session,\n\t\t\tagent: row.agent,\n\t\t\tstatus: agentSessionStatusFromSpan(span, messageCount, row.session.canceledAt),\n\t\t\tmessageCount,\n\t\t\ttriggerRaw: resolveAgentTriggerRaw(row.session, triggerTypes),\n\t\t\ttotalDurationMs: row.session.totalDurationMs,\n\t\t\ttotalCostUsd: rollups?.totalCostUsd ?? 0,\n\t\t\tmodelsUsed: rollups?.modelsUsed ?? [],\n\t\t\totherServicesUsed: otherServicesUsed.get(row.session.id) ?? []\n\t\t});\n\t});\n}\nfunction sortHistoryRuns(items) {\n\treturn [...items].sort((a, b) => new Date(b.startedAt).getTime() - new Date(a.startedAt).getTime());\n}\nasync function listHistoryRuns(options = {}) {\n\tconst limit = options.limit ?? 100;\n\tconst fetchLimit = resolveFetchLimit(limit, options.status);\n\tconst includeWorkflows = options.kind !== \"agent\";\n\tconst includeAgents = options.kind !== \"workflow\";\n\tconst projectFilter = options.projectIds !== void 0 ? { projectIds: options.projectIds } : void 0;\n\tconst [workflowItems, agentItems] = await Promise.all([includeWorkflows ? listWorkflowHistoryRuns(projectFilter, fetchLimit) : Promise.resolve([]), includeAgents ? listAgentHistoryRuns(projectFilter, fetchLimit) : Promise.resolve([])]);\n\tlet items = sortHistoryRuns([...workflowItems, ...agentItems]);\n\tif (options.status) items = items.filter((item) => matchesStatusFilter(item.status, options.status));\n\treturn items.slice(0, limit);\n}\n//#endregion\n//#region src/queries/history/find-run-core.ts\nasync function findHistoryRunCore(runId) {\n\tconst db = getDb();\n\tconst workflowRow = (await db.select({\n\t\trun: workflowRuns,\n\t\tworkflow: workflows\n\t}).from(workflowRuns).leftJoin(workflows, and$1(eq$1(workflows.projectId, workflowRuns.projectId), eq$1(workflows.slug, workflowRuns.workflowSlug), isNull(workflows.deletedAt))).where(eq$1(workflowRuns.id, runId)).limit(1))[0];\n\tif (workflowRow) {\n\t\tconst [stepCount, triggerTypes, usageRecords] = await Promise.all([\n\t\t\tcountStepCompletedEvents(workflowRow.run.id),\n\t\t\tselectTriggerTypesByIds(workflowRow.run.sourceKind === \"trigger\" && workflowRow.run.triggerRunId ? [workflowRow.run.triggerRunId] : []),\n\t\t\tlistUsageRecordsForRuns([workflowRow.run.id], \"workflow\")\n\t\t]);\n\t\tconst rollups = workflowUsageRollupsByRunId(usageRecords).get(workflowRow.run.id);\n\t\tconst otherServicesUsed = otherServicesUsedByRunId(usageRecords).get(workflowRow.run.id) ?? [];\n\t\treturn historyRunFromWorkflow({\n\t\t\trun: workflowRow.run,\n\t\t\tworkflow: workflowRow.workflow,\n\t\t\tstepCount,\n\t\t\ttriggerRaw: resolveWorkflowTriggerRaw(workflowRow.run, triggerTypes),\n\t\t\ttotalCostUsd: rollups?.totalCostUsd ?? 0,\n\t\t\tmodelsUsed: rollups?.modelsUsed ?? [],\n\t\t\totherServicesUsed\n\t\t});\n\t}\n\tconst agentRow = (await db.select({\n\t\tsession: agentSessions,\n\t\tagent: agents\n\t}).from(agentSessions).innerJoin(agents, eq$1(agents.id, agentSessions.agentId)).where(and$1(eq$1(agentSessions.id, runId), isNull(agentSessions.deletedAt), isNull(agents.deletedAt))).limit(1))[0];\n\tif (!agentRow) return null;\n\tconst sessionId = agentRow.session.id;\n\tconst [messageCounts, triggerTypes, spansBySessionId, usageRecords] = await Promise.all([\n\t\tcountMessageEventsBySessionIds([sessionId], MESSAGE_EVENT_TYPE),\n\t\tselectTriggerTypesByIds(agentRow.session.sourceKind === \"trigger\" && agentRow.session.sourceId ? [agentRow.session.sourceId] : []),\n\t\tselectLatestAgentSessionSpansByRefIds([sessionId]),\n\t\tlistUsageRecordsForRuns([sessionId], \"agent\")\n\t]);\n\tconst messageCount = messageCounts.get(sessionId) ?? 0;\n\tconst span = spansBySessionId.get(sessionId);\n\tconst rollups = workflowUsageRollupsByRunId(usageRecords).get(sessionId);\n\tconst otherServicesUsed = otherServicesUsedByRunId(usageRecords).get(sessionId) ?? [];\n\treturn historyRunFromAgent({\n\t\tsession: agentRow.session,\n\t\tagent: agentRow.agent,\n\t\tstatus: agentSessionStatusFromSpan(span, messageCount, agentRow.session.canceledAt),\n\t\tmessageCount,\n\t\ttriggerRaw: resolveAgentTriggerRaw(agentRow.session, triggerTypes),\n\t\ttotalDurationMs: agentRow.session.totalDurationMs,\n\t\ttotalCostUsd: rollups?.totalCostUsd ?? 0,\n\t\tmodelsUsed: rollups?.modelsUsed ?? [],\n\t\totherServicesUsed\n\t});\n}\n//#endregion\n//#region src/queries/credential-instances/index.ts\n/** Org/user credentials live once in the shared org database; project scope stays per-project. */\nfunction credentialScopeAnd(scopeType, ...conditions) {\n\tif (scopeType === \"project\") return scopedAnd(credentialInstances, ...conditions);\n\treturn and$1(...conditions.filter(Boolean));\n}\nfunction resolveCredentialProjectId(scopeType) {\n\tif (scopeType === \"project\") return projectScopeId();\n\treturn getServerTenantScopeId();\n}\n/** Every credential instance row in the org database (org/user rows plus all projects' rows). */\nasync function listAllCredentialInstances() {\n\treturn getDb().select().from(credentialInstances);\n}\nasync function listCredentialInstancesByConnectionId(connectionId) {\n\treturn getDb().select().from(credentialInstances).where(eq$1(credentialInstances.connectionId, connectionId));\n}\nasync function selectCredentialInstanceById(id) {\n\treturn (await getDb().select().from(credentialInstances).where(eq$1(credentialInstances.id, id)).limit(1))[0];\n}\nasync function listCredentialInstancesByScope(options) {\n\tconst db = getDb();\n\tconst conditions = [options.scopeId === null ? and$1(eq$1(credentialInstances.scopeType, options.scopeType), isNull(credentialInstances.scopeId)) : and$1(eq$1(credentialInstances.scopeType, options.scopeType), eq$1(credentialInstances.scopeId, options.scopeId))];\n\tif (options.appSlug) conditions.push(eq$1(credentialInstances.appSlug, options.appSlug));\n\treturn db.select().from(credentialInstances).where(credentialScopeAnd(options.scopeType, ...conditions));\n}\nasync function selectCredentialInstancesForScope(appSlug, scopeType, scopeId) {\n\tconst db = getDb();\n\tconst scopeCondition = scopeId === null ? and$1(eq$1(credentialInstances.scopeType, scopeType), isNull(credentialInstances.scopeId)) : and$1(eq$1(credentialInstances.scopeType, scopeType), eq$1(credentialInstances.scopeId, scopeId));\n\treturn db.select().from(credentialInstances).where(credentialScopeAnd(scopeType, eq$1(credentialInstances.appSlug, appSlug), scopeCondition));\n}\nasync function insertCredentialInstance(values) {\n\tawait getDb().insert(credentialInstances).values({\n\t\t...values,\n\t\tprojectId: resolveCredentialProjectId(values.scopeType),\n\t\tisDefault: values.isDefault ? 1 : 0,\n\t\tgrantedScopes: values.grantedScopes ?? null\n\t});\n}\nasync function upsertCredentialInstance(values) {\n\tif (await selectCredentialInstanceById(values.id)) {\n\t\tawait getDb().update(credentialInstances).set({\n\t\t\tappSlug: values.appSlug,\n\t\t\tslug: values.slug,\n\t\t\tname: values.name ?? null,\n\t\t\tscopeType: values.scopeType,\n\t\t\tscopeId: values.scopeId,\n\t\t\tlabel: values.label,\n\t\t\tisDefault: values.isDefault ? 1 : 0,\n\t\t\tauthKind: values.authKind,\n\t\t\tciphertext: values.ciphertext,\n\t\t\tconnectionId: values.connectionId,\n\t\t\tsharedConnectionId: values.sharedConnectionId,\n\t\t\t...values.grantedScopes !== void 0 ? { grantedScopes: values.grantedScopes } : {},\n\t\t\tupdatedAt: values.updatedAt\n\t\t}).where(eq$1(credentialInstances.id, values.id));\n\t\treturn;\n\t}\n\tawait insertCredentialInstance(values);\n}\n/** Record that a credential was just resolved/used. Targeted by id; never throws on a missing row. */\nasync function touchCredentialInstanceLastUsed(id) {\n\tawait getDb().update(credentialInstances).set({ lastUsedAt: /* @__PURE__ */ new Date() }).where(eq$1(credentialInstances.id, id));\n}\nasync function deleteCredentialInstanceById(id) {\n\tif (!await selectCredentialInstanceById(id)) return false;\n\tawait getDb().delete(credentialInstances).where(eq$1(credentialInstances.id, id));\n\treturn true;\n}\nasync function clearCredentialInstanceDefaults(options) {\n\tconst db = getDb();\n\tconst scopeCondition = options.scopeId === null ? and$1(eq$1(credentialInstances.scopeType, options.scopeType), isNull(credentialInstances.scopeId)) : and$1(eq$1(credentialInstances.scopeType, options.scopeType), eq$1(credentialInstances.scopeId, options.scopeId));\n\tconst conditions = [\n\t\teq$1(credentialInstances.appSlug, options.appSlug),\n\t\tscopeCondition,\n\t\teq$1(credentialInstances.isDefault, 1)\n\t];\n\tif (options.exceptId) conditions.push(ne(credentialInstances.id, options.exceptId));\n\tawait db.update(credentialInstances).set({\n\t\tisDefault: 0,\n\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t}).where(credentialScopeAnd(options.scopeType, ...conditions));\n}\n//#endregion\n//#region src/queries/credential-assignments/index.ts\nasync function listCredentialAssignmentsByTarget(options) {\n\treturn getDb().select().from(credentialAssignments).where(scopedAnd(credentialAssignments, eq$1(credentialAssignments.targetType, options.targetType), eq$1(credentialAssignments.targetKey, options.targetKey)));\n}\nasync function selectCredentialAssignmentById(id) {\n\treturn (await getDb().select().from(credentialAssignments).where(scopedAnd(credentialAssignments, eq$1(credentialAssignments.id, id))).limit(1))[0];\n}\nasync function upsertCredentialAssignment(values) {\n\tconst db = getDb();\n\tconst id = values.id ?? crypto.randomUUID();\n\tconst now = values.updatedAt;\n\tconst projectId = projectScopeId();\n\treturn (await db.insert(credentialAssignments).values({\n\t\tid,\n\t\tprojectId,\n\t\ttargetType: values.targetType,\n\t\ttargetKey: values.targetKey,\n\t\tconsumerId: values.consumerId,\n\t\tcredentialSlug: values.credentialSlug,\n\t\tinstanceId: values.instanceId,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t}).onConflictDoUpdate({\n\t\ttarget: [\n\t\t\tcredentialAssignments.projectId,\n\t\t\tcredentialAssignments.targetType,\n\t\t\tcredentialAssignments.targetKey,\n\t\t\tcredentialAssignments.consumerId,\n\t\t\tcredentialAssignments.credentialSlug\n\t\t],\n\t\tset: {\n\t\t\tinstanceId: values.instanceId,\n\t\t\tupdatedAt: now\n\t\t}\n\t}).returning())[0];\n}\nasync function deleteCredentialAssignmentById(id) {\n\tif (!await selectCredentialAssignmentById(id)) return false;\n\tawait getDb().delete(credentialAssignments).where(eq$1(credentialAssignments.id, id));\n\treturn true;\n}\n/** Distinct step correlation ids from recent completed workflow runs. */\nasync function listRecentWorkflowStepConsumers(workflowSlug, runLimit = 5) {\n\tconst db = getDb();\n\tconst runIds = (await db.select({ id: workflowRuns.id }).from(workflowRuns).where(scopedAnd(workflowRuns, eq$1(workflowRuns.workflowSlug, workflowSlug))).orderBy(desc(workflowRuns.triggeredAt)).limit(runLimit)).map((row) => row.id);\n\tif (runIds.length === 0) return [];\n\tconst events = await db.select({ correlationId: workflowEvents.correlationId }).from(workflowEvents).where(scopedAnd(workflowEvents, inArray$1(workflowEvents.runId, runIds), eq$1(workflowEvents.type, \"step_completed\")));\n\tconst seen = /* @__PURE__ */ new Set();\n\tconst consumers = [];\n\tfor (const event of events) {\n\t\tconst id = event.correlationId;\n\t\tif (!id || seen.has(id)) continue;\n\t\tseen.add(id);\n\t\tconsumers.push(id);\n\t}\n\treturn consumers;\n}\nasync function listDistinctAssignmentConsumerIds(options) {\n\tconst rows = await listCredentialAssignmentsByTarget(options);\n\treturn [...new Set(rows.map((row) => row.consumerId))];\n}\n//#endregion\n//#region src/queries/trace-spans/index.ts\nfunction traceRootJoins$1(rootId) {\n\treturn {\n\t\tworkflowRuns: eq$1(workflowRuns.id, rootId),\n\t\ttriggerRuns: eq$1(triggerRuns.id, rootId),\n\t\tagentSessions: eq$1(agentSessions.id, rootId)\n\t};\n}\nasync function insertTraceSpan(values) {\n\tawait getDb().insert(traceSpans).values({\n\t\t...values,\n\t\tparentSpanId: values.parentSpanId ?? null,\n\t\tfinishedAt: values.finishedAt ?? null,\n\t\tmetadata: values.metadata ?? null,\n\t\terror: values.error ?? null\n\t});\n}\nasync function updateTraceSpanStatus(id, status, finishedAt, error) {\n\tif (!await selectTraceSpanById(id)) return;\n\tawait getDb().update(traceSpans).set({\n\t\tstatus,\n\t\tfinishedAt,\n\t\terror: error ?? null\n\t}).where(eq$1(traceSpans.id, id));\n}\nasync function selectTraceSpanById(id) {\n\tconst db = getDb();\n\tconst rows = await db.select({ span: traceSpans }).from(traceSpans).leftJoin(workflowRuns, eq$1(workflowRuns.id, traceSpans.traceId)).leftJoin(triggerRuns, eq$1(triggerRuns.id, traceSpans.traceId)).leftJoin(agentSessions, eq$1(agentSessions.id, traceSpans.traceId)).where(and$1(eq$1(traceSpans.id, id), traceRootProjectScopeFilter())).limit(1);\n\tif (rows[0]) return rows[0].span;\n\treturn (await db.select({ span: traceSpans }).from(traceSpans).leftJoin(workflowRuns, eq$1(workflowRuns.id, traceSpans.refId)).leftJoin(triggerRuns, eq$1(triggerRuns.id, traceSpans.refId)).leftJoin(agentSessions, eq$1(agentSessions.id, traceSpans.refId)).where(and$1(eq$1(traceSpans.id, id), traceRootProjectScopeFilter())).limit(1))[0]?.span;\n}\nasync function selectTraceSpanByRefId(refId) {\n\tconst db = getDb();\n\tconst joins = traceRootJoins$1(refId);\n\treturn (await db.select({ span: traceSpans }).from(traceSpans).leftJoin(workflowRuns, joins.workflowRuns).leftJoin(triggerRuns, joins.triggerRuns).leftJoin(agentSessions, joins.agentSessions).where(and$1(eq$1(traceSpans.refId, refId), traceRootProjectScopeFilter())).limit(1))[0]?.span;\n}\nasync function selectLatestAgentSessionSpanByRefId(refId) {\n\tconst db = getDb();\n\tconst joins = traceRootJoins$1(refId);\n\treturn (await db.select({ span: traceSpans }).from(traceSpans).leftJoin(workflowRuns, joins.workflowRuns).leftJoin(triggerRuns, joins.triggerRuns).leftJoin(agentSessions, joins.agentSessions).where(and$1(eq$1(traceSpans.refId, refId), eq$1(traceSpans.kind, \"agent_session\"), traceRootProjectScopeFilter())).orderBy(desc(traceSpans.startedAt)).limit(1))[0]?.span;\n}\nasync function listTraceSpansByTraceId(traceId) {\n\tconst db = getDb();\n\tconst joins = traceRootJoins$1(traceId);\n\treturn (await db.select({ span: traceSpans }).from(traceSpans).leftJoin(workflowRuns, joins.workflowRuns).leftJoin(triggerRuns, joins.triggerRuns).leftJoin(agentSessions, joins.agentSessions).where(and$1(eq$1(traceSpans.traceId, traceId), traceRootProjectScopeFilter())).orderBy(asc(traceSpans.startedAt))).map((row) => row.span);\n}\nasync function maxTraceLogSeq(traceId) {\n\tconst db = getDb();\n\tconst joins = traceRootJoins$1(traceId);\n\treturn (await db.select({ value: max$1(traceLogs.seq) }).from(traceLogs).leftJoin(workflowRuns, joins.workflowRuns).leftJoin(triggerRuns, joins.triggerRuns).leftJoin(agentSessions, joins.agentSessions).where(and$1(eq$1(traceLogs.traceId, traceId), traceRootProjectScopeFilter())))[0]?.value ?? 0;\n}\n//#endregion\n//#region src/queries/trace-logs/index.ts\nfunction traceRootJoins(rootId) {\n\treturn {\n\t\tworkflowRuns: eq$1(workflowRuns.id, rootId),\n\t\ttriggerRuns: eq$1(triggerRuns.id, rootId),\n\t\tagentSessions: eq$1(agentSessions.id, rootId)\n\t};\n}\nasync function insertTraceLogs(values) {\n\tif (values.length === 0) return;\n\tawait getDb().insert(traceLogs).values(values.map((entry) => ({\n\t\t...entry,\n\t\tdata: entry.data ?? null\n\t})));\n}\nasync function listTraceLogsByTraceId(traceId, options) {\n\tconst db = getDb();\n\tconst joins = traceRootJoins(traceId);\n\tconst conditions = [eq$1(traceLogs.traceId, traceId), traceRootProjectScopeFilter()];\n\tif (options?.spanId) conditions.push(eq$1(traceLogs.spanId, options.spanId));\n\tif (options?.afterSeq !== void 0) conditions.push(gt(traceLogs.seq, options.afterSeq));\n\tlet rows = await db.select({ log: traceLogs }).from(traceLogs).leftJoin(workflowRuns, joins.workflowRuns).leftJoin(triggerRuns, joins.triggerRuns).leftJoin(agentSessions, joins.agentSessions).where(and$1(...conditions)).orderBy(asc(traceLogs.seq));\n\trows = rows.map((row) => ({ log: row.log }));\n\tif (options?.limit !== void 0) rows = rows.slice(0, options.limit);\n\treturn rows.map((row) => row.log);\n}\n//#endregion\n//#region src/runs/source.ts\nfunction runSource(kind, id) {\n\treturn {\n\t\tkind,\n\t\tid: id ?? null\n\t};\n}\nfunction sourceFromSpan(span) {\n\tswitch (span.kind) {\n\t\tcase \"workflow_run\": return runSource(\"workflow\", span.refId);\n\t\tcase \"agent_session\": return runSource(\"agent\", span.refId);\n\t\tcase \"trigger_run\": return runSource(\"trigger\", span.refId);\n\t\tcase \"gateway_event\": {\n\t\t\tconst metadata = span.metadata;\n\t\t\tif (metadata && typeof metadata === \"object\" && \"gatewayAttachmentId\" in metadata) {\n\t\t\t\tconst attachmentId = metadata.gatewayAttachmentId;\n\t\t\t\tif (typeof attachmentId === \"string\") return runSource(\"gateway\", attachmentId);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tcase \"action\": {\n\t\t\tconst metadata = span.metadata;\n\t\t\tif (metadata && typeof metadata === \"object\" && \"runId\" in metadata) {\n\t\t\t\tconst runId = metadata.runId;\n\t\t\t\tif (typeof runId === \"string\") return runSource(\"workflow\", runId);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tdefault: return;\n\t}\n}\nasync function resolveRunSourceFromTraceContext() {\n\tconst parent = getTraceContext();\n\tif (!parent?.spanId) return runSource(\"api\");\n\tconst span = await selectTraceSpanById(parent.spanId);\n\tif (!span) return runSource(\"api\");\n\treturn sourceFromSpan(span) ?? runSource(\"api\");\n}\n//#endregion\n//#region src/workflows/runs.ts\nfunction serializeError(error) {\n\tif (error instanceof Error) return {\n\t\tname: error.name,\n\t\tmessage: error.message\n\t};\n\treturn { message: String(error) };\n}\nfunction triggerRunType$1(trigger) {\n\treturn trigger;\n}\nfunction resolveWorkflowRunSource(input) {\n\tif (input.sourceKind) return runSource(input.sourceKind, input.sourceId);\n\tif (input.triggerRunId) return runSource(\"trigger\", input.triggerRunId);\n\tif (input.parentWorkflowRunId) return runSource(\"workflow\", input.parentWorkflowRunId);\n\treturn runSource(\"api\");\n}\nfunction workflowRunInsertValues(input, status) {\n\tconst source = resolveWorkflowRunSource(input);\n\tconst now = status === \"running\" ? /* @__PURE__ */ new Date() : null;\n\treturn {\n\t\tid: input.id,\n\t\tworkflowSlug: input.workflowSlug,\n\t\tattachmentId: input.attachmentId ?? null,\n\t\tsubscriptionId: input.subscriptionId ?? null,\n\t\ttriggerRunId: input.triggerRunId ?? null,\n\t\tparentWorkflowRunId: input.parentWorkflowRunId ?? null,\n\t\tparentSpanId: input.parentSpanId ?? null,\n\t\tsourceKind: source.kind,\n\t\tsourceId: source.id,\n\t\tranByUserId: input.ranByUserId ?? null,\n\t\tstatus,\n\t\ttrigger: input.trigger,\n\t\ttriggeredAt: input.triggeredAt,\n\t\tstartedAt: now,\n\t\tinput: input.input ?? null,\n\t\toutput: null,\n\t\terror: null,\n\t\tfinishedAt: null\n\t};\n}\nasync function createWorkflowRun(input) {\n\tawait insertWorkflowRun(workflowRunInsertValues(input, \"running\"));\n}\nasync function createPendingWorkflowRun(input) {\n\tawait insertWorkflowRun(workflowRunInsertValues(input, \"pending\"));\n}\nasync function markWorkflowRunRunning(id) {\n\tawait markWorkflowRunRunningRow(id, /* @__PURE__ */ new Date());\n}\nasync function markWorkflowRunSleeping(id) {\n\tawait setWorkflowRunStatusRow(id, \"sleeping\");\n}\nasync function markWorkflowRunWaitingHook(id) {\n\tawait setWorkflowRunStatusRow(id, \"waiting_hook\");\n}\nasync function completeWorkflowRun(id, output) {\n\tawait completeWorkflowRunRow(id, output, /* @__PURE__ */ new Date());\n}\nasync function failWorkflowRun(id, error) {\n\tawait failWorkflowRunRow(id, serializeError(error), /* @__PURE__ */ new Date());\n}\nasync function recordWorkflowLlmUsage(options) {\n\tconst { usage } = options;\n\tawait insertUsageRecord({\n\t\tid: crypto.randomUUID(),\n\t\trunId: options.workflowRunId,\n\t\trunKind: \"workflow\",\n\t\tkind: \"llm\",\n\t\tlabel: usage.label,\n\t\tquantity: usage.quantity,\n\t\tunit: \"tokens\",\n\t\tamount: usage.amount,\n\t\tmetadata: usage.metadata,\n\t\tcreatedAt: /* @__PURE__ */ new Date()\n\t});\n}\nasync function finalizeCanceledWorkflowRun(id) {\n\tif (await cancelWorkflowRunRow(id, /* @__PURE__ */ new Date())) await appendWorkflowEvent({\n\t\tid: `run_canceled:${id}`,\n\t\trunId: id,\n\t\ttype: \"run_canceled\"\n\t});\n}\nasync function createAttachmentExecution(input) {\n\tconst triggerRunId = input.triggerRunId ?? crypto.randomUUID();\n\tconst workflowRunId = crypto.randomUUID();\n\tif (!input.triggerRunId) await insertTriggerRun({\n\t\tid: triggerRunId,\n\t\ttriggerId: input.triggerId,\n\t\tsourcePath: input.sourcePath ?? null,\n\t\ttriggerType: triggerRunType$1(input.trigger),\n\t\tpayload: input.payload ?? null,\n\t\ttriggeredAt: input.triggeredAt\n\t});\n\tawait insertWorkflowRun({\n\t\tid: workflowRunId,\n\t\tworkflowSlug: input.workflowSlug,\n\t\tattachmentId: input.attachmentId,\n\t\tsubscriptionId: input.subscriptionId ?? null,\n\t\ttriggerRunId,\n\t\tsourceKind: \"trigger\",\n\t\tsourceId: triggerRunId,\n\t\tstatus: \"running\",\n\t\ttrigger: input.trigger,\n\t\ttriggeredAt: input.triggeredAt,\n\t\tstartedAt: /* @__PURE__ */ new Date(),\n\t\tinput: input.input ?? null,\n\t\toutput: null,\n\t\terror: null,\n\t\tfinishedAt: null\n\t});\n\treturn {\n\t\tworkflowRunId,\n\t\ttriggerRunId\n\t};\n}\nasync function createPendingAttachmentExecution(input) {\n\tconst triggerRunId = input.triggerRunId ?? crypto.randomUUID();\n\tconst workflowRunId = crypto.randomUUID();\n\tif (!input.triggerRunId) await insertTriggerRun({\n\t\tid: triggerRunId,\n\t\ttriggerId: input.triggerId,\n\t\tsourcePath: input.sourcePath ?? null,\n\t\ttriggerType: triggerRunType$1(input.trigger),\n\t\tpayload: input.payload ?? null,\n\t\ttriggeredAt: input.triggeredAt\n\t});\n\tawait insertWorkflowRun({\n\t\tid: workflowRunId,\n\t\tworkflowSlug: input.workflowSlug,\n\t\tattachmentId: input.attachmentId,\n\t\tsubscriptionId: input.subscriptionId ?? null,\n\t\ttriggerRunId,\n\t\tsourceKind: \"trigger\",\n\t\tsourceId: triggerRunId,\n\t\tstatus: \"pending\",\n\t\ttrigger: input.trigger,\n\t\ttriggeredAt: input.triggeredAt,\n\t\tstartedAt: null,\n\t\tinput: input.input ?? null,\n\t\toutput: null,\n\t\terror: null,\n\t\tfinishedAt: null\n\t});\n\treturn {\n\t\tworkflowRunId,\n\t\ttriggerRunId\n\t};\n}\nasync function markAttachmentExecutionRunning(workflowRunId) {\n\tawait markWorkflowRunRunning(workflowRunId);\n}\n//#endregion\n//#region src/history/cancel.ts\nconst CANCELABLE_STATUSES = new Set([\n\t\"pending\",\n\t\"running\",\n\t\"sleeping\",\n\t\"waiting_hook\"\n]);\nasync function cancelWorkflowRun(runId) {\n\tconst existing = await findHistoryRunCore(runId);\n\tif (!existing) return null;\n\tif (existing.kind !== \"workflow\") return existing;\n\tif (!CANCELABLE_STATUSES.has(existing.status)) return existing;\n\tawait finalizeCanceledWorkflowRun(runId);\n\treturn findHistoryRunCore(runId);\n}\nasync function cancelAgentSession(sessionId) {\n\tconst existing = await findHistoryRunCore(sessionId);\n\tif (!existing) return null;\n\tif (existing.kind !== \"agent\") return existing;\n\tif (existing.status === \"canceled\" || existing.status === \"completed\" || existing.status === \"failed\") return existing;\n\tawait cancelAgentSessionRow(sessionId, /* @__PURE__ */ new Date());\n\treturn findHistoryRunCore(sessionId);\n}\n//#endregion\n//#region src/agents/sync.ts\nfunction agentMetadata(record) {\n\treturn {\n\t\tname: record.name ?? null,\n\t\tdescription: record.description ?? null,\n\t\ttoolCount: record.toolCount ?? null,\n\t\tcredentialCount: record.credentialCount ?? null,\n\t\tappSlugs: record.appSlugs ?? null\n\t};\n}\nasync function syncAgentRegistry(records) {\n\tconst now = /* @__PURE__ */ new Date();\n\tconst slugs = records.map((record) => record.slug);\n\tconst byRoute = /* @__PURE__ */ new Map();\n\tfor (const record of records) {\n\t\tconst existing = await selectAgentBySlug(record.slug);\n\t\tif (existing) {\n\t\t\tawait updateAgentById(existing.id, {\n\t\t\t\troute: record.route,\n\t\t\t\tmoduleFile: record.moduleFile,\n\t\t\t\tmodel: record.model,\n\t\t\t\tsystemPrompt: record.systemPrompt,\n\t\t\t\t...agentMetadata(record),\n\t\t\t\tupdatedAt: now,\n\t\t\t\tdeletedAt: null\n\t\t\t});\n\t\t\tbyRoute.set(record.route, {\n\t\t\t\tid: existing.id,\n\t\t\t\tslug: record.slug\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst id = crypto.randomUUID();\n\t\tawait insertAgent({\n\t\t\tid,\n\t\t\tslug: record.slug,\n\t\t\troute: record.route,\n\t\t\tmoduleFile: record.moduleFile,\n\t\t\tmodel: record.model,\n\t\t\tsystemPrompt: record.systemPrompt,\n\t\t\t...agentMetadata(record),\n\t\t\tregisteredAt: now,\n\t\t\tupdatedAt: now,\n\t\t\tdeletedAt: null\n\t\t});\n\t\tbyRoute.set(record.route, {\n\t\t\tid,\n\t\t\tslug: record.slug\n\t\t});\n\t}\n\tif (slugs.length === 0) await softDeleteAllAgents(now);\n\telse await softDeleteAgentsNotInSlugs(slugs, now);\n\treturn byRoute;\n}\nasync function getAgentByRoute(route) {\n\treturn selectActiveAgentByRoute(route);\n}\n//#endregion\n//#region src/agents/sessions.ts\nasync function createSession(agentId, id, source = runSource(\"api\"), options) {\n\tconst now = /* @__PURE__ */ new Date();\n\tconst sessionId = id ?? crypto.randomUUID();\n\tawait insertAgentSession({\n\t\tid: sessionId,\n\t\tagentId,\n\t\tsourceKind: source.kind,\n\t\tsourceId: source.id,\n\t\tranByUserId: options?.ranByUserId ?? null,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now,\n\t\tdeletedAt: null\n\t});\n\treturn {\n\t\tid: sessionId,\n\t\tagentId,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t};\n}\nasync function getSession(sessionId) {\n\tconst row = await selectActiveAgentSession(sessionId);\n\tif (!row) return;\n\treturn {\n\t\tid: row.id,\n\t\tagentId: row.agentId,\n\t\tcreatedAt: row.createdAt,\n\t\tupdatedAt: row.updatedAt\n\t};\n}\nasync function touchSession(sessionId) {\n\tawait touchAgentSession(sessionId, /* @__PURE__ */ new Date());\n}\nasync function setSessionTitle(sessionId, title) {\n\tawait updateAgentSessionTitle(sessionId, title);\n}\nasync function nextSeq(sessionId) {\n\treturn await maxSeqForSession(sessionId) + 1;\n}\nasync function appendEvent(sessionId, eventType, payload) {\n\tconst seq = await nextSeq(sessionId);\n\tawait insertAgentEvent({\n\t\tid: crypto.randomUUID(),\n\t\tsessionId,\n\t\tseq,\n\t\teventType,\n\t\tpayload,\n\t\tcreatedAt: /* @__PURE__ */ new Date(),\n\t\tdeletedAt: null\n\t});\n\treturn seq;\n}\nasync function listMessageEvents(sessionId) {\n\treturn listMessagePayloads(sessionId, MESSAGE_EVENT_TYPE);\n}\nasync function countMessageEvents(sessionId) {\n\treturn countMessageEventsForSession(sessionId, MESSAGE_EVENT_TYPE);\n}\nasync function listSessionEvents(sessionId) {\n\treturn (await listAgentEventsForSession(sessionId)).map((row) => ({\n\t\tid: row.id,\n\t\tsessionId: row.sessionId,\n\t\tseq: row.seq,\n\t\teventType: row.eventType,\n\t\tpayload: row.payload,\n\t\tcreatedAt: row.createdAt\n\t}));\n}\nasync function setSessionLiveMessage(sessionId, message) {\n\tawait updateSessionLiveMessage(sessionId, message);\n}\nasync function clearLiveMessage(sessionId) {\n\tawait clearSessionLiveMessage(sessionId);\n}\nasync function getSessionLiveMessage(sessionId) {\n\treturn selectSessionLiveMessage(sessionId);\n}\n//#endregion\n//#region src/agents/runs.ts\nasync function recordLlmUsageFromAssistantMessage(options) {\n\tconst { usage } = options;\n\tawait insertUsageRecord({\n\t\tid: crypto.randomUUID(),\n\t\trunId: options.sessionId,\n\t\trunKind: \"agent\",\n\t\tkind: \"llm\",\n\t\tlabel: usage.label,\n\t\tquantity: usage.quantity,\n\t\tunit: \"tokens\",\n\t\tamount: usage.amount,\n\t\tmetadata: usage.metadata,\n\t\tcreatedAt: /* @__PURE__ */ new Date()\n\t});\n}\n//#endregion\n//#region src/agents/fail-session.ts\nfunction serializeSpanError(error) {\n\tif (error instanceof Error) return {\n\t\tname: error.name,\n\t\tmessage: error.message\n\t};\n\treturn { message: String(error) };\n}\n/**\n* Mark an agent session as failed by closing or inserting its terminal `agent_session`\n* trace span. History derives session status from that span.\n*/\nasync function failAgentSession(sessionId, error) {\n\tconst serializedError = serializeSpanError(error);\n\tconst finishedAt = /* @__PURE__ */ new Date();\n\tconst span = await selectLatestAgentSessionSpanByRefId(sessionId);\n\tif (span) {\n\t\tif (span.status !== \"running\") return;\n\t\tawait updateTraceSpanStatus(span.id, \"error\", finishedAt, serializedError);\n\t\treturn;\n\t}\n\tconst session = await selectAgentSessionById(sessionId);\n\tif (!session) return;\n\tawait insertTraceSpan({\n\t\tid: crypto.randomUUID(),\n\t\ttraceId: sessionId,\n\t\tkind: \"agent_session\",\n\t\trefId: sessionId,\n\t\tname: session.agentId,\n\t\tstatus: \"error\",\n\t\tstartedAt: finishedAt,\n\t\tfinishedAt,\n\t\tmetadata: {\n\t\t\tagentId: session.agentId,\n\t\t\ttrigger: \"api\"\n\t\t},\n\t\terror: serializedError\n\t});\n}\n//#endregion\n//#region src/skills/sync.ts\nfunction skillMetadata(record) {\n\treturn {\n\t\tname: record.name ?? null,\n\t\tdescription: record.description ?? null\n\t};\n}\nasync function syncSkillRegistry(records) {\n\tconst now = /* @__PURE__ */ new Date();\n\tconst slugs = records.map((record) => record.slug);\n\tconst bySlug = /* @__PURE__ */ new Map();\n\tfor (const record of records) {\n\t\tconst existing = await selectSkillBySlug(record.slug);\n\t\tif (existing) {\n\t\t\tawait updateSkillById(existing.id, {\n\t\t\t\tmoduleFile: record.moduleFile,\n\t\t\t\t...skillMetadata(record),\n\t\t\t\tupdatedAt: now,\n\t\t\t\tdeletedAt: null\n\t\t\t});\n\t\t\tbySlug.set(record.slug, {\n\t\t\t\tid: existing.id,\n\t\t\t\tslug: record.slug\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst id = crypto.randomUUID();\n\t\tawait insertSkill({\n\t\t\tid,\n\t\t\tslug: record.slug,\n\t\t\tmoduleFile: record.moduleFile,\n\t\t\t...skillMetadata(record),\n\t\t\tregisteredAt: now,\n\t\t\tupdatedAt: now,\n\t\t\tdeletedAt: null\n\t\t});\n\t\tbySlug.set(record.slug, {\n\t\t\tid,\n\t\t\tslug: record.slug\n\t\t});\n\t}\n\tif (slugs.length === 0) await softDeleteAllSkills(now);\n\telse await softDeleteSkillsNotInSlugs(slugs, now);\n\treturn bySlug;\n}\n//#endregion\n//#region src/triggers/source-slug.ts\n/** Read source slug from persisted JSON (`slug` preferred, legacy `key` fallback). */\nfunction storedTriggerSourceSlug(source) {\n\tconst slug = source.slug?.trim() || source.key?.trim();\n\tif (!slug) throw new Error(\"Stored trigger source requires slug or legacy key\");\n\treturn slug;\n}\n/** Write canonical persisted source JSON (uses `slug`; omits legacy `key`). */\nfunction normalizeStoredTriggerSource(source) {\n\tconst slug = storedTriggerSourceSlug(source);\n\tif (source.kind === \"webhook\") return {\n\t\tkind: \"webhook\",\n\t\tslug,\n\t\tendpoint: source.endpoint,\n\t\trequestSchema: source.requestSchema,\n\t\t...source.filterSchema ? { filterSchema: source.filterSchema } : {}\n\t};\n\tif (source.kind === \"cron\") return {\n\t\tkind: \"cron\",\n\t\tslug,\n\t\tschedule: source.schedule\n\t};\n\treturn {\n\t\tkind: \"poll\",\n\t\tslug,\n\t\tschedule: source.schedule,\n\t\t...source.code ? { code: source.code } : {},\n\t\t...source.id ? { id: source.id } : {}\n\t};\n}\n//#endregion\n//#region src/triggers/trigger-config.ts\nfunction triggerConfigFromSource(source) {\n\tif (source.kind === \"webhook\") return {\n\t\tendpoint: source.endpoint,\n\t\trequestSchema: source.requestSchema,\n\t\t...source.filterSchema ? { filterSchema: source.filterSchema } : {}\n\t};\n\tif (source.kind === \"poll\") return {\n\t\t...source.code ? { code: source.code } : {},\n\t\t...source.id ? { id: source.id } : {}\n\t};\n\treturn null;\n}\nfunction triggerScheduleFromSource(source) {\n\tif (source.kind === \"cron\" || source.kind === \"poll\") return source.schedule;\n\treturn null;\n}\n/** Stable key for grouping attachments that share the same trigger source. */\nfunction triggerSourceGroupKeyFromSource(source) {\n\tconst sourceSlug = storedTriggerSourceSlug(source);\n\tif (source.kind === \"poll\" && source.id) return `poll:${source.id}`;\n\treturn `${source.kind}:${sourceSlug}`;\n}\nfunction triggerSlugFromSource(source) {\n\treturn storedTriggerSourceSlug(normalizeStoredTriggerSource(source));\n}\nfunction webhookEndpointFromTriggerConfig(config) {\n\tif (config && \"endpoint\" in config) return config.endpoint;\n\treturn null;\n}\n/** Reconstruct the `StoredTriggerSource` JSON shape from a normalized `triggers` row. */\nfunction storedTriggerSourceFromTrigger(trigger) {\n\tif (trigger.kind === \"webhook\") {\n\t\tconst config = trigger.config ?? {};\n\t\treturn {\n\t\t\tkind: \"webhook\",\n\t\t\tslug: trigger.slug,\n\t\t\tendpoint: config.endpoint,\n\t\t\trequestSchema: config.requestSchema,\n\t\t\t...config.filterSchema ? { filterSchema: config.filterSchema } : {}\n\t\t};\n\t}\n\tif (trigger.kind === \"cron\") return {\n\t\tkind: \"cron\",\n\t\tslug: trigger.slug,\n\t\tschedule: trigger.schedule ?? \"\"\n\t};\n\tconst config = trigger.config ?? {};\n\treturn {\n\t\tkind: \"poll\",\n\t\tslug: trigger.slug,\n\t\tschedule: trigger.schedule ?? \"\",\n\t\t...config.code ? { code: config.code } : {},\n\t\t...config.id ? { id: config.id } : {}\n\t};\n}\n//#endregion\n//#region src/triggers/sync.ts\nfunction groupDiscoveredRecords(records) {\n\tconst groups = /* @__PURE__ */ new Map();\n\tfor (const record of records) {\n\t\tconst source = normalizeStoredTriggerSource(record.source);\n\t\tconst groupKey = triggerSourceGroupKeyFromSource(source);\n\t\tconst triggerSlug = triggerSlugFromSource(source);\n\t\tconst existing = groups.get(groupKey);\n\t\tif (existing) {\n\t\t\texisting.records.push(record);\n\t\t\tcontinue;\n\t\t}\n\t\tgroups.set(groupKey, {\n\t\t\tgroupKey,\n\t\t\ttriggerSlug,\n\t\t\trecords: [record]\n\t\t});\n\t}\n\treturn [...groups.values()];\n}\n/** Deterministic JSON with recursively sorted object keys, so the hash is stable. */\nfunction canonicalStringify(value) {\n\tif (Array.isArray(value)) return `[${value.map(canonicalStringify).join(\",\")}]`;\n\tif (value && typeof value === \"object\") return `{${Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${canonicalStringify(v)}`).join(\",\")}}`;\n\treturn JSON.stringify(value ?? null);\n}\n/**\n* Hash of the inputs an LLM overview is derived from. Written to `triggers.triggerHash`\n* on every deploy; the overview is stale (and regenerated) when it diverges from the\n* worker-stamped `overviewHash`.\n*/\nfunction computeTriggerHash(group, source, schedule) {\n\tconst primary = group.records[0];\n\tconst assignments = group.records.map((record) => ({\n\t\ttargetKind: record.targetKind,\n\t\tworkflowSlug: record.workflowSlug ?? null,\n\t\tagentSlug: record.agentSlug ?? null\n\t})).sort((a, b) => canonicalStringify(a).localeCompare(canonicalStringify(b)));\n\treturn createHash(\"sha256\").update(canonicalStringify({\n\t\tname: primary.name,\n\t\tdescription: primary.description,\n\t\tkind: source.kind,\n\t\tschedule,\n\t\tconfig: triggerConfigFromSource(source),\n\t\tmoduleFile: primary.moduleFile,\n\t\tsourceHash: primary.sourceHash ?? null,\n\t\tassignments\n\t})).digest(\"hex\");\n}\nasync function syncTriggerAttachmentRegistry(records) {\n\tconst now = /* @__PURE__ */ new Date();\n\tconst attachmentSlugs = records.map((record) => record.slug);\n\tconst triggerSlugs = [...new Set(records.map((record) => triggerSlugFromSource(record.source)))];\n\tconst byKey = /* @__PURE__ */ new Map();\n\tfor (const group of groupDiscoveredRecords(records)) {\n\t\tconst primary = group.records[0];\n\t\tconst source = normalizeStoredTriggerSource(primary.source);\n\t\tconst schedule = triggerScheduleFromSource(source);\n\t\tconst triggerHash = computeTriggerHash(group, source, schedule);\n\t\tconst existingTrigger = await selectTriggerBySlug(group.triggerSlug);\n\t\tlet triggerId;\n\t\tif (existingTrigger) {\n\t\t\ttriggerId = existingTrigger.id;\n\t\t\tawait updateTriggerById(existingTrigger.id, {\n\t\t\t\tname: primary.name,\n\t\t\t\tdescription: primary.description,\n\t\t\t\tmoduleFile: primary.moduleFile,\n\t\t\t\tconfig: triggerConfigFromSource(source),\n\t\t\t\tschedule,\n\t\t\t\ttriggerHash,\n\t\t\t\tupdatedAt: now,\n\t\t\t\tdeletedAt: null\n\t\t\t});\n\t\t} else {\n\t\t\ttriggerId = crypto.randomUUID();\n\t\t\tawait insertTrigger({\n\t\t\t\tid: triggerId,\n\t\t\t\tslug: group.triggerSlug,\n\t\t\t\tkind: source.kind,\n\t\t\t\tname: primary.name,\n\t\t\t\tdescription: primary.description,\n\t\t\t\tmoduleFile: primary.moduleFile,\n\t\t\t\tconfig: triggerConfigFromSource(source),\n\t\t\t\tschedule,\n\t\t\t\ttriggerHash,\n\t\t\t\torigin: \"project\",\n\t\t\t\tregisteredAt: now,\n\t\t\t\tupdatedAt: now,\n\t\t\t\tdeletedAt: null\n\t\t\t});\n\t\t}\n\t\tif (schedule && (source.kind === \"cron\" || source.kind === \"poll\")) await upsertTriggerScheduleFields({\n\t\t\ttriggerSlug: group.triggerSlug,\n\t\t\tschedule,\n\t\t\tnextRunAt: existingTrigger?.nextRunAt ?? now,\n\t\t\tenabled: true,\n\t\t\tupdatedAt: now\n\t\t});\n\t\tfor (const record of group.records) {\n\t\t\tconst existingAttachment = await selectTriggerAttachmentBySlug(record.slug);\n\t\t\tif (existingAttachment) {\n\t\t\t\tawait updateTriggerAttachmentById(existingAttachment.id, {\n\t\t\t\t\ttargetKind: record.targetKind,\n\t\t\t\t\tworkflowSlug: record.workflowSlug ?? null,\n\t\t\t\t\tagentSlug: record.agentSlug ?? null,\n\t\t\t\t\tupdatedAt: now,\n\t\t\t\t\tdeletedAt: null\n\t\t\t\t});\n\t\t\t\tbyKey.set(record.slug, {\n\t\t\t\t\tid: existingAttachment.id,\n\t\t\t\t\tslug: record.slug,\n\t\t\t\t\ttriggerId\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst attachmentId = crypto.randomUUID();\n\t\t\tawait insertTriggerAttachment({\n\t\t\t\tid: attachmentId,\n\t\t\t\ttriggerId,\n\t\t\t\tslug: record.slug,\n\t\t\t\ttargetKind: record.targetKind,\n\t\t\t\tworkflowSlug: record.workflowSlug ?? null,\n\t\t\t\tagentSlug: record.agentSlug ?? null,\n\t\t\t\tregisteredAt: now,\n\t\t\t\tupdatedAt: now,\n\t\t\t\tdeletedAt: null\n\t\t\t});\n\t\t\tbyKey.set(record.slug, {\n\t\t\t\tid: attachmentId,\n\t\t\t\tslug: record.slug,\n\t\t\t\ttriggerId\n\t\t\t});\n\t\t}\n\t}\n\tif (attachmentSlugs.length === 0) {\n\t\tawait softDeleteAllProjectTriggers(now);\n\t\tawait softDeleteAllTriggerAttachments(now);\n\t} else {\n\t\tawait softDeleteTriggerAttachmentsNotInSlugs(attachmentSlugs, now);\n\t\tawait softDeleteProjectTriggersNotInSlugs(triggerSlugs, now);\n\t}\n\treturn byKey;\n}\n//#endregion\n//#region src/triggers/agent-runs.ts\nfunction triggerRunType(trigger) {\n\tif (trigger === \"cron\" || trigger === \"poll\" || trigger === \"webhook\") return trigger;\n\tthrow new Error(`Unexpected trigger type for trigger run: ${trigger}`);\n}\nasync function createAgentAttachmentExecution(input) {\n\tconst triggerRunId = input.triggerRunId ?? crypto.randomUUID();\n\tconst sessionId = crypto.randomUUID();\n\tconst now = /* @__PURE__ */ new Date();\n\tif (!input.triggerRunId) await insertTriggerRun({\n\t\tid: triggerRunId,\n\t\ttriggerId: input.triggerId,\n\t\tsourcePath: input.sourcePath ?? null,\n\t\ttriggerType: triggerRunType(input.trigger),\n\t\tpayload: input.payload ?? null,\n\t\ttriggeredAt: input.triggeredAt\n\t});\n\tawait insertAgentSession({\n\t\tid: sessionId,\n\t\tagentId: input.agentId,\n\t\tsourceKind: \"trigger\",\n\t\tsourceId: triggerRunId,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now,\n\t\tdeletedAt: null\n\t});\n\treturn {\n\t\ttriggerRunId,\n\t\tsessionId\n\t};\n}\nasync function getTriggerRunForAgentSession(sessionId) {\n\tconst session = await selectAgentSessionById(sessionId);\n\tif (session?.sourceKind !== \"trigger\" || !session.sourceId) return;\n\treturn selectTriggerRunById(session.sourceId);\n}\n//#endregion\n//#region src/triggers/fire.ts\n/** Persist a trigger fire that did not dispatch a downstream workflow run or agent session. */\nasync function recordTriggerFire(input) {\n\tconst id = crypto.randomUUID();\n\tawait insertTriggerRun({\n\t\tid,\n\t\ttriggerId: input.triggerId,\n\t\ttriggerType: input.triggerType,\n\t\toutcome: input.outcome,\n\t\treason: input.reason ?? null,\n\t\tdetail: input.detail ?? null,\n\t\tpayload: input.payload ?? null,\n\t\tsourcePath: input.sourcePath ?? null,\n\t\ttriggeredAt: input.triggeredAt ?? /* @__PURE__ */ new Date()\n\t});\n\treturn id;\n}\n//#endregion\n//#region src/triggers/assignments.ts\nfunction triggerStatusFromRow(row) {\n\tif (row.deletedAt) return \"disabled\";\n\tconst lifecycleStatus = row.lifecycle?.status;\n\tif (lifecycleStatus === \"disabled\" || lifecycleStatus === \"completed\") return \"disabled\";\n\tif (row.kind === \"cron\" || row.kind === \"poll\") return row.enabled === 1 ? \"active\" : \"disabled\";\n\treturn \"active\";\n}\nasync function resolveTriggerAssignments(rows, trigger) {\n\tconst assignments = [];\n\tfor (const row of rows) {\n\t\tif (row.targetKind === \"workflow\" && row.workflowSlug) {\n\t\t\tconst workflow = await selectActiveWorkflowBySlug(row.workflowSlug);\n\t\t\tassignments.push({\n\t\t\t\tkind: \"workflow\",\n\t\t\t\tid: workflow?.id ?? row.id,\n\t\t\t\tslug: row.workflowSlug,\n\t\t\t\tname: workflow?.name?.trim() || trigger?.name?.trim() || row.workflowSlug\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (row.targetKind === \"agent\" && row.agentSlug) {\n\t\t\tconst agent = await selectAgentBySlug(row.agentSlug);\n\t\t\tassignments.push({\n\t\t\t\tkind: \"agent\",\n\t\t\t\tid: agent?.id ?? row.id,\n\t\t\t\tslug: row.agentSlug,\n\t\t\t\tname: agent?.name?.trim() || trigger?.name?.trim() || row.agentSlug\n\t\t\t});\n\t\t}\n\t}\n\treturn assignments;\n}\n//#endregion\n//#region src/triggers/workspace.ts\nfunction resourceKey(projectId, slug) {\n\treturn `${projectId}:${slug}`;\n}\nfunction assignmentsForGroup(attachments, trigger, workflows, agents) {\n\tconst assignments = [];\n\tconst seen = /* @__PURE__ */ new Set();\n\tfor (const row of attachments) {\n\t\tif (row.targetKind === \"workflow\" && row.workflowSlug) {\n\t\t\tconst key = `workflow:${row.workflowSlug}`;\n\t\t\tif (seen.has(key)) continue;\n\t\t\tseen.add(key);\n\t\t\tconst ref = workflows.get(resourceKey(row.projectId, row.workflowSlug));\n\t\t\tassignments.push({\n\t\t\t\tkind: \"workflow\",\n\t\t\t\tid: ref?.id ?? row.id,\n\t\t\t\tslug: row.workflowSlug,\n\t\t\t\tname: ref?.name?.trim() || trigger.name?.trim() || row.workflowSlug\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (row.targetKind === \"agent\" && row.agentSlug) {\n\t\t\tconst key = `agent:${row.agentSlug}`;\n\t\t\tif (seen.has(key)) continue;\n\t\t\tseen.add(key);\n\t\t\tconst ref = agents.get(resourceKey(row.projectId, row.agentSlug));\n\t\t\tassignments.push({\n\t\t\t\tkind: \"agent\",\n\t\t\t\tid: ref?.id ?? row.id,\n\t\t\t\tslug: row.agentSlug,\n\t\t\t\tname: ref?.name?.trim() || trigger.name?.trim() || row.agentSlug\n\t\t\t});\n\t\t}\n\t}\n\treturn assignments;\n}\nfunction buildRecord(trigger, attachments, workflows, agents, lastFiredAt, fireCount) {\n\tconst lastFired = lastFiredAt.get(trigger.id);\n\tconst fires = fireCount.get(trigger.id) ?? 0;\n\treturn {\n\t\tid: trigger.id,\n\t\tslug: trigger.slug,\n\t\tname: trigger.name?.trim() || trigger.slug,\n\t\tdescription: trigger.description ?? null,\n\t\ttype: trigger.kind,\n\t\tstatus: triggerStatusFromRow(trigger),\n\t\tprojectId: trigger.projectId,\n\t\tschedule: trigger.schedule,\n\t\tassignments: assignmentsForGroup(attachments, trigger, workflows, agents),\n\t\tlastFiredAt: lastFired ? lastFired.toISOString() : null,\n\t\tfireCount: fires,\n\t\tcreatedAt: trigger.registeredAt.toISOString(),\n\t\tsourcePath: trigger.moduleFile,\n\t\twebhookEndpoint: webhookEndpointFromTriggerConfig(trigger.config ?? null)\n\t};\n}\nasync function buildResourceMaps(projectIds) {\n\tconst [workflowRows, agentRows] = await Promise.all([listActiveWorkflows(projectIds ? { projectIds } : void 0), listActiveAgents(projectIds ? { projectIds } : void 0)]);\n\tconst workflows = /* @__PURE__ */ new Map();\n\tfor (const row of workflowRows) workflows.set(resourceKey(row.projectId, row.slug), {\n\t\tid: row.id,\n\t\tname: row.name\n\t});\n\tconst agents = /* @__PURE__ */ new Map();\n\tfor (const row of agentRows) agents.set(resourceKey(row.projectId, row.slug), {\n\t\tid: row.id,\n\t\tname: row.name\n\t});\n\treturn {\n\t\tworkflows,\n\t\tagents\n\t};\n}\n/** Workspace triggers across the projects the caller can access. */\nasync function listWorkspaceTriggers(projectIds) {\n\tconst triggers = await listActiveTriggersByProjectIds(projectIds);\n\tif (triggers.length === 0) return [];\n\tconst { workflows, agents } = await buildResourceMaps(projectIds);\n\tconst triggerIds = triggers.map((row) => row.id);\n\tconst [attachments, lastFiredAt, fireCount] = await Promise.all([\n\t\tlistAttachmentsByTriggerIds(triggerIds),\n\t\tselectTriggerLastFiredAtByTriggerIds(triggerIds),\n\t\tselectTriggerFireCountByTriggerIds(triggerIds)\n\t]);\n\tconst attachmentsByTriggerId = /* @__PURE__ */ new Map();\n\tfor (const attachment of attachments) {\n\t\tconst existing = attachmentsByTriggerId.get(attachment.triggerId) ?? [];\n\t\texisting.push(attachment);\n\t\tattachmentsByTriggerId.set(attachment.triggerId, existing);\n\t}\n\treturn triggers.map((trigger) => buildRecord(trigger, attachmentsByTriggerId.get(trigger.id) ?? [], workflows, agents, lastFiredAt, fireCount));\n}\nasync function getWorkspaceTrigger(projectId, triggerId) {\n\treturn (await listWorkspaceTriggers([projectId])).find((record) => record.id === triggerId) ?? null;\n}\n/**\n* Run history for a workspace trigger — every fire for the trigger, newest first.\n*/\nasync function listWorkspaceTriggerRunRows(options) {\n\treturn runWithProjectScope(options.projectId, async () => {\n\t\tconst trigger = await selectTriggerById(options.triggerId);\n\t\tif (!trigger || trigger.deletedAt !== null) return null;\n\t\tconst attachments = await listAttachmentsByTriggerIds([trigger.id]);\n\t\tconst result = await listTriggerRunRowsPaginated({\n\t\t\ttriggerIds: [trigger.id],\n\t\t\tlimit: options.limit,\n\t\t\tcursor: options.cursor,\n\t\t\ttriggerType: options.triggerType\n\t\t});\n\t\tif (!attachments.some((row) => row.targetKind === \"agent\" && row.agentSlug)) return result;\n\t\tconst triggerRunIds = result.items.map((item) => item.id);\n\t\tconst [sessionsByTriggerRunId, agents] = await Promise.all([listAgentSessionsBySourceIds({\n\t\t\tsourceKind: \"trigger\",\n\t\t\tsourceIds: triggerRunIds\n\t\t}), listActiveAgents({ projectIds: [options.projectId] })]);\n\t\tconst slugByAgentId = new Map(agents.map((agent) => [agent.id, agent.slug]));\n\t\treturn {\n\t\t\t...result,\n\t\t\titems: result.items.map((item) => {\n\t\t\t\tconst sessions = sessionsByTriggerRunId.get(item.id) ?? [];\n\t\t\t\tif (sessions.length === 0) return item;\n\t\t\t\treturn {\n\t\t\t\t\t...item,\n\t\t\t\t\tagentSessions: sessions.map((session) => ({\n\t\t\t\t\t\tid: session.id,\n\t\t\t\t\t\tagentSlug: slugByAgentId.get(session.agentId) ?? session.agentId\n\t\t\t\t\t}))\n\t\t\t\t};\n\t\t\t})\n\t\t};\n\t});\n}\n//#endregion\n//#region src/triggers/stored-source-from-row.ts\nfunction storedTriggerSourceFromRow(row) {\n\tconst slug = row.slug;\n\tif (row.kind === \"webhook\") {\n\t\tconst config = row.config ?? {};\n\t\treturn {\n\t\t\tkind: \"webhook\",\n\t\t\tslug,\n\t\t\tendpoint: config.endpoint,\n\t\t\trequestSchema: config.requestSchema,\n\t\t\t...config.filterSchema ? { filterSchema: config.filterSchema } : {}\n\t\t};\n\t}\n\tif (row.kind === \"cron\") return {\n\t\tkind: \"cron\",\n\t\tslug,\n\t\tschedule: row.schedule ?? \"\"\n\t};\n\tconst config = row.config ?? {};\n\treturn {\n\t\tkind: \"poll\",\n\t\tslug,\n\t\tschedule: row.schedule ?? \"\",\n\t\t...config.code ? { code: config.code } : {},\n\t\t...config.id ? { id: config.id } : {}\n\t};\n}\n//#endregion\n//#region src/triggers/ephemeral.ts\n/** Sentinel moduleFile for triggers that exist only in the database. */\nconst EPHEMERAL_TRIGGER_MODULE_FILE = \"__ephemeral__\";\nfunction initialLifecycle(input, existing) {\n\treturn {\n\t\t...input.lifecycle?.maxExecutions !== void 0 ? { maxExecutions: input.lifecycle.maxExecutions } : {},\n\t\t...input.lifecycle?.until !== void 0 ? { until: input.lifecycle.until } : {},\n\t\texecutionCount: existing?.executionCount ?? 0,\n\t\tstatus: input.enabled === false ? \"disabled\" : \"active\"\n\t};\n}\n/** Creates or updates a DB-only trigger for an agent; schedule lives on the trigger row. */\nasync function upsertEphemeralTrigger(input) {\n\tconst now = /* @__PURE__ */ new Date();\n\tconst source = normalizeStoredTriggerSource(input.source);\n\tconst triggerSlug = input.slug;\n\tconst sourceSlug = triggerSlugFromSource(source);\n\tconst existingTrigger = await selectTriggerBySlug(triggerSlug);\n\tconst existingProjectTrigger = await selectTriggerBySlug(sourceSlug);\n\tconst existingAttachment = await selectTriggerAttachmentBySlug(input.slug);\n\tif (existingProjectTrigger && existingProjectTrigger.origin !== \"ephemeral\") throw new Error(`Trigger \"${input.slug}\" is defined in the project and cannot be modified`);\n\tif (existingTrigger && existingTrigger.origin !== \"ephemeral\") throw new Error(`Trigger \"${input.slug}\" is defined in the project and cannot be modified`);\n\tif (existingAttachment && existingAttachment.agentSlug !== input.agentSlug) throw new Error(`Trigger \"${input.slug}\" belongs to another agent`);\n\tconst lifecycle = initialLifecycle(input, existingTrigger?.lifecycle);\n\tconst enabled = lifecycle.status === \"active\";\n\tconst schedule = triggerScheduleFromSource(source);\n\tlet triggerId;\n\tif (existingTrigger) {\n\t\ttriggerId = existingTrigger.id;\n\t\tawait updateTriggerById(existingTrigger.id, {\n\t\t\tname: input.name ?? existingTrigger.name ?? null,\n\t\t\tdescription: input.description ?? existingTrigger.description ?? null,\n\t\t\tmoduleFile: EPHEMERAL_TRIGGER_MODULE_FILE,\n\t\t\tconfig: triggerConfigFromSource(source),\n\t\t\tschedule,\n\t\t\tnextRunAt: source.kind === \"cron\" || source.kind === \"poll\" ? input.nextRunAt ?? existingTrigger.nextRunAt ?? now : null,\n\t\t\tenabled: enabled ? 1 : 0,\n\t\t\tlifecycle,\n\t\t\tupdatedAt: now,\n\t\t\tdeletedAt: null\n\t\t});\n\t} else {\n\t\ttriggerId = crypto.randomUUID();\n\t\tawait insertTrigger({\n\t\t\tid: triggerId,\n\t\t\tslug: triggerSlug,\n\t\t\tkind: source.kind,\n\t\t\tname: input.name ?? null,\n\t\t\tdescription: input.description ?? null,\n\t\t\tmoduleFile: EPHEMERAL_TRIGGER_MODULE_FILE,\n\t\t\torigin: \"ephemeral\",\n\t\t\tconfig: triggerConfigFromSource(source),\n\t\t\tschedule,\n\t\t\tnextRunAt: source.kind === \"cron\" || source.kind === \"poll\" ? input.nextRunAt ?? now : null,\n\t\t\tenabled: enabled ? 1 : 0,\n\t\t\tlifecycle,\n\t\t\tcreatedBySessionId: input.createdBySessionId ?? null,\n\t\t\tregisteredAt: now,\n\t\t\tupdatedAt: now,\n\t\t\tdeletedAt: null\n\t\t});\n\t}\n\tif (source.kind === \"cron\" || source.kind === \"poll\") {\n\t\tif (!input.nextRunAt) throw new Error(`Ephemeral ${source.kind} triggers require nextRunAt`);\n\t}\n\tif (existingAttachment) await updateTriggerAttachmentById(existingAttachment.id, {\n\t\ttargetKind: \"agent\",\n\t\tworkflowSlug: null,\n\t\tagentSlug: input.agentSlug,\n\t\tprompt: input.prompt,\n\t\tupdatedAt: now,\n\t\tdeletedAt: null\n\t});\n\telse await insertTriggerAttachment({\n\t\tid: crypto.randomUUID(),\n\t\ttriggerId,\n\t\tslug: input.slug,\n\t\ttargetKind: \"agent\",\n\t\tworkflowSlug: null,\n\t\tagentSlug: input.agentSlug,\n\t\tprompt: input.prompt,\n\t\tregisteredAt: now,\n\t\tupdatedAt: now,\n\t\tdeletedAt: null\n\t});\n\tconst row = await selectTriggerAttachmentBySlug(input.slug);\n\tif (!row) throw new Error(`Failed to persist ephemeral trigger \"${input.slug}\"`);\n\treturn row;\n}\n/** Soft-deletes an agent-owned ephemeral trigger and disables its schedule. */\nasync function deleteEphemeralTrigger(options) {\n\tconst row = await selectTriggerAttachmentBySlug(options.slug);\n\tif (!row || row.deletedAt !== null) return false;\n\tconst trigger = await selectTriggerById(row.triggerId);\n\tif (!trigger || trigger.origin !== \"ephemeral\") return false;\n\tif (row.agentSlug !== options.agentSlug) throw new Error(`Trigger \"${options.slug}\" belongs to another agent`);\n\tconst now = /* @__PURE__ */ new Date();\n\tawait updateTriggerAttachmentById(row.id, {\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t});\n\tawait updateTriggerById(trigger.id, {\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t});\n\tawait setTriggerScheduleEnabled(trigger.slug, false, now);\n\treturn true;\n}\n/** Returns true when the trigger may fire now (active status and `until` not passed). */\nfunction isEphemeralTriggerActive(row, now = /* @__PURE__ */ new Date()) {\n\tif (row.origin !== \"ephemeral\" || row.deletedAt !== null) return false;\n\tconst lifecycle = row.lifecycle;\n\tif (!lifecycle) return true;\n\tif (lifecycle.status !== \"active\") return false;\n\tif (lifecycle.until && now >= new Date(lifecycle.until)) return false;\n\treturn true;\n}\n/**\n* Increments executionCount after a fire and completes the trigger when either\n* `maxExecutions` or `until` is met (OR semantics). Row is kept for audit.\n*/\nasync function recordEphemeralTriggerExecution(triggerSlug, now = /* @__PURE__ */ new Date()) {\n\tconst trigger = await selectTriggerBySlug(triggerSlug);\n\tif (!trigger || trigger.origin !== \"ephemeral\") return;\n\tconst lifecycle = trigger.lifecycle ?? {\n\t\texecutionCount: 0,\n\t\tstatus: \"active\"\n\t};\n\tlifecycle.executionCount += 1;\n\tconst maxReached = lifecycle.maxExecutions !== void 0 && lifecycle.executionCount >= lifecycle.maxExecutions;\n\tconst untilPassed = lifecycle.until !== void 0 && now >= new Date(lifecycle.until);\n\tif (lifecycle.status === \"active\" && (maxReached || untilPassed)) {\n\t\tlifecycle.status = \"completed\";\n\t\tawait setTriggerScheduleEnabled(triggerSlug, false, now);\n\t}\n\tawait updateTriggerById(trigger.id, {\n\t\tlifecycle,\n\t\tupdatedAt: now\n\t});\n\treturn lifecycle;\n}\n/** Trigger slugs for active ephemeral scheduled triggers — excluded from project schedule sweeps. */\nasync function selectActiveEphemeralScheduledTriggerSlugs() {\n\treturn (await listActiveEphemeralTriggers()).filter((row) => (row.kind === \"cron\" || row.kind === \"poll\") && isEphemeralTriggerActive(row)).map((row) => row.slug);\n}\n/** @deprecated Use {@link selectActiveEphemeralScheduledTriggerSlugs}. */\nasync function selectActiveEphemeralScheduledAttachmentSlugs() {\n\treturn selectActiveEphemeralScheduledTriggerSlugs();\n}\n/** @deprecated Use {@link selectActiveEphemeralScheduledTriggerSlugs}. */\nasync function selectActiveEphemeralCronAttachmentSlugs() {\n\treturn selectActiveEphemeralScheduledTriggerSlugs();\n}\n//#endregion\n//#region src/triggers/agent-list.ts\nfunction triggerLabel(row, attachment) {\n\treturn row.name?.trim() || row.slug || attachment.slug;\n}\nfunction triggerSchedule(source) {\n\tif (source.kind === \"cron\" || source.kind === \"poll\") return source.schedule;\n\treturn null;\n}\nfunction triggerEndpoint(source) {\n\tif (source.kind === \"webhook\") return source.endpoint;\n\treturn null;\n}\nfunction agentTriggerSummaryFromRows(row, attachment) {\n\tconst source = storedTriggerSourceFromRow(row);\n\treturn {\n\t\tid: attachment.slug,\n\t\tlabel: triggerLabel(row, attachment),\n\t\tname: row.name ?? null,\n\t\tdescription: row.description ?? null,\n\t\ttype: row.kind,\n\t\tschedule: triggerSchedule(source),\n\t\tendpoint: triggerEndpoint(source),\n\t\torigin: row.origin,\n\t\tprompt: attachment.prompt ?? null,\n\t\tstatus: row.lifecycle?.status ?? \"active\",\n\t\texecutionCount: row.lifecycle?.executionCount ?? 0,\n\t\tuntil: row.lifecycle?.until ?? null\n\t};\n}\nasync function listAgentTriggers(agentSlug) {\n\tconst rows = await selectTriggerAttachmentsByAgentSlug(agentSlug);\n\tconst summaries = [];\n\tfor (const attachment of rows) {\n\t\tconst trigger = await selectTriggerById(attachment.triggerId);\n\t\tif (!trigger) continue;\n\t\tsummaries.push(agentTriggerSummaryFromRows(trigger, attachment));\n\t}\n\treturn summaries;\n}\n//#endregion\n//#region src/gateways/thread-sessions.ts\nasync function getOrCreateGatewayThreadSession(options) {\n\tconst existing = await selectGatewayThreadSessionByThreadId(options.threadId);\n\tif (existing) return existing.sessionId;\n\tconst session = await createSession(options.agentId, options.existingSessionId, runSource(\"gateway\", options.attachmentId));\n\tconst now = /* @__PURE__ */ new Date();\n\tawait upsertGatewayThreadSession({\n\t\tthreadId: options.threadId,\n\t\tagentId: options.agentId,\n\t\tsessionId: session.id,\n\t\tattachmentId: options.attachmentId,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t});\n\treturn session.id;\n}\n//#endregion\n//#region src/workflows/sync.ts\nfunction workflowMetadata(record) {\n\treturn {\n\t\tname: record.name ?? null,\n\t\tdescription: record.description ?? null\n\t};\n}\nasync function syncWorkflowRegistry(records) {\n\tconst now = /* @__PURE__ */ new Date();\n\tconst slugs = records.map((record) => record.slug);\n\tconst bySlug = /* @__PURE__ */ new Map();\n\tfor (const record of records) {\n\t\tconst existing = await selectWorkflowBySlug(record.slug);\n\t\tif (existing) {\n\t\t\tawait updateWorkflowById(existing.id, {\n\t\t\t\tmoduleFile: record.moduleFile,\n\t\t\t\tsubscribable: record.subscribable,\n\t\t\t\t...workflowMetadata(record),\n\t\t\t\tupdatedAt: now,\n\t\t\t\tdeletedAt: null\n\t\t\t});\n\t\t\tbySlug.set(record.slug, {\n\t\t\t\tid: existing.id,\n\t\t\t\tslug: record.slug,\n\t\t\t\tsubscribable: record.subscribable\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst id = crypto.randomUUID();\n\t\tawait insertWorkflow({\n\t\t\tid,\n\t\t\tslug: record.slug,\n\t\t\tmoduleFile: record.moduleFile,\n\t\t\tsubscribable: record.subscribable,\n\t\t\t...workflowMetadata(record),\n\t\t\tregisteredAt: now,\n\t\t\tupdatedAt: now,\n\t\t\tdeletedAt: null\n\t\t});\n\t\tbySlug.set(record.slug, {\n\t\t\tid,\n\t\t\tslug: record.slug,\n\t\t\tsubscribable: record.subscribable\n\t\t});\n\t}\n\tif (slugs.length === 0) await softDeleteAllWorkflows(now);\n\telse await softDeleteWorkflowsNotInSlugs(slugs, now);\n\treturn bySlug;\n}\n//#endregion\n//#region src/workflows/credentials.ts\nasync function getWorkflowSubscription(subscriptionId) {\n\tconst row = await selectWorkflowSubscriptionById(subscriptionId);\n\tif (!row) return;\n\treturn {\n\t\tid: row.id,\n\t\tworkflowSlug: row.workflowSlug,\n\t\tuserId: row.userId,\n\t\tenabled: Boolean(row.enabled)\n\t};\n}\nasync function listCredentialInstancesForAssignment(options) {\n\tconst tenantScopeId = getServerTenantScopeId();\n\tconst projectId = getProjectScopeId();\n\tconst rows = [];\n\tconst appendScope = async (scopeType, scopeId) => {\n\t\trows.push(...await listCredentialInstancesByScope({\n\t\t\t...options.appSlug ? { appSlug: options.appSlug } : {},\n\t\t\tscopeType,\n\t\t\tscopeId\n\t\t}));\n\t};\n\tawait appendScope(\"organization\", tenantScopeId);\n\tawait appendScope(\"project\", projectId);\n\tif (options.userId) await appendScope(\"user\", options.userId);\n\treturn rows;\n}\n//#endregion\n//#region src/workflows/event-log.ts\nfunction createDatabaseEventLog() {\n\treturn {\n\t\tappend(event) {\n\t\t\treturn appendWorkflowEvent(event);\n\t\t},\n\t\tasync listReplay(runId) {\n\t\t\treturn (await listReplayEvents(runId)).map((row) => ({\n\t\t\t\tid: row.id,\n\t\t\t\trunId: row.runId,\n\t\t\t\tseq: row.seq,\n\t\t\t\ttype: row.type,\n\t\t\t\tcorrelationId: row.correlationId,\n\t\t\t\tdata: row.data\n\t\t\t}));\n\t\t}\n\t};\n}\n//#endregion\n//#region src/workflows/hook-store.ts\nfunction createDatabaseHookStore() {\n\treturn {\n\t\tcreate(values) {\n\t\t\treturn insertWorkflowHook(values);\n\t\t},\n\t\tasync getByToken(token) {\n\t\t\tconst row = await selectWorkflowHookByToken(token);\n\t\t\tif (!row) return;\n\t\t\treturn {\n\t\t\t\thookId: row.hookId,\n\t\t\t\trunId: row.runId,\n\t\t\t\ttoken: row.token,\n\t\t\t\tcorrelationId: row.correlationId,\n\t\t\t\tstatus: row.status,\n\t\t\t\tpayload: row.payload\n\t\t\t};\n\t\t},\n\t\tmarkResumed(hookId, payload) {\n\t\t\treturn markWorkflowHookResumed(hookId, payload);\n\t\t}\n\t};\n}\n//#endregion\n//#region src/triggers/run-api.ts\nasync function listTriggerRunsPaginated(options) {\n\tconst attachment = await selectTriggerAttachmentBySlug(options.attachmentSlug);\n\tif (!attachment) return null;\n\tconst result = await listTriggerRunRowsPaginated({\n\t\ttriggerIds: [attachment.triggerId],\n\t\tlimit: options.limit,\n\t\tcursor: options.cursor,\n\t\ttriggerType: options.triggerType\n\t});\n\tconst triggerRunIds = result.items.map((item) => item.id);\n\tif (triggerRunIds.length === 0) return result;\n\tconst [sessionsByTriggerRunId, agents] = await Promise.all([listAgentSessionsBySourceIds({\n\t\tsourceKind: \"trigger\",\n\t\tsourceIds: triggerRunIds\n\t}), listActiveAgents()]);\n\tconst slugByAgentId = new Map(agents.map((agent) => [agent.id, agent.slug]));\n\treturn {\n\t\t...result,\n\t\titems: result.items.map((item) => {\n\t\t\tconst sessions = sessionsByTriggerRunId.get(item.id) ?? [];\n\t\t\tif (sessions.length === 0) return item;\n\t\t\treturn {\n\t\t\t\t...item,\n\t\t\t\tagentSessions: sessions.map((session) => ({\n\t\t\t\t\tid: session.id,\n\t\t\t\t\tagentSlug: slugByAgentId.get(session.agentId) ?? session.agentId\n\t\t\t\t}))\n\t\t\t};\n\t\t})\n\t};\n}\nasync function buildTriggerRunDetail(options) {\n\tconst attachment = await selectTriggerAttachmentBySlug(options.attachmentSlug);\n\tif (!attachment) return null;\n\tconst row = await selectTriggerRunForTrigger(attachment.triggerId, options.runId);\n\tif (!row) return null;\n\tconst includeWorkflows = options.include.includes(\"workflows\");\n\tconst includeAgents = options.include.includes(\"agents\");\n\tconst includeTrace = options.include.includes(\"trace\");\n\tconst workflowRuns = includeWorkflows ? (await listWorkflowRunsByTriggerRunId(row.id)).map(workflowRunSummaryFromRow) : [];\n\tlet agentSessions = [];\n\tif (includeAgents) {\n\t\tconst sessions = (await listAgentSessionsBySourceIds({\n\t\t\tsourceKind: \"trigger\",\n\t\t\tsourceIds: [row.id]\n\t\t})).get(row.id) ?? [];\n\t\tif (sessions.length > 0) {\n\t\t\tconst agents = await listActiveAgents();\n\t\t\tconst slugByAgentId = new Map(agents.map((agent) => [agent.id, agent.slug]));\n\t\t\tagentSessions = sessions.map((session) => ({\n\t\t\t\tid: session.id,\n\t\t\t\tagentSlug: slugByAgentId.get(session.agentId) ?? session.agentId\n\t\t\t}));\n\t\t}\n\t}\n\tlet trace = null;\n\tif (includeTrace) {\n\t\tconst traceData = await getTraceForTriggerRun(row.id);\n\t\ttrace = traceData ? traceResponseToJson(traceData) : null;\n\t}\n\treturn {\n\t\trun: triggerRunRecordFromRow(row, attachment.slug),\n\t\tworkflowRuns,\n\t\tagentSessions,\n\t\ttrace\n\t};\n}\n//#endregion\n//#region src/credentials/crypto.ts\nconst ALGORITHM = \"aes-256-gcm\";\nconst IV_LENGTH = 12;\nfunction resolveEncryptionKey() {\n\tconst secret = process.env.CREDENTIALS_ENCRYPTION_KEY?.trim();\n\tif (!secret) throw new Error(\"CREDENTIALS_ENCRYPTION_KEY is required\");\n\treturn createHash(\"sha256\").update(secret).digest();\n}\nfunction encryptCredentialPayload(plaintext) {\n\tconst iv = randomBytes(IV_LENGTH);\n\tconst cipher = createCipheriv(ALGORITHM, resolveEncryptionKey(), iv);\n\tconst encrypted = Buffer.concat([cipher.update(plaintext, \"utf8\"), cipher.final()]);\n\tconst tag = cipher.getAuthTag();\n\treturn Buffer.concat([\n\t\tiv,\n\t\ttag,\n\t\tencrypted\n\t]).toString(\"base64\");\n}\nfunction decryptCredentialPayload(ciphertext) {\n\tconst buffer = Buffer.from(ciphertext, \"base64\");\n\tconst iv = buffer.subarray(0, IV_LENGTH);\n\tconst tag = buffer.subarray(IV_LENGTH, 28);\n\tconst encrypted = buffer.subarray(28);\n\tconst decipher = createDecipheriv(ALGORITHM, resolveEncryptionKey(), iv);\n\tdecipher.setAuthTag(tag);\n\treturn Buffer.concat([decipher.update(encrypted), decipher.final()]).toString(\"utf8\");\n}\n//#endregion\n//#region src/credentials/set-instance-value.ts\nasync function setCredentialInstanceValue(options) {\n\tconst now = /* @__PURE__ */ new Date();\n\tconst siblings = await selectCredentialInstancesForScope(options.appSlug, options.scopeType, options.scopeId);\n\tconst isDefault = options.isDefault ?? siblings.length === 0;\n\tconst name = options.name ?? options.label ?? null;\n\tconst slug = options.slug ?? deriveCredentialInstanceSlug({\n\t\tappSlug: options.appSlug,\n\t\tname,\n\t\ttakenSlugs: siblings.map((row) => row.slug)\n\t});\n\tif (isDefault) await clearCredentialInstanceDefaults({\n\t\tappSlug: options.appSlug,\n\t\tscopeType: options.scopeType,\n\t\tscopeId: options.scopeId,\n\t\texceptId: options.id\n\t});\n\tawait upsertCredentialInstance({\n\t\tid: options.id,\n\t\tappSlug: options.appSlug,\n\t\tslug,\n\t\tname,\n\t\tscopeType: options.scopeType,\n\t\tscopeId: options.scopeId,\n\t\tlabel: name,\n\t\tisDefault,\n\t\tauthKind: \"api_key\",\n\t\tciphertext: encryptCredentialPayload(JSON.stringify(options.value)),\n\t\tconnectionId: null,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t});\n}\n//#endregion\n//#region src/oauth/credential-instance.ts\nfunction resolveOAuthInstanceLabel(options) {\n\tconst appName = displayCredentialAppName(options.credentialKey);\n\treturn resolveUniqueCredentialInstanceLabel({\n\t\tbaseLabel: options.userLabel?.trim() || buildCredentialInstanceLabel({\n\t\t\tscopeType: options.scopeType,\n\t\t\tappName,\n\t\t\tprojectName: options.projectName\n\t\t}),\n\t\ttakenLabels: options.rows.filter((row) => !(row.authKind === \"oauth_managed\" && row.connectionId === options.connectionId)).map((row) => row.label),\n\t\tdisambiguator: options.accountLabel?.trim() || options.externalId\n\t});\n}\nasync function reconnectOAuthCredentialInstance(options) {\n\tconst existing = await selectCredentialInstanceById(options.credentialInstanceId);\n\tif (!existing || existing.appSlug !== options.credentialKey || existing.authKind !== \"oauth_managed\") throw new Error(\"Credential not found\");\n\tconst now = /* @__PURE__ */ new Date();\n\tawait upsertCredentialInstance({\n\t\tid: existing.id,\n\t\tappSlug: existing.appSlug,\n\t\tslug: existing.slug,\n\t\tname: existing.name,\n\t\tscopeType: existing.scopeType,\n\t\tscopeId: existing.scopeId,\n\t\tlabel: existing.label,\n\t\tisDefault: Boolean(existing.isDefault),\n\t\tauthKind: \"oauth_managed\",\n\t\tciphertext: null,\n\t\tconnectionId: options.connectionId,\n\t\tcreatedAt: existing.createdAt,\n\t\tupdatedAt: now\n\t});\n}\nasync function ensureOAuthInstanceForScope(options) {\n\tconst rows = await selectCredentialInstancesForScope(options.credentialKey, options.scopeType, options.scopeId);\n\tconst oauthRow = rows.find((row) => row.authKind === \"oauth_managed\" && row.connectionId === options.connectionId);\n\tconst now = /* @__PURE__ */ new Date();\n\tif (oauthRow) {\n\t\tconst name = oauthRow.name ?? oauthRow.label ?? resolveOAuthInstanceLabel({\n\t\t\trows,\n\t\t\tconnectionId: options.connectionId,\n\t\t\tcredentialKey: options.credentialKey,\n\t\t\tscopeType: options.scopeType,\n\t\t\tprojectName: options.projectName,\n\t\t\taccountLabel: options.accountLabel,\n\t\t\texternalId: options.externalId,\n\t\t\tuserLabel: options.userLabel\n\t\t});\n\t\tawait upsertCredentialInstance({\n\t\t\tid: oauthRow.id,\n\t\t\tappSlug: options.credentialKey,\n\t\t\tslug: oauthRow.slug,\n\t\t\tname,\n\t\t\tscopeType: options.scopeType,\n\t\t\tscopeId: options.scopeId,\n\t\t\tlabel: name,\n\t\t\tisDefault: Boolean(oauthRow.isDefault),\n\t\t\tauthKind: \"oauth_managed\",\n\t\t\tciphertext: null,\n\t\t\tconnectionId: options.connectionId,\n\t\t\tcreatedAt: oauthRow.createdAt,\n\t\t\tupdatedAt: now\n\t\t});\n\t\treturn;\n\t}\n\tconst name = resolveOAuthInstanceLabel({\n\t\trows,\n\t\tconnectionId: options.connectionId,\n\t\tcredentialKey: options.credentialKey,\n\t\tscopeType: options.scopeType,\n\t\tprojectName: options.projectName,\n\t\taccountLabel: options.accountLabel,\n\t\texternalId: options.externalId,\n\t\tuserLabel: options.userLabel\n\t});\n\tconst slug = deriveCredentialInstanceSlug({\n\t\tappSlug: options.credentialKey,\n\t\tname,\n\t\ttakenSlugs: rows.map((row) => row.slug)\n\t});\n\tawait upsertCredentialInstance({\n\t\tid: crypto.randomUUID(),\n\t\tappSlug: options.credentialKey,\n\t\tslug,\n\t\tname,\n\t\tscopeType: options.scopeType,\n\t\tscopeId: options.scopeId,\n\t\tlabel: name,\n\t\tisDefault: rows.length === 0,\n\t\tauthKind: \"oauth_managed\",\n\t\tciphertext: null,\n\t\tconnectionId: options.connectionId,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t});\n}\n/**\n* Materialize `oauth_managed` credential instances for a connection. Without explicit targets\n* (CLI `keystroke connect`, local server) this keeps the historical behavior of a single\n* org-scoped instance; with targets it fans out one instance per selected scope.\n*\n* Within each scope, instances are keyed by connectionId — the same installation upserts in\n* place; a different external account creates a new labeled row (one default per scope).\n*/\nasync function ensureOAuthCredentialInstance(options) {\n\tconst { credentialKey, connectionId, accountLabel, externalId, userLabel, targets, credentialInstanceId } = options;\n\tif (credentialInstanceId) {\n\t\tconst existing = await selectCredentialInstanceById(credentialInstanceId);\n\t\tif (!existing) throw new Error(\"Credential not found\");\n\t\tconst reconnect = () => reconnectOAuthCredentialInstance({\n\t\t\tcredentialInstanceId,\n\t\t\tcredentialKey,\n\t\t\tconnectionId\n\t\t});\n\t\tif (existing.scopeType === \"project\" && existing.scopeId) {\n\t\t\tawait runWithProjectScope(existing.scopeId, reconnect);\n\t\t\treturn;\n\t\t}\n\t\tawait reconnect();\n\t\treturn;\n\t}\n\tconst hasTargets = Boolean(targets && ((targets.projectIds?.length ?? 0) > 0 || targets.organization || targets.userId));\n\tconst scopeOptions = {\n\t\tcredentialKey,\n\t\tconnectionId,\n\t\taccountLabel,\n\t\texternalId,\n\t\tuserLabel\n\t};\n\tif (!hasTargets || targets?.organization) await ensureOAuthInstanceForScope({\n\t\t...scopeOptions,\n\t\tscopeType: \"organization\",\n\t\tscopeId: getServerTenantScopeId()\n\t});\n\tfor (const projectId of targets?.projectIds ?? []) await runWithProjectScope(projectId, () => ensureOAuthInstanceForScope({\n\t\t...scopeOptions,\n\t\tscopeType: \"project\",\n\t\tscopeId: projectId,\n\t\tprojectName: targets?.projectNamesById?.[projectId]\n\t}));\n\tif (targets?.userId) await ensureOAuthInstanceForScope({\n\t\t...scopeOptions,\n\t\tscopeType: \"user\",\n\t\tscopeId: targets.userId\n\t});\n}\n//#endregion\n//#region src/oauth/keystroke-credential-instance.ts\nfunction resolveKeystrokeInstanceLabel(options) {\n\tconst appName = displayCredentialAppName(options.credentialKey);\n\treturn resolveUniqueCredentialInstanceLabel({\n\t\tbaseLabel: options.accountLabel?.trim() || buildCredentialInstanceLabel({\n\t\t\tscopeType: options.scopeType,\n\t\t\tappName,\n\t\t\tprojectName: options.projectName\n\t\t}),\n\t\ttakenLabels: options.rows.filter((row) => !(row.authKind === \"keystroke\" && row.connectionId === options.connectionId)).map((row) => row.label)\n\t});\n}\nasync function reconnectKeystrokeCredentialInstance(options) {\n\tconst existing = await selectCredentialInstanceById(options.credentialInstanceId);\n\tif (!existing || existing.appSlug !== options.credentialKey || existing.authKind !== \"keystroke\") throw new Error(\"Credential not found\");\n\tconst now = /* @__PURE__ */ new Date();\n\tawait upsertCredentialInstance({\n\t\tid: existing.id,\n\t\tappSlug: existing.appSlug,\n\t\tslug: existing.slug,\n\t\tname: existing.name,\n\t\tscopeType: existing.scopeType,\n\t\tscopeId: existing.scopeId,\n\t\tlabel: existing.label,\n\t\tisDefault: Boolean(existing.isDefault),\n\t\tauthKind: \"keystroke\",\n\t\tciphertext: null,\n\t\tconnectionId: options.connectionId,\n\t\tsharedConnectionId: options.sharedConnectionId,\n\t\tgrantedScopes: options.grantedScopes ?? existing.grantedScopes ?? null,\n\t\tcreatedAt: existing.createdAt,\n\t\tupdatedAt: now\n\t});\n}\nasync function ensureKeystrokeInstanceForScope(options) {\n\tconst rows = await selectCredentialInstancesForScope(options.credentialKey, options.scopeType, options.scopeId);\n\tconst existingByConnection = rows.find((row) => row.authKind === \"keystroke\" && row.connectionId === options.connectionId);\n\tconst now = /* @__PURE__ */ new Date();\n\tconst name = existingByConnection?.name ?? existingByConnection?.label ?? resolveKeystrokeInstanceLabel({\n\t\trows,\n\t\tconnectionId: options.connectionId,\n\t\tcredentialKey: options.credentialKey,\n\t\tscopeType: options.scopeType,\n\t\tprojectName: options.projectName,\n\t\taccountLabel: options.accountLabel\n\t});\n\tconst existing = existingByConnection;\n\tconst slug = existing?.slug ?? deriveCredentialInstanceSlug({\n\t\tappSlug: options.credentialKey,\n\t\tname,\n\t\ttakenSlugs: rows.map((row) => row.slug)\n\t});\n\tawait upsertCredentialInstance({\n\t\tid: existing?.id ?? crypto.randomUUID(),\n\t\tappSlug: options.credentialKey,\n\t\tslug,\n\t\tname,\n\t\tscopeType: options.scopeType,\n\t\tscopeId: options.scopeId,\n\t\tlabel: name,\n\t\tisDefault: existing ? Boolean(existing.isDefault) : rows.length === 0,\n\t\tauthKind: \"keystroke\",\n\t\tciphertext: null,\n\t\tconnectionId: options.connectionId,\n\t\tsharedConnectionId: options.sharedConnectionId,\n\t\tgrantedScopes: options.grantedScopes ?? existing?.grantedScopes ?? null,\n\t\tcreatedAt: existing?.createdAt ?? now,\n\t\tupdatedAt: now\n\t});\n}\nasync function ensureKeystrokeCredentialInstance(options) {\n\tif (options.credentialInstanceId) {\n\t\tconst existing = await selectCredentialInstanceById(options.credentialInstanceId);\n\t\tif (!existing) throw new Error(\"Credential not found\");\n\t\tconst reconnect = () => reconnectKeystrokeCredentialInstance({\n\t\t\tcredentialInstanceId: options.credentialInstanceId,\n\t\t\tcredentialKey: options.credentialKey,\n\t\t\tconnectionId: options.connectionId,\n\t\t\tsharedConnectionId: options.sharedConnectionId,\n\t\t\tgrantedScopes: options.grantedScopes\n\t\t});\n\t\tif (existing.scopeType === \"project\" && existing.scopeId) {\n\t\t\tawait runWithProjectScope(existing.scopeId, reconnect);\n\t\t\treturn;\n\t\t}\n\t\tawait reconnect();\n\t\treturn;\n\t}\n\tconst { scopeType, scopeId, ...scopeOptions } = options;\n\tif (scopeType === \"project\") {\n\t\tawait runWithProjectScope(scopeId, () => ensureKeystrokeInstanceForScope({\n\t\t\t...scopeOptions,\n\t\t\tscopeType,\n\t\t\tscopeId\n\t\t}));\n\t\treturn;\n\t}\n\tawait ensureKeystrokeInstanceForScope({\n\t\t...scopeOptions,\n\t\tscopeType,\n\t\tscopeId\n\t});\n}\n//#endregion\n//#region src/scheduler/jobs.ts\nconst DEFAULT_MAX_ATTEMPTS = 3;\nasync function enqueueJob(input) {\n\tconst id = crypto.randomUUID();\n\tawait insertJob({\n\t\tid,\n\t\tkind: input.kind,\n\t\ttargetId: input.targetId,\n\t\trunId: input.runId,\n\t\ttrigger: input.trigger,\n\t\tpayload: input.payload ?? null,\n\t\tstatus: \"pending\",\n\t\tscheduledAt: input.scheduledAt ?? /* @__PURE__ */ new Date(),\n\t\tattempt: input.attempt ?? 1,\n\t\tmaxAttempts: input.maxAttempts ?? DEFAULT_MAX_ATTEMPTS,\n\t\tleasedBy: null,\n\t\tleaseExpiresAt: null,\n\t\tcompletedAt: null,\n\t\terror: null\n\t});\n\treturn id;\n}\nasync function claimNextJob(workerId) {\n\tconst row = await claimNextJobRow(workerId);\n\tif (!row) return;\n\tawait markJobRunning(row.id);\n\treturn {\n\t\tid: row.id,\n\t\tkind: row.kind,\n\t\ttargetId: row.targetId,\n\t\trunId: row.runId,\n\t\ttrigger: row.trigger,\n\t\tpayload: row.payload ?? {},\n\t\tattempt: row.attempt,\n\t\tmaxAttempts: row.maxAttempts,\n\t\tscheduledAt: row.scheduledAt\n\t};\n}\nasync function markJobComplete(jobId) {\n\tawait completeJobRow(jobId, /* @__PURE__ */ new Date());\n}\nasync function markJobFailed(jobId, error) {\n\tawait failJobRow(jobId, error instanceof Error ? {\n\t\tname: error.name,\n\t\tmessage: error.message\n\t} : { message: String(error) }, /* @__PURE__ */ new Date());\n}\nasync function scheduleJobRetry(jobId, attempt, delayMs) {\n\tawait resetJobForRetry(jobId, new Date(Date.now() + delayMs), attempt);\n}\nasync function getJobByRunId(runId) {\n\tconst row = await selectJobByRunId(runId);\n\tif (!row) return;\n\treturn {\n\t\tid: row.id,\n\t\tkind: row.kind,\n\t\ttargetId: row.targetId,\n\t\trunId: row.runId,\n\t\tstatus: row.status,\n\t\ttrigger: row.trigger,\n\t\tpayload: row.payload ?? {},\n\t\tattempt: row.attempt,\n\t\tmaxAttempts: row.maxAttempts,\n\t\tscheduledAt: row.scheduledAt,\n\t\terror: row.error ?? null\n\t};\n}\n//#endregion\nexport { DEFAULT_DATABASE_URL, DEFAULT_PROJECT_ID, EPHEMERAL_TRIGGER_MODULE_FILE, GatewayChannelConflictError, MESSAGE_EVENT_TYPE, adaptPgMigrationsForSearchPath, addAgentSessionDuration, appendEvent, appendSearchPathToUrl, buildAgentSessionChatState, buildAgentSessionDetail, buildHistoryAgentSessionDetail, buildHistoryWorkflowRunDetail, buildPostgresUrl, buildTriggerRunDetail, buildWorkflowRunDetail, cancelAgentSession, cancelWorkflowRun, claimDueTriggers, claimDueTriggersForOrg, claimNextJob, clearAgentSessionCancellation, clearCredentialInstanceDefaults, clearLiveMessage, closeAllProjectDatabasePools, closeDatabase, completeWorkflowRun, countMessageEvents, createAgentAttachmentExecution, createAttachmentExecution, createConnection, createDatabaseEventLog, createDatabaseHookStore, createDatabaseTracingSink, createPendingAttachmentExecution, createPendingWorkflowRun, createPgConnection, createPostgresCancelChannel, createSession, createSqliteConnection, createWorkflowRun, decryptCredentialPayload, deleteCredentialAssignmentById, deleteCredentialInstanceById, deleteEphemeralTrigger, deleteWorkflowSubscriptionById, disableAllTriggerSchedules, disableTriggerSchedulesNotInSlugs, encryptCredentialPayload, enqueueJob, ensureKeystrokeCredentialInstance, ensureOAuthCredentialInstance, failAgentSession, failWorkflowRun, finalizeCanceledWorkflowRun, findHistoryRunCore, gatewayAttachmentKeyForChannel, getActiveGatewayAttachmentByChannel, getActiveOrgGatewayAttachmentByChannel, getActiveOrgGatewayAttachmentByTeamAndChannel, getAgentByRoute, getBoundProjectScopeId, getDatabaseHandle, getGatewayAttachmentBySlug, getJobByRunId, getOrCreateGatewayThreadSession, getProjectScopeId, getServerTenantScopeId, getSession, getSessionLiveMessage, getTraceForAgentSession, getTraceForTriggerRun, getTraceForWorkflowRun, getTriggerAttachmentBySlug, getTriggerRunForAgentSession, getWorkflowSubscription, getWorkspaceTrigger, inferDialect, initDatabase, insertWorkflowSubscription, isDatabaseInitialized, isEphemeralTriggerActive, listActiveAgents, listActiveGatewayAttachments, listActiveGatewayAttachmentsByAgentSlug, listActiveGatewayAttachmentsByPlatform, listActiveOrgGatewayBindingsByPlatform, listActiveSkills, listActiveTriggerAttachments, listActiveWorkflows, listAgentSessionsPaginated, listAgentTriggers, listAllCredentialInstances, listAttachmentsByTriggerIds, listCredentialAssignmentsByTarget, listCredentialInstancesByConnectionId, listCredentialInstancesByScope, listCredentialInstancesForAssignment, listDistinctAssignmentConsumerIds, listEnabledScheduledTriggers, listEnabledWorkflowSubscriptionsByWorkflowSlug, listHistoryRuns, listMessageEvents, listRecentResourceActivity, listRecentWorkflowStepConsumers, listSessionEvents, listStepCompletedEvents, listTriggerRunsPaginated, listTriggersByIds, listWorkflowRunsByWorkflowSlug, listWorkflowRunsPaginated, listWorkflowSubscriptionsByWorkflowSlug, listWorkspaceTriggerRunRows, listWorkspaceTriggers, loadMigrations, markAttachmentExecutionRunning, markJobComplete, markJobFailed, markWorkflowRunRunning, markWorkflowRunSleeping, markWorkflowRunWaitingHook, migratePgDatabase, nextSeq, normalizeStoredTriggerSource, parsePostgresUrl, primarySearchPathSchema, qualifyConnectionUser, recordEphemeralTriggerExecution, recordLlmUsageFromAssistantMessage, recordTriggerFire, recordWorkflowLlmUsage, requeueExpiredLeases, resolveAgentProjectId, resolveDatabaseUrlFromEnv, resolveMigrationsFolder, resolveMigrationsSchema, resolvePostgresConfigFromEnv, resolvePostgresUrlFromEnv, resolveProjectDatabaseUrlFromEnv, resolveRunSourceFromTraceContext, resolveSearchPath, resolveSqlitePath, resolveTriggerAssignments, resolveWorkflowRunProjectId, runMigrations, runSource, runWithProjectDatabase, runWithProjectScope, runWithTenantScope, scheduleJobRetry, selectActiveAgentById, selectActiveAgentsByIds, selectActiveEphemeralCronAttachmentSlugs, selectActiveEphemeralScheduledAttachmentSlugs, selectActiveEphemeralScheduledTriggerSlugs, selectActiveSkillById, selectActiveSkillsByIds, selectActiveWorkflowById, selectActiveWorkflowBySlug, selectActiveWorkflowsByIds, selectAgentBySlug, selectAgentLastRunAtByIds, selectAgentSessionById, selectCredentialAssignmentById, selectCredentialInstanceById, selectCredentialInstancesForScope, selectEphemeralTriggerAttachments, selectEphemeralTriggerAttachmentsByAgentSlug, selectGatewayThreadSessionByThreadId, selectProjectResourceCounts, selectTriggerAttachmentsByAgentSlug, selectTriggerById, selectTriggerBySlug, selectWebhookTriggerAttachments, selectWebhookTriggers, selectWorkflowLastRunAtByIds, selectWorkflowRunById, selectWorkflowRunForWorkflow, selectWorkflowSubscriptionById, selectWorkflowSubscriptionByWorkflowAndUser, setCredentialInstanceValue, setSessionLiveMessage, setSessionTitle, setTriggerOverviewGenerating, softDeleteGatewayAttachmentByChannel, softDeleteGatewayAttachmentsForAgentPlatformTeam, sourceFromSpan, storedTriggerSourceFromRow, storedTriggerSourceFromTrigger, storedTriggerSourceSlug, syncAgentRegistry, syncSkillRegistry, syncTriggerAttachmentRegistry, syncWorkflowRegistry, touchCredentialInstanceLastUsed, touchResourceActivity, touchSession, triggerScheduleFromSource, triggerSourceGroupKeyFromSource, triggerStatusFromRow, updateTriggerOverview, updateWorkflowSubscriptionById, upsertCredentialAssignment, upsertCredentialInstance, upsertEphemeralTrigger, upsertGatewayAttachmentByChannel, upsertTriggerScheduleFields };\n\n//# sourceMappingURL=index.mjs.map","import { boolean, index, integer, jsonb, pgTable, text, timestamp } from \"drizzle-orm/pg-core\";\nimport { index as index$1, integer as integer$1, sqliteTable, text as text$1 } from \"drizzle-orm/sqlite-core\";\n//#region src/client/context.ts\nlet handle;\nfunction isDatabaseInitialized() {\n\treturn handle !== void 0;\n}\nfunction getDatabaseHandle() {\n\tif (!handle) throw new Error(\"Database not initialized. Call initDatabase() before getDb().\");\n\treturn handle;\n}\nfunction setDatabaseHandle(next) {\n\thandle = next;\n}\nfunction getDbFromContext() {\n\treturn getDatabaseHandle().db;\n}\n//#endregion\n//#region src/schema/tables/users.ts\nconst users = pgTable(\"users\", {\n\tid: text(\"id\").primaryKey(),\n\tname: text(\"name\").notNull(),\n\temail: text(\"email\").notNull().unique(),\n\temailVerified: boolean(\"email_verified\").notNull(),\n\timage: text(\"image\"),\n\tpreferences: jsonb(\"preferences\"),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n});\nconst usersSqlite = sqliteTable(\"users\", {\n\tid: text$1(\"id\").primaryKey(),\n\tname: text$1(\"name\").notNull(),\n\temail: text$1(\"email\").notNull().unique(),\n\temailVerified: integer$1(\"email_verified\", { mode: \"boolean\" }).notNull(),\n\timage: text$1(\"image\"),\n\tpreferences: text$1(\"preferences\", { mode: \"json\" }),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n});\n//#endregion\n//#region src/schema/tables/auth-accounts.ts\nconst authAccounts = pgTable(\"accounts\", {\n\tid: text(\"id\").primaryKey(),\n\taccountId: text(\"account_id\").notNull(),\n\tproviderId: text(\"provider_id\").notNull(),\n\tuserId: text(\"user_id\").notNull().references(() => users.id, { onDelete: \"cascade\" }),\n\taccessToken: text(\"access_token\"),\n\trefreshToken: text(\"refresh_token\"),\n\tidToken: text(\"id_token\"),\n\taccessTokenExpiresAt: timestamp(\"access_token_expires_at\", { withTimezone: true }),\n\trefreshTokenExpiresAt: timestamp(\"refresh_token_expires_at\", { withTimezone: true }),\n\tscope: text(\"scope\"),\n\tpassword: text(\"password\"),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [index(\"account_user_id_idx\").on(table.userId)]);\nconst authAccountsSqlite = sqliteTable(\"accounts\", {\n\tid: text$1(\"id\").primaryKey(),\n\taccountId: text$1(\"account_id\").notNull(),\n\tproviderId: text$1(\"provider_id\").notNull(),\n\tuserId: text$1(\"user_id\").notNull().references(() => usersSqlite.id, { onDelete: \"cascade\" }),\n\taccessToken: text$1(\"access_token\"),\n\trefreshToken: text$1(\"refresh_token\"),\n\tidToken: text$1(\"id_token\"),\n\taccessTokenExpiresAt: integer$1(\"access_token_expires_at\", { mode: \"timestamp_ms\" }),\n\trefreshTokenExpiresAt: integer$1(\"refresh_token_expires_at\", { mode: \"timestamp_ms\" }),\n\tscope: text$1(\"scope\"),\n\tpassword: text$1(\"password\"),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [index$1(\"account_user_id_idx\").on(table.userId)]);\n//#endregion\n//#region src/schema/tables/auth-device-codes.ts\nconst authDeviceCodes = pgTable(\"device_auth_codes\", {\n\tid: text(\"id\").primaryKey(),\n\tdeviceCode: text(\"device_code\").notNull(),\n\tuserCode: text(\"user_code\").notNull(),\n\tuserId: text(\"user_id\"),\n\texpiresAt: timestamp(\"expires_at\", { withTimezone: true }).notNull(),\n\tstatus: text(\"status\").notNull(),\n\tlastPolledAt: timestamp(\"last_polled_at\", { withTimezone: true }),\n\tpollingInterval: integer(\"polling_interval\"),\n\tclientId: text(\"client_id\"),\n\tscope: text(\"scope\")\n});\nconst authDeviceCodesSqlite = sqliteTable(\"device_auth_codes\", {\n\tid: text$1(\"id\").primaryKey(),\n\tdeviceCode: text$1(\"device_code\").notNull(),\n\tuserCode: text$1(\"user_code\").notNull(),\n\tuserId: text$1(\"user_id\"),\n\texpiresAt: integer$1(\"expires_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tstatus: text$1(\"status\").notNull(),\n\tlastPolledAt: integer$1(\"last_polled_at\", { mode: \"timestamp_ms\" }),\n\tpollingInterval: integer$1(\"polling_interval\"),\n\tclientId: text$1(\"client_id\"),\n\tscope: text$1(\"scope\")\n});\n//#endregion\n//#region src/schema/tables/auth-jwks.ts\nconst authJwks = pgTable(\"jwks\", {\n\tid: text(\"id\").primaryKey(),\n\tpublicKey: text(\"public_key\").notNull(),\n\tprivateKey: text(\"private_key\").notNull(),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\texpiresAt: timestamp(\"expires_at\", { withTimezone: true })\n});\nconst authJwksSqlite = sqliteTable(\"jwks\", {\n\tid: text$1(\"id\").primaryKey(),\n\tpublicKey: text$1(\"public_key\").notNull(),\n\tprivateKey: text$1(\"private_key\").notNull(),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\texpiresAt: integer$1(\"expires_at\", { mode: \"timestamp_ms\" })\n});\n//#endregion\n//#region src/schema/tables/auth-sessions.ts\nconst authSessions = pgTable(\"sessions\", {\n\tid: text(\"id\").primaryKey(),\n\texpiresAt: timestamp(\"expires_at\", { withTimezone: true }).notNull(),\n\ttoken: text(\"token\").notNull().unique(),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tipAddress: text(\"ip_address\"),\n\tuserAgent: text(\"user_agent\"),\n\tuserId: text(\"user_id\").notNull().references(() => users.id, { onDelete: \"cascade\" })\n}, (table) => [index(\"session_user_id_idx\").on(table.userId)]);\nconst authSessionsSqlite = sqliteTable(\"sessions\", {\n\tid: text$1(\"id\").primaryKey(),\n\texpiresAt: integer$1(\"expires_at\", { mode: \"timestamp_ms\" }).notNull(),\n\ttoken: text$1(\"token\").notNull().unique(),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tipAddress: text$1(\"ip_address\"),\n\tuserAgent: text$1(\"user_agent\"),\n\tuserId: text$1(\"user_id\").notNull().references(() => usersSqlite.id, { onDelete: \"cascade\" })\n}, (table) => [index$1(\"session_user_id_idx\").on(table.userId)]);\n//#endregion\n//#region src/schema/tables/auth-verifications.ts\nconst authVerifications = pgTable(\"verification\", {\n\tid: text(\"id\").primaryKey(),\n\tidentifier: text(\"identifier\").notNull(),\n\tvalue: text(\"value\").notNull(),\n\texpiresAt: timestamp(\"expires_at\", { withTimezone: true }).notNull(),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [index(\"verification_identifier_idx\").on(table.identifier)]);\nconst authVerificationsSqlite = sqliteTable(\"verification\", {\n\tid: text$1(\"id\").primaryKey(),\n\tidentifier: text$1(\"identifier\").notNull(),\n\tvalue: text$1(\"value\").notNull(),\n\texpiresAt: integer$1(\"expires_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [index$1(\"verification_identifier_idx\").on(table.identifier)]);\n//#endregion\nexport { authJwks as a, authDeviceCodesSqlite as c, users as d, usersSqlite as f, setDatabaseHandle as g, isDatabaseInitialized as h, authSessionsSqlite as i, authAccounts as l, getDbFromContext as m, authVerificationsSqlite as n, authJwksSqlite as o, getDatabaseHandle as p, authSessions as r, authDeviceCodes as s, authVerifications as t, authAccountsSqlite as u };\n\n//# sourceMappingURL=auth-verifications-D-no86bc.mjs.map","import { a as authJwks, c as authDeviceCodesSqlite, d as users, f as usersSqlite, g as setDatabaseHandle, h as isDatabaseInitialized, i as authSessionsSqlite, l as authAccounts, m as getDbFromContext, n as authVerificationsSqlite, o as authJwksSqlite, p as getDatabaseHandle, r as authSessions, s as authDeviceCodes, t as authVerifications, u as authAccountsSqlite } from \"./auth-verifications-D-no86bc.mjs\";\nimport { n as resolvePlatformPostgresConfig, r as DEFAULT_PLATFORM_DATABASE_URL, t as resolvePlatformDatabaseUrl } from \"./database-url-w9bkrlHx.mjs\";\nimport { createRequire } from \"node:module\";\nimport { DEFAULT_PROJECT_ID, adaptPgMigrationsForSearchPath, buildPostgresUrl, decryptCredentialPayload, decryptCredentialPayload as decryptCredentialPayload$1, encryptCredentialPayload, encryptCredentialPayload as encryptCredentialPayload$1, inferDialect, loadMigrations, migratePgDatabase, qualifyConnectionUser, resolveMigrationsSchema, resolveSearchPath, resolveSqlitePath, runWithProjectScope, runWithTenantScope } from \"@keystrokehq/database\";\nimport { boolean, index, integer, jsonb, pgEnum, pgTable, primaryKey, text, timestamp, uniqueIndex } from \"drizzle-orm/pg-core\";\nimport { index as index$1, integer as integer$1, primaryKey as primaryKey$1, sqliteTable, text as text$1, uniqueIndex as uniqueIndex$1 } from \"drizzle-orm/sqlite-core\";\nimport { and, and as and$1, asc, desc, eq, eq as eq$1, gt, inArray, inArray as inArray$1, isNull, isNull as isNull$1, max, ne, or, sql, sql as sql$1 } from \"drizzle-orm\";\nimport { existsSync, mkdirSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport BetterSqlite3 from \"better-sqlite3\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\nimport { fileURLToPath } from \"node:url\";\nimport { migrate } from \"drizzle-orm/better-sqlite3/migrator\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { AppSlugSchema, ClaimableOrganizationSlugSchema, ORGANIZATION_SLUG_TAKEN_MESSAGE, OrganizationSlugSchema, PROJECT_SLUG_TAKEN_MESSAGE, ProjectSlugSchema, RESERVED_ORGANIZATION_SLUGS, normalizeOrganizationSidebarBranding, qualifyOrgSlug, slugifyAppName, slugifyOrganizationName, slugifyProjectName } from \"@keystrokehq/shared\";\nimport { createHash, randomBytes, timingSafeEqual } from \"node:crypto\";\nimport { containerPresignEndpointFromEnv, createContainerPresignStorage, createStorage, orgAgentBucketName } from \"@keystrokehq/storage\";\n//#region \\0rolldown/runtime.js\nvar __defProp = Object.defineProperty;\nvar __exportAll = (all, no_symbols) => {\n\tlet target = {};\n\tfor (var name in all) __defProp(target, name, {\n\t\tget: all[name],\n\t\tenumerable: true\n\t});\n\tif (!no_symbols) __defProp(target, Symbol.toStringTag, { value: \"Module\" });\n\treturn target;\n};\n//#endregion\n//#region src/client/close.ts\nasync function closeDatabase() {\n\tif (!isDatabaseInitialized()) return;\n\tawait getDatabaseHandle().close();\n\tsetDatabaseHandle(void 0);\n}\n//#endregion\n//#region src/connection/pg/driver.ts\nconst require = createRequire(import.meta.url);\n/**\n* Lazily load the native `pg` driver. Keeping it off the static import graph means\n* consumers that only reference platform-database helpers/types never force `pg`\n* into their bundle — it resolves from the runtime image only when a connection is\n* actually opened.\n*/\nfunction loadPg() {\n\treturn require(\"pg\");\n}\n/** Lazily load drizzle's node-postgres adapter — it statically imports `pg`. */\nfunction loadDrizzlePg() {\n\treturn require(\"drizzle-orm/node-postgres\");\n}\n//#endregion\n//#region src/schema/bundle.ts\nfunction buildPgSchema(registry) {\n\treturn Object.fromEntries(Object.entries(registry).map(([name, { pg }]) => [name, pg]));\n}\nfunction buildSqliteSchema(registry) {\n\treturn Object.fromEntries(Object.entries(registry).map(([name, { sqlite }]) => [name, sqlite]));\n}\n//#endregion\n//#region src/schema/tables/api-keys.ts\n/** Better Auth API Key shape (`apikey` model → physical `api_keys`). */\nconst authApiKeys = pgTable(\"api_keys\", {\n\tid: text(\"id\").primaryKey(),\n\tconfigId: text(\"config_id\").notNull().default(\"default\"),\n\tname: text(\"name\"),\n\tstart: text(\"start\"),\n\tprefix: text(\"prefix\"),\n\t/** Hashed secret for verification (Better Auth `key`). */\n\tkey: text(\"key\").notNull(),\n\t/** Encrypted plaintext secret — keystroke extension for re-display. */\n\tkeyCiphertext: text(\"key_ciphertext\"),\n\treferenceId: text(\"reference_id\").notNull(),\n\trefillInterval: integer(\"refill_interval\"),\n\trefillAmount: integer(\"refill_amount\"),\n\tlastRefillAt: timestamp(\"last_refill_at\", { withTimezone: true }),\n\tenabled: boolean(\"enabled\").default(true),\n\trateLimitEnabled: boolean(\"rate_limit_enabled\").default(true),\n\trateLimitTimeWindow: integer(\"rate_limit_time_window\"),\n\trateLimitMax: integer(\"rate_limit_max\"),\n\trequestCount: integer(\"request_count\").default(0),\n\tremaining: integer(\"remaining\"),\n\tlastRequest: timestamp(\"last_request\", { withTimezone: true }),\n\texpiresAt: timestamp(\"expires_at\", { withTimezone: true }),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tpermissions: text(\"permissions\"),\n\tmetadata: text(\"metadata\")\n}, (table) => [\n\tindex(\"api_keys_reference_id_idx\").on(table.referenceId),\n\tindex(\"api_keys_config_id_idx\").on(table.configId),\n\tindex(\"api_keys_key_idx\").on(table.key)\n]);\nconst authApiKeysSqlite = sqliteTable(\"api_keys\", {\n\tid: text$1(\"id\").primaryKey(),\n\tconfigId: text$1(\"config_id\").notNull().default(\"default\"),\n\tname: text$1(\"name\"),\n\tstart: text$1(\"start\"),\n\tprefix: text$1(\"prefix\"),\n\tkey: text$1(\"key\").notNull(),\n\tkeyCiphertext: text$1(\"key_ciphertext\"),\n\treferenceId: text$1(\"reference_id\").notNull(),\n\trefillInterval: integer$1(\"refill_interval\"),\n\trefillAmount: integer$1(\"refill_amount\"),\n\tlastRefillAt: integer$1(\"last_refill_at\", { mode: \"timestamp_ms\" }),\n\tenabled: integer$1(\"enabled\", { mode: \"boolean\" }).default(true),\n\trateLimitEnabled: integer$1(\"rate_limit_enabled\", { mode: \"boolean\" }).default(true),\n\trateLimitTimeWindow: integer$1(\"rate_limit_time_window\"),\n\trateLimitMax: integer$1(\"rate_limit_max\"),\n\trequestCount: integer$1(\"request_count\").default(0),\n\tremaining: integer$1(\"remaining\"),\n\tlastRequest: integer$1(\"last_request\", { mode: \"timestamp_ms\" }),\n\texpiresAt: integer$1(\"expires_at\", { mode: \"timestamp_ms\" }),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tpermissions: text$1(\"permissions\"),\n\tmetadata: text$1(\"metadata\")\n}, (table) => [\n\tindex$1(\"api_keys_reference_id_idx\").on(table.referenceId),\n\tindex$1(\"api_keys_config_id_idx\").on(table.configId),\n\tindex$1(\"api_keys_key_idx\").on(table.key)\n]);\n//#endregion\n//#region src/schema/tables/organizations.ts\nconst organizations = pgTable(\"organizations\", {\n\tid: text(\"id\").primaryKey(),\n\tname: text(\"name\").notNull(),\n\tslug: text(\"slug\").notNull(),\n\tdbSchema: text(\"db_schema\").notNull(),\n\tdbUser: text(\"db_user\").notNull(),\n\tdbPasswordCiphertext: text(\"db_password_ciphertext\").notNull(),\n\thostingAppName: text(\"hosting_app_name\"),\n\truntimeId: text(\"runtime_id\"),\n\tbaseUrl: text(\"base_url\"),\n\tstorageBucket: text(\"storage_bucket\"),\n\tstorageEndpoint: text(\"storage_endpoint\"),\n\tstorageAccessKeyIdCiphertext: text(\"storage_access_key_id_ciphertext\"),\n\tstorageSecretAccessKeyCiphertext: text(\"storage_secret_access_key_ciphertext\"),\n\tstorageRegion: text(\"storage_region\"),\n\tstorageForcePathStyle: boolean(\"storage_force_path_style\"),\n\tcustomLogoEnabled: boolean(\"custom_logo_enabled\").notNull().default(false),\n\tcustomLogoExplicitlyDisabled: boolean(\"custom_logo_explicitly_disabled\").notNull().default(false),\n\tlogoLightUrl: text(\"logo_light_url\"),\n\tlogoDarkUrl: text(\"logo_dark_url\"),\n\tlogoHeightPx: integer(\"logo_height_px\").notNull().default(20),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tverifiedAt: timestamp(\"verified_at\", { withTimezone: true }),\n\tdeletedAt: timestamp(\"deleted_at\", { withTimezone: true })\n}, (table) => [uniqueIndex(\"organizations_slug_unique\").on(table.slug)]);\nconst organizationsSqlite = sqliteTable(\"organizations\", {\n\tid: text$1(\"id\").primaryKey(),\n\tname: text$1(\"name\").notNull(),\n\tslug: text$1(\"slug\").notNull(),\n\tdbSchema: text$1(\"db_schema\").notNull(),\n\tdbUser: text$1(\"db_user\").notNull(),\n\tdbPasswordCiphertext: text$1(\"db_password_ciphertext\").notNull(),\n\thostingAppName: text$1(\"hosting_app_name\"),\n\truntimeId: text$1(\"runtime_id\"),\n\tbaseUrl: text$1(\"base_url\"),\n\tstorageBucket: text$1(\"storage_bucket\"),\n\tstorageEndpoint: text$1(\"storage_endpoint\"),\n\tstorageAccessKeyIdCiphertext: text$1(\"storage_access_key_id_ciphertext\"),\n\tstorageSecretAccessKeyCiphertext: text$1(\"storage_secret_access_key_ciphertext\"),\n\tstorageRegion: text$1(\"storage_region\"),\n\tstorageForcePathStyle: integer$1(\"storage_force_path_style\", { mode: \"boolean\" }),\n\tcustomLogoEnabled: integer$1(\"custom_logo_enabled\", { mode: \"boolean\" }).notNull().default(false),\n\tcustomLogoExplicitlyDisabled: integer$1(\"custom_logo_explicitly_disabled\", { mode: \"boolean\" }).notNull().default(false),\n\tlogoLightUrl: text$1(\"logo_light_url\"),\n\tlogoDarkUrl: text$1(\"logo_dark_url\"),\n\tlogoHeightPx: integer$1(\"logo_height_px\").notNull().default(20),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tverifiedAt: integer$1(\"verified_at\", { mode: \"timestamp_ms\" }),\n\tdeletedAt: integer$1(\"deleted_at\", { mode: \"timestamp_ms\" })\n}, (table) => [uniqueIndex$1(\"organizations_slug_unique\").on(table.slug)]);\n//#endregion\n//#region src/schema/tables/apps.ts\nconst apps = pgTable(\"apps\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").references(() => organizations.id, { onDelete: \"cascade\" }),\n\tslug: text(\"slug\").notNull(),\n\tname: text(\"name\").notNull(),\n\tdescription: text(\"description\").notNull(),\n\tcategory: text(\"category\").notNull(),\n\tlogo: text(\"logo\"),\n\tauthKind: text(\"auth_kind\").$type().notNull(),\n\toauthScopes: jsonb(\"oauth_scopes\").$type().notNull(),\n\tcredentialFields: jsonb(\"credential_fields\").$type().notNull().default({}),\n\tcredentialScheme: text(\"credential_scheme\").$type(),\n\tsource: text(\"source\").$type().notNull(),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [uniqueIndex(\"apps_slug_idx\").on(table.slug), index(\"apps_organization_id_idx\").on(table.organizationId)]);\nconst appsSqlite = sqliteTable(\"apps\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").references(() => organizationsSqlite.id, { onDelete: \"cascade\" }),\n\tslug: text$1(\"slug\").notNull(),\n\tname: text$1(\"name\").notNull(),\n\tdescription: text$1(\"description\").notNull(),\n\tcategory: text$1(\"category\").notNull(),\n\tlogo: text$1(\"logo\"),\n\tauthKind: text$1(\"auth_kind\").$type().notNull(),\n\toauthScopes: text$1(\"oauth_scopes\", { mode: \"json\" }).$type().notNull(),\n\tcredentialFields: text$1(\"credential_fields\", { mode: \"json\" }).$type().notNull().default({}),\n\tcredentialScheme: text$1(\"credential_scheme\").$type(),\n\tsource: text$1(\"source\").$type().notNull(),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [uniqueIndex$1(\"apps_slug_idx\").on(table.slug), index$1(\"apps_organization_id_idx\").on(table.organizationId)]);\n//#endregion\n//#region src/schema/tables/oauth-apps.ts\nconst oauthApps = pgTable(\"oauth_apps\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id, { onDelete: \"cascade\" }),\n\tprovider: text(\"provider\").notNull(),\n\tslug: text(\"slug\").notNull(),\n\ttokenStrategy: text(\"token_strategy\").$type().notNull(),\n\tclientIdCiphertext: text(\"client_id_ciphertext\").notNull(),\n\tclientSecretCiphertext: text(\"client_secret_ciphertext\").notNull(),\n\tsigningSecretCiphertext: text(\"signing_secret_ciphertext\"),\n\tredirectUri: text(\"redirect_uri\"),\n\tmetadata: jsonb(\"metadata\").$type(),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [uniqueIndex(\"oauth_apps_organization_id_slug_idx\").on(table.organizationId, table.slug), index(\"oauth_apps_slug_idx\").on(table.slug)]);\nconst oauthAppsSqlite = sqliteTable(\"oauth_apps\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id, { onDelete: \"cascade\" }),\n\tprovider: text$1(\"provider\").notNull(),\n\tslug: text$1(\"slug\").notNull(),\n\ttokenStrategy: text$1(\"token_strategy\").$type().notNull(),\n\tclientIdCiphertext: text$1(\"client_id_ciphertext\").notNull(),\n\tclientSecretCiphertext: text$1(\"client_secret_ciphertext\").notNull(),\n\tsigningSecretCiphertext: text$1(\"signing_secret_ciphertext\"),\n\tredirectUri: text$1(\"redirect_uri\"),\n\tmetadata: text$1(\"metadata\", { mode: \"json\" }).$type(),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [uniqueIndex$1(\"oauth_apps_organization_id_slug_idx\").on(table.organizationId, table.slug), index$1(\"oauth_apps_slug_idx\").on(table.slug)]);\n//#endregion\n//#region src/schema/tables/oauth-connections.ts\nconst oauthConnections = pgTable(\"oauth_connections\", {\n\tid: text(\"id\").primaryKey(),\n\tappId: text(\"app_id\").notNull().references(() => oauthApps.id, { onDelete: \"cascade\" }),\n\texternalId: text(\"external_id\").notNull(),\n\taccessTokenCiphertext: text(\"access_token_ciphertext\").notNull(),\n\trefreshTokenCiphertext: text(\"refresh_token_ciphertext\"),\n\taccessTokenExpiresAt: timestamp(\"access_token_expires_at\", { withTimezone: true }),\n\tgrantedScopes: jsonb(\"granted_scopes\").$type(),\n\tmetadata: jsonb(\"metadata\").$type(),\n\tconnectedAt: timestamp(\"connected_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [uniqueIndex(\"oauth_connections_app_external_unique\").on(table.appId, table.externalId), index(\"oauth_connections_external_id_idx\").on(table.externalId)]);\nconst oauthConnectionsSqlite = sqliteTable(\"oauth_connections\", {\n\tid: text$1(\"id\").primaryKey(),\n\tappId: text$1(\"app_id\").notNull().references(() => oauthAppsSqlite.id, { onDelete: \"cascade\" }),\n\texternalId: text$1(\"external_id\").notNull(),\n\taccessTokenCiphertext: text$1(\"access_token_ciphertext\").notNull(),\n\trefreshTokenCiphertext: text$1(\"refresh_token_ciphertext\"),\n\taccessTokenExpiresAt: integer$1(\"access_token_expires_at\", { mode: \"timestamp_ms\" }),\n\tgrantedScopes: text$1(\"granted_scopes\", { mode: \"json\" }).$type(),\n\tmetadata: text$1(\"metadata\", { mode: \"json\" }).$type(),\n\tconnectedAt: integer$1(\"connected_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [uniqueIndex$1(\"oauth_connections_app_external_unique\").on(table.appId, table.externalId), index$1(\"oauth_connections_external_id_idx\").on(table.externalId)]);\n//#endregion\n//#region src/schema/tables/organization-users.ts\nconst organizationUserRoles = [\n\t\"owner\",\n\t\"admin\",\n\t\"builder\"\n];\nconst organizationUsers = pgTable(\"organization_users\", {\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id, { onDelete: \"cascade\" }),\n\tuserId: text(\"user_id\").notNull().references(() => users.id, { onDelete: \"cascade\" }),\n\trole: text(\"role\").notNull().$type(),\n\tstatus: text(\"status\").notNull().$type().default(\"active\"),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tdeletedAt: timestamp(\"deleted_at\", { withTimezone: true })\n}, (table) => [primaryKey({ columns: [table.organizationId, table.userId] }), index(\"organization_users_user_id_idx\").on(table.userId)]);\nconst organizationUsersSqlite = sqliteTable(\"organization_users\", {\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id, { onDelete: \"cascade\" }),\n\tuserId: text$1(\"user_id\").notNull().references(() => usersSqlite.id, { onDelete: \"cascade\" }),\n\trole: text$1(\"role\").notNull().$type(),\n\tstatus: text$1(\"status\").notNull().$type().default(\"active\"),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tdeletedAt: integer$1(\"deleted_at\", { mode: \"timestamp_ms\" })\n}, (table) => [primaryKey$1({ columns: [table.organizationId, table.userId] }), index$1(\"organization_users_user_id_idx\").on(table.userId)]);\n//#endregion\n//#region src/schema/tables/organization-invitations.ts\nconst organizationInvitationStatuses = [\n\t\"pending\",\n\t\"accepted\",\n\t\"declined\",\n\t\"revoked\"\n];\nconst organizationInvitations = pgTable(\"organization_invitations\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id, { onDelete: \"cascade\" }),\n\tuserId: text(\"user_id\").notNull().references(() => users.id, { onDelete: \"cascade\" }),\n\temail: text(\"email\").notNull(),\n\trole: text(\"role\").notNull().$type(),\n\tstatus: text(\"status\").notNull().$type(),\n\tinvitedByUserId: text(\"invited_by_user_id\").notNull().references(() => users.id, { onDelete: \"cascade\" }),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\texpiresAt: timestamp(\"expires_at\", { withTimezone: true })\n}, (table) => [\n\tindex(\"organization_invitations_user_id_idx\").on(table.userId),\n\tindex(\"organization_invitations_organization_id_idx\").on(table.organizationId),\n\tuniqueIndex(\"organization_invitations_org_user_pending_unique\").on(table.organizationId, table.userId).where(sql`${table.status} = 'pending'`)\n]);\nconst organizationInvitationsSqlite = sqliteTable(\"organization_invitations\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id, { onDelete: \"cascade\" }),\n\tuserId: text$1(\"user_id\").notNull().references(() => usersSqlite.id, { onDelete: \"cascade\" }),\n\temail: text$1(\"email\").notNull(),\n\trole: text$1(\"role\").notNull().$type(),\n\tstatus: text$1(\"status\").notNull().$type(),\n\tinvitedByUserId: text$1(\"invited_by_user_id\").notNull().references(() => usersSqlite.id, { onDelete: \"cascade\" }),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\texpiresAt: integer$1(\"expires_at\", { mode: \"timestamp_ms\" })\n}, (table) => [\n\tindex$1(\"organization_invitations_user_id_idx\").on(table.userId),\n\tindex$1(\"organization_invitations_organization_id_idx\").on(table.organizationId),\n\tuniqueIndex$1(\"organization_invitations_org_user_pending_unique\").on(table.organizationId, table.userId).where(sql`${table.status} = 'pending'`)\n]);\n//#endregion\n//#region src/schema/tables/projects.ts\nconst projectStatuses = [\n\t\"inactive\",\n\t\"starting\",\n\t\"active\",\n\t\"failed\"\n];\nconst projectStatusEnum = pgEnum(\"project_status\", projectStatuses);\nconst projects = pgTable(\"projects\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id, { onDelete: \"cascade\" }),\n\tname: text(\"name\").notNull(),\n\tslug: text(\"slug\").notNull(),\n\tdescription: text(\"description\"),\n\tdefaultMemberRole: text(\"default_member_role\").notNull().$type().default(\"builder\"),\n\tinvitePermission: text(\"invite_permission\").notNull().$type().default(\"admin\"),\n\tcreatedByUserId: text(\"created_by_user_id\").references(() => users.id, { onDelete: \"set null\" }),\n\tstatus: projectStatusEnum(\"status\").notNull(),\n\tbaseUrl: text(\"base_url\"),\n\truntimeId: text(\"runtime_id\"),\n\tactiveArtifactId: text(\"active_artifact_id\"),\n\tpendingArtifactId: text(\"pending_artifact_id\"),\n\tlastError: text(\"last_error\"),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tdeletedAt: timestamp(\"deleted_at\", { withTimezone: true })\n}, (table) => [index(\"projects_organization_id_idx\").on(table.organizationId), uniqueIndex(\"projects_organization_slug_unique\").on(table.organizationId, table.slug).where(sql`${table.deletedAt} IS NULL`)]);\nconst projectsSqlite = sqliteTable(\"projects\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id, { onDelete: \"cascade\" }),\n\tname: text$1(\"name\").notNull(),\n\tslug: text$1(\"slug\").notNull(),\n\tdescription: text$1(\"description\"),\n\tdefaultMemberRole: text$1(\"default_member_role\").notNull().$type().default(\"builder\"),\n\tinvitePermission: text$1(\"invite_permission\").notNull().$type().default(\"admin\"),\n\tcreatedByUserId: text$1(\"created_by_user_id\").references(() => usersSqlite.id, { onDelete: \"set null\" }),\n\tstatus: text$1(\"status\").$type().notNull(),\n\tbaseUrl: text$1(\"base_url\"),\n\truntimeId: text$1(\"runtime_id\"),\n\tactiveArtifactId: text$1(\"active_artifact_id\"),\n\tpendingArtifactId: text$1(\"pending_artifact_id\"),\n\tlastError: text$1(\"last_error\"),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tdeletedAt: integer$1(\"deleted_at\", { mode: \"timestamp_ms\" })\n}, (table) => [index$1(\"projects_organization_id_idx\").on(table.organizationId), uniqueIndex$1(\"projects_organization_slug_unique\").on(table.organizationId, table.slug).where(sql`${table.deletedAt} IS NULL`)]);\n//#endregion\n//#region src/schema/tables/project-artifacts.ts\nconst projectArtifactStatuses = [\"pending\", \"ready\"];\nconst projectArtifactStatusEnum = pgEnum(\"project_artifact_status\", projectArtifactStatuses);\nconst projectArtifacts = pgTable(\"project_artifacts\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull().references(() => projects.id, { onDelete: \"cascade\" }),\n\tstorageKey: text(\"storage_key\").notNull(),\n\tmanifestJson: jsonb(\"manifest_json\"),\n\tsourceManifestJson: jsonb(\"source_manifest_json\"),\n\tversion: integer(\"version\").notNull(),\n\tcreatedByUserId: text(\"created_by_user_id\").references(() => users.id, { onDelete: \"set null\" }),\n\tstatus: projectArtifactStatusEnum(\"status\").notNull(),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [index(\"project_artifacts_project_id_idx\").on(table.projectId)]);\nconst projectArtifactsSqlite = sqliteTable(\"project_artifacts\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull().references(() => projectsSqlite.id, { onDelete: \"cascade\" }),\n\tstorageKey: text$1(\"storage_key\").notNull(),\n\tmanifestJson: text$1(\"manifest_json\", { mode: \"json\" }),\n\tsourceManifestJson: text$1(\"source_manifest_json\", { mode: \"json\" }),\n\tversion: integer$1(\"version\").notNull(),\n\tcreatedByUserId: text$1(\"created_by_user_id\").references(() => usersSqlite.id, { onDelete: \"set null\" }),\n\tstatus: text$1(\"status\").$type().notNull(),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [index$1(\"project_artifacts_project_id_idx\").on(table.projectId)]);\n//#endregion\n//#region src/schema/tables/project-users.ts\nconst projectUsers = pgTable(\"project_users\", {\n\tprojectId: text(\"project_id\").notNull().references(() => projects.id, { onDelete: \"cascade\" }),\n\tuserId: text(\"user_id\").notNull().references(() => users.id, { onDelete: \"cascade\" }),\n\trole: text(\"role\").notNull().$type(),\n\tstatus: text(\"status\").notNull().$type().default(\"active\"),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tdeletedAt: timestamp(\"deleted_at\", { withTimezone: true })\n}, (table) => [primaryKey({ columns: [table.projectId, table.userId] }), index(\"project_users_user_id_idx\").on(table.userId)]);\nconst projectUsersSqlite = sqliteTable(\"project_users\", {\n\tprojectId: text$1(\"project_id\").notNull().references(() => projectsSqlite.id, { onDelete: \"cascade\" }),\n\tuserId: text$1(\"user_id\").notNull().references(() => usersSqlite.id, { onDelete: \"cascade\" }),\n\trole: text$1(\"role\").notNull().$type(),\n\tstatus: text$1(\"status\").notNull().$type().default(\"active\"),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tdeletedAt: integer$1(\"deleted_at\", { mode: \"timestamp_ms\" })\n}, (table) => [primaryKey$1({ columns: [table.projectId, table.userId] }), index$1(\"project_users_user_id_idx\").on(table.userId)]);\n//#endregion\n//#region src/schema/tables/secret-values.ts\nconst secretValues = pgTable(\"secret_values\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id, { onDelete: \"cascade\" }),\n\trefKind: text(\"ref_kind\").$type().notNull(),\n\trefId: text(\"ref_id\").notNull(),\n\tfield: text(\"field\").$type().notNull(),\n\tciphertext: text(\"ciphertext\").notNull(),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [uniqueIndex(\"secret_values_ref_unique\").on(table.organizationId, table.refKind, table.refId, table.field), index(\"secret_values_ref_idx\").on(table.organizationId, table.refKind, table.refId)]);\nconst secretValuesSqlite = sqliteTable(\"secret_values\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id, { onDelete: \"cascade\" }),\n\trefKind: text$1(\"ref_kind\").$type().notNull(),\n\trefId: text$1(\"ref_id\").notNull(),\n\tfield: text$1(\"field\").$type().notNull(),\n\tciphertext: text$1(\"ciphertext\").notNull(),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [uniqueIndex$1(\"secret_values_ref_unique\").on(table.organizationId, table.refKind, table.refId, table.field), index$1(\"secret_values_ref_idx\").on(table.organizationId, table.refKind, table.refId)]);\n//#endregion\n//#region src/schema/registrations.ts\n/**\n* Platform control-plane tables — Postgres (hosted) or SQLite (local dev).\n*/\nconst tableRegistry = {\n\torganizations: {\n\t\tpg: organizations,\n\t\tsqlite: organizationsSqlite\n\t},\n\torganizationUsers: {\n\t\tpg: organizationUsers,\n\t\tsqlite: organizationUsersSqlite\n\t},\n\torganizationInvitations: {\n\t\tpg: organizationInvitations,\n\t\tsqlite: organizationInvitationsSqlite\n\t},\n\tprojects: {\n\t\tpg: projects,\n\t\tsqlite: projectsSqlite\n\t},\n\tprojectUsers: {\n\t\tpg: projectUsers,\n\t\tsqlite: projectUsersSqlite\n\t},\n\tprojectArtifacts: {\n\t\tpg: projectArtifacts,\n\t\tsqlite: projectArtifactsSqlite\n\t},\n\tusers: {\n\t\tpg: users,\n\t\tsqlite: usersSqlite\n\t},\n\tauthSessions: {\n\t\tpg: authSessions,\n\t\tsqlite: authSessionsSqlite\n\t},\n\tauthAccounts: {\n\t\tpg: authAccounts,\n\t\tsqlite: authAccountsSqlite\n\t},\n\tauthVerifications: {\n\t\tpg: authVerifications,\n\t\tsqlite: authVerificationsSqlite\n\t},\n\tauthDeviceCodes: {\n\t\tpg: authDeviceCodes,\n\t\tsqlite: authDeviceCodesSqlite\n\t},\n\tauthJwks: {\n\t\tpg: authJwks,\n\t\tsqlite: authJwksSqlite\n\t},\n\tauthApiKeys: {\n\t\tpg: authApiKeys,\n\t\tsqlite: authApiKeysSqlite\n\t},\n\tapps: {\n\t\tpg: apps,\n\t\tsqlite: appsSqlite\n\t},\n\toauthApps: {\n\t\tpg: oauthApps,\n\t\tsqlite: oauthAppsSqlite\n\t},\n\toauthConnections: {\n\t\tpg: oauthConnections,\n\t\tsqlite: oauthConnectionsSqlite\n\t},\n\tsecretValues: {\n\t\tpg: secretValues,\n\t\tsqlite: secretValuesSqlite\n\t}\n};\nconst schema = buildPgSchema(tableRegistry);\nbuildSqliteSchema(tableRegistry);\n//#endregion\n//#region src/connection/pg/db.ts\n/** Inferred from `schema` — `getDb()` and query files use this type. */\nfunction createPgDb(pool) {\n\treturn loadDrizzlePg().drizzle(pool, { schema });\n}\n//#endregion\n//#region src/connection/pg/index.ts\nfunction createPgConnection(options) {\n\tconst searchPath = resolveSearchPath(options.url, options.searchPath);\n\tconst { Pool } = loadPg();\n\tconst pool = new Pool({\n\t\tconnectionString: options.url,\n\t\tmax: options.max ?? 10,\n\t\tconnectionTimeoutMillis: 5e3,\n\t\tidleTimeoutMillis: 3e4,\n\t\tkeepAlive: true\n\t});\n\treturn {\n\t\tdialect: \"postgres\",\n\t\tdb: createPgDb(pool),\n\t\tpool,\n\t\tsearchPath,\n\t\tclose: () => pool.end()\n\t};\n}\n//#endregion\n//#region src/connection/sqlite/index.ts\nfunction configureSqlite(client) {\n\tclient.pragma(\"journal_mode = WAL\");\n\tclient.pragma(\"foreign_keys = ON\");\n}\nfunction createSqliteConnection(options) {\n\tconst path = resolveSqlitePath(options.url);\n\tif (path !== \":memory:\") mkdirSync(dirname(path), { recursive: true });\n\tconst client = new BetterSqlite3(path);\n\tconfigureSqlite(client);\n\treturn {\n\t\tdialect: \"sqlite\",\n\t\tdb: drizzle(client, { schema }),\n\t\tclose: () => client.close()\n\t};\n}\n//#endregion\n//#region src/connection/create-connection.ts\nfunction createConnection(options) {\n\tif ((options.dialect ?? inferDialect(options.url)) === \"postgres\") return createPgConnection({\n\t\turl: options.url,\n\t\tmax: options.max,\n\t\tsearchPath: options.searchPath\n\t});\n\treturn createSqliteConnection({ url: options.url });\n}\n//#endregion\n//#region src/migrate/resolve-folder.ts\nfunction resolvePackageRoot() {\n\tlet dir = dirname(fileURLToPath(import.meta.url));\n\tfor (;;) {\n\t\tif (existsSync(join(dir, \"drizzle\", \"pg\", \"meta\", \"_journal.json\"))) return dir;\n\t\tconst parent = dirname(dir);\n\t\tif (parent === dir) break;\n\t\tdir = parent;\n\t}\n\tthrow new Error(\"Could not resolve @keystrokehq/platform-database package root for migrations\");\n}\nfunction resolveMigrationsFolder(dialect, override) {\n\tif (override) return override;\n\ttry {\n\t\treturn join(resolvePackageRoot(), \"drizzle\", dialect);\n\t} catch {\n\t\treturn join(dirname(fileURLToPath(import.meta.url)), \"..\", \"..\", \"drizzle\", dialect);\n\t}\n}\n//#endregion\n//#region src/migrate/migrations.pg.generated.ts\nconst platformPgMigrations = [\n\t{\n\t\t\"sql\": [\n\t\t\t\"CREATE TYPE \\\"public\\\".\\\"project_artifact_status\\\" AS ENUM('pending', 'ready');\",\n\t\t\t\"\\nCREATE TYPE \\\"public\\\".\\\"project_status\\\" AS ENUM('inactive', 'starting', 'active', 'failed');\",\n\t\t\t\"\\nCREATE TABLE \\\"accounts\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"account_id\\\" text NOT NULL,\\n\t\\\"provider_id\\\" text NOT NULL,\\n\t\\\"user_id\\\" text NOT NULL,\\n\t\\\"access_token\\\" text,\\n\t\\\"refresh_token\\\" text,\\n\t\\\"id_token\\\" text,\\n\t\\\"access_token_expires_at\\\" timestamp with time zone,\\n\t\\\"refresh_token_expires_at\\\" timestamp with time zone,\\n\t\\\"scope\\\" text,\\n\t\\\"password\\\" text,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"api_keys\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"config_id\\\" text DEFAULT 'default' NOT NULL,\\n\t\\\"name\\\" text,\\n\t\\\"start\\\" text,\\n\t\\\"prefix\\\" text,\\n\t\\\"key\\\" text NOT NULL,\\n\t\\\"key_ciphertext\\\" text,\\n\t\\\"reference_id\\\" text NOT NULL,\\n\t\\\"refill_interval\\\" integer,\\n\t\\\"refill_amount\\\" integer,\\n\t\\\"last_refill_at\\\" timestamp with time zone,\\n\t\\\"enabled\\\" boolean DEFAULT true,\\n\t\\\"rate_limit_enabled\\\" boolean DEFAULT true,\\n\t\\\"rate_limit_time_window\\\" integer,\\n\t\\\"rate_limit_max\\\" integer,\\n\t\\\"request_count\\\" integer DEFAULT 0,\\n\t\\\"remaining\\\" integer,\\n\t\\\"last_request\\\" timestamp with time zone,\\n\t\\\"expires_at\\\" timestamp with time zone,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"permissions\\\" text,\\n\t\\\"metadata\\\" text\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"device_auth_codes\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"device_code\\\" text NOT NULL,\\n\t\\\"user_code\\\" text NOT NULL,\\n\t\\\"user_id\\\" text,\\n\t\\\"expires_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"status\\\" text NOT NULL,\\n\t\\\"last_polled_at\\\" timestamp with time zone,\\n\t\\\"polling_interval\\\" integer,\\n\t\\\"client_id\\\" text,\\n\t\\\"scope\\\" text\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"jwks\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"public_key\\\" text NOT NULL,\\n\t\\\"private_key\\\" text NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"expires_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"sessions\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"expires_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"token\\\" text NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"ip_address\\\" text,\\n\t\\\"user_agent\\\" text,\\n\t\\\"user_id\\\" text NOT NULL,\\n\tCONSTRAINT \\\"sessions_token_unique\\\" UNIQUE(\\\"token\\\")\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"verification\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"identifier\\\" text NOT NULL,\\n\t\\\"value\\\" text NOT NULL,\\n\t\\\"expires_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"oauth_apps\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text NOT NULL,\\n\t\\\"provider\\\" text NOT NULL,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"token_strategy\\\" text NOT NULL,\\n\t\\\"client_id_ciphertext\\\" text NOT NULL,\\n\t\\\"client_secret_ciphertext\\\" text NOT NULL,\\n\t\\\"signing_secret_ciphertext\\\" text,\\n\t\\\"redirect_uri\\\" text,\\n\t\\\"metadata\\\" jsonb,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"oauth_connections\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"app_id\\\" text NOT NULL,\\n\t\\\"external_id\\\" text NOT NULL,\\n\t\\\"access_token_ciphertext\\\" text NOT NULL,\\n\t\\\"refresh_token_ciphertext\\\" text,\\n\t\\\"access_token_expires_at\\\" timestamp with time zone,\\n\t\\\"granted_scopes\\\" jsonb,\\n\t\\\"metadata\\\" jsonb,\\n\t\\\"connected_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"organization_invitations\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text NOT NULL,\\n\t\\\"user_id\\\" text NOT NULL,\\n\t\\\"email\\\" text NOT NULL,\\n\t\\\"role\\\" text NOT NULL,\\n\t\\\"status\\\" text NOT NULL,\\n\t\\\"invited_by_user_id\\\" text NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"expires_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"organization_users\\\" (\\n\t\\\"organization_id\\\" text NOT NULL,\\n\t\\\"user_id\\\" text NOT NULL,\\n\t\\\"role\\\" text NOT NULL,\\n\t\\\"status\\\" text DEFAULT 'active' NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"deleted_at\\\" timestamp with time zone,\\n\tCONSTRAINT \\\"organization_users_organization_id_user_id_pk\\\" PRIMARY KEY(\\\"organization_id\\\",\\\"user_id\\\")\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"organizations\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"name\\\" text NOT NULL,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"db_schema\\\" text NOT NULL,\\n\t\\\"db_user\\\" text NOT NULL,\\n\t\\\"db_password_ciphertext\\\" text NOT NULL,\\n\t\\\"hosting_app_name\\\" text,\\n\t\\\"storage_bucket\\\" text,\\n\t\\\"storage_endpoint\\\" text,\\n\t\\\"storage_access_key_id_ciphertext\\\" text,\\n\t\\\"storage_secret_access_key_ciphertext\\\" text,\\n\t\\\"storage_region\\\" text,\\n\t\\\"storage_force_path_style\\\" boolean,\\n\t\\\"custom_logo_enabled\\\" boolean DEFAULT false NOT NULL,\\n\t\\\"custom_logo_explicitly_disabled\\\" boolean DEFAULT false NOT NULL,\\n\t\\\"logo_light_url\\\" text,\\n\t\\\"logo_dark_url\\\" text,\\n\t\\\"logo_height_px\\\" integer DEFAULT 20 NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"deleted_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"project_artifacts\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"storage_key\\\" text NOT NULL,\\n\t\\\"manifest_json\\\" jsonb,\\n\t\\\"source_manifest_json\\\" jsonb,\\n\t\\\"version\\\" integer NOT NULL,\\n\t\\\"created_by_user_id\\\" text,\\n\t\\\"status\\\" \\\"project_artifact_status\\\" NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"projects\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text NOT NULL,\\n\t\\\"name\\\" text NOT NULL,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"description\\\" text,\\n\t\\\"created_by_user_id\\\" text,\\n\t\\\"status\\\" \\\"project_status\\\" NOT NULL,\\n\t\\\"base_url\\\" text,\\n\t\\\"runtime_id\\\" text,\\n\t\\\"active_artifact_id\\\" text,\\n\t\\\"pending_artifact_id\\\" text,\\n\t\\\"last_error\\\" text,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"deleted_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"secret_values\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text NOT NULL,\\n\t\\\"ref_kind\\\" text NOT NULL,\\n\t\\\"ref_id\\\" text NOT NULL,\\n\t\\\"field\\\" text NOT NULL,\\n\t\\\"ciphertext\\\" text NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"users\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"name\\\" text NOT NULL,\\n\t\\\"email\\\" text NOT NULL,\\n\t\\\"email_verified\\\" boolean NOT NULL,\\n\t\\\"image\\\" text,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\tCONSTRAINT \\\"users_email_unique\\\" UNIQUE(\\\"email\\\")\\n);\\n\",\n\t\t\t\"\\nALTER TABLE \\\"accounts\\\" ADD CONSTRAINT \\\"accounts_user_id_users_id_fk\\\" FOREIGN KEY (\\\"user_id\\\") REFERENCES \\\"public\\\".\\\"users\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"sessions\\\" ADD CONSTRAINT \\\"sessions_user_id_users_id_fk\\\" FOREIGN KEY (\\\"user_id\\\") REFERENCES \\\"public\\\".\\\"users\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"oauth_apps\\\" ADD CONSTRAINT \\\"oauth_apps_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"oauth_connections\\\" ADD CONSTRAINT \\\"oauth_connections_app_id_oauth_apps_id_fk\\\" FOREIGN KEY (\\\"app_id\\\") REFERENCES \\\"public\\\".\\\"oauth_apps\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"organization_invitations\\\" ADD CONSTRAINT \\\"organization_invitations_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"organization_invitations\\\" ADD CONSTRAINT \\\"organization_invitations_user_id_users_id_fk\\\" FOREIGN KEY (\\\"user_id\\\") REFERENCES \\\"public\\\".\\\"users\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"organization_invitations\\\" ADD CONSTRAINT \\\"organization_invitations_invited_by_user_id_users_id_fk\\\" FOREIGN KEY (\\\"invited_by_user_id\\\") REFERENCES \\\"public\\\".\\\"users\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"organization_users\\\" ADD CONSTRAINT \\\"organization_users_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"organization_users\\\" ADD CONSTRAINT \\\"organization_users_user_id_users_id_fk\\\" FOREIGN KEY (\\\"user_id\\\") REFERENCES \\\"public\\\".\\\"users\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"project_artifacts\\\" ADD CONSTRAINT \\\"project_artifacts_project_id_projects_id_fk\\\" FOREIGN KEY (\\\"project_id\\\") REFERENCES \\\"public\\\".\\\"projects\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"project_artifacts\\\" ADD CONSTRAINT \\\"project_artifacts_created_by_user_id_users_id_fk\\\" FOREIGN KEY (\\\"created_by_user_id\\\") REFERENCES \\\"public\\\".\\\"users\\\"(\\\"id\\\") ON DELETE set null ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"projects\\\" ADD CONSTRAINT \\\"projects_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"projects\\\" ADD CONSTRAINT \\\"projects_created_by_user_id_users_id_fk\\\" FOREIGN KEY (\\\"created_by_user_id\\\") REFERENCES \\\"public\\\".\\\"users\\\"(\\\"id\\\") ON DELETE set null ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"secret_values\\\" ADD CONSTRAINT \\\"secret_values_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nCREATE INDEX \\\"account_user_id_idx\\\" ON \\\"accounts\\\" USING btree (\\\"user_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"api_keys_reference_id_idx\\\" ON \\\"api_keys\\\" USING btree (\\\"reference_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"api_keys_config_id_idx\\\" ON \\\"api_keys\\\" USING btree (\\\"config_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"api_keys_key_idx\\\" ON \\\"api_keys\\\" USING btree (\\\"key\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"session_user_id_idx\\\" ON \\\"sessions\\\" USING btree (\\\"user_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"verification_identifier_idx\\\" ON \\\"verification\\\" USING btree (\\\"identifier\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"oauth_apps_organization_id_slug_idx\\\" ON \\\"oauth_apps\\\" USING btree (\\\"organization_id\\\",\\\"slug\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"oauth_apps_slug_idx\\\" ON \\\"oauth_apps\\\" USING btree (\\\"slug\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"oauth_connections_app_external_unique\\\" ON \\\"oauth_connections\\\" USING btree (\\\"app_id\\\",\\\"external_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"oauth_connections_external_id_idx\\\" ON \\\"oauth_connections\\\" USING btree (\\\"external_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"organization_invitations_user_id_idx\\\" ON \\\"organization_invitations\\\" USING btree (\\\"user_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"organization_invitations_organization_id_idx\\\" ON \\\"organization_invitations\\\" USING btree (\\\"organization_id\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"organization_invitations_org_user_pending_unique\\\" ON \\\"organization_invitations\\\" USING btree (\\\"organization_id\\\",\\\"user_id\\\") WHERE \\\"organization_invitations\\\".\\\"status\\\" = 'pending';\",\n\t\t\t\"\\nCREATE INDEX \\\"organization_users_user_id_idx\\\" ON \\\"organization_users\\\" USING btree (\\\"user_id\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"organizations_slug_unique\\\" ON \\\"organizations\\\" USING btree (\\\"slug\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"project_artifacts_project_id_idx\\\" ON \\\"project_artifacts\\\" USING btree (\\\"project_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"projects_organization_id_idx\\\" ON \\\"projects\\\" USING btree (\\\"organization_id\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"projects_org_auto_created_by_user_unique\\\" ON \\\"projects\\\" USING btree (\\\"organization_id\\\",\\\"created_by_user_id\\\") WHERE \\\"projects\\\".\\\"created_by_user_id\\\" IS NOT NULL AND \\\"projects\\\".\\\"deleted_at\\\" IS NULL;\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"projects_organization_slug_unique\\\" ON \\\"projects\\\" USING btree (\\\"organization_id\\\",\\\"slug\\\") WHERE \\\"projects\\\".\\\"deleted_at\\\" IS NULL;\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"secret_values_ref_unique\\\" ON \\\"secret_values\\\" USING btree (\\\"organization_id\\\",\\\"ref_kind\\\",\\\"ref_id\\\",\\\"field\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"secret_values_ref_idx\\\" ON \\\"secret_values\\\" USING btree (\\\"organization_id\\\",\\\"ref_kind\\\",\\\"ref_id\\\");\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1781213647047,\n\t\t\"hash\": \"48e4b0a3b93c74edcdf88867eb21556327144131da0870bc764edee3e08560c1\"\n\t},\n\t{\n\t\t\"sql\": [\"ALTER TABLE \\\"users\\\" ADD COLUMN \\\"preferences\\\" jsonb;\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1781276711832,\n\t\t\"hash\": \"aa68be6edc75bf379abd0d5ce031ff60008fe881d7d785a996b002b63d424bc7\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"CREATE TABLE \\\"project_users\\\" (\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"user_id\\\" text NOT NULL,\\n\t\\\"role\\\" text NOT NULL,\\n\t\\\"status\\\" text DEFAULT 'active' NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"deleted_at\\\" timestamp with time zone,\\n\tCONSTRAINT \\\"project_users_project_id_user_id_pk\\\" PRIMARY KEY(\\\"project_id\\\",\\\"user_id\\\")\\n);\\n\",\n\t\t\t\"\\nALTER TABLE \\\"projects\\\" ADD COLUMN \\\"default_member_role\\\" text DEFAULT 'builder' NOT NULL;\",\n\t\t\t\"\\nALTER TABLE \\\"projects\\\" ADD COLUMN \\\"invite_permission\\\" text DEFAULT 'admin' NOT NULL;\",\n\t\t\t\"\\nALTER TABLE \\\"project_users\\\" ADD CONSTRAINT \\\"project_users_project_id_projects_id_fk\\\" FOREIGN KEY (\\\"project_id\\\") REFERENCES \\\"public\\\".\\\"projects\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"project_users\\\" ADD CONSTRAINT \\\"project_users_user_id_users_id_fk\\\" FOREIGN KEY (\\\"user_id\\\") REFERENCES \\\"public\\\".\\\"users\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nCREATE INDEX \\\"project_users_user_id_idx\\\" ON \\\"project_users\\\" USING btree (\\\"user_id\\\");\",\n\t\t\t\"\\nINSERT INTO \\\"project_users\\\" (\\\"project_id\\\", \\\"user_id\\\", \\\"role\\\", \\\"status\\\", \\\"created_at\\\", \\\"updated_at\\\")\\nSELECT p.id, p.created_by_user_id, 'admin', 'active', NOW(), NOW()\\nFROM \\\"projects\\\" p\\nWHERE p.created_by_user_id IS NOT NULL AND p.deleted_at IS NULL\\nON CONFLICT (\\\"project_id\\\", \\\"user_id\\\") DO NOTHING;\\n\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 178128e7,\n\t\t\"hash\": \"d8809c81a5d2340d8651c36dfddad9427f039ac1481d3d0b3dcd63a73a79d11a\"\n\t},\n\t{\n\t\t\"sql\": [\"DELETE FROM \\\"project_users\\\" AS pu\\nUSING \\\"projects\\\" AS p, \\\"organization_users\\\" AS ou\\nWHERE pu.project_id = p.id\\n AND pu.user_id = ou.user_id\\n AND ou.organization_id = p.organization_id\\n AND ou.role = 'builder'\\n AND pu.role = 'builder'\\n AND pu.user_id IS DISTINCT FROM p.created_by_user_id;\\n\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 17812836e5,\n\t\t\"hash\": \"a025effc73d9ea3e21e734834a60a74f9e2b84c558eeef2c1bd18fd0311f8c5c\"\n\t},\n\t{\n\t\t\"sql\": [\"DROP INDEX IF EXISTS \\\"projects_org_auto_created_by_user_unique\\\";\\n\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 17812872e5,\n\t\t\"hash\": \"51ceed699b982b1ea96119e6ca7261a5e2ca854c456b7b89c65736a91114e1a6\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"CREATE TABLE \\\"apps\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"name\\\" text NOT NULL,\\n\t\\\"description\\\" text NOT NULL,\\n\t\\\"category\\\" text NOT NULL,\\n\t\\\"logo\\\" text,\\n\t\\\"auth_kind\\\" text NOT NULL,\\n\t\\\"oauth_scopes\\\" jsonb NOT NULL,\\n\t\\\"source\\\" text NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nALTER TABLE \\\"apps\\\" ADD CONSTRAINT \\\"apps_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"apps_slug_idx\\\" ON \\\"apps\\\" USING btree (\\\"slug\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"apps_organization_id_idx\\\" ON \\\"apps\\\" USING btree (\\\"organization_id\\\");\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1781819893736,\n\t\t\"hash\": \"22be601d95e9d4dd557036fd150112e7f05e98f33d0a99315aabd4739d1730b0\"\n\t},\n\t{\n\t\t\"sql\": [\"ALTER TABLE \\\"organizations\\\" ADD COLUMN \\\"runtime_id\\\" text;\", \"\\nALTER TABLE \\\"organizations\\\" ADD COLUMN \\\"base_url\\\" text;\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1781990311400,\n\t\t\"hash\": \"41b6a62e955cf3accd8292902c3762f01712dc3a6068388edcc42b66b4c1d6a0\"\n\t},\n\t{\n\t\t\"sql\": [\"ALTER TABLE \\\"apps\\\" ADD COLUMN \\\"credential_fields\\\" jsonb DEFAULT '{}'::jsonb NOT NULL;\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1782105700654,\n\t\t\"hash\": \"063e3b85fb5a17325381bfd0425edc0b8ee8cbf0677c390fa67a7e52b7e758c2\"\n\t},\n\t{\n\t\t\"sql\": [\"ALTER TABLE \\\"organizations\\\" ADD COLUMN \\\"verified_at\\\" timestamp with time zone;\", \"\\nUPDATE \\\"organizations\\\" SET \\\"verified_at\\\" = \\\"created_at\\\" WHERE \\\"verified_at\\\" IS NULL;\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1782144854087,\n\t\t\"hash\": \"316191ff040fe6d2b4de9b49d6d0de8a607ab87660bbdfbd9b697aaf387f5e1b\"\n\t},\n\t{\n\t\t\"sql\": [\"ALTER TABLE \\\"apps\\\" ADD COLUMN \\\"credential_scheme\\\" text;\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1782409311909,\n\t\t\"hash\": \"6f345d63c2bab17b2eb9b9726b07d8523f1e1b1bad73001f07ceb4f2eee54326\"\n\t}\n];\n//#endregion\n//#region src/migrate/run.ts\nasync function runMigrations(handle, migrationsFolder) {\n\tif (handle.dialect === \"sqlite\") {\n\t\tmigrate(handle.db, { migrationsFolder });\n\t\treturn;\n\t}\n\tconst config = {\n\t\tmigrationsFolder,\n\t\tmigrationsSchema: resolveMigrationsSchema(handle.searchPath)\n\t};\n\tconst loaded = loadMigrations(migrationsFolder, platformPgMigrations);\n\tconst migrations = handle.searchPath ? adaptPgMigrationsForSearchPath(loaded) : loaded;\n\tawait migratePgDatabase(handle.db, config, migrations);\n}\n//#endregion\n//#region src/client/init.ts\nfunction resolveUrl(url) {\n\treturn url ?? resolvePlatformDatabaseUrl();\n}\nasync function initDatabase(options = {}) {\n\tif (isDatabaseInitialized()) return;\n\tconst url = resolveUrl(options.url);\n\tconst dialect = options.dialect ?? inferDialect(url);\n\tconst searchPath = dialect === \"postgres\" ? resolveSearchPath(url, options.searchPath) : void 0;\n\tconst next = createConnection({\n\t\turl,\n\t\tdialect,\n\t\tmax: options.max,\n\t\tsearchPath\n\t});\n\tsetDatabaseHandle(next);\n\tif (options.migrate ?? true) await runMigrations(next, resolveMigrationsFolder(dialect, options.migrationsFolder));\n}\n//#endregion\n//#region src/config/organization-scope.ts\nconst organizationScopeStorage = new AsyncLocalStorage();\nfunction runWithOrganizationScope(organizationId, fn) {\n\treturn organizationScopeStorage.run(organizationId, fn);\n}\nfunction getOrganizationScopeId() {\n\treturn organizationScopeStorage.getStore();\n}\nfunction requireOrganizationScopeId() {\n\tconst organizationId = getOrganizationScopeId();\n\tif (!organizationId) throw new Error(\"Organization scope is not set\");\n\treturn organizationId;\n}\n//#endregion\n//#region src/project-database/names.ts\nconst PG_IDENT = /^[a-zA-Z_][a-zA-Z0-9_]*$/;\nfunction sanitizeIdForPgIdent(id) {\n\treturn id.replace(/-/g, \"_\");\n}\n/**\n* Per-org sqlite db lives beside the platform (public) sqlite db so that each\n* standalone instance / test working directory is isolated. Falls back to\n* `<cwd>/data` when the platform db is in-memory or not a file URL.\n*/\nfunction orgDbFilePath(organizationId) {\n\tconst standaloneDataDir = process.env.KEYSTROKE_STANDALONE_DATA_DIR?.trim();\n\tif (standaloneDataDir) return join(standaloneDataDir, `org_${sanitizeIdForPgIdent(organizationId)}.db`);\n\tconst platformPath = resolveSqlitePath(resolvePlatformDatabaseUrl());\n\treturn join(platformPath !== \"\" && !platformPath.startsWith(\":memory:\") ? dirname(platformPath) : join(process.cwd(), \"data\"), `org_${sanitizeIdForPgIdent(organizationId)}.db`);\n}\n/** @deprecated Use {@link orgDbSchemaName} — per-project schemas replaced by org schema + project_id. */\nfunction projectDbSchemaName(projectId) {\n\tconst name = `project_${sanitizeIdForPgIdent(projectId)}`;\n\tassertPgIdent(name);\n\treturn name;\n}\n/** @deprecated Use {@link orgDbRoleName}. */\nfunction projectDbRoleName(projectId) {\n\tconst name = `project_${sanitizeIdForPgIdent(projectId)}_user`;\n\tassertPgIdent(name);\n\treturn name;\n}\nfunction orgDbSchemaName(organizationId) {\n\tconst name = `org_${sanitizeIdForPgIdent(organizationId)}`;\n\tassertPgIdent(name);\n\treturn name;\n}\nfunction orgDbRoleName(organizationId) {\n\tconst name = `org_${sanitizeIdForPgIdent(organizationId)}_user`;\n\tassertPgIdent(name);\n\treturn name;\n}\nfunction assertPgIdent(name) {\n\tif (!PG_IDENT.test(name)) throw new Error(`Invalid Postgres identifier: ${name}`);\n}\nfunction quotePgIdent(name) {\n\tassertPgIdent(name);\n\treturn `\"${name.replace(/\"/g, \"\\\"\\\"\")}\"`;\n}\n//#endregion\n//#region src/project-database/provision.ts\nasync function provisionOrgDatabaseSqlite(organizationId) {\n\tconst { createConnection, resolveMigrationsFolder, runMigrations } = await import(\"@keystrokehq/database\");\n\tconst dbSchema = orgDbFilePath(organizationId);\n\tmkdirSync(dirname(dbSchema), { recursive: true });\n\tconst handle = createConnection({\n\t\turl: `file:${dbSchema}`,\n\t\tdialect: \"sqlite\"\n\t});\n\ttry {\n\t\tawait runMigrations(handle, resolveMigrationsFolder(\"sqlite\"));\n\t} finally {\n\t\thandle.close();\n\t}\n\treturn {\n\t\tdbSchema,\n\t\tdbUser: \"\",\n\t\tdbPasswordCiphertext: \"\"\n\t};\n}\nasync function quoteLiteral(pool, value) {\n\tconst { rows } = await pool.query(\"SELECT quote_literal($1) AS quoted\", [value]);\n\tconst quoted = rows[0]?.quoted;\n\tif (!quoted) throw new Error(\"Failed to quote Postgres literal\");\n\treturn quoted;\n}\nasync function grantOrgSchemaObjects(pool, dbSchema, dbUser) {\n\tconst schemaIdent = quotePgIdent(dbSchema);\n\tconst roleIdent = quotePgIdent(dbUser);\n\tawait pool.query(`GRANT ALL ON ALL TABLES IN SCHEMA ${schemaIdent} TO ${roleIdent}`);\n\tawait pool.query(`GRANT ALL ON ALL SEQUENCES IN SCHEMA ${schemaIdent} TO ${roleIdent}`);\n\tawait pool.query(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${schemaIdent} GRANT ALL ON TABLES TO ${roleIdent}`);\n\tawait pool.query(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${schemaIdent} GRANT ALL ON SEQUENCES TO ${roleIdent}`);\n\tconst { rows } = await pool.query(`SELECT n.nspname, t.typname\n FROM pg_type t\n JOIN pg_namespace n ON n.oid = t.typnamespace\n WHERE n.nspname = $1 AND t.typtype = 'e'`, [dbSchema]);\n\tfor (const row of rows) {\n\t\tconst typeIdent = `${quotePgIdent(row.nspname)}.${quotePgIdent(row.typname)}`;\n\t\tawait pool.query(`GRANT USAGE ON TYPE ${typeIdent} TO ${roleIdent}`);\n\t}\n}\nasync function provisionOrgDatabasePostgres(organizationId) {\n\tconst { randomBytes } = await import(\"node:crypto\");\n\tconst { Pool: PgPool } = await import(\"pg\");\n\tconst { createConnection, encryptCredentialPayload, resolveMigrationsFolder, runMigrations } = await import(\"@keystrokehq/database\");\n\tconst { buildOrgDatabaseUrl } = await Promise.resolve().then(() => build_url_exports);\n\tconst { grantPgBossAccess } = await Promise.resolve().then(() => pgboss_grants_exports);\n\tconst dbSchema = orgDbSchemaName(organizationId);\n\tconst dbUser = orgDbRoleName(organizationId);\n\tconst password = randomBytes(32).toString(\"base64url\");\n\tconst pool = new PgPool({ connectionString: resolvePlatformDatabaseUrl() });\n\ttry {\n\t\tconst quotedPassword = await quoteLiteral(pool, password);\n\t\tconst schemaIdent = quotePgIdent(dbSchema);\n\t\tconst roleIdent = quotePgIdent(dbUser);\n\t\tawait pool.query(`CREATE ROLE ${roleIdent} WITH LOGIN PASSWORD ${quotedPassword}`);\n\t\tawait pool.query(`REVOKE ALL ON SCHEMA public FROM ${roleIdent}`);\n\t\tawait pool.query(`CREATE SCHEMA ${schemaIdent}`);\n\t\tawait pool.query(`GRANT ALL ON SCHEMA ${schemaIdent} TO ${roleIdent}`);\n\t\tconst { rows: dbRows } = await pool.query(\"SELECT current_database() AS name\");\n\t\tconst databaseName = dbRows[0]?.name;\n\t\tif (!databaseName) throw new Error(\"Failed to resolve current database name\");\n\t\tawait pool.query(`GRANT CREATE ON DATABASE ${quotePgIdent(databaseName)} TO ${roleIdent}`);\n\t\tawait pool.query(`ALTER ROLE ${roleIdent} SET search_path TO ${schemaIdent}`);\n\t\tawait grantPgBossAccess(pool, dbUser);\n\t\tconst handle = createConnection({\n\t\t\turl: buildOrgDatabaseUrl(dbUser, password),\n\t\t\tdialect: \"postgres\",\n\t\t\tsearchPath: dbSchema\n\t\t});\n\t\ttry {\n\t\t\tawait runMigrations(handle, resolveMigrationsFolder(\"postgres\"));\n\t\t} finally {\n\t\t\tawait handle.close();\n\t\t}\n\t\tawait grantOrgSchemaObjects(pool, dbSchema, dbUser);\n\t\treturn {\n\t\t\tdbSchema,\n\t\t\tdbUser,\n\t\t\tdbPasswordCiphertext: encryptCredentialPayload(password)\n\t\t};\n\t} catch (error) {\n\t\tawait deprovisionOrgDatabase({\n\t\t\tdbSchema,\n\t\t\tdbUser\n\t\t}).catch(() => void 0);\n\t\tthrow error;\n\t} finally {\n\t\tawait pool.end();\n\t}\n}\nasync function provisionOrgDatabase(organizationId) {\n\tif (inferDialect(resolvePlatformDatabaseUrl()) === \"sqlite\") return provisionOrgDatabaseSqlite(organizationId);\n\treturn provisionOrgDatabasePostgres(organizationId);\n}\nasync function deprovisionOrgDatabase(input) {\n\tif (inferDialect(resolvePlatformDatabaseUrl()) === \"sqlite\") {\n\t\tconst { unlinkSync } = await import(\"node:fs\");\n\t\ttry {\n\t\t\tunlinkSync(input.dbSchema);\n\t\t} catch {}\n\t\treturn;\n\t}\n\tconst { Pool: PgPool } = await import(\"pg\");\n\tconst pool = new PgPool({ connectionString: resolvePlatformDatabaseUrl() });\n\ttry {\n\t\tconst roleIdent = quotePgIdent(input.dbUser);\n\t\tawait pool.query(`DROP SCHEMA IF EXISTS ${quotePgIdent(input.dbSchema)} CASCADE`);\n\t\tif (input.dbUser) {\n\t\t\tawait pool.query(`DROP OWNED BY ${roleIdent}`);\n\t\t\tawait pool.query(`DROP ROLE IF EXISTS ${roleIdent}`);\n\t\t}\n\t} finally {\n\t\tawait pool.end();\n\t}\n}\n//#endregion\n//#region src/queries/_internal.ts\n/** Internal: only `queries/**` may call this. */\nfunction getDb() {\n\treturn getDbFromContext();\n}\nfunction isSqliteDialect() {\n\treturn getDatabaseHandle().dialect === \"sqlite\";\n}\n/** Drizzle sqlite handle when the control-plane runs on sqlite. */\nfunction getSqliteDb() {\n\treturn getDbFromContext();\n}\n//#endregion\n//#region src/queries/users/email.ts\nfunction normalizeUserEmail(email) {\n\treturn email.trim().toLowerCase();\n}\nfunction placeholderNameFromEmail(email) {\n\tconst localPart = email.split(\"@\")[0]?.trim();\n\treturn localPart && localPart.length > 0 ? localPart : \"User\";\n}\n//#endregion\n//#region src/queries/users/index.ts\nasync function selectUserByNormalizedEmail(email) {\n\tconst normalized = normalizeUserEmail(email);\n\treturn (await getDb().select().from(users).where(sql$1`lower(${users.email}) = ${normalized}`).limit(1))[0];\n}\nasync function selectUserByEmail(email) {\n\treturn selectUserByNormalizedEmail(email);\n}\nasync function findOrCreateUserByEmail(email) {\n\tconst normalized = normalizeUserEmail(email);\n\tconst existing = await selectUserByNormalizedEmail(normalized);\n\tif (existing) return existing;\n\tconst now = /* @__PURE__ */ new Date();\n\tconst db = getDb();\n\ttry {\n\t\tconst [created] = await db.insert(users).values({\n\t\t\tid: crypto.randomUUID(),\n\t\t\tname: placeholderNameFromEmail(normalized),\n\t\t\temail: normalized,\n\t\t\temailVerified: false,\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now\n\t\t}).returning();\n\t\tif (!created) throw new Error(\"Failed to create user\");\n\t\treturn created;\n\t} catch (error) {\n\t\tconst raced = await selectUserByNormalizedEmail(normalized);\n\t\tif (raced) return raced;\n\t\tthrow error;\n\t}\n}\nasync function selectUserById(id) {\n\treturn (await getDb().select().from(users).where(eq$1(users.id, id)).limit(1))[0];\n}\nasync function selectUsersByIds(ids) {\n\tif (ids.length === 0) return [];\n\treturn getDb().select().from(users).where(inArray$1(users.id, ids));\n}\nasync function updateUserById(id, values) {\n\tawait getDb().update(users).set(values).where(eq$1(users.id, id));\n}\n//#endregion\n//#region src/queries/projects/slug.ts\nvar ProjectSlugTakenError = class extends Error {\n\tconstructor() {\n\t\tsuper(PROJECT_SLUG_TAKEN_MESSAGE);\n\t\tthis.name = \"ProjectSlugTakenError\";\n\t}\n};\nfunction isProjectSlugUniqueViolation(error) {\n\tif (typeof error !== \"object\" || error === null) return false;\n\treturn (\"code\" in error ? String(error.code) : \"\") === \"23505\";\n}\nasync function isProjectSlugTaken(executor, organizationId, slug, excludeProjectId) {\n\treturn (await executor.select({ id: projects.id }).from(projects).where(and(eq(projects.organizationId, organizationId), eq(projects.slug, slug), isNull(projects.deletedAt), excludeProjectId ? ne(projects.id, excludeProjectId) : void 0)).limit(1)).length > 0;\n}\nasync function resolveAvailableProjectSlug(executor, organizationId, name) {\n\tconst base = slugifyProjectName(name);\n\tif (!await isProjectSlugTaken(executor, organizationId, base)) return base;\n\tfor (let suffix = 2; suffix < 1e4; suffix += 1) {\n\t\tconst candidate = ProjectSlugSchema.parse(`${base}-${suffix}`);\n\t\tif (!await isProjectSlugTaken(executor, organizationId, candidate)) return candidate;\n\t}\n\tthrow new Error(\"Unable to allocate a unique project slug\");\n}\nasync function checkProjectSlugAvailability(organizationId, slug, excludeProjectId) {\n\tconst normalized = slug.trim().toLowerCase();\n\tconst format = ProjectSlugSchema.safeParse(normalized);\n\tif (!format.success) return {\n\t\tslug: normalized,\n\t\tavailable: false,\n\t\treason: \"invalid\"\n\t};\n\tconst parsed = format.data;\n\tif (await isProjectSlugTaken(getDb(), organizationId, parsed, excludeProjectId)) return {\n\t\tslug: parsed,\n\t\tavailable: false,\n\t\treason: \"taken\",\n\t\tsuggestion: await resolveAvailableProjectSlug(getDb(), organizationId, parsed)\n\t};\n\treturn {\n\t\tslug: parsed,\n\t\tavailable: true\n\t};\n}\n//#endregion\n//#region src/queries/projects/default-project.ts\n/** e.g. Alex → Alex's, Wells → Wells' */\nfunction formatPossessive(name) {\n\treturn name.endsWith(\"s\") || name.endsWith(\"S\") ? `${name}'` : `${name}'s`;\n}\n/** Auto-created projects only — not used for manual `POST /api/projects`. */\nfunction buildDefaultProjectDescription(displayName) {\n\treturn `${formatPossessive(displayName)} personal project for agents, workflows, and other stuff.`;\n}\nfunction firstNameFromUser(user) {\n\tconst fromName = user.name.trim().split(/\\s+/)[0];\n\tif (fromName) return fromName;\n\tconst local = user.email.split(\"@\")[0]?.replace(/[._+-]/g, \" \").trim();\n\treturn local && local.length > 0 ? local : \"My\";\n}\nfunction buildDefaultProjectForUser(user) {\n\tconst firstName = firstNameFromUser(user);\n\treturn {\n\t\tname: `${formatPossessive(firstName)} Project`,\n\t\tdescription: buildDefaultProjectDescription(firstName)\n\t};\n}\nasync function selectAutoCreatedProjectForUser(executor, organizationId, userId) {\n\treturn (await executor.select().from(projects).where(and$1(eq$1(projects.organizationId, organizationId), eq$1(projects.createdByUserId, userId), isNull$1(projects.deletedAt))).limit(1))[0];\n}\nasync function insertAutoCreatedProject(executor, organizationId, userId, name, description) {\n\tconst existing = await selectAutoCreatedProjectForUser(executor, organizationId, userId);\n\tif (existing) return existing;\n\tconst now = /* @__PURE__ */ new Date();\n\tconst projectId = crypto.randomUUID();\n\tconst slug = await resolveAvailableProjectSlug(executor, organizationId, name);\n\tconst [inserted] = await executor.insert(projects).values({\n\t\tid: projectId,\n\t\torganizationId,\n\t\tname,\n\t\tslug,\n\t\tdescription,\n\t\tdefaultMemberRole: \"builder\",\n\t\tinvitePermission: \"admin\",\n\t\tcreatedByUserId: userId,\n\t\tstatus: \"inactive\",\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t}).returning();\n\tif (inserted) {\n\t\tawait executor.insert(projectUsers).values({\n\t\t\tprojectId: inserted.id,\n\t\t\tuserId,\n\t\t\trole: \"admin\",\n\t\t\tstatus: \"active\",\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now\n\t\t}).onConflictDoNothing();\n\t\treturn inserted;\n\t}\n\treturn selectAutoCreatedProjectForUser(executor, organizationId, userId);\n}\n/**\n* Creates the user's personal default project in `organizationId` when they do\n* not already have an auto-created project there.\n*/\nasync function ensureDefaultProjectForUserInTransaction(tx, userId, organizationId) {\n\tconst user = await selectUserById(userId);\n\tif (!user) throw new Error(\"User not found\");\n\tconst { name, description } = buildDefaultProjectForUser(user);\n\treturn insertAutoCreatedProject(tx, organizationId, userId, name, description);\n}\nasync function ensureDefaultProjectForUser(userId, organizationId) {\n\tconst user = await selectUserById(userId);\n\tif (!user) throw new Error(\"User not found\");\n\tconst { name, description } = buildDefaultProjectForUser(user);\n\treturn insertAutoCreatedProject(getDb(), organizationId, userId, name, description);\n}\n//#endregion\n//#region src/queries/organizations/slug.ts\nasync function checkOrganizationSlugAvailability(slug, excludeOrganizationId) {\n\tconst normalized = slug.trim().toLowerCase();\n\tconst format = OrganizationSlugSchema.safeParse(normalized);\n\tif (!format.success) return {\n\t\tslug: normalized,\n\t\tavailable: false,\n\t\treason: \"invalid\"\n\t};\n\tconst parsed = format.data;\n\tif (RESERVED_ORGANIZATION_SLUGS.has(parsed)) return {\n\t\tslug: parsed,\n\t\tavailable: false,\n\t\treason: \"reserved\"\n\t};\n\tif (await isOrganizationSlugTaken(parsed, excludeOrganizationId)) return {\n\t\tslug: parsed,\n\t\tavailable: false,\n\t\treason: \"taken\",\n\t\tsuggestion: await resolveAvailableOrganizationSlug(parsed, parsed)\n\t};\n\treturn {\n\t\tslug: parsed,\n\t\tavailable: true\n\t};\n}\nasync function isOrganizationSlugTaken(slug, excludeOrganizationId) {\n\treturn (await getDb().select({ id: organizations.id }).from(organizations).where(excludeOrganizationId ? and(eq(organizations.slug, slug), ne(organizations.id, excludeOrganizationId)) : eq(organizations.slug, slug)).limit(1)).length > 0;\n}\nfunction normalizeOrganizationSlugInput(name, slug) {\n\tif (slug?.trim()) {\n\t\tconst normalized = slug.trim().toLowerCase();\n\t\tif (normalized === slugifyOrganizationName(name)) return OrganizationSlugSchema.parse(normalized);\n\t\treturn ClaimableOrganizationSlugSchema.parse(normalized);\n\t}\n\treturn OrganizationSlugSchema.parse(slugifyOrganizationName(name));\n}\nasync function resolveAvailableOrganizationSlug(name, preferredSlug) {\n\tconst base = normalizeOrganizationSlugInput(name, preferredSlug);\n\tif (!RESERVED_ORGANIZATION_SLUGS.has(base) && !await isOrganizationSlugTaken(base)) return base;\n\tfor (let suffix = 2; suffix < 1e4; suffix += 1) {\n\t\tconst candidate = OrganizationSlugSchema.parse(`${base}-${suffix}`);\n\t\tif (!await isOrganizationSlugTaken(candidate)) return candidate;\n\t}\n\tthrow new Error(\"Unable to allocate a unique organization slug\");\n}\n//#endregion\n//#region src/queries/organizations/branding.ts\nfunction organizationRowToSidebarBranding(organization) {\n\treturn normalizeOrganizationSidebarBranding({\n\t\tcustomLogoEnabled: organization.customLogoEnabled,\n\t\tcustomLogoExplicitlyDisabled: organization.customLogoExplicitlyDisabled,\n\t\tlogoLightUrl: organization.logoLightUrl,\n\t\tlogoDarkUrl: organization.logoDarkUrl,\n\t\tlogoHeightPx: organization.logoHeightPx\n\t});\n}\nasync function updateOrganizationSidebarBranding(organizationId, input) {\n\tconst db = getDb();\n\tconst updates = { updatedAt: /* @__PURE__ */ new Date() };\n\tif (input.customLogoEnabled !== void 0) updates.customLogoEnabled = input.customLogoEnabled;\n\tif (input.customLogoExplicitlyDisabled !== void 0) updates.customLogoExplicitlyDisabled = input.customLogoExplicitlyDisabled;\n\tif (input.logoLightUrl !== void 0) updates.logoLightUrl = input.logoLightUrl;\n\tif (input.logoDarkUrl !== void 0) updates.logoDarkUrl = input.logoDarkUrl;\n\tif (input.logoHeightPx !== void 0) updates.logoHeightPx = input.logoHeightPx;\n\tconst [organization] = await db.update(organizations).set(updates).where(eq(organizations.id, organizationId)).returning();\n\tif (!organization) throw new Error(`Organization not found: ${organizationId}`);\n\treturn organization;\n}\n//#endregion\n//#region src/queries/organizations/index.ts\nfunction userOrganizationSelect() {\n\treturn {\n\t\torganization: organizations,\n\t\trole: organizationUsers.role\n\t};\n}\nasync function selectOrganizationById(id) {\n\treturn (await getDb().select().from(organizations).where(eq(organizations.id, id)).limit(1))[0];\n}\nasync function selectOrganizationBySlug(slug) {\n\treturn (await getDb().select().from(organizations).where(eq(organizations.slug, slug)).limit(1))[0];\n}\nasync function isOrganizationStorageBucketInUse(bucket) {\n\treturn (await getDb().select({ id: organizations.id }).from(organizations).where(and(eq(organizations.storageBucket, bucket), isNull(organizations.deletedAt))).limit(1)).length > 0;\n}\nasync function selectActiveOrganizationIds() {\n\treturn (await getDb().select({ id: organizations.id }).from(organizations).where(isNull(organizations.deletedAt))).map((row) => row.id);\n}\nfunction activeOrganizationUserFilter(userId, organizationId) {\n\tconst clauses = [\n\t\teq(organizationUsers.userId, userId),\n\t\teq(organizationUsers.status, \"active\"),\n\t\tisNull(organizationUsers.deletedAt)\n\t];\n\tif (organizationId) clauses.push(eq(organizationUsers.organizationId, organizationId));\n\treturn and(...clauses);\n}\nasync function selectUserOrganizations(userId) {\n\treturn getDb().select(userOrganizationSelect()).from(organizationUsers).innerJoin(organizations, eq(organizationUsers.organizationId, organizations.id)).where(activeOrganizationUserFilter(userId));\n}\nasync function selectUserOrganization(userId) {\n\treturn (await selectUserOrganizations(userId))[0];\n}\nasync function selectUserOrganizationMembership(userId, organizationId) {\n\treturn (await getDb().select(userOrganizationSelect()).from(organizationUsers).innerJoin(organizations, eq(organizationUsers.organizationId, organizations.id)).where(activeOrganizationUserFilter(userId, organizationId)).limit(1))[0];\n}\nasync function updateOrganizationActive(organizationId, input) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\treturn (await db.update(organizations).set({\n\t\tbaseUrl: input.baseUrl,\n\t\truntimeId: input.runtimeId,\n\t\tupdatedAt: now\n\t}).where(eq(organizations.id, organizationId)).returning())[0];\n}\nasync function updateOrganizationFailed(organizationId, _lastError) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\treturn (await db.update(organizations).set({ updatedAt: now }).where(eq(organizations.id, organizationId)).returning())[0];\n}\nasync function updateOrganizationName(organizationId, name) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\tconst [organization] = await db.update(organizations).set({\n\t\tname,\n\t\tupdatedAt: now\n\t}).where(eq(organizations.id, organizationId)).returning();\n\tif (!organization) throw new Error(`Organization not found: ${organizationId}`);\n\treturn organization;\n}\nasync function updateOrganizationSlug(organizationId, slug) {\n\tconst db = getDb();\n\tconst parsedSlug = ClaimableOrganizationSlugSchema.parse(slug);\n\tif (await isOrganizationSlugTaken(parsedSlug, organizationId)) throw new OrganizationSlugTakenError();\n\tconst now = /* @__PURE__ */ new Date();\n\ttry {\n\t\tconst [organization] = await db.update(organizations).set({\n\t\t\tslug: parsedSlug,\n\t\t\tupdatedAt: now\n\t\t}).where(eq(organizations.id, organizationId)).returning();\n\t\tif (!organization) throw new Error(`Organization not found: ${organizationId}`);\n\t\treturn organization;\n\t} catch (error) {\n\t\tif (isOrganizationSlugUniqueViolation(error)) throw new OrganizationSlugTakenError();\n\t\tthrow error;\n\t}\n}\nvar OrganizationSlugTakenError = class extends Error {\n\tconstructor() {\n\t\tsuper(ORGANIZATION_SLUG_TAKEN_MESSAGE);\n\t\tthis.name = \"OrganizationSlugTakenError\";\n\t}\n};\nfunction isOrganizationSlugUniqueViolation(error) {\n\tif (typeof error !== \"object\" || error === null) return false;\n\tif ((\"code\" in error ? String(error.code) : \"\") === \"23505\") return true;\n\treturn (\"message\" in error ? String(error.message) : \"\").includes(\"organizations_slug_unique\");\n}\nasync function resolveNewOrganizationIdentity(name, preferredSlug) {\n\tconst trimmedName = name.trim();\n\tif (!trimmedName) throw new Error(\"Organization name is required\");\n\tconst organizationId = crypto.randomUUID();\n\tconst autoSlug = slugifyOrganizationName(trimmedName);\n\tconst requestedSlug = preferredSlug?.trim() ? normalizeOrganizationSlugInput(trimmedName, preferredSlug) : autoSlug;\n\treturn {\n\t\torganizationId,\n\t\tslug: Boolean(preferredSlug?.trim()) ? await (async () => {\n\t\t\tif (await isOrganizationSlugTaken(requestedSlug)) throw new OrganizationSlugTakenError();\n\t\t\treturn requestedSlug;\n\t\t})() : await resolveAvailableOrganizationSlug(trimmedName, requestedSlug)\n\t};\n}\nasync function createOrganizationForUser(userId, name, preferredSlug, options = {}) {\n\tconst db = getDb();\n\tconst trimmedName = name.trim();\n\tif (!trimmedName) throw new Error(\"Organization name is required\");\n\tconst { organizationId, slug } = options.organizationId && options.slug ? {\n\t\torganizationId: options.organizationId,\n\t\tslug: options.slug\n\t} : await resolveNewOrganizationIdentity(trimmedName, preferredSlug);\n\tconst now = /* @__PURE__ */ new Date();\n\tconst database = await provisionOrgDatabase(organizationId);\n\ttry {\n\t\treturn await db.transaction(async (tx) => {\n\t\t\tconst [organization] = await tx.insert(organizations).values({\n\t\t\t\tid: organizationId,\n\t\t\t\tname: trimmedName,\n\t\t\t\tslug,\n\t\t\t\tdbSchema: database.dbSchema,\n\t\t\t\tdbUser: database.dbUser,\n\t\t\t\tdbPasswordCiphertext: database.dbPasswordCiphertext,\n\t\t\t\thostingAppName: options.hostingAppName ?? null,\n\t\t\t\tstorageBucket: options.storage?.bucket ?? null,\n\t\t\t\tstorageEndpoint: options.storage?.endpoint ?? null,\n\t\t\t\tstorageAccessKeyIdCiphertext: options.storage?.accessKeyIdCiphertext ?? null,\n\t\t\t\tstorageSecretAccessKeyCiphertext: options.storage?.secretAccessKeyCiphertext ?? null,\n\t\t\t\tstorageRegion: options.storage?.region ?? null,\n\t\t\t\tstorageForcePathStyle: options.storage?.forcePathStyle ?? null,\n\t\t\t\tcreatedAt: now,\n\t\t\t\tupdatedAt: now\n\t\t\t}).returning();\n\t\t\tawait tx.insert(organizationUsers).values({\n\t\t\t\torganizationId,\n\t\t\t\tuserId,\n\t\t\t\trole: \"owner\",\n\t\t\t\tstatus: \"active\",\n\t\t\t\tcreatedAt: now,\n\t\t\t\tupdatedAt: now\n\t\t\t});\n\t\t\tif (!organization) throw new Error(\"Failed to create organization\");\n\t\t\tawait ensureDefaultProjectForUserInTransaction(tx, userId, organizationId);\n\t\t\treturn {\n\t\t\t\torganization,\n\t\t\t\trole: \"owner\"\n\t\t\t};\n\t\t});\n\t} catch (error) {\n\t\tawait deprovisionOrgDatabase(database).catch(() => void 0);\n\t\tif (isOrganizationSlugUniqueViolation(error)) throw new OrganizationSlugTakenError();\n\t\tthrow error;\n\t}\n}\n//#endregion\n//#region src/queries/project-users/index.ts\nasync function selectUserProjectMembership(userId, projectId) {\n\treturn (await getDb().select().from(projectUsers).where(and$1(eq$1(projectUsers.projectId, projectId), eq$1(projectUsers.userId, userId), isNull$1(projectUsers.deletedAt))).limit(1))[0];\n}\nasync function selectProjectMembers(projectId) {\n\treturn (await getDb().select({\n\t\tid: users.id,\n\t\tprojectId: projectUsers.projectId,\n\t\tname: users.name,\n\t\temail: users.email,\n\t\trole: projectUsers.role,\n\t\torgStatus: organizationUsers.status,\n\t\timage: users.image,\n\t\tcreatedAt: projectUsers.createdAt\n\t}).from(projectUsers).innerJoin(users, eq$1(projectUsers.userId, users.id)).innerJoin(projects, eq$1(projectUsers.projectId, projects.id)).leftJoin(organizationUsers, and$1(eq$1(organizationUsers.organizationId, projects.organizationId), eq$1(organizationUsers.userId, projectUsers.userId), isNull$1(organizationUsers.deletedAt))).where(and$1(eq$1(projectUsers.projectId, projectId), isNull$1(projectUsers.deletedAt)))).map(({ orgStatus, ...row }) => ({\n\t\t...row,\n\t\tstatus: orgStatus === \"invited\" ? \"invited\" : \"active\"\n\t}));\n}\nasync function selectProjectIdsForUser(organizationId, userId) {\n\treturn (await getDb().select({ projectId: projectUsers.projectId }).from(projectUsers).innerJoin(projects, eq$1(projectUsers.projectId, projects.id)).where(and$1(eq$1(projects.organizationId, organizationId), eq$1(projectUsers.userId, userId), isNull$1(projectUsers.deletedAt), isNull$1(projects.deletedAt)))).map((row) => row.projectId);\n}\nasync function upsertProjectMember(input) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\tconst [existing] = await db.select().from(projectUsers).where(and$1(eq$1(projectUsers.projectId, input.projectId), eq$1(projectUsers.userId, input.userId))).limit(1);\n\tif (!existing) {\n\t\tawait db.insert(projectUsers).values({\n\t\t\tprojectId: input.projectId,\n\t\t\tuserId: input.userId,\n\t\t\trole: input.role,\n\t\t\tstatus: \"active\",\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now\n\t\t});\n\t\treturn;\n\t}\n\tawait db.update(projectUsers).set({\n\t\trole: input.role,\n\t\tstatus: \"active\",\n\t\tupdatedAt: now,\n\t\tdeletedAt: null\n\t}).where(and$1(eq$1(projectUsers.projectId, input.projectId), eq$1(projectUsers.userId, input.userId)));\n}\nasync function updateProjectMemberRole(projectId, userId, role) {\n\tif (!await selectUserProjectMembership(userId, projectId)) throw new ProjectMemberNotFoundError();\n\tconst now = /* @__PURE__ */ new Date();\n\tawait getDb().update(projectUsers).set({\n\t\trole,\n\t\tupdatedAt: now\n\t}).where(and$1(eq$1(projectUsers.projectId, projectId), eq$1(projectUsers.userId, userId), isNull$1(projectUsers.deletedAt)));\n\tconst [member] = (await selectProjectMembers(projectId)).filter((row) => row.id === userId);\n\tif (!member) throw new ProjectMemberNotFoundError();\n\treturn member;\n}\nasync function removeProjectMember(projectId, userId) {\n\tif (!await selectUserProjectMembership(userId, projectId)) throw new ProjectMemberNotFoundError();\n\tconst now = /* @__PURE__ */ new Date();\n\tawait getDb().update(projectUsers).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(and$1(eq$1(projectUsers.projectId, projectId), eq$1(projectUsers.userId, userId), isNull$1(projectUsers.deletedAt)));\n}\nasync function backfillProjectUsers() {\n\tconst activeProjects = await getDb().select({\n\t\tid: projects.id,\n\t\tcreatedByUserId: projects.createdByUserId\n\t}).from(projects).where(isNull$1(projects.deletedAt));\n\tfor (const project of activeProjects) if (project.createdByUserId) await upsertProjectMember({\n\t\tprojectId: project.id,\n\t\tuserId: project.createdByUserId,\n\t\trole: \"admin\"\n\t});\n}\nasync function inviteProjectMembers(input) {\n\tconst seen = /* @__PURE__ */ new Set();\n\tconst results = [];\n\tconst db = getDb();\n\tfor (const rawEmail of input.emails) {\n\t\tconst normalized = normalizeUserEmail(rawEmail);\n\t\tif (seen.has(normalized)) continue;\n\t\tseen.add(normalized);\n\t\tif (!/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(normalized)) {\n\t\t\tresults.push({\n\t\t\t\temail: rawEmail.trim(),\n\t\t\t\tstatus: \"invalid\"\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst [orgUser] = await db.select({ userId: organizationUsers.userId }).from(organizationUsers).innerJoin(users, eq$1(organizationUsers.userId, users.id)).where(and$1(eq$1(organizationUsers.organizationId, input.organizationId), eq$1(users.email, normalized), inArray$1(organizationUsers.status, [\"active\", \"invited\"]), isNull$1(organizationUsers.deletedAt))).limit(1);\n\t\tif (!orgUser) {\n\t\t\tresults.push({\n\t\t\t\temail: normalized,\n\t\t\t\tstatus: \"not_org_member\"\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (await selectUserProjectMembership(orgUser.userId, input.projectId)) {\n\t\t\tresults.push({\n\t\t\t\temail: normalized,\n\t\t\t\tstatus: \"already_member\"\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tawait upsertProjectMember({\n\t\t\tprojectId: input.projectId,\n\t\t\tuserId: orgUser.userId,\n\t\t\trole: input.role\n\t\t});\n\t\tresults.push({\n\t\t\temail: normalized,\n\t\t\tstatus: \"added\"\n\t\t});\n\t}\n\treturn results;\n}\nvar ProjectMemberNotFoundError = class extends Error {\n\tconstructor(message = \"Project member not found\") {\n\t\tsuper(message);\n\t\tthis.name = \"ProjectMemberNotFoundError\";\n\t}\n};\n//#endregion\n//#region src/queries/projects/index.ts\nasync function selectProjectById(projectId) {\n\treturn (await getDb().select().from(projects).where(eq(projects.id, projectId)).limit(1))[0];\n}\nasync function selectProjectsByOrganizationId(organizationId, options) {\n\tconst db = getDb();\n\tconst grantedIds = options?.grantedProjectIds;\n\tconst conditions = [eq(projects.organizationId, organizationId), isNull(projects.deletedAt)];\n\tif (grantedIds !== void 0) {\n\t\tif (grantedIds.length === 0) return [];\n\t\tconditions.push(inArray(projects.id, grantedIds));\n\t}\n\treturn db.select().from(projects).where(and(...conditions)).orderBy(asc(projects.createdAt));\n}\nasync function selectProjectForOrganization(organizationId, projectId) {\n\treturn (await getDb().select().from(projects).where(and(eq(projects.id, projectId), eq(projects.organizationId, organizationId), isNull(projects.deletedAt))).limit(1))[0];\n}\nasync function selectProjectForOrganizationBySlug(organizationId, slug) {\n\tconst db = getDb();\n\tconst normalizedSlug = slug.trim().toLowerCase();\n\treturn (await db.select().from(projects).where(and(eq(projects.organizationId, organizationId), eq(projects.slug, normalizedSlug), isNull(projects.deletedAt))).limit(1))[0];\n}\nasync function createProjectForOrganization(organizationId, name, description, createdByUserId) {\n\tconst db = getDb();\n\tconst trimmedName = name.trim();\n\tif (!trimmedName) throw new Error(\"Project name is required\");\n\tconst trimmedDescription = description === void 0 || description === null ? null : description.trim() || null;\n\tconst now = /* @__PURE__ */ new Date();\n\tconst projectId = crypto.randomUUID();\n\tconst slug = await resolveAvailableProjectSlug(db, organizationId, trimmedName);\n\tconst [project] = await db.insert(projects).values({\n\t\tid: projectId,\n\t\torganizationId,\n\t\tname: trimmedName,\n\t\tslug,\n\t\tdescription: trimmedDescription,\n\t\tdefaultMemberRole: \"builder\",\n\t\tinvitePermission: \"admin\",\n\t\tcreatedByUserId: createdByUserId ?? null,\n\t\tstatus: \"inactive\",\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t}).returning();\n\tif (!project) throw new Error(\"Failed to create project\");\n\tif (createdByUserId) await upsertProjectMember({\n\t\tprojectId: project.id,\n\t\tuserId: createdByUserId,\n\t\trole: \"admin\"\n\t});\n\treturn project;\n}\nasync function updateProjectForOrganization(organizationId, projectId, patch) {\n\tconst existing = await selectProjectForOrganization(organizationId, projectId);\n\tif (!existing) return;\n\tconst updates = { updatedAt: /* @__PURE__ */ new Date() };\n\tif (patch.name !== void 0) {\n\t\tconst trimmedName = patch.name.trim();\n\t\tif (!trimmedName) throw new Error(\"Project name is required\");\n\t\tupdates.name = trimmedName;\n\t}\n\tif (patch.description !== void 0) updates.description = patch.description.trim() || null;\n\tconst db = getDb();\n\tif (patch.slug !== void 0) {\n\t\tconst parsedSlug = ProjectSlugSchema.parse(patch.slug.trim().toLowerCase());\n\t\tif (parsedSlug !== existing.slug) {\n\t\t\tif (await isProjectSlugTaken(db, organizationId, parsedSlug, projectId)) throw new ProjectSlugTakenError();\n\t\t\tupdates.slug = parsedSlug;\n\t\t}\n\t}\n\ttry {\n\t\treturn (await db.update(projects).set(updates).where(eq(projects.id, projectId)).returning())[0];\n\t} catch (error) {\n\t\tif (isProjectSlugUniqueViolation(error)) throw new ProjectSlugTakenError();\n\t\tthrow error;\n\t}\n}\nasync function updateProjectSettings(organizationId, projectId, patch) {\n\tif (!await selectProjectForOrganization(organizationId, projectId)) return;\n\tconst updates = { updatedAt: /* @__PURE__ */ new Date() };\n\tif (patch.description !== void 0) updates.description = patch.description.trim() || null;\n\tif (patch.defaultMemberRole !== void 0) updates.defaultMemberRole = patch.defaultMemberRole;\n\tif (patch.invitePermission !== void 0) updates.invitePermission = patch.invitePermission;\n\treturn (await getDb().update(projects).set(updates).where(eq(projects.id, projectId)).returning())[0];\n}\nasync function deleteProjectForOrganization(organizationId, projectId) {\n\tif (!await selectProjectForOrganization(organizationId, projectId)) return;\n\tconst now = /* @__PURE__ */ new Date();\n\treturn (await getDb().update(projects).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(eq(projects.id, projectId)).returning())[0];\n}\nasync function updateProjectActive(projectId, input) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\treturn (await db.update(projects).set({\n\t\tstatus: \"active\",\n\t\tbaseUrl: input.baseUrl,\n\t\truntimeId: input.runtimeId,\n\t\tlastError: null,\n\t\tupdatedAt: now\n\t}).where(eq(projects.id, projectId)).returning())[0];\n}\nasync function updateProjectFailed(projectId, lastError) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\treturn (await db.update(projects).set({\n\t\tstatus: \"failed\",\n\t\tlastError,\n\t\tupdatedAt: now\n\t}).where(eq(projects.id, projectId)).returning())[0];\n}\n//#endregion\n//#region src/standalone/default-org.ts\nconst DEFAULT_STANDALONE_ORGANIZATION_ID = \"default\";\nconst DEFAULT_STANDALONE_ORGANIZATION_SLUG = \"default\";\nconst DEFAULT_STANDALONE_ORGANIZATION_NAME = \"Default Organization\";\nconst DEFAULT_STANDALONE_PROJECT_NAME = \"Default Project\";\nconst DEFAULT_STANDALONE_PROJECT_SLUG = \"default\";\nfunction isStandaloneMode(env = process.env) {\n\treturn env.KEYSTROKE_APP_MODE === \"standalone\" || env.KEYSTROKE_STANDALONE === \"1\";\n}\nasync function ensureDefaultOrganization() {\n\tconst organizationId = DEFAULT_STANDALONE_ORGANIZATION_ID;\n\tif (await selectOrganizationById(organizationId)) return { organizationId };\n\tconst now = /* @__PURE__ */ new Date();\n\tconst provisioned = await provisionOrgDatabase(organizationId);\n\tif (isSqliteDialect()) await getSqliteDb().insert(organizationsSqlite).values({\n\t\tid: organizationId,\n\t\tname: DEFAULT_STANDALONE_ORGANIZATION_NAME,\n\t\tslug: DEFAULT_STANDALONE_ORGANIZATION_SLUG,\n\t\tdbSchema: provisioned.dbSchema,\n\t\tdbUser: provisioned.dbUser,\n\t\tdbPasswordCiphertext: provisioned.dbPasswordCiphertext,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now,\n\t\tverifiedAt: now\n\t});\n\telse await getDb().insert(organizations).values({\n\t\tid: organizationId,\n\t\tname: DEFAULT_STANDALONE_ORGANIZATION_NAME,\n\t\tslug: DEFAULT_STANDALONE_ORGANIZATION_SLUG,\n\t\tdbSchema: provisioned.dbSchema,\n\t\tdbUser: provisioned.dbUser,\n\t\tdbPasswordCiphertext: provisioned.dbPasswordCiphertext,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now,\n\t\tverifiedAt: now\n\t});\n\treturn { organizationId };\n}\nasync function ensureDefaultProject(organizationId) {\n\tconst projectId = DEFAULT_PROJECT_ID;\n\tif (await selectProjectForOrganization(organizationId, projectId)) return { projectId };\n\tconst now = /* @__PURE__ */ new Date();\n\tif (isSqliteDialect()) await getSqliteDb().insert(projectsSqlite).values({\n\t\tid: projectId,\n\t\torganizationId,\n\t\tname: DEFAULT_STANDALONE_PROJECT_NAME,\n\t\tslug: DEFAULT_STANDALONE_PROJECT_SLUG,\n\t\tdescription: \"Default standalone project\",\n\t\tdefaultMemberRole: \"builder\",\n\t\tinvitePermission: \"admin\",\n\t\tstatus: \"inactive\",\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t});\n\telse await getDb().insert(projects).values({\n\t\tid: projectId,\n\t\torganizationId,\n\t\tname: DEFAULT_STANDALONE_PROJECT_NAME,\n\t\tslug: DEFAULT_STANDALONE_PROJECT_SLUG,\n\t\tdescription: \"Default standalone project\",\n\t\tdefaultMemberRole: \"builder\",\n\t\tinvitePermission: \"admin\",\n\t\tstatus: \"inactive\",\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t});\n\treturn { projectId };\n}\nasync function ensureDefaultOrganizationAndProject() {\n\tconst { organizationId } = await ensureDefaultOrganization();\n\tconst { projectId } = await ensureDefaultProject(organizationId);\n\treturn {\n\t\torganizationId,\n\t\tprojectId\n\t};\n}\nasync function runWithStandaloneScope(fn) {\n\tconst { organizationId, projectId } = await ensureDefaultOrganizationAndProject();\n\treturn runWithOrganizationScope(organizationId, () => runWithTenantScope(organizationId, () => runWithProjectScope(projectId, fn)));\n}\n//#endregion\n//#region src/queries/api-keys/index.ts\nasync function selectApiKeyByConfigName(configId, name) {\n\treturn (await getDb().select().from(authApiKeys).where(and$1(eq$1(authApiKeys.configId, configId), eq$1(authApiKeys.name, name))).limit(1))[0];\n}\nasync function selectApiKeyById(id) {\n\treturn (await getDb().select().from(authApiKeys).where(eq$1(authApiKeys.id, id)).limit(1))[0];\n}\nasync function selectApiKeyByConfigAndHash(configId, keyHash) {\n\treturn (await getDb().select().from(authApiKeys).where(and$1(eq$1(authApiKeys.configId, configId), eq$1(authApiKeys.key, keyHash))).limit(1))[0];\n}\nasync function listApiKeysByConfigId(configId) {\n\treturn getDb().select().from(authApiKeys).where(eq$1(authApiKeys.configId, configId));\n}\nasync function listApiKeysByConfigReferenceId(configId, referenceId) {\n\treturn getDb().select().from(authApiKeys).where(and$1(eq$1(authApiKeys.configId, configId), eq$1(authApiKeys.referenceId, referenceId)));\n}\nasync function insertApiKey(values) {\n\tif (isSqliteDialect()) {\n\t\tawait getSqliteDb().insert(authApiKeysSqlite).values(values);\n\t\treturn;\n\t}\n\tawait getDb().insert(authApiKeys).values(values);\n}\nasync function deleteApiKeyById(id) {\n\tawait getDb().delete(authApiKeys).where(eq$1(authApiKeys.id, id));\n}\n//#endregion\n//#region src/queries/members/errors.ts\nvar OrganizationMemberMutationError = class extends Error {\n\tcode;\n\tconstructor(code, message) {\n\t\tsuper(message);\n\t\tthis.name = \"OrganizationMemberMutationError\";\n\t\tthis.code = code;\n\t}\n};\nvar CannotModifyOwnerError = class extends OrganizationMemberMutationError {\n\tconstructor(message = \"Organization owners cannot be modified this way\") {\n\t\tsuper(\"cannot_modify_owner\", message);\n\t}\n};\nvar LastOwnerError = class extends OrganizationMemberMutationError {\n\tconstructor(message = \"The organization must have at least one owner\") {\n\t\tsuper(\"last_owner\", message);\n\t}\n};\nvar OrganizationMemberNotFoundError = class extends OrganizationMemberMutationError {\n\tconstructor(message = \"Member not found\") {\n\t\tsuper(\"member_not_found\", message);\n\t}\n};\n//#endregion\n//#region src/queries/members/index.ts\nconst INVITATION_TTL_MS = 336 * 60 * 60 * 1e3;\nasync function selectOrganizationMembers(organizationId) {\n\treturn getDb().select({\n\t\tid: users.id,\n\t\tname: users.name,\n\t\temail: users.email,\n\t\trole: organizationUsers.role,\n\t\tstatus: organizationUsers.status,\n\t\timage: users.image,\n\t\tcreatedAt: organizationUsers.createdAt\n\t}).from(organizationUsers).innerJoin(users, eq$1(organizationUsers.userId, users.id)).where(and$1(eq$1(organizationUsers.organizationId, organizationId), isNull$1(organizationUsers.deletedAt)));\n}\nasync function selectOrganizationMembership(organizationId, userId) {\n\treturn (await getDb().select().from(organizationUsers).where(and$1(eq$1(organizationUsers.organizationId, organizationId), eq$1(organizationUsers.userId, userId), isNull$1(organizationUsers.deletedAt))).limit(1))[0];\n}\nasync function selectPendingInvitation(organizationId, userId) {\n\treturn (await getDb().select().from(organizationInvitations).where(and$1(eq$1(organizationInvitations.organizationId, organizationId), eq$1(organizationInvitations.userId, userId), eq$1(organizationInvitations.status, \"pending\"))).limit(1))[0];\n}\nfunction isValidInviteEmail(email) {\n\treturn /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email);\n}\nasync function inviteOrganizationMembers(input) {\n\tconst seen = /* @__PURE__ */ new Set();\n\tconst results = [];\n\tfor (const rawEmail of input.emails) {\n\t\tconst normalized = normalizeUserEmail(rawEmail);\n\t\tif (seen.has(normalized)) continue;\n\t\tseen.add(normalized);\n\t\tif (!isValidInviteEmail(normalized)) {\n\t\t\tresults.push({\n\t\t\t\temail: rawEmail.trim(),\n\t\t\t\tstatus: \"invalid\"\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst user = await findOrCreateUserByEmail(normalized);\n\t\tif ((await selectOrganizationMembership(input.organizationId, user.id))?.status === \"active\") {\n\t\t\tresults.push({\n\t\t\t\temail: normalized,\n\t\t\t\tstatus: \"already_member\"\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst pending = await selectPendingInvitation(input.organizationId, user.id);\n\t\tif (pending) {\n\t\t\tresults.push({\n\t\t\t\temail: normalized,\n\t\t\t\tstatus: \"pending\",\n\t\t\t\tinvitationId: pending.id\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst now = /* @__PURE__ */ new Date();\n\t\tconst db = getDb();\n\t\tconst invitationId = crypto.randomUUID();\n\t\ttry {\n\t\t\tawait db.transaction(async (tx) => {\n\t\t\t\tawait tx.insert(organizationInvitations).values({\n\t\t\t\t\tid: invitationId,\n\t\t\t\t\torganizationId: input.organizationId,\n\t\t\t\t\tuserId: user.id,\n\t\t\t\t\temail: normalized,\n\t\t\t\t\trole: input.role,\n\t\t\t\t\tstatus: \"pending\",\n\t\t\t\t\tinvitedByUserId: input.invitedByUserId,\n\t\t\t\t\tcreatedAt: now,\n\t\t\t\t\tupdatedAt: now,\n\t\t\t\t\texpiresAt: new Date(now.getTime() + INVITATION_TTL_MS)\n\t\t\t\t});\n\t\t\t\tconst [existing] = await tx.select().from(organizationUsers).where(and$1(eq$1(organizationUsers.organizationId, input.organizationId), eq$1(organizationUsers.userId, user.id))).limit(1);\n\t\t\t\tif (!existing) await tx.insert(organizationUsers).values({\n\t\t\t\t\torganizationId: input.organizationId,\n\t\t\t\t\tuserId: user.id,\n\t\t\t\t\trole: input.role,\n\t\t\t\t\tstatus: \"invited\",\n\t\t\t\t\tcreatedAt: now,\n\t\t\t\t\tupdatedAt: now\n\t\t\t\t});\n\t\t\t\telse await tx.update(organizationUsers).set({\n\t\t\t\t\trole: input.role,\n\t\t\t\t\tstatus: \"invited\",\n\t\t\t\t\tupdatedAt: now,\n\t\t\t\t\tdeletedAt: null\n\t\t\t\t}).where(and$1(eq$1(organizationUsers.organizationId, input.organizationId), eq$1(organizationUsers.userId, user.id)));\n\t\t\t});\n\t\t\tresults.push({\n\t\t\t\temail: normalized,\n\t\t\t\tstatus: \"sent\",\n\t\t\t\tinvitationId\n\t\t\t});\n\t\t} catch {\n\t\t\tconst raced = await selectPendingInvitation(input.organizationId, user.id);\n\t\t\tresults.push({\n\t\t\t\temail: normalized,\n\t\t\t\tstatus: raced ? \"pending\" : \"sent\",\n\t\t\t\tinvitationId: raced?.id ?? invitationId\n\t\t\t});\n\t\t}\n\t}\n\treturn results;\n}\nfunction isEditableOrganizationMemberStatus(status) {\n\treturn status === \"active\" || status === \"invited\";\n}\nasync function updateOrganizationMemberRole(organizationId, userId, role) {\n\tconst membership = await selectOrganizationMembership(organizationId, userId);\n\tif (!membership || !isEditableOrganizationMemberStatus(membership.status)) throw new OrganizationMemberNotFoundError();\n\tif (membership.role === \"owner\") throw new CannotModifyOwnerError();\n\tconst now = /* @__PURE__ */ new Date();\n\tawait getDb().transaction(async (tx) => {\n\t\tawait tx.update(organizationUsers).set({\n\t\t\trole,\n\t\t\tupdatedAt: now\n\t\t}).where(and$1(eq$1(organizationUsers.organizationId, organizationId), eq$1(organizationUsers.userId, userId), isNull$1(organizationUsers.deletedAt)));\n\t\tif (membership.status === \"invited\") await tx.update(organizationInvitations).set({\n\t\t\trole,\n\t\t\tupdatedAt: now\n\t\t}).where(and$1(eq$1(organizationInvitations.organizationId, organizationId), eq$1(organizationInvitations.userId, userId), eq$1(organizationInvitations.status, \"pending\")));\n\t});\n\tconst [member] = await selectOrganizationMembers(organizationId).then((rows) => rows.filter((row) => row.id === userId));\n\tif (!member) throw new OrganizationMemberNotFoundError();\n\treturn member;\n}\nasync function removeOrganizationMember(organizationId, userId) {\n\tconst membership = await selectOrganizationMembership(organizationId, userId);\n\tif (!membership) throw new OrganizationMemberNotFoundError();\n\tif (membership.role === \"owner\" && membership.status === \"active\") throw new CannotModifyOwnerError(\"Organization owners cannot be removed\");\n\tif (membership.status === \"suspended\") return;\n\tconst now = /* @__PURE__ */ new Date();\n\tawait getDb().transaction(async (tx) => {\n\t\tif (membership.status === \"invited\") await tx.update(organizationInvitations).set({\n\t\t\tstatus: \"declined\",\n\t\t\tupdatedAt: now\n\t\t}).where(and$1(eq$1(organizationInvitations.organizationId, organizationId), eq$1(organizationInvitations.userId, userId), eq$1(organizationInvitations.status, \"pending\")));\n\t\tawait tx.update(organizationUsers).set({\n\t\t\tstatus: \"suspended\",\n\t\t\tupdatedAt: now,\n\t\t\tdeletedAt: null\n\t\t}).where(and$1(eq$1(organizationUsers.organizationId, organizationId), eq$1(organizationUsers.userId, userId), isNull$1(organizationUsers.deletedAt)));\n\t});\n}\n//#endregion\n//#region src/queries/invitations/index.ts\nvar OrganizationInvitationNotFoundError = class extends Error {\n\tconstructor(message = \"Invitation not found\") {\n\t\tsuper(message);\n\t\tthis.name = \"OrganizationInvitationNotFoundError\";\n\t}\n};\nvar OrganizationInvitationForbiddenError = class extends Error {\n\tconstructor(message = \"Forbidden\") {\n\t\tsuper(message);\n\t\tthis.name = \"OrganizationInvitationForbiddenError\";\n\t}\n};\nvar OrganizationInvitationExpiredError = class extends Error {\n\tconstructor(message = \"Invitation has expired\") {\n\t\tsuper(message);\n\t\tthis.name = \"OrganizationInvitationExpiredError\";\n\t}\n};\nasync function selectInvitationById(invitationId) {\n\treturn (await getDb().select().from(organizationInvitations).where(eq$1(organizationInvitations.id, invitationId)).limit(1))[0];\n}\nfunction isInvitationExpired(invitation, now = /* @__PURE__ */ new Date()) {\n\treturn invitation.expiresAt !== null && invitation.expiresAt.getTime() <= now.getTime();\n}\nasync function selectPendingInvitationsForUser(userId) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\treturn db.select({\n\t\tid: organizationInvitations.id,\n\t\torganizationName: organizations.name,\n\t\torganizationSlug: organizations.slug,\n\t\trole: organizationInvitations.role,\n\t\tinvitedByName: users.name,\n\t\tinvitedByEmail: users.email\n\t}).from(organizationInvitations).innerJoin(organizations, eq$1(organizationInvitations.organizationId, organizations.id)).innerJoin(users, eq$1(organizationInvitations.invitedByUserId, users.id)).where(and$1(eq$1(organizationInvitations.userId, userId), eq$1(organizationInvitations.status, \"pending\"), or(isNull$1(organizationInvitations.expiresAt), gt(organizationInvitations.expiresAt, now))));\n}\nasync function acceptInvitation(invitationId, userId) {\n\tconst invitation = await selectInvitationById(invitationId);\n\tif (!invitation || invitation.status !== \"pending\") throw new OrganizationInvitationNotFoundError();\n\tif (invitation.userId !== userId) throw new OrganizationInvitationForbiddenError();\n\tif (isInvitationExpired(invitation)) throw new OrganizationInvitationExpiredError();\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\tawait db.transaction(async (tx) => {\n\t\tconst [existing] = await tx.select().from(organizationUsers).where(and$1(eq$1(organizationUsers.organizationId, invitation.organizationId), eq$1(organizationUsers.userId, userId))).limit(1);\n\t\tif (!existing) await tx.insert(organizationUsers).values({\n\t\t\torganizationId: invitation.organizationId,\n\t\t\tuserId,\n\t\t\trole: invitation.role,\n\t\t\tstatus: \"active\",\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now\n\t\t});\n\t\telse await tx.update(organizationUsers).set({\n\t\t\trole: existing.role === \"owner\" ? \"owner\" : invitation.role,\n\t\t\tstatus: \"active\",\n\t\t\tupdatedAt: now,\n\t\t\tdeletedAt: null\n\t\t}).where(and$1(eq$1(organizationUsers.organizationId, invitation.organizationId), eq$1(organizationUsers.userId, userId)));\n\t\tawait ensureDefaultProjectForUserInTransaction(tx, userId, invitation.organizationId);\n\t\tawait tx.update(organizationInvitations).set({\n\t\t\tstatus: \"accepted\",\n\t\t\tupdatedAt: now\n\t\t}).where(eq$1(organizationInvitations.id, invitationId));\n\t});\n\tconst membership = await selectUserOrganizationMembership(userId, invitation.organizationId);\n\tif (!membership) throw new OrganizationMemberNotFoundError(\"Failed to load membership after accept\");\n\treturn membership;\n}\nasync function declineInvitation(invitationId, userId) {\n\tconst invitation = await selectInvitationById(invitationId);\n\tif (!invitation || invitation.status !== \"pending\") throw new OrganizationInvitationNotFoundError();\n\tif (invitation.userId !== userId) throw new OrganizationInvitationForbiddenError();\n\tconst now = /* @__PURE__ */ new Date();\n\tawait getDb().transaction(async (tx) => {\n\t\tawait tx.update(organizationUsers).set({\n\t\t\tstatus: \"rejected\",\n\t\t\tupdatedAt: now\n\t\t}).where(and$1(eq$1(organizationUsers.organizationId, invitation.organizationId), eq$1(organizationUsers.userId, userId), isNull$1(organizationUsers.deletedAt)));\n\t\tawait tx.update(organizationInvitations).set({\n\t\t\tstatus: \"declined\",\n\t\t\tupdatedAt: now\n\t\t}).where(eq$1(organizationInvitations.id, invitationId));\n\t});\n}\n//#endregion\n//#region src/queries/organization-users/index.ts\nasync function selectOrganizationUsersByUserId(userId) {\n\treturn getDb().select().from(organizationUsers).where(eq(organizationUsers.userId, userId));\n}\n//#endregion\n//#region src/queries/project-artifacts/complete-promote.ts\n/** Mark artifact ready and stage it as pending — does not flip activeArtifactId or sync registry. */\nasync function completeProjectArtifact(input) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\tif (isSqliteDialect()) {\n\t\tconst [artifact] = await db.update(projectArtifacts).set({\n\t\t\tstatus: \"ready\",\n\t\t\tmanifestJson: input.manifestJson ?? null,\n\t\t\tupdatedAt: now\n\t\t}).where(and(eq(projectArtifacts.id, input.artifactId), eq(projectArtifacts.projectId, input.projectId), eq(projectArtifacts.status, \"pending\"))).returning();\n\t\tif (!artifact) throw new Error(\"Artifact not found or already completed\");\n\t\tconst [project] = await db.update(projects).set({\n\t\t\tpendingArtifactId: artifact.id,\n\t\t\tstatus: \"starting\",\n\t\t\tlastError: null,\n\t\t\tupdatedAt: now\n\t\t}).where(eq(projects.id, input.projectId)).returning();\n\t\tif (!project) throw new Error(\"Project not found\");\n\t\treturn {\n\t\t\tartifact,\n\t\t\tproject\n\t\t};\n\t}\n\treturn db.transaction(async (tx) => {\n\t\tconst [artifact] = await tx.update(projectArtifacts).set({\n\t\t\tstatus: \"ready\",\n\t\t\tmanifestJson: input.manifestJson ?? null,\n\t\t\tupdatedAt: now\n\t\t}).where(and(eq(projectArtifacts.id, input.artifactId), eq(projectArtifacts.projectId, input.projectId), eq(projectArtifacts.status, \"pending\"))).returning();\n\t\tif (!artifact) throw new Error(\"Artifact not found or already completed\");\n\t\tconst [project] = await tx.update(projects).set({\n\t\t\tpendingArtifactId: artifact.id,\n\t\t\tstatus: \"starting\",\n\t\t\tlastError: null,\n\t\t\tupdatedAt: now\n\t\t}).where(eq(projects.id, input.projectId)).returning();\n\t\tif (!project) throw new Error(\"Project not found\");\n\t\treturn {\n\t\t\tartifact,\n\t\t\tproject\n\t\t};\n\t});\n}\n/** Cut over live deploy to a staged artifact after the new runtime is healthy. */\nasync function promoteProjectArtifact(input) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\tif (isSqliteDialect()) {\n\t\tconst [project] = await db.select().from(projects).where(eq(projects.id, input.projectId)).limit(1);\n\t\tif (!project) throw new Error(\"Project not found\");\n\t\tif (project.pendingArtifactId !== input.artifactId) throw new Error(\"Artifact is not the pending deploy for this project\");\n\t\tconst [artifact] = await db.select().from(projectArtifacts).where(and(eq(projectArtifacts.id, input.artifactId), eq(projectArtifacts.projectId, input.projectId), eq(projectArtifacts.status, \"ready\"))).limit(1);\n\t\tif (!artifact) throw new Error(\"Pending artifact not found or not ready\");\n\t\tconst [updatedProject] = await db.update(projects).set({\n\t\t\tactiveArtifactId: artifact.id,\n\t\t\tpendingArtifactId: null,\n\t\t\tupdatedAt: now\n\t\t}).where(eq(projects.id, input.projectId)).returning();\n\t\tif (!updatedProject) throw new Error(\"Project not found\");\n\t\treturn {\n\t\t\tartifact,\n\t\t\tproject: updatedProject\n\t\t};\n\t}\n\treturn db.transaction(async (tx) => {\n\t\tconst [project] = await tx.select().from(projects).where(eq(projects.id, input.projectId)).limit(1);\n\t\tif (!project) throw new Error(\"Project not found\");\n\t\tif (project.pendingArtifactId !== input.artifactId) throw new Error(\"Artifact is not the pending deploy for this project\");\n\t\tconst [artifact] = await tx.select().from(projectArtifacts).where(and(eq(projectArtifacts.id, input.artifactId), eq(projectArtifacts.projectId, input.projectId), eq(projectArtifacts.status, \"ready\"))).limit(1);\n\t\tif (!artifact) throw new Error(\"Pending artifact not found or not ready\");\n\t\tconst [updatedProject] = await tx.update(projects).set({\n\t\t\tactiveArtifactId: artifact.id,\n\t\t\tpendingArtifactId: null,\n\t\t\tupdatedAt: now\n\t\t}).where(eq(projects.id, input.projectId)).returning();\n\t\tif (!updatedProject) throw new Error(\"Project not found\");\n\t\treturn {\n\t\t\tartifact,\n\t\t\tproject: updatedProject\n\t\t};\n\t});\n}\nasync function updateProjectArtifactManifest(input) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\tconst [artifact] = await db.update(projectArtifacts).set({\n\t\tmanifestJson: input.manifestJson,\n\t\tupdatedAt: now\n\t}).where(eq(projectArtifacts.id, input.artifactId)).returning();\n\tif (!artifact) throw new Error(\"Artifact not found\");\n\treturn artifact;\n}\n/** Attach a deploy's source manifest (file tree) to its artifact. */\nasync function updateProjectArtifactSourceManifest(input) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\tconst [artifact] = await db.update(projectArtifacts).set({\n\t\tsourceManifestJson: input.sourceManifestJson,\n\t\tupdatedAt: now\n\t}).where(and(eq(projectArtifacts.id, input.artifactId), eq(projectArtifacts.projectId, input.projectId))).returning();\n\tif (!artifact) throw new Error(\"Artifact not found\");\n\treturn artifact;\n}\n//#endregion\n//#region src/queries/project-artifacts/last-deployment.ts\n/** Latest ready artifact timestamp per project for an organization. */\nasync function selectLastDeploymentAtByProject(organizationId) {\n\tconst rows = await getDb().select({\n\t\tprojectId: projectArtifacts.projectId,\n\t\tlastDeploymentAt: max(projectArtifacts.updatedAt)\n\t}).from(projectArtifacts).innerJoin(projects, eq(projects.id, projectArtifacts.projectId)).where(and(eq(projects.organizationId, organizationId), isNull(projects.deletedAt), eq(projectArtifacts.status, \"ready\"))).groupBy(projectArtifacts.projectId);\n\tconst result = {};\n\tfor (const row of rows) if (row.lastDeploymentAt) result[row.projectId] = row.lastDeploymentAt;\n\treturn result;\n}\n//#endregion\n//#region src/queries/project-artifacts/deployments.ts\n/** Ready artifact deploy history for a project, newest first. */\nasync function selectProjectDeployments(projectId) {\n\treturn (await getDb().select({\n\t\tid: projectArtifacts.id,\n\t\tprojectId: projectArtifacts.projectId,\n\t\tversion: projectArtifacts.version,\n\t\tcreatedAt: projectArtifacts.createdAt,\n\t\tactiveArtifactId: projects.activeArtifactId,\n\t\tdeployedByName: users.name,\n\t\tdeployedByEmail: users.email,\n\t\tdeployedByAvatarUrl: users.image\n\t}).from(projectArtifacts).innerJoin(projects, eq(projects.id, projectArtifacts.projectId)).leftJoin(users, eq(users.id, projectArtifacts.createdByUserId)).where(and(eq(projectArtifacts.projectId, projectId), eq(projectArtifacts.status, \"ready\"))).orderBy(desc(projectArtifacts.createdAt))).map((row) => ({\n\t\tid: row.id,\n\t\tprojectId: row.projectId,\n\t\tversion: row.version,\n\t\tcreatedAt: row.createdAt,\n\t\tactive: row.activeArtifactId === row.id,\n\t\tdeployedByName: row.deployedByName,\n\t\tdeployedByEmail: row.deployedByEmail,\n\t\tdeployedByAvatarUrl: row.deployedByAvatarUrl\n\t}));\n}\n//#endregion\n//#region src/queries/project-artifacts/index.ts\nasync function insertProjectArtifact(input) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\tconst [versionRow] = await db.select({ maxVersion: max(projectArtifacts.version) }).from(projectArtifacts).where(eq(projectArtifacts.projectId, input.projectId));\n\tconst version = (versionRow?.maxVersion ?? 0) + 1;\n\tconst [row] = await db.insert(projectArtifacts).values({\n\t\tid: input.id,\n\t\tprojectId: input.projectId,\n\t\tstorageKey: input.storageKey,\n\t\tversion,\n\t\tcreatedByUserId: input.createdByUserId ?? null,\n\t\tstatus: \"pending\",\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t}).returning();\n\tif (!row) throw new Error(\"Failed to create project artifact\");\n\treturn row;\n}\nasync function selectProjectArtifactById(artifactId) {\n\treturn (await getDb().select().from(projectArtifacts).where(eq(projectArtifacts.id, artifactId)).limit(1))[0];\n}\nasync function selectProjectArtifactForProject(artifactId, projectId) {\n\treturn (await getDb().select().from(projectArtifacts).where(and(eq(projectArtifacts.id, artifactId), eq(projectArtifacts.projectId, projectId))).limit(1))[0];\n}\nasync function selectActiveProjectArtifactForProject(projectId) {\n\tconst activeArtifactId = (await getDb().select({ activeArtifactId: projects.activeArtifactId }).from(projects).where(eq(projects.id, projectId)).limit(1))[0]?.activeArtifactId;\n\tif (!activeArtifactId) return;\n\treturn selectProjectArtifactForProject(activeArtifactId, projectId);\n}\nasync function selectActiveArtifactManifestForProject(projectId) {\n\treturn (await getDb().select({ manifestJson: projectArtifacts.manifestJson }).from(projects).innerJoin(projectArtifacts, eq(projects.activeArtifactId, projectArtifacts.id)).where(eq(projects.id, projectId)).limit(1))[0]?.manifestJson ?? void 0;\n}\n/** Source manifest (file tree) for the project's currently active deploy. */\nasync function selectActiveArtifactSourceManifestForProject(projectId) {\n\treturn (await getDb().select({\n\t\tartifactId: projectArtifacts.id,\n\t\tsourceManifestJson: projectArtifacts.sourceManifestJson\n\t}).from(projects).innerJoin(projectArtifacts, eq(projects.activeArtifactId, projectArtifacts.id)).where(eq(projects.id, projectId)).limit(1))[0];\n}\n/** Runtime and source manifests for active deploys in an organization. */\nasync function selectActiveArtifactManifestsByOrganizationId(organizationId) {\n\treturn getDb().select({\n\t\tprojectId: projects.id,\n\t\tprojectUpdatedAt: projects.updatedAt,\n\t\tartifactId: projectArtifacts.id,\n\t\tartifactUpdatedAt: projectArtifacts.updatedAt,\n\t\tmanifestJson: projectArtifacts.manifestJson,\n\t\tsourceManifestJson: projectArtifacts.sourceManifestJson\n\t}).from(projects).innerJoin(projectArtifacts, eq(projects.activeArtifactId, projectArtifacts.id)).where(and(eq(projects.organizationId, organizationId), isNull(projects.deletedAt)));\n}\n//#endregion\n//#region src/api-keys/constants.ts\nconst WEBHOOK_API_KEY_CONFIG_ID = \"webhook\";\nconst ORG_PLATFORM_API_KEY_CONFIG_ID = \"org-platform\";\nfunction generateApiKeySecret(prefix = \"wh_\") {\n\treturn `${prefix}${randomBytes(32).toString(\"base64url\")}`;\n}\nfunction apiKeyStart(secret, length = 8) {\n\treturn secret.slice(0, length);\n}\nfunction encryptApiKeySecret(secret) {\n\treturn encryptCredentialPayload$1(secret);\n}\nfunction decryptApiKeySecret(ciphertext) {\n\treturn decryptCredentialPayload$1(ciphertext);\n}\nfunction hashApiKeySecret(secret) {\n\treturn createHash(\"sha256\").update(secret).digest(\"base64\");\n}\nfunction verifyApiKeySecret(secret, storedHash) {\n\tconst actual = Buffer.from(hashApiKeySecret(secret));\n\tconst expected = Buffer.from(storedHash);\n\tif (actual.length !== expected.length) return false;\n\treturn timingSafeEqual(actual, expected);\n}\n//#endregion\n//#region src/api-keys/metadata.ts\nfunction parseWebhookApiKeyMetadata(metadata) {\n\tif (!metadata) return null;\n\ttry {\n\t\tconst value = JSON.parse(metadata);\n\t\tif (value.kind !== \"trigger-webhook\" || typeof value.route !== \"string\" || typeof value.projectId !== \"string\") return null;\n\t\tconst rawSlugs = value.attachmentSlugs ?? value.attachmentKeys;\n\t\tconst attachmentSlugs = Array.isArray(rawSlugs) ? rawSlugs.filter((slug) => typeof slug === \"string\") : [];\n\t\treturn {\n\t\t\tkind: \"trigger-webhook\",\n\t\t\tprojectId: value.projectId,\n\t\t\troute: value.route,\n\t\t\tattachmentSlugs\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\nfunction serializeWebhookApiKeyMetadata(metadata) {\n\treturn JSON.stringify(metadata);\n}\n//#endregion\n//#region src/api-keys/list.ts\nasync function listWebhookApiKeys() {\n\tconst rows = await listApiKeysByConfigId(WEBHOOK_API_KEY_CONFIG_ID);\n\tconst views = [];\n\tfor (const row of rows) {\n\t\tconst parsed = parseWebhookApiKeyMetadata(row.metadata);\n\t\tif (!parsed || !row.keyCiphertext) continue;\n\t\tviews.push({\n\t\t\tid: row.id,\n\t\t\tprojectId: parsed.projectId,\n\t\t\troute: parsed.route,\n\t\t\tname: row.name,\n\t\t\tstart: row.start,\n\t\t\tprefix: row.prefix,\n\t\t\ttoken: decryptApiKeySecret(row.keyCiphertext),\n\t\t\tattachmentSlugs: parsed.attachmentSlugs,\n\t\t\tcreatedAt: row.createdAt,\n\t\t\tupdatedAt: row.updatedAt\n\t\t});\n\t}\n\treturn views;\n}\nasync function listWebhookApiKeysForProject(projectId) {\n\treturn (await listWebhookApiKeys()).filter((key) => key.projectId === projectId);\n}\n//#endregion\n//#region src/api-keys/ensure.ts\nfunction webhookEndpointSuffix(route) {\n\treturn route.startsWith(\"/triggers/\") ? route.slice(10) : route;\n}\nfunction webhookApiKeyName(projectId, route) {\n\treturn `${projectId}:${webhookEndpointSuffix(route)}`;\n}\nasync function ensureWebhookApiKeys(projectId, routes, referenceId) {\n\tconst created = [];\n\tconst existing = [];\n\tfor (const { route, attachmentSlugs } of routes) {\n\t\tconst name = webhookApiKeyName(projectId, route);\n\t\tif (await selectApiKeyByConfigName(\"webhook\", name)) {\n\t\t\texisting.push(route);\n\t\t\tcontinue;\n\t\t}\n\t\tconst secret = generateApiKeySecret();\n\t\tconst now = /* @__PURE__ */ new Date();\n\t\tconst metadata = {\n\t\t\tkind: \"trigger-webhook\",\n\t\t\tprojectId,\n\t\t\troute,\n\t\t\tattachmentSlugs\n\t\t};\n\t\tawait insertApiKey({\n\t\t\tid: crypto.randomUUID(),\n\t\t\tconfigId: WEBHOOK_API_KEY_CONFIG_ID,\n\t\t\tname,\n\t\t\tstart: apiKeyStart(secret),\n\t\t\tprefix: \"wh_\",\n\t\t\tkey: hashApiKeySecret(secret),\n\t\t\tkeyCiphertext: encryptApiKeySecret(secret),\n\t\t\treferenceId,\n\t\t\tmetadata: serializeWebhookApiKeyMetadata(metadata),\n\t\t\tpermissions: JSON.stringify({ triggers: [\"invoke\"] }),\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now\n\t\t});\n\t\tcreated.push({\n\t\t\troute,\n\t\t\ttoken: secret\n\t\t});\n\t}\n\treturn {\n\t\tcreated,\n\t\texisting\n\t};\n}\n/** Idempotently ensures a webhook API key exists and returns the plaintext token. */\nasync function ensureWebhookApiKeyForRoute(projectId, route, attachmentSlugs) {\n\tconst created = (await ensureWebhookApiKeys(projectId, [{\n\t\troute,\n\t\tattachmentSlugs\n\t}], projectId)).created.find((entry) => entry.route === route);\n\tif (created) return created.token;\n\tconst existing = (await listWebhookApiKeysForProject(projectId)).find((entry) => entry.route === route);\n\tif (!existing?.token) throw new Error(`Webhook API key not found for route ${route}`);\n\treturn existing.token;\n}\n//#endregion\n//#region src/api-keys/verify.ts\nasync function verifyWebhookApiKeyForRoute(projectId, route, secret) {\n\tconst row = await selectApiKeyByConfigName(WEBHOOK_API_KEY_CONFIG_ID, webhookApiKeyName(projectId, route));\n\tif (!row) return false;\n\treturn verifyApiKeySecret(secret, row.key);\n}\n//#endregion\n//#region src/api-keys/org-platform-metadata.ts\nfunction parseOrgPlatformApiKeyMetadata(metadata) {\n\tif (!metadata) return null;\n\ttry {\n\t\tconst value = JSON.parse(metadata);\n\t\tif (value.kind !== \"org-platform\" || typeof value.organizationId !== \"string\" || typeof value.createdByUserId !== \"string\" || typeof value.keyPreview !== \"string\") return null;\n\t\treturn {\n\t\t\tkind: \"org-platform\",\n\t\t\torganizationId: value.organizationId,\n\t\t\tcreatedByUserId: value.createdByUserId,\n\t\t\tkeyPreview: value.keyPreview\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\nfunction serializeOrgPlatformApiKeyMetadata(metadata) {\n\treturn JSON.stringify(metadata);\n}\n//#endregion\n//#region src/api-keys/org-platform.ts\nvar OrgPlatformApiKeyNotFoundError = class extends Error {\n\tconstructor() {\n\t\tsuper(\"API key not found\");\n\t\tthis.name = \"OrgPlatformApiKeyNotFoundError\";\n\t}\n};\nfunction keyPreviewFromSecret(secret) {\n\treturn `******${secret.slice(-4)}`;\n}\nfunction parseOrgPlatformRow(row) {\n\tconst metadata = parseOrgPlatformApiKeyMetadata(row.metadata);\n\tif (!metadata || row.name == null) return null;\n\treturn {\n\t\tid: row.id,\n\t\tname: row.name,\n\t\tkeyPreview: metadata.keyPreview,\n\t\tcreatedAt: row.createdAt,\n\t\tcreatedByUserId: metadata.createdByUserId\n\t};\n}\nfunction isActiveApiKey(row) {\n\tif (row.enabled === false) return false;\n\tif (row.expiresAt && row.expiresAt.getTime() <= Date.now()) return false;\n\treturn true;\n}\nasync function listOrgPlatformApiKeysForUser(organizationId, userId) {\n\tconst rows = await listApiKeysByConfigReferenceId(ORG_PLATFORM_API_KEY_CONFIG_ID, userId);\n\tconst records = [];\n\tfor (const row of rows) {\n\t\tconst metadata = parseOrgPlatformApiKeyMetadata(row.metadata);\n\t\tif (!metadata || metadata.organizationId !== organizationId || metadata.createdByUserId !== userId) continue;\n\t\tconst record = parseOrgPlatformRow(row);\n\t\tif (record) records.push(record);\n\t}\n\treturn records;\n}\nasync function listOrgPlatformApiKeysForOrganization(organizationId) {\n\tconst rows = await listApiKeysByConfigId(ORG_PLATFORM_API_KEY_CONFIG_ID);\n\tconst records = [];\n\tfor (const row of rows) {\n\t\tconst metadata = parseOrgPlatformApiKeyMetadata(row.metadata);\n\t\tif (!metadata || metadata.organizationId !== organizationId) continue;\n\t\tconst record = parseOrgPlatformRow(row);\n\t\tif (record) records.push(record);\n\t}\n\treturn records;\n}\nasync function createOrgPlatformApiKey(input) {\n\tconst secret = generateApiKeySecret(\"sk_\");\n\tconst now = /* @__PURE__ */ new Date();\n\tconst metadata = serializeOrgPlatformApiKeyMetadata({\n\t\tkind: \"org-platform\",\n\t\torganizationId: input.organizationId,\n\t\tcreatedByUserId: input.userId,\n\t\tkeyPreview: keyPreviewFromSecret(secret)\n\t});\n\tconst record = {\n\t\tid: crypto.randomUUID(),\n\t\tname: input.name,\n\t\tkeyPreview: keyPreviewFromSecret(secret),\n\t\tcreatedAt: now,\n\t\tcreatedByUserId: input.userId,\n\t\tsecret\n\t};\n\tawait insertApiKey({\n\t\tid: record.id,\n\t\tconfigId: ORG_PLATFORM_API_KEY_CONFIG_ID,\n\t\tname: input.name,\n\t\tstart: apiKeyStart(secret),\n\t\tprefix: \"sk_\",\n\t\tkey: hashApiKeySecret(secret),\n\t\tkeyCiphertext: encryptApiKeySecret(secret),\n\t\treferenceId: input.userId,\n\t\tmetadata,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t});\n\treturn record;\n}\nasync function selectOrgPlatformApiKeyForOrganization(apiKeyId, organizationId) {\n\tconst row = await selectApiKeyById(apiKeyId);\n\tif (!row || row.configId !== \"org-platform\") return null;\n\tconst record = parseOrgPlatformRow(row);\n\tif (!record) return null;\n\tif (parseOrgPlatformApiKeyMetadata(row.metadata)?.organizationId !== organizationId) return null;\n\treturn record;\n}\nasync function revokeOrgPlatformApiKey(apiKeyId, organizationId) {\n\tif (!await selectOrgPlatformApiKeyForOrganization(apiKeyId, organizationId)) throw new OrgPlatformApiKeyNotFoundError();\n\tawait deleteApiKeyById(apiKeyId);\n}\nasync function verifyOrgPlatformApiKeySecret(secret) {\n\tif (!secret.startsWith(\"sk_\")) return null;\n\tconst row = await selectApiKeyByConfigAndHash(ORG_PLATFORM_API_KEY_CONFIG_ID, hashApiKeySecret(secret));\n\tif (!row || !isActiveApiKey(row)) return null;\n\tconst metadata = parseOrgPlatformApiKeyMetadata(row.metadata);\n\tif (!metadata) return null;\n\treturn {\n\t\tapiKeyId: row.id,\n\t\torganizationId: metadata.organizationId,\n\t\tuserId: metadata.createdByUserId\n\t};\n}\nasync function loadOrgPlatformApiKeyUser(userId) {\n\treturn await selectUserById(userId) ?? null;\n}\nfunction mapOrgPlatformApiKeyCreator(user) {\n\treturn {\n\t\tid: user.id,\n\t\tname: user.name,\n\t\temail: user.email,\n\t\tavatarUrl: user.image ?? void 0\n\t};\n}\nfunction mapOrgPlatformApiKeyCreatorOrDeleted(userId, user) {\n\tif (user) return mapOrgPlatformApiKeyCreator(user);\n\treturn {\n\t\tid: userId,\n\t\tname: \"Deleted user\",\n\t\tdeleted: true\n\t};\n}\n//#endregion\n//#region src/client/workspace-context.ts\nconst storage = new AsyncLocalStorage();\nfunction runWithWorkspaceContext(context, fn) {\n\treturn storage.run(context, fn);\n}\nfunction getWorkspaceContext() {\n\treturn storage.getStore();\n}\nfunction requireWorkspaceContext() {\n\tconst context = getWorkspaceContext();\n\tif (!context) throw new Error(\"Workspace context is not set\");\n\treturn context;\n}\n//#endregion\n//#region src/project-database/build-url.ts\nvar build_url_exports = /* @__PURE__ */ __exportAll({\n\tbuildOrgDatabaseUrl: () => buildOrgDatabaseUrl,\n\tbuildProjectDatabaseUrl: () => buildProjectDatabaseUrl,\n\tresolveOrgDatabaseUrl: () => resolveOrgDatabaseUrl,\n\tresolveProjectDatabaseUrl: () => resolveProjectDatabaseUrl\n});\nfunction buildOrgDatabaseUrl(user, password, env = process.env) {\n\treturn buildPostgresUrl({\n\t\t...resolvePlatformPostgresConfig(env),\n\t\tuser: qualifyConnectionUser(user, env),\n\t\tpassword\n\t});\n}\nfunction resolveOrgDatabaseUrl(organization) {\n\tif (inferDialect(resolvePlatformDatabaseUrl()) === \"sqlite\") return organization.dbSchema.startsWith(\"file:\") ? organization.dbSchema : `file:${organization.dbSchema}`;\n\tconst password = decryptCredentialPayload$1(organization.dbPasswordCiphertext);\n\treturn buildOrgDatabaseUrl(organization.dbUser, password);\n}\n/** @deprecated Use {@link resolveOrgDatabaseUrl}. */\nfunction resolveProjectDatabaseUrl(organization) {\n\treturn resolveOrgDatabaseUrl(organization);\n}\n/** @deprecated Use {@link buildOrgDatabaseUrl}. */\nfunction buildProjectDatabaseUrl(_baseUrl, user, password) {\n\treturn buildOrgDatabaseUrl(user, password);\n}\n//#endregion\n//#region src/project-database/runtime-env.ts\nasync function resolveOrgRuntimeDatabase(organizationId) {\n\tconst organization = await selectOrganizationById(organizationId);\n\tif (!organization) throw new Error(`Organization not found: ${organizationId}`);\n\tif (inferDialect(resolvePlatformDatabaseUrl()) === \"sqlite\") {\n\t\tconst url = organization.dbSchema.startsWith(\"file:\") ? organization.dbSchema : `file:${organization.dbSchema}`;\n\t\treturn {\n\t\t\thost: \"\",\n\t\t\tport: 0,\n\t\t\tdatabase: organization.dbSchema,\n\t\t\tuser: \"\",\n\t\t\tpassword: \"\",\n\t\t\tsearchPath: \"\",\n\t\t\turl\n\t\t};\n\t}\n\tconst platform = resolvePlatformPostgresConfig();\n\treturn {\n\t\thost: platform.host,\n\t\tport: platform.port,\n\t\tdatabase: platform.database,\n\t\tuser: qualifyConnectionUser(organization.dbUser),\n\t\tpassword: decryptCredentialPayload$1(organization.dbPasswordCiphertext),\n\t\tsearchPath: organization.dbSchema\n\t};\n}\nasync function resolveProjectRuntimeDatabase(input) {\n\treturn {\n\t\t...await resolveOrgRuntimeDatabase(input.organizationId),\n\t\tprojectId: input.projectId,\n\t\torganizationId: input.organizationId\n\t};\n}\n//#endregion\n//#region src/project-database/pgboss-grants.ts\nvar pgboss_grants_exports = /* @__PURE__ */ __exportAll({ grantPgBossAccess: () => grantPgBossAccess });\nasync function grantPgBossAccess(pool, dbUser) {\n\tconst roleIdent = quotePgIdent(dbUser);\n\tconst { rows } = await pool.query(`SELECT EXISTS (\n SELECT 1 FROM information_schema.schemata WHERE schema_name = 'pgboss'\n ) AS exists`);\n\tif (!rows[0]?.exists) return;\n\tawait pool.query(`GRANT USAGE ON SCHEMA pgboss TO ${roleIdent}`);\n\tawait pool.query(`GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA pgboss TO ${roleIdent}`);\n\tawait pool.query(`GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA pgboss TO ${roleIdent}`);\n}\n//#endregion\n//#region src/project-database/ensure-pgboss-grants.ts\nasync function ensureOrgPgBossGrants() {\n\tconst { Pool: PgPool } = loadPg();\n\tconst pool = new PgPool({ connectionString: resolvePlatformDatabaseUrl() });\n\ttry {\n\t\tconst rows = await getDb().select({ dbUser: organizations.dbUser }).from(organizations).where(isNull(organizations.deletedAt));\n\t\tconst users = [...new Set(rows.map((row) => row.dbUser))];\n\t\tfor (const dbUser of users) await grantPgBossAccess(pool, dbUser);\n\t} finally {\n\t\tawait pool.end();\n\t}\n}\n/** @deprecated Use {@link ensureOrgPgBossGrants}. */\nconst ensureProjectPgBossGrants = ensureOrgPgBossGrants;\n//#endregion\n//#region src/project-database/ensure-org-runtime-migrations.ts\nasync function ensureOrgRuntimeMigrations() {\n\tconst dialect = inferDialect(resolvePlatformDatabaseUrl());\n\tconst { createConnection, resolveMigrationsFolder, runMigrations } = await import(\"@keystrokehq/database\");\n\tconst rows = await getDb().select({\n\t\tdbSchema: organizations.dbSchema,\n\t\tdbUser: organizations.dbUser,\n\t\tdbPasswordCiphertext: organizations.dbPasswordCiphertext\n\t}).from(organizations).where(isNull(organizations.deletedAt));\n\tconst migrationsFolder = resolveMigrationsFolder(dialect);\n\tfor (const org of rows) {\n\t\tconst handle = createConnection({\n\t\t\turl: resolveOrgDatabaseUrl(org),\n\t\t\tdialect,\n\t\t\t...dialect === \"postgres\" ? { searchPath: org.dbSchema } : {}\n\t\t});\n\t\ttry {\n\t\t\tawait runMigrations(handle, migrationsFolder);\n\t\t} finally {\n\t\t\thandle.close();\n\t\t}\n\t}\n}\n/** @deprecated Use {@link ensureOrgRuntimeMigrations}. */\nconst ensureProjectRuntimeMigrations = ensureOrgRuntimeMigrations;\n//#endregion\n//#region src/org-storage/resolve-config.ts\nfunction hasOrgStorageConfig(organization) {\n\treturn !!organization.storageBucket && !!organization.storageEndpoint && !!organization.storageAccessKeyIdCiphertext && !!organization.storageSecretAccessKeyCiphertext;\n}\nfunction resolveOrgStorageConfig(organization) {\n\tif (!hasOrgStorageConfig(organization)) throw new Error(\"Organization storage is not configured\");\n\treturn {\n\t\tbucket: organization.storageBucket,\n\t\tendpoint: organization.storageEndpoint,\n\t\taccessKeyId: decryptCredentialPayload$1(organization.storageAccessKeyIdCiphertext),\n\t\tsecretAccessKey: decryptCredentialPayload$1(organization.storageSecretAccessKeyCiphertext),\n\t\tregion: organization.storageRegion ?? \"us-east-1\",\n\t\tforcePathStyle: organization.storageForcePathStyle ?? true\n\t};\n}\n//#endregion\n//#region src/org-storage/client.ts\nfunction createOrgStorageClient(organization) {\n\treturn createStorage(resolveOrgStorageConfig(organization));\n}\nfunction createOrgAgentStorageClient(organization, agentId) {\n\tconst config = resolveOrgStorageConfig(organization);\n\tconst bucket = orgAgentBucketName({\n\t\torgBucket: config.bucket,\n\t\tagentId\n\t});\n\treturn createStorage({\n\t\t...config,\n\t\tbucket\n\t});\n}\nfunction createOrgContainerPresign(organization) {\n\treturn createContainerPresignStorage(resolveOrgStorageConfig(organization));\n}\n//#endregion\n//#region src/org-storage/runtime-env.ts\nfunction orgStorageRuntimeEnv(config, containerEnv) {\n\treturn {\n\t\tSTORAGE_ACCESS_KEY_ID: config.accessKeyId,\n\t\tSTORAGE_SECRET_ACCESS_KEY: config.secretAccessKey,\n\t\tSTORAGE_ENDPOINT: containerEnv ? containerPresignEndpointFromEnv(config.endpoint, containerEnv) : config.endpoint,\n\t\tSTORAGE_REGION: config.region,\n\t\tSTORAGE_FORCE_PATH_STYLE: String(config.forcePathStyle),\n\t\tKEYSTROKE_WORKSPACES_BUCKET: config.bucket\n\t};\n}\nfunction orgWorkspacesRuntimeEnv(organization, options) {\n\tif (!hasOrgStorageConfig(organization)) return {};\n\treturn orgStorageRuntimeEnv(resolveOrgStorageConfig(organization), options?.containerEnv);\n}\n//#endregion\n//#region src/queries/_internal/organization-scope.ts\nfunction eqOrganizationScope(table) {\n\treturn eq$1(table.organizationId, requireOrganizationScopeId());\n}\nfunction scopedAnd(table, ...conditions) {\n\treturn and$1(eqOrganizationScope(table), ...conditions);\n}\nfunction organizationScopeId() {\n\treturn requireOrganizationScopeId();\n}\n//#endregion\n//#region src/queries/oauth-apps/index.ts\nasync function selectOAuthAppBySlug(slug) {\n\treturn (await getDb().select().from(oauthApps).where(scopedAnd(oauthApps, eq$1(oauthApps.slug, slug))).limit(1))[0];\n}\nasync function selectOAuthAppById(id) {\n\treturn (await getDb().select().from(oauthApps).where(scopedAnd(oauthApps, eq$1(oauthApps.id, id))).limit(1))[0];\n}\nasync function insertOAuthApp(values) {\n\tawait getDb().insert(oauthApps).values({\n\t\t...values,\n\t\torganizationId: organizationScopeId()\n\t});\n}\nasync function updateOAuthAppBySlug(slug, values) {\n\tawait getDb().update(oauthApps).set(values).where(scopedAnd(oauthApps, eq$1(oauthApps.slug, slug)));\n}\n//#endregion\n//#region src/queries/oauth-apps/global.ts\n/** Org-unscoped lookup — used before organization scope is known (e.g. inbound Slack webhooks). */\nasync function listOAuthAppsBySlugUnscoped(slug) {\n\treturn getDb().select().from(oauthApps).where(eq$1(oauthApps.slug, slug));\n}\n//#endregion\n//#region src/queries/oauth-connections/index.ts\nasync function selectOAuthConnectionById(id) {\n\treturn (await getDb().select({ connection: oauthConnections }).from(oauthConnections).innerJoin(oauthApps, eq$1(oauthApps.id, oauthConnections.appId)).where(scopedAnd(oauthApps, eq$1(oauthConnections.id, id))).limit(1))[0]?.connection;\n}\nasync function selectOAuthConnectionsByIds(ids) {\n\tif (ids.length === 0) return [];\n\treturn (await getDb().select({ connection: oauthConnections }).from(oauthConnections).innerJoin(oauthApps, eq$1(oauthApps.id, oauthConnections.appId)).where(scopedAnd(oauthApps, inArray$1(oauthConnections.id, ids)))).map((row) => row.connection);\n}\nasync function selectOAuthConnectionByAppAndExternalId(appId, externalId) {\n\treturn (await getDb().select({ connection: oauthConnections }).from(oauthConnections).innerJoin(oauthApps, eq$1(oauthApps.id, oauthConnections.appId)).where(scopedAnd(oauthApps, eq$1(oauthConnections.appId, appId), eq$1(oauthConnections.externalId, externalId))).limit(1))[0]?.connection;\n}\nasync function listOAuthConnectionsByAppId(appId) {\n\treturn (await getDb().select({ connection: oauthConnections }).from(oauthConnections).innerJoin(oauthApps, eq$1(oauthApps.id, oauthConnections.appId)).where(scopedAnd(oauthApps, eq$1(oauthConnections.appId, appId)))).map((row) => row.connection);\n}\nasync function deleteOAuthConnectionById(id) {\n\tif (!await selectOAuthConnectionById(id)) return false;\n\tawait getDb().delete(oauthConnections).where(eq$1(oauthConnections.id, id));\n\treturn true;\n}\nasync function insertOAuthConnection(values) {\n\tawait getDb().insert(oauthConnections).values(values);\n}\n/** Returns the id of the persisted row: the existing row's id on update, `values.id` on insert. */\nasync function upsertOAuthConnection(values) {\n\tconst existing = await selectOAuthConnectionByAppAndExternalId(values.appId, values.externalId);\n\tif (existing) {\n\t\tawait getDb().update(oauthConnections).set({\n\t\t\taccessTokenCiphertext: values.accessTokenCiphertext,\n\t\t\trefreshTokenCiphertext: values.refreshTokenCiphertext,\n\t\t\taccessTokenExpiresAt: values.accessTokenExpiresAt,\n\t\t\tgrantedScopes: values.grantedScopes && values.grantedScopes.length > 0 ? values.grantedScopes : existing.grantedScopes,\n\t\t\tmetadata: values.metadata,\n\t\t\tupdatedAt: values.updatedAt\n\t\t}).where(eq$1(oauthConnections.id, existing.id));\n\t\treturn existing.id;\n\t}\n\tawait insertOAuthConnection(values);\n\treturn values.id;\n}\n//#endregion\n//#region src/queries/oauth-connections/global.ts\n/** Org-unscoped lookup — resolves a Slack team_id (externalId) to org + connection via oauth_apps.slug. */\nasync function selectOAuthInstallationsByAppSlugAndExternalId(appSlug, externalId) {\n\treturn getDb().select({\n\t\torganizationId: oauthApps.organizationId,\n\t\tconnectionId: oauthConnections.id,\n\t\tappId: oauthApps.id,\n\t\texternalId: oauthConnections.externalId\n\t}).from(oauthConnections).innerJoin(oauthApps, eq$1(oauthApps.id, oauthConnections.appId)).where(and$1(eq$1(oauthApps.slug, appSlug), eq$1(oauthConnections.externalId, externalId)));\n}\n//#endregion\n//#region src/queries/secret-values/index.ts\nasync function selectSecretValue(refKind, refId, field) {\n\treturn (await getDb().select().from(secretValues).where(scopedAnd(secretValues, eq$1(secretValues.refKind, refKind), eq$1(secretValues.refId, refId), eq$1(secretValues.field, field))).limit(1))[0];\n}\nasync function upsertSecretValue(values) {\n\tconst db = getDb();\n\tconst existing = await selectSecretValue(values.refKind, values.refId, values.field);\n\tif (existing) {\n\t\tawait db.update(secretValues).set({\n\t\t\tciphertext: values.ciphertext,\n\t\t\tupdatedAt: values.updatedAt\n\t\t}).where(eq$1(secretValues.id, existing.id));\n\t\treturn;\n\t}\n\tawait db.insert(secretValues).values({\n\t\t...values,\n\t\torganizationId: organizationScopeId()\n\t});\n}\nasync function deleteSecretValuesForRef(refKind, refId) {\n\tawait getDb().delete(secretValues).where(scopedAnd(secretValues, eq$1(secretValues.refKind, refKind), eq$1(secretValues.refId, refId)));\n}\n//#endregion\n//#region src/oauth/app.ts\nfunction metadataMatches(existing, next) {\n\treturn JSON.stringify(existing ?? null) === JSON.stringify(next ?? null);\n}\nfunction oauthAppValuesDiffer(existing, options) {\n\tconst nextSigningSecret = options.signingSecret ?? \"\";\n\treturn existing.clientId !== options.clientId || existing.clientSecret !== options.clientSecret || existing.signingSecret !== nextSigningSecret || !metadataMatches(existing.metadata, options.metadata ?? null);\n}\nfunction encryptOAuthAppValues(options) {\n\treturn {\n\t\tclientIdCiphertext: encryptCredentialPayload$1(options.clientId),\n\t\tclientSecretCiphertext: encryptCredentialPayload$1(options.clientSecret),\n\t\tsigningSecretCiphertext: options.signingSecret ? encryptCredentialPayload$1(options.signingSecret) : null,\n\t\tmetadata: options.metadata ?? null\n\t};\n}\nfunction decryptOAuthAppRow(row) {\n\treturn {\n\t\tid: row.id,\n\t\tprovider: row.provider,\n\t\tslug: row.slug,\n\t\ttokenStrategy: row.tokenStrategy,\n\t\tclientId: decryptCredentialPayload$1(row.clientIdCiphertext),\n\t\tclientSecret: decryptCredentialPayload$1(row.clientSecretCiphertext),\n\t\tsigningSecret: row.signingSecretCiphertext ? decryptCredentialPayload$1(row.signingSecretCiphertext) : \"\",\n\t\tredirectUri: row.redirectUri,\n\t\tmetadata: row.metadata ?? null\n\t};\n}\nasync function getDecryptedOAuthAppBySlug(slug) {\n\tconst row = await selectOAuthAppBySlug(slug);\n\tif (!row) return null;\n\treturn decryptOAuthAppRow(row);\n}\nasync function getDecryptedOAuthAppById(id) {\n\tconst row = await selectOAuthAppById(id);\n\tif (!row) return null;\n\treturn decryptOAuthAppRow(row);\n}\nasync function ensureOAuthApp(options) {\n\tconst existing = await selectOAuthAppBySlug(options.slug);\n\tif (existing) {\n\t\tif (!oauthAppValuesDiffer(decryptOAuthAppRow(existing), options)) return {\n\t\t\tid: existing.id,\n\t\t\tcreated: false,\n\t\t\tupdated: false\n\t\t};\n\t\tawait updateOAuthAppBySlug(options.slug, {\n\t\t\t...encryptOAuthAppValues(options),\n\t\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t\t});\n\t\treturn {\n\t\t\tid: existing.id,\n\t\t\tcreated: false,\n\t\t\tupdated: true\n\t\t};\n\t}\n\tconst now = /* @__PURE__ */ new Date();\n\tconst id = crypto.randomUUID();\n\tawait insertOAuthApp({\n\t\tid,\n\t\tprovider: options.provider,\n\t\tslug: options.slug,\n\t\ttokenStrategy: options.tokenStrategy,\n\t\t...encryptOAuthAppValues(options),\n\t\tredirectUri: null,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t});\n\treturn {\n\t\tid,\n\t\tcreated: true,\n\t\tupdated: false\n\t};\n}\n//#endregion\n//#region src/oauth/connection.ts\nfunction decryptOAuthConnectionRow(row) {\n\treturn {\n\t\tid: row.id,\n\t\tappId: row.appId,\n\t\texternalId: row.externalId,\n\t\taccessToken: decryptCredentialPayload$1(row.accessTokenCiphertext),\n\t\trefreshToken: row.refreshTokenCiphertext ? decryptCredentialPayload$1(row.refreshTokenCiphertext) : null,\n\t\taccessTokenExpiresAt: row.accessTokenExpiresAt ?? null,\n\t\tgrantedScopes: row.grantedScopes ?? null,\n\t\tmetadata: row.metadata ?? null\n\t};\n}\nasync function getDecryptedOAuthConnectionById(id) {\n\tconst row = await selectOAuthConnectionById(id);\n\tif (!row) return null;\n\treturn decryptOAuthConnectionRow(row);\n}\nasync function getDecryptedOAuthConnectionsByAppSlug(appSlug) {\n\tconst app = await selectOAuthAppBySlug(appSlug);\n\tif (!app) return [];\n\treturn (await listOAuthConnectionsByAppId(app.id)).map(decryptOAuthConnectionRow);\n}\nasync function getDecryptedOAuthConnectionByAppSlugAndExternalId(appSlug, externalId) {\n\tconst app = await selectOAuthAppBySlug(appSlug);\n\tif (!app) return null;\n\tconst row = await selectOAuthConnectionByAppAndExternalId(app.id, externalId);\n\tif (!row) return null;\n\treturn decryptOAuthConnectionRow(row);\n}\nasync function saveOAuthConnection(options) {\n\tconst now = /* @__PURE__ */ new Date();\n\treturn upsertOAuthConnection({\n\t\tid: options.connectionId ?? crypto.randomUUID(),\n\t\tappId: options.appId,\n\t\texternalId: options.externalId,\n\t\taccessTokenCiphertext: encryptCredentialPayload$1(options.accessToken),\n\t\trefreshTokenCiphertext: options.refreshToken ? encryptCredentialPayload$1(options.refreshToken) : null,\n\t\taccessTokenExpiresAt: options.accessTokenExpiresAt ?? null,\n\t\tgrantedScopes: options.grantedScopes ?? null,\n\t\tmetadata: options.metadata ?? null,\n\t\tconnectedAt: now,\n\t\tupdatedAt: now\n\t});\n}\n//#endregion\n//#region src/oauth/refresh-token.ts\nconst TOKEN_EXPIRY_BUFFER_MS = 6e4;\nfunction accessTokenIsStale(expiresAt) {\n\tif (!expiresAt) return true;\n\treturn expiresAt.getTime() <= Date.now() + TOKEN_EXPIRY_BUFFER_MS;\n}\nasync function resolveOAuthAccessToken(connection, app, tokenRefresh) {\n\tif (app.tokenStrategy === \"installation\" || app.tokenStrategy === \"app_installation\") return connection.accessToken;\n\tif (!accessTokenIsStale(connection.accessTokenExpiresAt)) return connection.accessToken;\n\tif (!connection.refreshToken) throw new Error(`OAuth connection \"${connection.id}\" is missing a refresh token.`);\n\tconst refresh = tokenRefresh?.get(app.slug);\n\tif (!refresh) throw new Error(`OAuth refresh is not registered for app \"${app.slug}\".`);\n\tconst refreshed = await refresh({\n\t\tclientId: app.clientId,\n\t\tclientSecret: app.clientSecret,\n\t\trefreshToken: connection.refreshToken\n\t});\n\tawait saveOAuthConnection({\n\t\tappId: connection.appId,\n\t\texternalId: connection.externalId,\n\t\taccessToken: refreshed.accessToken,\n\t\trefreshToken: refreshed.refreshToken ?? connection.refreshToken,\n\t\taccessTokenExpiresAt: refreshed.accessTokenExpiresAt,\n\t\tgrantedScopes: connection.grantedScopes ?? void 0,\n\t\tmetadata: connection.metadata ?? void 0,\n\t\tconnectionId: connection.id\n\t});\n\treturn refreshed.accessToken;\n}\n//#endregion\n//#region src/oauth/global-lookup.ts\n/** Signing secret for inbound webhooks before org scope is known (shared managed Slack app). */\nasync function getOAuthAppSigningSecretBySlugGlobal(appSlug) {\n\tconst fromEnv = process.env.SLACK_SIGNING_SECRET?.trim();\n\tif (fromEnv) return fromEnv;\n\tconst apps = await listOAuthAppsBySlugUnscoped(appSlug);\n\tfor (const app of apps) if (app.signingSecretCiphertext) return decryptCredentialPayload$1(app.signingSecretCiphertext);\n\treturn null;\n}\n/** All orgs connected to a Slack workspace (team_id). */\nasync function listOAuthInstallationsByAppSlugAndExternalId(appSlug, externalId) {\n\treturn (await selectOAuthInstallationsByAppSlugAndExternalId(appSlug, externalId)).map((row) => ({\n\t\torganizationId: row.organizationId,\n\t\tconnectionId: row.connectionId\n\t}));\n}\n/** Bot token for a team from any org's connection (same Slack app + team → same token). */\nasync function getGlobalOAuthAccessTokenByAppSlugAndExternalId(appSlug, externalId) {\n\tconst first = (await selectOAuthInstallationsByAppSlugAndExternalId(appSlug, externalId))[0];\n\tif (!first) return null;\n\tconst connection = await selectOAuthConnectionById(first.connectionId);\n\tif (!connection) return null;\n\treturn decryptCredentialPayload$1(connection.accessTokenCiphertext);\n}\n//#endregion\n//#region src/queries/apps/slug.ts\nasync function isOrgAppSlugTaken(orgSlug, slugPart) {\n\tconst qualified = qualifyOrgSlug(orgSlug, slugPart);\n\treturn (await getDb().select({ id: apps.id }).from(apps).where(eq$1(apps.slug, qualified)).limit(1)).length > 0;\n}\nasync function resolveAvailableOrgAppSlug(orgSlug, nameOrSlug) {\n\tconst base = slugifyAppName(nameOrSlug);\n\tif (!await isOrgAppSlugTaken(orgSlug, base)) return base;\n\tfor (let suffix = 2; suffix < 1e4; suffix += 1) {\n\t\tconst candidate = AppSlugSchema.parse(`${base}-${suffix}`);\n\t\tif (!await isOrgAppSlugTaken(orgSlug, candidate)) return candidate;\n\t}\n\tthrow new Error(\"Unable to allocate a unique app slug\");\n}\nasync function checkOrgAppSlugAvailability(orgSlug, slugPart) {\n\tconst normalized = slugPart.trim().toLowerCase();\n\tconst format = AppSlugSchema.safeParse(normalized);\n\tif (!format.success) return {\n\t\tslug: normalized,\n\t\tavailable: false,\n\t\treason: \"invalid\"\n\t};\n\tconst parsed = format.data;\n\tif (await isOrgAppSlugTaken(orgSlug, parsed)) return {\n\t\tslug: parsed,\n\t\tavailable: false,\n\t\treason: \"taken\",\n\t\tsuggestion: await resolveAvailableOrgAppSlug(orgSlug, parsed)\n\t};\n\treturn {\n\t\tslug: parsed,\n\t\tavailable: true\n\t};\n}\n//#endregion\n//#region src/queries/apps/index.ts\nvar OrgAppSlugTakenError = class extends Error {\n\tslug;\n\tconstructor(slug) {\n\t\tsuper(`App slug already exists: ${slug}`);\n\t\tthis.name = \"OrgAppSlugTakenError\";\n\t\tthis.slug = slug;\n\t}\n};\nasync function selectAppBySlug(slug) {\n\treturn (await getDb().select().from(apps).where(eq$1(apps.slug, slug)).limit(1))[0];\n}\nasync function listOfficialApps() {\n\treturn getDb().select().from(apps).where(isNull$1(apps.organizationId));\n}\nasync function listAppsForOrganization(organizationId) {\n\treturn getDb().select().from(apps).where(or(isNull$1(apps.organizationId), eq$1(apps.organizationId, organizationId)));\n}\nasync function selectAppForOrganization(organizationId, slug) {\n\tconst row = await selectAppBySlug(slug);\n\tif (!row) return;\n\tif (row.organizationId === null || row.organizationId === organizationId) return row;\n}\nasync function createOrgApp(values) {\n\tconst db = getDb();\n\tconst slug = qualifyOrgSlug(values.orgSlug, values.slug);\n\tif (await selectAppBySlug(slug)) throw new OrgAppSlugTakenError(slug);\n\tconst now = /* @__PURE__ */ new Date();\n\treturn (await db.insert(apps).values({\n\t\tid: crypto.randomUUID(),\n\t\torganizationId: values.organizationId,\n\t\tslug,\n\t\tname: values.name,\n\t\tdescription: values.description,\n\t\tcategory: \"Custom\",\n\t\tlogo: null,\n\t\tauthKind: \"api_key\",\n\t\toauthScopes: [],\n\t\tcredentialFields: values.credentialFields,\n\t\tsource: \"custom\",\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t}).returning())[0];\n}\nasync function upsertOfficialApp(values) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\tif (await selectAppBySlug(values.slug)) return (await db.update(apps).set({\n\t\tname: values.name,\n\t\tdescription: values.description,\n\t\tcategory: values.category,\n\t\t...values.logo !== void 0 ? { logo: values.logo } : {},\n\t\tauthKind: values.authKind,\n\t\toauthScopes: values.oauthScopes,\n\t\tsource: values.source,\n\t\t...values.credentialFields !== void 0 ? { credentialFields: values.credentialFields } : {},\n\t\t...values.credentialScheme !== void 0 ? { credentialScheme: values.credentialScheme } : {},\n\t\tupdatedAt: now\n\t}).where(eq$1(apps.slug, values.slug)).returning())[0];\n\treturn (await db.insert(apps).values({\n\t\tid: crypto.randomUUID(),\n\t\torganizationId: null,\n\t\tcredentialFields: values.credentialFields ?? {},\n\t\tcredentialScheme: values.credentialScheme ?? null,\n\t\t...values,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t}).returning())[0];\n}\nfunction hasCredentialFieldTemplate(row) {\n\treturn Object.keys(row.credentialFields).length > 0;\n}\nasync function selectOrgAppBySlug(organizationId, slug) {\n\treturn (await getDb().select().from(apps).where(and$1(eq$1(apps.slug, slug), eq$1(apps.organizationId, organizationId))).limit(1))[0];\n}\n//#endregion\n//#region src/apps/seed.ts\n/** Upsert official apps from a hosted manifest. Idempotent — safe to run on a schedule. */\nasync function seedOfficialApps(entries) {\n\tfor (const entry of entries) await upsertOfficialApp({\n\t\tslug: entry.slug,\n\t\tname: entry.name,\n\t\tdescription: entry.description,\n\t\tcategory: entry.category,\n\t\t...entry.logo !== void 0 ? { logo: entry.logo } : {},\n\t\tauthKind: entry.authKind,\n\t\toauthScopes: entry.oauthScopes,\n\t\tsource: entry.source\n\t});\n}\n//#endregion\nexport { CannotModifyOwnerError, DEFAULT_PLATFORM_DATABASE_URL, DEFAULT_STANDALONE_ORGANIZATION_ID, DEFAULT_STANDALONE_ORGANIZATION_NAME, DEFAULT_STANDALONE_ORGANIZATION_SLUG, DEFAULT_STANDALONE_PROJECT_NAME, DEFAULT_STANDALONE_PROJECT_SLUG, LastOwnerError, ORG_PLATFORM_API_KEY_CONFIG_ID, OrgAppSlugTakenError, OrgPlatformApiKeyNotFoundError, OrganizationInvitationExpiredError, OrganizationInvitationForbiddenError, OrganizationInvitationNotFoundError, OrganizationMemberNotFoundError, OrganizationSlugTakenError, ProjectMemberNotFoundError, ProjectSlugTakenError, WEBHOOK_API_KEY_CONFIG_ID, acceptInvitation, apps, backfillProjectUsers, buildDefaultProjectDescription, buildDefaultProjectForUser, buildOrgDatabaseUrl, buildProjectDatabaseUrl, checkOrgAppSlugAvailability, checkOrganizationSlugAvailability, checkProjectSlugAvailability, closeDatabase, completeProjectArtifact, createConnection, createOrgAgentStorageClient, createOrgApp, createOrgContainerPresign, createOrgPlatformApiKey, createOrgStorageClient, createOrganizationForUser, createPgConnection, createProjectForOrganization, createSqliteConnection, declineInvitation, decryptCredentialPayload, deleteOAuthConnectionById, deleteProjectForOrganization, deleteSecretValuesForRef, deprovisionOrgDatabase, encryptCredentialPayload, ensureDefaultOrganization, ensureDefaultOrganizationAndProject, ensureDefaultProject, ensureDefaultProjectForUser, ensureDefaultProjectForUserInTransaction, ensureOAuthApp, ensureOrgPgBossGrants, ensureOrgRuntimeMigrations, ensureProjectPgBossGrants, ensureProjectRuntimeMigrations, ensureWebhookApiKeyForRoute, ensureWebhookApiKeys, findOrCreateUserByEmail, firstNameFromUser, getDatabaseHandle, getDecryptedOAuthAppById, getDecryptedOAuthAppBySlug, getDecryptedOAuthConnectionByAppSlugAndExternalId, getDecryptedOAuthConnectionById, getDecryptedOAuthConnectionsByAppSlug, getGlobalOAuthAccessTokenByAppSlugAndExternalId, getOAuthAppSigningSecretBySlugGlobal, getOrganizationScopeId, getWorkspaceContext, hasCredentialFieldTemplate, initDatabase, insertOAuthApp, insertProjectArtifact, inviteOrganizationMembers, inviteProjectMembers, isDatabaseInitialized, isOrganizationStorageBucketInUse, isStandaloneMode, listAppsForOrganization, listOAuthAppsBySlugUnscoped, listOAuthConnectionsByAppId, listOAuthInstallationsByAppSlugAndExternalId, listOfficialApps, listOrgPlatformApiKeysForOrganization, listOrgPlatformApiKeysForUser, listWebhookApiKeys, listWebhookApiKeysForProject, loadOrgPlatformApiKeyUser, mapOrgPlatformApiKeyCreator, mapOrgPlatformApiKeyCreatorOrDeleted, normalizeUserEmail, orgDbRoleName, orgDbSchemaName, orgWorkspacesRuntimeEnv, organizationInvitationStatuses, organizationRowToSidebarBranding, organizationUserRoles, projectArtifactStatuses, projectDbRoleName, projectDbSchemaName, projectStatuses, promoteProjectArtifact, provisionOrgDatabase, removeOrganizationMember, removeProjectMember, requireOrganizationScopeId, requireWorkspaceContext, resolveMigrationsFolder, resolveNewOrganizationIdentity, resolveOAuthAccessToken, resolveOrgDatabaseUrl, resolveOrgRuntimeDatabase, resolveOrgStorageConfig, resolveProjectDatabaseUrl, resolveProjectRuntimeDatabase, revokeOrgPlatformApiKey, runMigrations, runWithOrganizationScope, runWithStandaloneScope, runWithWorkspaceContext, saveOAuthConnection, seedOfficialApps, selectActiveArtifactManifestForProject, selectActiveArtifactManifestsByOrganizationId, selectActiveArtifactSourceManifestForProject, selectActiveOrganizationIds, selectActiveProjectArtifactForProject, selectAppBySlug, selectAppForOrganization, selectLastDeploymentAtByProject, selectOAuthAppById, selectOAuthAppBySlug, selectOAuthConnectionByAppAndExternalId, selectOAuthConnectionById, selectOAuthConnectionsByIds, selectOAuthInstallationsByAppSlugAndExternalId, selectOrgAppBySlug, selectOrgPlatformApiKeyForOrganization, selectOrganizationById, selectOrganizationBySlug, selectOrganizationMembers, selectOrganizationUsersByUserId, selectPendingInvitationsForUser, selectProjectArtifactById, selectProjectArtifactForProject, selectProjectById, selectProjectDeployments, selectProjectForOrganization, selectProjectForOrganizationBySlug, selectProjectIdsForUser, selectProjectMembers, selectProjectsByOrganizationId, selectSecretValue, selectUserByEmail, selectUserById, selectUserByNormalizedEmail, selectUserOrganization, selectUserOrganizationMembership, selectUserOrganizations, selectUserProjectMembership, selectUsersByIds, updateOAuthAppBySlug, updateOrganizationActive, updateOrganizationFailed, updateOrganizationMemberRole, updateOrganizationName, updateOrganizationSidebarBranding, updateOrganizationSlug, updateProjectActive, updateProjectArtifactManifest, updateProjectArtifactSourceManifest, updateProjectFailed, updateProjectForOrganization, updateProjectMemberRole, updateProjectSettings, updateUserById, upsertOAuthConnection, upsertOfficialApp, upsertProjectMember, upsertSecretValue, verifyOrgPlatformApiKeySecret, verifyWebhookApiKeyForRoute, webhookApiKeyName, webhookEndpointSuffix };\n\n//# sourceMappingURL=index.mjs.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.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;\n// eslint-disable-next-line @typescript-eslint/no-extraneous-class\nclass _CodeOrName {\n}\nexports._CodeOrName = _CodeOrName;\nexports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;\nclass Name extends _CodeOrName {\n constructor(s) {\n super();\n if (!exports.IDENTIFIER.test(s))\n throw new Error(\"CodeGen: name must be a valid identifier\");\n this.str = s;\n }\n toString() {\n return this.str;\n }\n emptyStr() {\n return false;\n }\n get names() {\n return { [this.str]: 1 };\n }\n}\nexports.Name = Name;\nclass _Code extends _CodeOrName {\n constructor(code) {\n super();\n this._items = typeof code === \"string\" ? [code] : code;\n }\n toString() {\n return this.str;\n }\n emptyStr() {\n if (this._items.length > 1)\n return false;\n const item = this._items[0];\n return item === \"\" || item === '\"\"';\n }\n get str() {\n var _a;\n return ((_a = this._str) !== null && _a !== void 0 ? _a : (this._str = this._items.reduce((s, c) => `${s}${c}`, \"\")));\n }\n get names() {\n var _a;\n return ((_a = this._names) !== null && _a !== void 0 ? _a : (this._names = this._items.reduce((names, c) => {\n if (c instanceof Name)\n names[c.str] = (names[c.str] || 0) + 1;\n return names;\n }, {})));\n }\n}\nexports._Code = _Code;\nexports.nil = new _Code(\"\");\nfunction _(strs, ...args) {\n const code = [strs[0]];\n let i = 0;\n while (i < args.length) {\n addCodeArg(code, args[i]);\n code.push(strs[++i]);\n }\n return new _Code(code);\n}\nexports._ = _;\nconst plus = new _Code(\"+\");\nfunction str(strs, ...args) {\n const expr = [safeStringify(strs[0])];\n let i = 0;\n while (i < args.length) {\n expr.push(plus);\n addCodeArg(expr, args[i]);\n expr.push(plus, safeStringify(strs[++i]));\n }\n optimize(expr);\n return new _Code(expr);\n}\nexports.str = str;\nfunction addCodeArg(code, arg) {\n if (arg instanceof _Code)\n code.push(...arg._items);\n else if (arg instanceof Name)\n code.push(arg);\n else\n code.push(interpolate(arg));\n}\nexports.addCodeArg = addCodeArg;\nfunction optimize(expr) {\n let i = 1;\n while (i < expr.length - 1) {\n if (expr[i] === plus) {\n const res = mergeExprItems(expr[i - 1], expr[i + 1]);\n if (res !== undefined) {\n expr.splice(i - 1, 3, res);\n continue;\n }\n expr[i++] = \"+\";\n }\n i++;\n }\n}\nfunction mergeExprItems(a, b) {\n if (b === '\"\"')\n return a;\n if (a === '\"\"')\n return b;\n if (typeof a == \"string\") {\n if (b instanceof Name || a[a.length - 1] !== '\"')\n return;\n if (typeof b != \"string\")\n return `${a.slice(0, -1)}${b}\"`;\n if (b[0] === '\"')\n return a.slice(0, -1) + b.slice(1);\n return;\n }\n if (typeof b == \"string\" && b[0] === '\"' && !(a instanceof Name))\n return `\"${a}${b.slice(1)}`;\n return;\n}\nfunction strConcat(c1, c2) {\n return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str `${c1}${c2}`;\n}\nexports.strConcat = strConcat;\n// TODO do not allow arrays here\nfunction interpolate(x) {\n return typeof x == \"number\" || typeof x == \"boolean\" || x === null\n ? x\n : safeStringify(Array.isArray(x) ? x.join(\",\") : x);\n}\nfunction stringify(x) {\n return new _Code(safeStringify(x));\n}\nexports.stringify = stringify;\nfunction safeStringify(x) {\n return JSON.stringify(x)\n .replace(/\\u2028/g, \"\\\\u2028\")\n .replace(/\\u2029/g, \"\\\\u2029\");\n}\nexports.safeStringify = safeStringify;\nfunction getProperty(key) {\n return typeof key == \"string\" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _ `[${key}]`;\n}\nexports.getProperty = getProperty;\n//Does best effort to format the name properly\nfunction getEsmExportName(key) {\n if (typeof key == \"string\" && exports.IDENTIFIER.test(key)) {\n return new _Code(`${key}`);\n }\n throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`);\n}\nexports.getEsmExportName = getEsmExportName;\nfunction regexpCode(rx) {\n return new _Code(rx.toString());\n}\nexports.regexpCode = regexpCode;\n//# sourceMappingURL=code.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0;\nconst code_1 = require(\"./code\");\nclass ValueError extends Error {\n constructor(name) {\n super(`CodeGen: \"code\" for ${name} not defined`);\n this.value = name.value;\n }\n}\nvar UsedValueState;\n(function (UsedValueState) {\n UsedValueState[UsedValueState[\"Started\"] = 0] = \"Started\";\n UsedValueState[UsedValueState[\"Completed\"] = 1] = \"Completed\";\n})(UsedValueState || (exports.UsedValueState = UsedValueState = {}));\nexports.varKinds = {\n const: new code_1.Name(\"const\"),\n let: new code_1.Name(\"let\"),\n var: new code_1.Name(\"var\"),\n};\nclass Scope {\n constructor({ prefixes, parent } = {}) {\n this._names = {};\n this._prefixes = prefixes;\n this._parent = parent;\n }\n toName(nameOrPrefix) {\n return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix);\n }\n name(prefix) {\n return new code_1.Name(this._newName(prefix));\n }\n _newName(prefix) {\n const ng = this._names[prefix] || this._nameGroup(prefix);\n return `${prefix}${ng.index++}`;\n }\n _nameGroup(prefix) {\n var _a, _b;\n if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || (this._prefixes && !this._prefixes.has(prefix))) {\n throw new Error(`CodeGen: prefix \"${prefix}\" is not allowed in this scope`);\n }\n return (this._names[prefix] = { prefix, index: 0 });\n }\n}\nexports.Scope = Scope;\nclass ValueScopeName extends code_1.Name {\n constructor(prefix, nameStr) {\n super(nameStr);\n this.prefix = prefix;\n }\n setValue(value, { property, itemIndex }) {\n this.value = value;\n this.scopePath = (0, code_1._) `.${new code_1.Name(property)}[${itemIndex}]`;\n }\n}\nexports.ValueScopeName = ValueScopeName;\nconst line = (0, code_1._) `\\n`;\nclass ValueScope extends Scope {\n constructor(opts) {\n super(opts);\n this._values = {};\n this._scope = opts.scope;\n this.opts = { ...opts, _n: opts.lines ? line : code_1.nil };\n }\n get() {\n return this._scope;\n }\n name(prefix) {\n return new ValueScopeName(prefix, this._newName(prefix));\n }\n value(nameOrPrefix, value) {\n var _a;\n if (value.ref === undefined)\n throw new Error(\"CodeGen: ref must be passed in value\");\n const name = this.toName(nameOrPrefix);\n const { prefix } = name;\n const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref;\n let vs = this._values[prefix];\n if (vs) {\n const _name = vs.get(valueKey);\n if (_name)\n return _name;\n }\n else {\n vs = this._values[prefix] = new Map();\n }\n vs.set(valueKey, name);\n const s = this._scope[prefix] || (this._scope[prefix] = []);\n const itemIndex = s.length;\n s[itemIndex] = value.ref;\n name.setValue(value, { property: prefix, itemIndex });\n return name;\n }\n getValue(prefix, keyOrRef) {\n const vs = this._values[prefix];\n if (!vs)\n return;\n return vs.get(keyOrRef);\n }\n scopeRefs(scopeName, values = this._values) {\n return this._reduceValues(values, (name) => {\n if (name.scopePath === undefined)\n throw new Error(`CodeGen: name \"${name}\" has no value`);\n return (0, code_1._) `${scopeName}${name.scopePath}`;\n });\n }\n scopeCode(values = this._values, usedValues, getCode) {\n return this._reduceValues(values, (name) => {\n if (name.value === undefined)\n throw new Error(`CodeGen: name \"${name}\" has no value`);\n return name.value.code;\n }, usedValues, getCode);\n }\n _reduceValues(values, valueCode, usedValues = {}, getCode) {\n let code = code_1.nil;\n for (const prefix in values) {\n const vs = values[prefix];\n if (!vs)\n continue;\n const nameSet = (usedValues[prefix] = usedValues[prefix] || new Map());\n vs.forEach((name) => {\n if (nameSet.has(name))\n return;\n nameSet.set(name, UsedValueState.Started);\n let c = valueCode(name);\n if (c) {\n const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const;\n code = (0, code_1._) `${code}${def} ${name} = ${c};${this.opts._n}`;\n }\n else if ((c = getCode === null || getCode === void 0 ? void 0 : getCode(name))) {\n code = (0, code_1._) `${code}${c}${this.opts._n}`;\n }\n else {\n throw new ValueError(name);\n }\n nameSet.set(name, UsedValueState.Completed);\n });\n }\n return code;\n }\n}\nexports.ValueScope = ValueScope;\n//# sourceMappingURL=scope.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.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;\nconst code_1 = require(\"./code\");\nconst scope_1 = require(\"./scope\");\nvar code_2 = require(\"./code\");\nObject.defineProperty(exports, \"_\", { enumerable: true, get: function () { return code_2._; } });\nObject.defineProperty(exports, \"str\", { enumerable: true, get: function () { return code_2.str; } });\nObject.defineProperty(exports, \"strConcat\", { enumerable: true, get: function () { return code_2.strConcat; } });\nObject.defineProperty(exports, \"nil\", { enumerable: true, get: function () { return code_2.nil; } });\nObject.defineProperty(exports, \"getProperty\", { enumerable: true, get: function () { return code_2.getProperty; } });\nObject.defineProperty(exports, \"stringify\", { enumerable: true, get: function () { return code_2.stringify; } });\nObject.defineProperty(exports, \"regexpCode\", { enumerable: true, get: function () { return code_2.regexpCode; } });\nObject.defineProperty(exports, \"Name\", { enumerable: true, get: function () { return code_2.Name; } });\nvar scope_2 = require(\"./scope\");\nObject.defineProperty(exports, \"Scope\", { enumerable: true, get: function () { return scope_2.Scope; } });\nObject.defineProperty(exports, \"ValueScope\", { enumerable: true, get: function () { return scope_2.ValueScope; } });\nObject.defineProperty(exports, \"ValueScopeName\", { enumerable: true, get: function () { return scope_2.ValueScopeName; } });\nObject.defineProperty(exports, \"varKinds\", { enumerable: true, get: function () { return scope_2.varKinds; } });\nexports.operators = {\n GT: new code_1._Code(\">\"),\n GTE: new code_1._Code(\">=\"),\n LT: new code_1._Code(\"<\"),\n LTE: new code_1._Code(\"<=\"),\n EQ: new code_1._Code(\"===\"),\n NEQ: new code_1._Code(\"!==\"),\n NOT: new code_1._Code(\"!\"),\n OR: new code_1._Code(\"||\"),\n AND: new code_1._Code(\"&&\"),\n ADD: new code_1._Code(\"+\"),\n};\nclass Node {\n optimizeNodes() {\n return this;\n }\n optimizeNames(_names, _constants) {\n return this;\n }\n}\nclass Def extends Node {\n constructor(varKind, name, rhs) {\n super();\n this.varKind = varKind;\n this.name = name;\n this.rhs = rhs;\n }\n render({ es5, _n }) {\n const varKind = es5 ? scope_1.varKinds.var : this.varKind;\n const rhs = this.rhs === undefined ? \"\" : ` = ${this.rhs}`;\n return `${varKind} ${this.name}${rhs};` + _n;\n }\n optimizeNames(names, constants) {\n if (!names[this.name.str])\n return;\n if (this.rhs)\n this.rhs = optimizeExpr(this.rhs, names, constants);\n return this;\n }\n get names() {\n return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {};\n }\n}\nclass Assign extends Node {\n constructor(lhs, rhs, sideEffects) {\n super();\n this.lhs = lhs;\n this.rhs = rhs;\n this.sideEffects = sideEffects;\n }\n render({ _n }) {\n return `${this.lhs} = ${this.rhs};` + _n;\n }\n optimizeNames(names, constants) {\n if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects)\n return;\n this.rhs = optimizeExpr(this.rhs, names, constants);\n return this;\n }\n get names() {\n const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names };\n return addExprNames(names, this.rhs);\n }\n}\nclass AssignOp extends Assign {\n constructor(lhs, op, rhs, sideEffects) {\n super(lhs, rhs, sideEffects);\n this.op = op;\n }\n render({ _n }) {\n return `${this.lhs} ${this.op}= ${this.rhs};` + _n;\n }\n}\nclass Label extends Node {\n constructor(label) {\n super();\n this.label = label;\n this.names = {};\n }\n render({ _n }) {\n return `${this.label}:` + _n;\n }\n}\nclass Break extends Node {\n constructor(label) {\n super();\n this.label = label;\n this.names = {};\n }\n render({ _n }) {\n const label = this.label ? ` ${this.label}` : \"\";\n return `break${label};` + _n;\n }\n}\nclass Throw extends Node {\n constructor(error) {\n super();\n this.error = error;\n }\n render({ _n }) {\n return `throw ${this.error};` + _n;\n }\n get names() {\n return this.error.names;\n }\n}\nclass AnyCode extends Node {\n constructor(code) {\n super();\n this.code = code;\n }\n render({ _n }) {\n return `${this.code};` + _n;\n }\n optimizeNodes() {\n return `${this.code}` ? this : undefined;\n }\n optimizeNames(names, constants) {\n this.code = optimizeExpr(this.code, names, constants);\n return this;\n }\n get names() {\n return this.code instanceof code_1._CodeOrName ? this.code.names : {};\n }\n}\nclass ParentNode extends Node {\n constructor(nodes = []) {\n super();\n this.nodes = nodes;\n }\n render(opts) {\n return this.nodes.reduce((code, n) => code + n.render(opts), \"\");\n }\n optimizeNodes() {\n const { nodes } = this;\n let i = nodes.length;\n while (i--) {\n const n = nodes[i].optimizeNodes();\n if (Array.isArray(n))\n nodes.splice(i, 1, ...n);\n else if (n)\n nodes[i] = n;\n else\n nodes.splice(i, 1);\n }\n return nodes.length > 0 ? this : undefined;\n }\n optimizeNames(names, constants) {\n const { nodes } = this;\n let i = nodes.length;\n while (i--) {\n // iterating backwards improves 1-pass optimization\n const n = nodes[i];\n if (n.optimizeNames(names, constants))\n continue;\n subtractNames(names, n.names);\n nodes.splice(i, 1);\n }\n return nodes.length > 0 ? this : undefined;\n }\n get names() {\n return this.nodes.reduce((names, n) => addNames(names, n.names), {});\n }\n}\nclass BlockNode extends ParentNode {\n render(opts) {\n return \"{\" + opts._n + super.render(opts) + \"}\" + opts._n;\n }\n}\nclass Root extends ParentNode {\n}\nclass Else extends BlockNode {\n}\nElse.kind = \"else\";\nclass If extends BlockNode {\n constructor(condition, nodes) {\n super(nodes);\n this.condition = condition;\n }\n render(opts) {\n let code = `if(${this.condition})` + super.render(opts);\n if (this.else)\n code += \"else \" + this.else.render(opts);\n return code;\n }\n optimizeNodes() {\n super.optimizeNodes();\n const cond = this.condition;\n if (cond === true)\n return this.nodes; // else is ignored here\n let e = this.else;\n if (e) {\n const ns = e.optimizeNodes();\n e = this.else = Array.isArray(ns) ? new Else(ns) : ns;\n }\n if (e) {\n if (cond === false)\n return e instanceof If ? e : e.nodes;\n if (this.nodes.length)\n return this;\n return new If(not(cond), e instanceof If ? [e] : e.nodes);\n }\n if (cond === false || !this.nodes.length)\n return undefined;\n return this;\n }\n optimizeNames(names, constants) {\n var _a;\n this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);\n if (!(super.optimizeNames(names, constants) || this.else))\n return;\n this.condition = optimizeExpr(this.condition, names, constants);\n return this;\n }\n get names() {\n const names = super.names;\n addExprNames(names, this.condition);\n if (this.else)\n addNames(names, this.else.names);\n return names;\n }\n}\nIf.kind = \"if\";\nclass For extends BlockNode {\n}\nFor.kind = \"for\";\nclass ForLoop extends For {\n constructor(iteration) {\n super();\n this.iteration = iteration;\n }\n render(opts) {\n return `for(${this.iteration})` + super.render(opts);\n }\n optimizeNames(names, constants) {\n if (!super.optimizeNames(names, constants))\n return;\n this.iteration = optimizeExpr(this.iteration, names, constants);\n return this;\n }\n get names() {\n return addNames(super.names, this.iteration.names);\n }\n}\nclass ForRange extends For {\n constructor(varKind, name, from, to) {\n super();\n this.varKind = varKind;\n this.name = name;\n this.from = from;\n this.to = to;\n }\n render(opts) {\n const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind;\n const { name, from, to } = this;\n return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts);\n }\n get names() {\n const names = addExprNames(super.names, this.from);\n return addExprNames(names, this.to);\n }\n}\nclass ForIter extends For {\n constructor(loop, varKind, name, iterable) {\n super();\n this.loop = loop;\n this.varKind = varKind;\n this.name = name;\n this.iterable = iterable;\n }\n render(opts) {\n return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);\n }\n optimizeNames(names, constants) {\n if (!super.optimizeNames(names, constants))\n return;\n this.iterable = optimizeExpr(this.iterable, names, constants);\n return this;\n }\n get names() {\n return addNames(super.names, this.iterable.names);\n }\n}\nclass Func extends BlockNode {\n constructor(name, args, async) {\n super();\n this.name = name;\n this.args = args;\n this.async = async;\n }\n render(opts) {\n const _async = this.async ? \"async \" : \"\";\n return `${_async}function ${this.name}(${this.args})` + super.render(opts);\n }\n}\nFunc.kind = \"func\";\nclass Return extends ParentNode {\n render(opts) {\n return \"return \" + super.render(opts);\n }\n}\nReturn.kind = \"return\";\nclass Try extends BlockNode {\n render(opts) {\n let code = \"try\" + super.render(opts);\n if (this.catch)\n code += this.catch.render(opts);\n if (this.finally)\n code += this.finally.render(opts);\n return code;\n }\n optimizeNodes() {\n var _a, _b;\n super.optimizeNodes();\n (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNodes();\n (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes();\n return this;\n }\n optimizeNames(names, constants) {\n var _a, _b;\n super.optimizeNames(names, constants);\n (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);\n (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants);\n return this;\n }\n get names() {\n const names = super.names;\n if (this.catch)\n addNames(names, this.catch.names);\n if (this.finally)\n addNames(names, this.finally.names);\n return names;\n }\n}\nclass Catch extends BlockNode {\n constructor(error) {\n super();\n this.error = error;\n }\n render(opts) {\n return `catch(${this.error})` + super.render(opts);\n }\n}\nCatch.kind = \"catch\";\nclass Finally extends BlockNode {\n render(opts) {\n return \"finally\" + super.render(opts);\n }\n}\nFinally.kind = \"finally\";\nclass CodeGen {\n constructor(extScope, opts = {}) {\n this._values = {};\n this._blockStarts = [];\n this._constants = {};\n this.opts = { ...opts, _n: opts.lines ? \"\\n\" : \"\" };\n this._extScope = extScope;\n this._scope = new scope_1.Scope({ parent: extScope });\n this._nodes = [new Root()];\n }\n toString() {\n return this._root.render(this.opts);\n }\n // returns unique name in the internal scope\n name(prefix) {\n return this._scope.name(prefix);\n }\n // reserves unique name in the external scope\n scopeName(prefix) {\n return this._extScope.name(prefix);\n }\n // reserves unique name in the external scope and assigns value to it\n scopeValue(prefixOrName, value) {\n const name = this._extScope.value(prefixOrName, value);\n const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set());\n vs.add(name);\n return name;\n }\n getScopeValue(prefix, keyOrRef) {\n return this._extScope.getValue(prefix, keyOrRef);\n }\n // return code that assigns values in the external scope to the names that are used internally\n // (same names that were returned by gen.scopeName or gen.scopeValue)\n scopeRefs(scopeName) {\n return this._extScope.scopeRefs(scopeName, this._values);\n }\n scopeCode() {\n return this._extScope.scopeCode(this._values);\n }\n _def(varKind, nameOrPrefix, rhs, constant) {\n const name = this._scope.toName(nameOrPrefix);\n if (rhs !== undefined && constant)\n this._constants[name.str] = rhs;\n this._leafNode(new Def(varKind, name, rhs));\n return name;\n }\n // `const` declaration (`var` in es5 mode)\n const(nameOrPrefix, rhs, _constant) {\n return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant);\n }\n // `let` declaration with optional assignment (`var` in es5 mode)\n let(nameOrPrefix, rhs, _constant) {\n return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant);\n }\n // `var` declaration with optional assignment\n var(nameOrPrefix, rhs, _constant) {\n return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant);\n }\n // assignment code\n assign(lhs, rhs, sideEffects) {\n return this._leafNode(new Assign(lhs, rhs, sideEffects));\n }\n // `+=` code\n add(lhs, rhs) {\n return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs));\n }\n // appends passed SafeExpr to code or executes Block\n code(c) {\n if (typeof c == \"function\")\n c();\n else if (c !== code_1.nil)\n this._leafNode(new AnyCode(c));\n return this;\n }\n // returns code for object literal for the passed argument list of key-value pairs\n object(...keyValues) {\n const code = [\"{\"];\n for (const [key, value] of keyValues) {\n if (code.length > 1)\n code.push(\",\");\n code.push(key);\n if (key !== value || this.opts.es5) {\n code.push(\":\");\n (0, code_1.addCodeArg)(code, value);\n }\n }\n code.push(\"}\");\n return new code_1._Code(code);\n }\n // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)\n if(condition, thenBody, elseBody) {\n this._blockNode(new If(condition));\n if (thenBody && elseBody) {\n this.code(thenBody).else().code(elseBody).endIf();\n }\n else if (thenBody) {\n this.code(thenBody).endIf();\n }\n else if (elseBody) {\n throw new Error('CodeGen: \"else\" body without \"then\" body');\n }\n return this;\n }\n // `else if` clause - invalid without `if` or after `else` clauses\n elseIf(condition) {\n return this._elseNode(new If(condition));\n }\n // `else` clause - only valid after `if` or `else if` clauses\n else() {\n return this._elseNode(new Else());\n }\n // end `if` statement (needed if gen.if was used only with condition)\n endIf() {\n return this._endBlockNode(If, Else);\n }\n _for(node, forBody) {\n this._blockNode(node);\n if (forBody)\n this.code(forBody).endFor();\n return this;\n }\n // a generic `for` clause (or statement if `forBody` is passed)\n for(iteration, forBody) {\n return this._for(new ForLoop(iteration), forBody);\n }\n // `for` statement for a range of values\n forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) {\n const name = this._scope.toName(nameOrPrefix);\n return this._for(new ForRange(varKind, name, from, to), () => forBody(name));\n }\n // `for-of` statement (in es5 mode replace with a normal for loop)\n forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) {\n const name = this._scope.toName(nameOrPrefix);\n if (this.opts.es5) {\n const arr = iterable instanceof code_1.Name ? iterable : this.var(\"_arr\", iterable);\n return this.forRange(\"_i\", 0, (0, code_1._) `${arr}.length`, (i) => {\n this.var(name, (0, code_1._) `${arr}[${i}]`);\n forBody(name);\n });\n }\n return this._for(new ForIter(\"of\", varKind, name, iterable), () => forBody(name));\n }\n // `for-in` statement.\n // With option `ownProperties` replaced with a `for-of` loop for object keys\n forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) {\n if (this.opts.ownProperties) {\n return this.forOf(nameOrPrefix, (0, code_1._) `Object.keys(${obj})`, forBody);\n }\n const name = this._scope.toName(nameOrPrefix);\n return this._for(new ForIter(\"in\", varKind, name, obj), () => forBody(name));\n }\n // end `for` loop\n endFor() {\n return this._endBlockNode(For);\n }\n // `label` statement\n label(label) {\n return this._leafNode(new Label(label));\n }\n // `break` statement\n break(label) {\n return this._leafNode(new Break(label));\n }\n // `return` statement\n return(value) {\n const node = new Return();\n this._blockNode(node);\n this.code(value);\n if (node.nodes.length !== 1)\n throw new Error('CodeGen: \"return\" should have one node');\n return this._endBlockNode(Return);\n }\n // `try` statement\n try(tryBody, catchCode, finallyCode) {\n if (!catchCode && !finallyCode)\n throw new Error('CodeGen: \"try\" without \"catch\" and \"finally\"');\n const node = new Try();\n this._blockNode(node);\n this.code(tryBody);\n if (catchCode) {\n const error = this.name(\"e\");\n this._currNode = node.catch = new Catch(error);\n catchCode(error);\n }\n if (finallyCode) {\n this._currNode = node.finally = new Finally();\n this.code(finallyCode);\n }\n return this._endBlockNode(Catch, Finally);\n }\n // `throw` statement\n throw(error) {\n return this._leafNode(new Throw(error));\n }\n // start self-balancing block\n block(body, nodeCount) {\n this._blockStarts.push(this._nodes.length);\n if (body)\n this.code(body).endBlock(nodeCount);\n return this;\n }\n // end the current self-balancing block\n endBlock(nodeCount) {\n const len = this._blockStarts.pop();\n if (len === undefined)\n throw new Error(\"CodeGen: not in self-balancing block\");\n const toClose = this._nodes.length - len;\n if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) {\n throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`);\n }\n this._nodes.length = len;\n return this;\n }\n // `function` heading (or definition if funcBody is passed)\n func(name, args = code_1.nil, async, funcBody) {\n this._blockNode(new Func(name, args, async));\n if (funcBody)\n this.code(funcBody).endFunc();\n return this;\n }\n // end function definition\n endFunc() {\n return this._endBlockNode(Func);\n }\n optimize(n = 1) {\n while (n-- > 0) {\n this._root.optimizeNodes();\n this._root.optimizeNames(this._root.names, this._constants);\n }\n }\n _leafNode(node) {\n this._currNode.nodes.push(node);\n return this;\n }\n _blockNode(node) {\n this._currNode.nodes.push(node);\n this._nodes.push(node);\n }\n _endBlockNode(N1, N2) {\n const n = this._currNode;\n if (n instanceof N1 || (N2 && n instanceof N2)) {\n this._nodes.pop();\n return this;\n }\n throw new Error(`CodeGen: not in block \"${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}\"`);\n }\n _elseNode(node) {\n const n = this._currNode;\n if (!(n instanceof If)) {\n throw new Error('CodeGen: \"else\" without \"if\"');\n }\n this._currNode = n.else = node;\n return this;\n }\n get _root() {\n return this._nodes[0];\n }\n get _currNode() {\n const ns = this._nodes;\n return ns[ns.length - 1];\n }\n set _currNode(node) {\n const ns = this._nodes;\n ns[ns.length - 1] = node;\n }\n}\nexports.CodeGen = CodeGen;\nfunction addNames(names, from) {\n for (const n in from)\n names[n] = (names[n] || 0) + (from[n] || 0);\n return names;\n}\nfunction addExprNames(names, from) {\n return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names;\n}\nfunction optimizeExpr(expr, names, constants) {\n if (expr instanceof code_1.Name)\n return replaceName(expr);\n if (!canOptimize(expr))\n return expr;\n return new code_1._Code(expr._items.reduce((items, c) => {\n if (c instanceof code_1.Name)\n c = replaceName(c);\n if (c instanceof code_1._Code)\n items.push(...c._items);\n else\n items.push(c);\n return items;\n }, []));\n function replaceName(n) {\n const c = constants[n.str];\n if (c === undefined || names[n.str] !== 1)\n return n;\n delete names[n.str];\n return c;\n }\n function canOptimize(e) {\n return (e instanceof code_1._Code &&\n e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== undefined));\n }\n}\nfunction subtractNames(names, from) {\n for (const n in from)\n names[n] = (names[n] || 0) - (from[n] || 0);\n}\nfunction not(x) {\n return typeof x == \"boolean\" || typeof x == \"number\" || x === null ? !x : (0, code_1._) `!${par(x)}`;\n}\nexports.not = not;\nconst andCode = mappend(exports.operators.AND);\n// boolean AND (&&) expression with the passed arguments\nfunction and(...args) {\n return args.reduce(andCode);\n}\nexports.and = and;\nconst orCode = mappend(exports.operators.OR);\n// boolean OR (||) expression with the passed arguments\nfunction or(...args) {\n return args.reduce(orCode);\n}\nexports.or = or;\nfunction mappend(op) {\n return (x, y) => (x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._) `${par(x)} ${op} ${par(y)}`);\n}\nfunction par(x) {\n return x instanceof code_1.Name ? x : (0, code_1._) `(${x})`;\n}\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.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;\nconst codegen_1 = require(\"./codegen\");\nconst code_1 = require(\"./codegen/code\");\n// TODO refactor to use Set\nfunction toHash(arr) {\n const hash = {};\n for (const item of arr)\n hash[item] = true;\n return hash;\n}\nexports.toHash = toHash;\nfunction alwaysValidSchema(it, schema) {\n if (typeof schema == \"boolean\")\n return schema;\n if (Object.keys(schema).length === 0)\n return true;\n checkUnknownRules(it, schema);\n return !schemaHasRules(schema, it.self.RULES.all);\n}\nexports.alwaysValidSchema = alwaysValidSchema;\nfunction checkUnknownRules(it, schema = it.schema) {\n const { opts, self } = it;\n if (!opts.strictSchema)\n return;\n if (typeof schema === \"boolean\")\n return;\n const rules = self.RULES.keywords;\n for (const key in schema) {\n if (!rules[key])\n checkStrictMode(it, `unknown keyword: \"${key}\"`);\n }\n}\nexports.checkUnknownRules = checkUnknownRules;\nfunction schemaHasRules(schema, rules) {\n if (typeof schema == \"boolean\")\n return !schema;\n for (const key in schema)\n if (rules[key])\n return true;\n return false;\n}\nexports.schemaHasRules = schemaHasRules;\nfunction schemaHasRulesButRef(schema, RULES) {\n if (typeof schema == \"boolean\")\n return !schema;\n for (const key in schema)\n if (key !== \"$ref\" && RULES.all[key])\n return true;\n return false;\n}\nexports.schemaHasRulesButRef = schemaHasRulesButRef;\nfunction schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) {\n if (!$data) {\n if (typeof schema == \"number\" || typeof schema == \"boolean\")\n return schema;\n if (typeof schema == \"string\")\n return (0, codegen_1._) `${schema}`;\n }\n return (0, codegen_1._) `${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`;\n}\nexports.schemaRefOrVal = schemaRefOrVal;\nfunction unescapeFragment(str) {\n return unescapeJsonPointer(decodeURIComponent(str));\n}\nexports.unescapeFragment = unescapeFragment;\nfunction escapeFragment(str) {\n return encodeURIComponent(escapeJsonPointer(str));\n}\nexports.escapeFragment = escapeFragment;\nfunction escapeJsonPointer(str) {\n if (typeof str == \"number\")\n return `${str}`;\n return str.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n}\nexports.escapeJsonPointer = escapeJsonPointer;\nfunction unescapeJsonPointer(str) {\n return str.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n}\nexports.unescapeJsonPointer = unescapeJsonPointer;\nfunction eachItem(xs, f) {\n if (Array.isArray(xs)) {\n for (const x of xs)\n f(x);\n }\n else {\n f(xs);\n }\n}\nexports.eachItem = eachItem;\nfunction makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName, }) {\n return (gen, from, to, toName) => {\n const res = to === undefined\n ? from\n : to instanceof codegen_1.Name\n ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to)\n : from instanceof codegen_1.Name\n ? (mergeToName(gen, to, from), from)\n : mergeValues(from, to);\n return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res;\n };\n}\nexports.mergeEvaluated = {\n props: makeMergeEvaluated({\n mergeNames: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true && ${from} !== undefined`, () => {\n 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})`));\n }),\n mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => {\n if (from === true) {\n gen.assign(to, true);\n }\n else {\n gen.assign(to, (0, codegen_1._) `${to} || {}`);\n setEvaluated(gen, to, from);\n }\n }),\n mergeValues: (from, to) => (from === true ? true : { ...from, ...to }),\n resultToName: evaluatedPropsToName,\n }),\n items: makeMergeEvaluated({\n 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}`)),\n mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._) `${to} > ${from} ? ${to} : ${from}`)),\n mergeValues: (from, to) => (from === true ? true : Math.max(from, to)),\n resultToName: (gen, items) => gen.var(\"items\", items),\n }),\n};\nfunction evaluatedPropsToName(gen, ps) {\n if (ps === true)\n return gen.var(\"props\", true);\n const props = gen.var(\"props\", (0, codegen_1._) `{}`);\n if (ps !== undefined)\n setEvaluated(gen, props, ps);\n return props;\n}\nexports.evaluatedPropsToName = evaluatedPropsToName;\nfunction setEvaluated(gen, props, ps) {\n Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._) `${props}${(0, codegen_1.getProperty)(p)}`, true));\n}\nexports.setEvaluated = setEvaluated;\nconst snippets = {};\nfunction useFunc(gen, f) {\n return gen.scopeValue(\"func\", {\n ref: f,\n code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)),\n });\n}\nexports.useFunc = useFunc;\nvar Type;\n(function (Type) {\n Type[Type[\"Num\"] = 0] = \"Num\";\n Type[Type[\"Str\"] = 1] = \"Str\";\n})(Type || (exports.Type = Type = {}));\nfunction getErrorPath(dataProp, dataPropType, jsPropertySyntax) {\n // let path\n if (dataProp instanceof codegen_1.Name) {\n const isNumber = dataPropType === Type.Num;\n return jsPropertySyntax\n ? isNumber\n ? (0, codegen_1._) `\"[\" + ${dataProp} + \"]\"`\n : (0, codegen_1._) `\"['\" + ${dataProp} + \"']\"`\n : isNumber\n ? (0, codegen_1._) `\"/\" + ${dataProp}`\n : (0, codegen_1._) `\"/\" + ${dataProp}.replace(/~/g, \"~0\").replace(/\\\\//g, \"~1\")`; // TODO maybe use global escapePointer\n }\n return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : \"/\" + escapeJsonPointer(dataProp);\n}\nexports.getErrorPath = getErrorPath;\nfunction checkStrictMode(it, msg, mode = it.opts.strictSchema) {\n if (!mode)\n return;\n msg = `strict mode: ${msg}`;\n if (mode === true)\n throw new Error(msg);\n it.self.logger.warn(msg);\n}\nexports.checkStrictMode = checkStrictMode;\n//# sourceMappingURL=util.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"./codegen\");\nconst names = {\n // validation function arguments\n data: new codegen_1.Name(\"data\"), // data passed to validation function\n // args passed from referencing schema\n valCxt: new codegen_1.Name(\"valCxt\"), // validation/data context - should not be used directly, it is destructured to the names below\n instancePath: new codegen_1.Name(\"instancePath\"),\n parentData: new codegen_1.Name(\"parentData\"),\n parentDataProperty: new codegen_1.Name(\"parentDataProperty\"),\n rootData: new codegen_1.Name(\"rootData\"), // root data - same as the data passed to the first/top validation function\n dynamicAnchors: new codegen_1.Name(\"dynamicAnchors\"), // used to support recursiveRef and dynamicRef\n // function scoped variables\n vErrors: new codegen_1.Name(\"vErrors\"), // null or array of validation errors\n errors: new codegen_1.Name(\"errors\"), // counter of validation errors\n this: new codegen_1.Name(\"this\"),\n // \"globals\"\n self: new codegen_1.Name(\"self\"),\n scope: new codegen_1.Name(\"scope\"),\n // JTD serialize/parse name for JSON string and position\n json: new codegen_1.Name(\"json\"),\n jsonPos: new codegen_1.Name(\"jsonPos\"),\n jsonLen: new codegen_1.Name(\"jsonLen\"),\n jsonPart: new codegen_1.Name(\"jsonPart\"),\n};\nexports.default = names;\n//# sourceMappingURL=names.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0;\nconst codegen_1 = require(\"./codegen\");\nconst util_1 = require(\"./util\");\nconst names_1 = require(\"./names\");\nexports.keywordError = {\n message: ({ keyword }) => (0, codegen_1.str) `must pass \"${keyword}\" keyword validation`,\n};\nexports.keyword$DataError = {\n message: ({ keyword, schemaType }) => schemaType\n ? (0, codegen_1.str) `\"${keyword}\" keyword must be ${schemaType} ($data)`\n : (0, codegen_1.str) `\"${keyword}\" keyword is invalid ($data)`,\n};\nfunction reportError(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) {\n const { it } = cxt;\n const { gen, compositeRule, allErrors } = it;\n const errObj = errorObjectCode(cxt, error, errorPaths);\n if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : (compositeRule || allErrors)) {\n addError(gen, errObj);\n }\n else {\n returnErrors(it, (0, codegen_1._) `[${errObj}]`);\n }\n}\nexports.reportError = reportError;\nfunction reportExtraError(cxt, error = exports.keywordError, errorPaths) {\n const { it } = cxt;\n const { gen, compositeRule, allErrors } = it;\n const errObj = errorObjectCode(cxt, error, errorPaths);\n addError(gen, errObj);\n if (!(compositeRule || allErrors)) {\n returnErrors(it, names_1.default.vErrors);\n }\n}\nexports.reportExtraError = reportExtraError;\nfunction resetErrorsCount(gen, errsCount) {\n gen.assign(names_1.default.errors, errsCount);\n 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)));\n}\nexports.resetErrorsCount = resetErrorsCount;\nfunction extendErrors({ gen, keyword, schemaValue, data, errsCount, it, }) {\n /* istanbul ignore if */\n if (errsCount === undefined)\n throw new Error(\"ajv implementation error\");\n const err = gen.name(\"err\");\n gen.forRange(\"i\", errsCount, names_1.default.errors, (i) => {\n gen.const(err, (0, codegen_1._) `${names_1.default.vErrors}[${i}]`);\n 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)));\n gen.assign((0, codegen_1._) `${err}.schemaPath`, (0, codegen_1.str) `${it.errSchemaPath}/${keyword}`);\n if (it.opts.verbose) {\n gen.assign((0, codegen_1._) `${err}.schema`, schemaValue);\n gen.assign((0, codegen_1._) `${err}.data`, data);\n }\n });\n}\nexports.extendErrors = extendErrors;\nfunction addError(gen, errObj) {\n const err = gen.const(\"err\", errObj);\n 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})`);\n gen.code((0, codegen_1._) `${names_1.default.errors}++`);\n}\nfunction returnErrors(it, errs) {\n const { gen, validateName, schemaEnv } = it;\n if (schemaEnv.$async) {\n gen.throw((0, codegen_1._) `new ${it.ValidationError}(${errs})`);\n }\n else {\n gen.assign((0, codegen_1._) `${validateName}.errors`, errs);\n gen.return(false);\n }\n}\nconst E = {\n keyword: new codegen_1.Name(\"keyword\"),\n schemaPath: new codegen_1.Name(\"schemaPath\"), // also used in JTD errors\n params: new codegen_1.Name(\"params\"),\n propertyName: new codegen_1.Name(\"propertyName\"),\n message: new codegen_1.Name(\"message\"),\n schema: new codegen_1.Name(\"schema\"),\n parentSchema: new codegen_1.Name(\"parentSchema\"),\n};\nfunction errorObjectCode(cxt, error, errorPaths) {\n const { createErrors } = cxt.it;\n if (createErrors === false)\n return (0, codegen_1._) `{}`;\n return errorObject(cxt, error, errorPaths);\n}\nfunction errorObject(cxt, error, errorPaths = {}) {\n const { gen, it } = cxt;\n const keyValues = [\n errorInstancePath(it, errorPaths),\n errorSchemaPath(cxt, errorPaths),\n ];\n extraErrorProps(cxt, error, keyValues);\n return gen.object(...keyValues);\n}\nfunction errorInstancePath({ errorPath }, { instancePath }) {\n const instPath = instancePath\n ? (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}`\n : errorPath;\n return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)];\n}\nfunction errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) {\n let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str) `${errSchemaPath}/${keyword}`;\n if (schemaPath) {\n schPath = (0, codegen_1.str) `${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`;\n }\n return [E.schemaPath, schPath];\n}\nfunction extraErrorProps(cxt, { params, message }, keyValues) {\n const { keyword, data, schemaValue, it } = cxt;\n const { opts, propertyName, topSchemaRef, schemaPath } = it;\n keyValues.push([E.keyword, keyword], [E.params, typeof params == \"function\" ? params(cxt) : params || (0, codegen_1._) `{}`]);\n if (opts.messages) {\n keyValues.push([E.message, typeof message == \"function\" ? message(cxt) : message]);\n }\n if (opts.verbose) {\n keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._) `${topSchemaRef}${schemaPath}`], [names_1.default.data, data]);\n }\n if (propertyName)\n keyValues.push([E.propertyName, propertyName]);\n}\n//# sourceMappingURL=errors.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0;\nconst errors_1 = require(\"../errors\");\nconst codegen_1 = require(\"../codegen\");\nconst names_1 = require(\"../names\");\nconst boolError = {\n message: \"boolean schema is false\",\n};\nfunction topBoolOrEmptySchema(it) {\n const { gen, schema, validateName } = it;\n if (schema === false) {\n falseSchemaError(it, false);\n }\n else if (typeof schema == \"object\" && schema.$async === true) {\n gen.return(names_1.default.data);\n }\n else {\n gen.assign((0, codegen_1._) `${validateName}.errors`, null);\n gen.return(true);\n }\n}\nexports.topBoolOrEmptySchema = topBoolOrEmptySchema;\nfunction boolOrEmptySchema(it, valid) {\n const { gen, schema } = it;\n if (schema === false) {\n gen.var(valid, false); // TODO var\n falseSchemaError(it);\n }\n else {\n gen.var(valid, true); // TODO var\n }\n}\nexports.boolOrEmptySchema = boolOrEmptySchema;\nfunction falseSchemaError(it, overrideAllErrors) {\n const { gen, data } = it;\n // TODO maybe some other interface should be used for non-keyword validation errors...\n const cxt = {\n gen,\n keyword: \"false schema\",\n data,\n schema: false,\n schemaCode: false,\n schemaValue: false,\n params: {},\n it,\n };\n (0, errors_1.reportError)(cxt, boolError, undefined, overrideAllErrors);\n}\n//# sourceMappingURL=boolSchema.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getRules = exports.isJSONType = void 0;\nconst _jsonTypes = [\"string\", \"number\", \"integer\", \"boolean\", \"null\", \"object\", \"array\"];\nconst jsonTypes = new Set(_jsonTypes);\nfunction isJSONType(x) {\n return typeof x == \"string\" && jsonTypes.has(x);\n}\nexports.isJSONType = isJSONType;\nfunction getRules() {\n const groups = {\n number: { type: \"number\", rules: [] },\n string: { type: \"string\", rules: [] },\n array: { type: \"array\", rules: [] },\n object: { type: \"object\", rules: [] },\n };\n return {\n types: { ...groups, integer: true, boolean: true, null: true },\n rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object],\n post: { rules: [] },\n all: {},\n keywords: {},\n };\n}\nexports.getRules = getRules;\n//# sourceMappingURL=rules.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0;\nfunction schemaHasRulesForType({ schema, self }, type) {\n const group = self.RULES.types[type];\n return group && group !== true && shouldUseGroup(schema, group);\n}\nexports.schemaHasRulesForType = schemaHasRulesForType;\nfunction shouldUseGroup(schema, group) {\n return group.rules.some((rule) => shouldUseRule(schema, rule));\n}\nexports.shouldUseGroup = shouldUseGroup;\nfunction shouldUseRule(schema, rule) {\n var _a;\n return (schema[rule.keyword] !== undefined ||\n ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== undefined)));\n}\nexports.shouldUseRule = shouldUseRule;\n//# sourceMappingURL=applicability.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0;\nconst rules_1 = require(\"../rules\");\nconst applicability_1 = require(\"./applicability\");\nconst errors_1 = require(\"../errors\");\nconst codegen_1 = require(\"../codegen\");\nconst util_1 = require(\"../util\");\nvar DataType;\n(function (DataType) {\n DataType[DataType[\"Correct\"] = 0] = \"Correct\";\n DataType[DataType[\"Wrong\"] = 1] = \"Wrong\";\n})(DataType || (exports.DataType = DataType = {}));\nfunction getSchemaTypes(schema) {\n const types = getJSONTypes(schema.type);\n const hasNull = types.includes(\"null\");\n if (hasNull) {\n if (schema.nullable === false)\n throw new Error(\"type: null contradicts nullable: false\");\n }\n else {\n if (!types.length && schema.nullable !== undefined) {\n throw new Error('\"nullable\" cannot be used without \"type\"');\n }\n if (schema.nullable === true)\n types.push(\"null\");\n }\n return types;\n}\nexports.getSchemaTypes = getSchemaTypes;\n// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents\nfunction getJSONTypes(ts) {\n const types = Array.isArray(ts) ? ts : ts ? [ts] : [];\n if (types.every(rules_1.isJSONType))\n return types;\n throw new Error(\"type must be JSONType or JSONType[]: \" + types.join(\",\"));\n}\nexports.getJSONTypes = getJSONTypes;\nfunction coerceAndCheckDataType(it, types) {\n const { gen, data, opts } = it;\n const coerceTo = coerceToTypes(types, opts.coerceTypes);\n const checkTypes = types.length > 0 &&\n !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0]));\n if (checkTypes) {\n const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong);\n gen.if(wrongType, () => {\n if (coerceTo.length)\n coerceData(it, types, coerceTo);\n else\n reportTypeError(it);\n });\n }\n return checkTypes;\n}\nexports.coerceAndCheckDataType = coerceAndCheckDataType;\nconst COERCIBLE = new Set([\"string\", \"number\", \"integer\", \"boolean\", \"null\"]);\nfunction coerceToTypes(types, coerceTypes) {\n return coerceTypes\n ? types.filter((t) => COERCIBLE.has(t) || (coerceTypes === \"array\" && t === \"array\"))\n : [];\n}\nfunction coerceData(it, types, coerceTo) {\n const { gen, data, opts } = it;\n const dataType = gen.let(\"dataType\", (0, codegen_1._) `typeof ${data}`);\n const coerced = gen.let(\"coerced\", (0, codegen_1._) `undefined`);\n if (opts.coerceTypes === \"array\") {\n gen.if((0, codegen_1._) `${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen\n .assign(data, (0, codegen_1._) `${data}[0]`)\n .assign(dataType, (0, codegen_1._) `typeof ${data}`)\n .if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data)));\n }\n gen.if((0, codegen_1._) `${coerced} !== undefined`);\n for (const t of coerceTo) {\n if (COERCIBLE.has(t) || (t === \"array\" && opts.coerceTypes === \"array\")) {\n coerceSpecificType(t);\n }\n }\n gen.else();\n reportTypeError(it);\n gen.endIf();\n gen.if((0, codegen_1._) `${coerced} !== undefined`, () => {\n gen.assign(data, coerced);\n assignParentData(it, coerced);\n });\n function coerceSpecificType(t) {\n switch (t) {\n case \"string\":\n gen\n .elseIf((0, codegen_1._) `${dataType} == \"number\" || ${dataType} == \"boolean\"`)\n .assign(coerced, (0, codegen_1._) `\"\" + ${data}`)\n .elseIf((0, codegen_1._) `${data} === null`)\n .assign(coerced, (0, codegen_1._) `\"\"`);\n return;\n case \"number\":\n gen\n .elseIf((0, codegen_1._) `${dataType} == \"boolean\" || ${data} === null\n || (${dataType} == \"string\" && ${data} && ${data} == +${data})`)\n .assign(coerced, (0, codegen_1._) `+${data}`);\n return;\n case \"integer\":\n gen\n .elseIf((0, codegen_1._) `${dataType} === \"boolean\" || ${data} === null\n || (${dataType} === \"string\" && ${data} && ${data} == +${data} && !(${data} % 1))`)\n .assign(coerced, (0, codegen_1._) `+${data}`);\n return;\n case \"boolean\":\n gen\n .elseIf((0, codegen_1._) `${data} === \"false\" || ${data} === 0 || ${data} === null`)\n .assign(coerced, false)\n .elseIf((0, codegen_1._) `${data} === \"true\" || ${data} === 1`)\n .assign(coerced, true);\n return;\n case \"null\":\n gen.elseIf((0, codegen_1._) `${data} === \"\" || ${data} === 0 || ${data} === false`);\n gen.assign(coerced, null);\n return;\n case \"array\":\n gen\n .elseIf((0, codegen_1._) `${dataType} === \"string\" || ${dataType} === \"number\"\n || ${dataType} === \"boolean\" || ${data} === null`)\n .assign(coerced, (0, codegen_1._) `[${data}]`);\n }\n }\n}\nfunction assignParentData({ gen, parentData, parentDataProperty }, expr) {\n // TODO use gen.property\n gen.if((0, codegen_1._) `${parentData} !== undefined`, () => gen.assign((0, codegen_1._) `${parentData}[${parentDataProperty}]`, expr));\n}\nfunction checkDataType(dataType, data, strictNums, correct = DataType.Correct) {\n const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ;\n let cond;\n switch (dataType) {\n case \"null\":\n return (0, codegen_1._) `${data} ${EQ} null`;\n case \"array\":\n cond = (0, codegen_1._) `Array.isArray(${data})`;\n break;\n case \"object\":\n cond = (0, codegen_1._) `${data} && typeof ${data} == \"object\" && !Array.isArray(${data})`;\n break;\n case \"integer\":\n cond = numCond((0, codegen_1._) `!(${data} % 1) && !isNaN(${data})`);\n break;\n case \"number\":\n cond = numCond();\n break;\n default:\n return (0, codegen_1._) `typeof ${data} ${EQ} ${dataType}`;\n }\n return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond);\n function numCond(_cond = codegen_1.nil) {\n return (0, codegen_1.and)((0, codegen_1._) `typeof ${data} == \"number\"`, _cond, strictNums ? (0, codegen_1._) `isFinite(${data})` : codegen_1.nil);\n }\n}\nexports.checkDataType = checkDataType;\nfunction checkDataTypes(dataTypes, data, strictNums, correct) {\n if (dataTypes.length === 1) {\n return checkDataType(dataTypes[0], data, strictNums, correct);\n }\n let cond;\n const types = (0, util_1.toHash)(dataTypes);\n if (types.array && types.object) {\n const notObj = (0, codegen_1._) `typeof ${data} != \"object\"`;\n cond = types.null ? notObj : (0, codegen_1._) `!${data} || ${notObj}`;\n delete types.null;\n delete types.array;\n delete types.object;\n }\n else {\n cond = codegen_1.nil;\n }\n if (types.number)\n delete types.integer;\n for (const t in types)\n cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct));\n return cond;\n}\nexports.checkDataTypes = checkDataTypes;\nconst typeError = {\n message: ({ schema }) => `must be ${schema}`,\n params: ({ schema, schemaValue }) => typeof schema == \"string\" ? (0, codegen_1._) `{type: ${schema}}` : (0, codegen_1._) `{type: ${schemaValue}}`,\n};\nfunction reportTypeError(it) {\n const cxt = getTypeErrorContext(it);\n (0, errors_1.reportError)(cxt, typeError);\n}\nexports.reportTypeError = reportTypeError;\nfunction getTypeErrorContext(it) {\n const { gen, data, schema } = it;\n const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, \"type\");\n return {\n gen,\n keyword: \"type\",\n data,\n schema: schema.type,\n schemaCode,\n schemaValue: schemaCode,\n parentSchema: schema,\n params: {},\n it,\n };\n}\n//# sourceMappingURL=dataType.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.assignDefaults = void 0;\nconst codegen_1 = require(\"../codegen\");\nconst util_1 = require(\"../util\");\nfunction assignDefaults(it, ty) {\n const { properties, items } = it.schema;\n if (ty === \"object\" && properties) {\n for (const key in properties) {\n assignDefault(it, key, properties[key].default);\n }\n }\n else if (ty === \"array\" && Array.isArray(items)) {\n items.forEach((sch, i) => assignDefault(it, i, sch.default));\n }\n}\nexports.assignDefaults = assignDefaults;\nfunction assignDefault(it, prop, defaultValue) {\n const { gen, compositeRule, data, opts } = it;\n if (defaultValue === undefined)\n return;\n const childData = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(prop)}`;\n if (compositeRule) {\n (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`);\n return;\n }\n let condition = (0, codegen_1._) `${childData} === undefined`;\n if (opts.useDefaults === \"empty\") {\n condition = (0, codegen_1._) `${condition} || ${childData} === null || ${childData} === \"\"`;\n }\n // `${childData} === undefined` +\n // (opts.useDefaults === \"empty\" ? ` || ${childData} === null || ${childData} === \"\"` : \"\")\n gen.if(condition, (0, codegen_1._) `${childData} = ${(0, codegen_1.stringify)(defaultValue)}`);\n}\n//# sourceMappingURL=defaults.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.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;\nconst codegen_1 = require(\"../compile/codegen\");\nconst util_1 = require(\"../compile/util\");\nconst names_1 = require(\"../compile/names\");\nconst util_2 = require(\"../compile/util\");\nfunction checkReportMissingProp(cxt, prop) {\n const { gen, data, it } = cxt;\n gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => {\n cxt.setParams({ missingProperty: (0, codegen_1._) `${prop}` }, true);\n cxt.error();\n });\n}\nexports.checkReportMissingProp = checkReportMissingProp;\nfunction checkMissingProp({ gen, data, it: { opts } }, properties, missing) {\n return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._) `${missing} = ${prop}`)));\n}\nexports.checkMissingProp = checkMissingProp;\nfunction reportMissingProp(cxt, missing) {\n cxt.setParams({ missingProperty: missing }, true);\n cxt.error();\n}\nexports.reportMissingProp = reportMissingProp;\nfunction hasPropFunc(gen) {\n return gen.scopeValue(\"func\", {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n ref: Object.prototype.hasOwnProperty,\n code: (0, codegen_1._) `Object.prototype.hasOwnProperty`,\n });\n}\nexports.hasPropFunc = hasPropFunc;\nfunction isOwnProperty(gen, data, property) {\n return (0, codegen_1._) `${hasPropFunc(gen)}.call(${data}, ${property})`;\n}\nexports.isOwnProperty = isOwnProperty;\nfunction propertyInData(gen, data, property, ownProperties) {\n const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} !== undefined`;\n return ownProperties ? (0, codegen_1._) `${cond} && ${isOwnProperty(gen, data, property)}` : cond;\n}\nexports.propertyInData = propertyInData;\nfunction noPropertyInData(gen, data, property, ownProperties) {\n const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} === undefined`;\n return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond;\n}\nexports.noPropertyInData = noPropertyInData;\nfunction allSchemaProperties(schemaMap) {\n return schemaMap ? Object.keys(schemaMap).filter((p) => p !== \"__proto__\") : [];\n}\nexports.allSchemaProperties = allSchemaProperties;\nfunction schemaProperties(it, schemaMap) {\n return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p]));\n}\nexports.schemaProperties = schemaProperties;\nfunction callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) {\n const dataAndSchema = passSchema ? (0, codegen_1._) `${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data;\n const valCxt = [\n [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)],\n [names_1.default.parentData, it.parentData],\n [names_1.default.parentDataProperty, it.parentDataProperty],\n [names_1.default.rootData, names_1.default.rootData],\n ];\n if (it.opts.dynamicRef)\n valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]);\n const args = (0, codegen_1._) `${dataAndSchema}, ${gen.object(...valCxt)}`;\n return context !== codegen_1.nil ? (0, codegen_1._) `${func}.call(${context}, ${args})` : (0, codegen_1._) `${func}(${args})`;\n}\nexports.callValidateCode = callValidateCode;\nconst newRegExp = (0, codegen_1._) `new RegExp`;\nfunction usePattern({ gen, it: { opts } }, pattern) {\n const u = opts.unicodeRegExp ? \"u\" : \"\";\n const { regExp } = opts.code;\n const rx = regExp(pattern, u);\n return gen.scopeValue(\"pattern\", {\n key: rx.toString(),\n ref: rx,\n code: (0, codegen_1._) `${regExp.code === \"new RegExp\" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})`,\n });\n}\nexports.usePattern = usePattern;\nfunction validateArray(cxt) {\n const { gen, data, keyword, it } = cxt;\n const valid = gen.name(\"valid\");\n if (it.allErrors) {\n const validArr = gen.let(\"valid\", true);\n validateItems(() => gen.assign(validArr, false));\n return validArr;\n }\n gen.var(valid, true);\n validateItems(() => gen.break());\n return valid;\n function validateItems(notValid) {\n const len = gen.const(\"len\", (0, codegen_1._) `${data}.length`);\n gen.forRange(\"i\", 0, len, (i) => {\n cxt.subschema({\n keyword,\n dataProp: i,\n dataPropType: util_1.Type.Num,\n }, valid);\n gen.if((0, codegen_1.not)(valid), notValid);\n });\n }\n}\nexports.validateArray = validateArray;\nfunction validateUnion(cxt) {\n const { gen, schema, keyword, it } = cxt;\n /* istanbul ignore if */\n if (!Array.isArray(schema))\n throw new Error(\"ajv implementation error\");\n const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch));\n if (alwaysValid && !it.opts.unevaluated)\n return;\n const valid = gen.let(\"valid\", false);\n const schValid = gen.name(\"_valid\");\n gen.block(() => schema.forEach((_sch, i) => {\n const schCxt = cxt.subschema({\n keyword,\n schemaProp: i,\n compositeRule: true,\n }, schValid);\n gen.assign(valid, (0, codegen_1._) `${valid} || ${schValid}`);\n const merged = cxt.mergeValidEvaluated(schCxt, schValid);\n // can short-circuit if `unevaluatedProperties/Items` not supported (opts.unevaluated !== true)\n // or if all properties and items were evaluated (it.props === true && it.items === true)\n if (!merged)\n gen.if((0, codegen_1.not)(valid));\n }));\n cxt.result(valid, () => cxt.reset(), () => cxt.error(true));\n}\nexports.validateUnion = validateUnion;\n//# sourceMappingURL=code.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0;\nconst codegen_1 = require(\"../codegen\");\nconst names_1 = require(\"../names\");\nconst code_1 = require(\"../../vocabularies/code\");\nconst errors_1 = require(\"../errors\");\nfunction macroKeywordCode(cxt, def) {\n const { gen, keyword, schema, parentSchema, it } = cxt;\n const macroSchema = def.macro.call(it.self, schema, parentSchema, it);\n const schemaRef = useKeyword(gen, keyword, macroSchema);\n if (it.opts.validateSchema !== false)\n it.self.validateSchema(macroSchema, true);\n const valid = gen.name(\"valid\");\n cxt.subschema({\n schema: macroSchema,\n schemaPath: codegen_1.nil,\n errSchemaPath: `${it.errSchemaPath}/${keyword}`,\n topSchemaRef: schemaRef,\n compositeRule: true,\n }, valid);\n cxt.pass(valid, () => cxt.error(true));\n}\nexports.macroKeywordCode = macroKeywordCode;\nfunction funcKeywordCode(cxt, def) {\n var _a;\n const { gen, keyword, schema, parentSchema, $data, it } = cxt;\n checkAsyncKeyword(it, def);\n const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate;\n const validateRef = useKeyword(gen, keyword, validate);\n const valid = gen.let(\"valid\");\n cxt.block$data(valid, validateKeyword);\n cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid);\n function validateKeyword() {\n if (def.errors === false) {\n assignValid();\n if (def.modifying)\n modifyData(cxt);\n reportErrs(() => cxt.error());\n }\n else {\n const ruleErrs = def.async ? validateAsync() : validateSync();\n if (def.modifying)\n modifyData(cxt);\n reportErrs(() => addErrs(cxt, ruleErrs));\n }\n }\n function validateAsync() {\n const ruleErrs = gen.let(\"ruleErrs\", null);\n gen.try(() => assignValid((0, codegen_1._) `await `), (e) => gen.assign(valid, false).if((0, codegen_1._) `${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._) `${e}.errors`), () => gen.throw(e)));\n return ruleErrs;\n }\n function validateSync() {\n const validateErrs = (0, codegen_1._) `${validateRef}.errors`;\n gen.assign(validateErrs, null);\n assignValid(codegen_1.nil);\n return validateErrs;\n }\n function assignValid(_await = def.async ? (0, codegen_1._) `await ` : codegen_1.nil) {\n const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self;\n const passSchema = !((\"compile\" in def && !$data) || def.schema === false);\n gen.assign(valid, (0, codegen_1._) `${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying);\n }\n function reportErrs(errors) {\n var _a;\n gen.if((0, codegen_1.not)((_a = def.valid) !== null && _a !== void 0 ? _a : valid), errors);\n }\n}\nexports.funcKeywordCode = funcKeywordCode;\nfunction modifyData(cxt) {\n const { gen, data, it } = cxt;\n gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._) `${it.parentData}[${it.parentDataProperty}]`));\n}\nfunction addErrs(cxt, errs) {\n const { gen } = cxt;\n gen.if((0, codegen_1._) `Array.isArray(${errs})`, () => {\n gen\n .assign(names_1.default.vErrors, (0, codegen_1._) `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`)\n .assign(names_1.default.errors, (0, codegen_1._) `${names_1.default.vErrors}.length`);\n (0, errors_1.extendErrors)(cxt);\n }, () => cxt.error());\n}\nfunction checkAsyncKeyword({ schemaEnv }, def) {\n if (def.async && !schemaEnv.$async)\n throw new Error(\"async keyword in sync schema\");\n}\nfunction useKeyword(gen, keyword, result) {\n if (result === undefined)\n throw new Error(`keyword \"${keyword}\" failed to compile`);\n return gen.scopeValue(\"keyword\", typeof result == \"function\" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) });\n}\nfunction validSchemaType(schema, schemaType, allowUndefined = false) {\n // TODO add tests\n return (!schemaType.length ||\n schemaType.some((st) => st === \"array\"\n ? Array.isArray(schema)\n : st === \"object\"\n ? schema && typeof schema == \"object\" && !Array.isArray(schema)\n : typeof schema == st || (allowUndefined && typeof schema == \"undefined\")));\n}\nexports.validSchemaType = validSchemaType;\nfunction validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) {\n /* istanbul ignore if */\n if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) {\n throw new Error(\"ajv implementation error\");\n }\n const deps = def.dependencies;\n if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {\n throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(\",\")}`);\n }\n if (def.validateSchema) {\n const valid = def.validateSchema(schema[keyword]);\n if (!valid) {\n const msg = `keyword \"${keyword}\" value is invalid at path \"${errSchemaPath}\": ` +\n self.errorsText(def.validateSchema.errors);\n if (opts.validateSchema === \"log\")\n self.logger.error(msg);\n else\n throw new Error(msg);\n }\n }\n}\nexports.validateKeywordUsage = validateKeywordUsage;\n//# sourceMappingURL=keyword.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0;\nconst codegen_1 = require(\"../codegen\");\nconst util_1 = require(\"../util\");\nfunction getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) {\n if (keyword !== undefined && schema !== undefined) {\n throw new Error('both \"keyword\" and \"schema\" passed, only one allowed');\n }\n if (keyword !== undefined) {\n const sch = it.schema[keyword];\n return schemaProp === undefined\n ? {\n schema: sch,\n schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`,\n errSchemaPath: `${it.errSchemaPath}/${keyword}`,\n }\n : {\n schema: sch[schemaProp],\n schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`,\n errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}`,\n };\n }\n if (schema !== undefined) {\n if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) {\n throw new Error('\"schemaPath\", \"errSchemaPath\" and \"topSchemaRef\" are required with \"schema\"');\n }\n return {\n schema,\n schemaPath,\n topSchemaRef,\n errSchemaPath,\n };\n }\n throw new Error('either \"keyword\" or \"schema\" must be passed');\n}\nexports.getSubschema = getSubschema;\nfunction extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) {\n if (data !== undefined && dataProp !== undefined) {\n throw new Error('both \"data\" and \"dataProp\" passed, only one allowed');\n }\n const { gen } = it;\n if (dataProp !== undefined) {\n const { errorPath, dataPathArr, opts } = it;\n const nextData = gen.let(\"data\", (0, codegen_1._) `${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true);\n dataContextProps(nextData);\n subschema.errorPath = (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`;\n subschema.parentDataProperty = (0, codegen_1._) `${dataProp}`;\n subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty];\n }\n if (data !== undefined) {\n const nextData = data instanceof codegen_1.Name ? data : gen.let(\"data\", data, true); // replaceable if used once?\n dataContextProps(nextData);\n if (propertyName !== undefined)\n subschema.propertyName = propertyName;\n // TODO something is possibly wrong here with not changing parentDataProperty and not appending dataPathArr\n }\n if (dataTypes)\n subschema.dataTypes = dataTypes;\n function dataContextProps(_nextData) {\n subschema.data = _nextData;\n subschema.dataLevel = it.dataLevel + 1;\n subschema.dataTypes = [];\n it.definedProperties = new Set();\n subschema.parentData = it.data;\n subschema.dataNames = [...it.dataNames, _nextData];\n }\n}\nexports.extendSubschemaData = extendSubschemaData;\nfunction extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) {\n if (compositeRule !== undefined)\n subschema.compositeRule = compositeRule;\n if (createErrors !== undefined)\n subschema.createErrors = createErrors;\n if (allErrors !== undefined)\n subschema.allErrors = allErrors;\n subschema.jtdDiscriminator = jtdDiscriminator; // not inherited\n subschema.jtdMetadata = jtdMetadata; // not inherited\n}\nexports.extendSubschemaMode = extendSubschemaMode;\n//# sourceMappingURL=subschema.js.map","'use strict';\n\n// do not edit .js files directly - edit src/index.jst\n\n\n\nmodule.exports = function equal(a, b) {\n if (a === b) return true;\n\n if (a && b && typeof a == 'object' && typeof b == 'object') {\n if (a.constructor !== b.constructor) return false;\n\n var length, i, keys;\n if (Array.isArray(a)) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0;)\n if (!equal(a[i], b[i])) return false;\n return true;\n }\n\n\n\n if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;\n if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();\n if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();\n\n keys = Object.keys(a);\n length = keys.length;\n if (length !== Object.keys(b).length) return false;\n\n for (i = length; i-- !== 0;)\n if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;\n\n for (i = length; i-- !== 0;) {\n var key = keys[i];\n\n if (!equal(a[key], b[key])) return false;\n }\n\n return true;\n }\n\n // true if both NaN, false otherwise\n return a!==a && b!==b;\n};\n","'use strict';\n\nvar traverse = module.exports = function (schema, opts, cb) {\n // Legacy support for v0.3.1 and earlier.\n if (typeof opts == 'function') {\n cb = opts;\n opts = {};\n }\n\n cb = opts.cb || cb;\n var pre = (typeof cb == 'function') ? cb : cb.pre || function() {};\n var post = cb.post || function() {};\n\n _traverse(opts, pre, post, schema, '', schema);\n};\n\n\ntraverse.keywords = {\n additionalItems: true,\n items: true,\n contains: true,\n additionalProperties: true,\n propertyNames: true,\n not: true,\n if: true,\n then: true,\n else: true\n};\n\ntraverse.arrayKeywords = {\n items: true,\n allOf: true,\n anyOf: true,\n oneOf: true\n};\n\ntraverse.propsKeywords = {\n $defs: true,\n definitions: true,\n properties: true,\n patternProperties: true,\n dependencies: true\n};\n\ntraverse.skipKeywords = {\n default: true,\n enum: true,\n const: true,\n required: true,\n maximum: true,\n minimum: true,\n exclusiveMaximum: true,\n exclusiveMinimum: true,\n multipleOf: true,\n maxLength: true,\n minLength: true,\n pattern: true,\n format: true,\n maxItems: true,\n minItems: true,\n uniqueItems: true,\n maxProperties: true,\n minProperties: true\n};\n\n\nfunction _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {\n if (schema && typeof schema == 'object' && !Array.isArray(schema)) {\n pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);\n for (var key in schema) {\n var sch = schema[key];\n if (Array.isArray(sch)) {\n if (key in traverse.arrayKeywords) {\n for (var i=0; i<sch.length; i++)\n _traverse(opts, pre, post, sch[i], jsonPtr + '/' + key + '/' + i, rootSchema, jsonPtr, key, schema, i);\n }\n } else if (key in traverse.propsKeywords) {\n if (sch && typeof sch == 'object') {\n for (var prop in sch)\n _traverse(opts, pre, post, sch[prop], jsonPtr + '/' + key + '/' + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);\n }\n } else if (key in traverse.keywords || (opts.allKeys && !(key in traverse.skipKeywords))) {\n _traverse(opts, pre, post, sch, jsonPtr + '/' + key, rootSchema, jsonPtr, key, schema);\n }\n }\n post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);\n }\n}\n\n\nfunction escapeJsonPtr(str) {\n return str.replace(/~/g, '~0').replace(/\\//g, '~1');\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0;\nconst util_1 = require(\"./util\");\nconst equal = require(\"fast-deep-equal\");\nconst traverse = require(\"json-schema-traverse\");\n// TODO refactor to use keyword definitions\nconst SIMPLE_INLINED = new Set([\n \"type\",\n \"format\",\n \"pattern\",\n \"maxLength\",\n \"minLength\",\n \"maxProperties\",\n \"minProperties\",\n \"maxItems\",\n \"minItems\",\n \"maximum\",\n \"minimum\",\n \"uniqueItems\",\n \"multipleOf\",\n \"required\",\n \"enum\",\n \"const\",\n]);\nfunction inlineRef(schema, limit = true) {\n if (typeof schema == \"boolean\")\n return true;\n if (limit === true)\n return !hasRef(schema);\n if (!limit)\n return false;\n return countKeys(schema) <= limit;\n}\nexports.inlineRef = inlineRef;\nconst REF_KEYWORDS = new Set([\n \"$ref\",\n \"$recursiveRef\",\n \"$recursiveAnchor\",\n \"$dynamicRef\",\n \"$dynamicAnchor\",\n]);\nfunction hasRef(schema) {\n for (const key in schema) {\n if (REF_KEYWORDS.has(key))\n return true;\n const sch = schema[key];\n if (Array.isArray(sch) && sch.some(hasRef))\n return true;\n if (typeof sch == \"object\" && hasRef(sch))\n return true;\n }\n return false;\n}\nfunction countKeys(schema) {\n let count = 0;\n for (const key in schema) {\n if (key === \"$ref\")\n return Infinity;\n count++;\n if (SIMPLE_INLINED.has(key))\n continue;\n if (typeof schema[key] == \"object\") {\n (0, util_1.eachItem)(schema[key], (sch) => (count += countKeys(sch)));\n }\n if (count === Infinity)\n return Infinity;\n }\n return count;\n}\nfunction getFullPath(resolver, id = \"\", normalize) {\n if (normalize !== false)\n id = normalizeId(id);\n const p = resolver.parse(id);\n return _getFullPath(resolver, p);\n}\nexports.getFullPath = getFullPath;\nfunction _getFullPath(resolver, p) {\n const serialized = resolver.serialize(p);\n return serialized.split(\"#\")[0] + \"#\";\n}\nexports._getFullPath = _getFullPath;\nconst TRAILING_SLASH_HASH = /#\\/?$/;\nfunction normalizeId(id) {\n return id ? id.replace(TRAILING_SLASH_HASH, \"\") : \"\";\n}\nexports.normalizeId = normalizeId;\nfunction resolveUrl(resolver, baseId, id) {\n id = normalizeId(id);\n return resolver.resolve(baseId, id);\n}\nexports.resolveUrl = resolveUrl;\nconst ANCHOR = /^[a-z_][-a-z0-9._]*$/i;\nfunction getSchemaRefs(schema, baseId) {\n if (typeof schema == \"boolean\")\n return {};\n const { schemaId, uriResolver } = this.opts;\n const schId = normalizeId(schema[schemaId] || baseId);\n const baseIds = { \"\": schId };\n const pathPrefix = getFullPath(uriResolver, schId, false);\n const localRefs = {};\n const schemaRefs = new Set();\n traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => {\n if (parentJsonPtr === undefined)\n return;\n const fullPath = pathPrefix + jsonPtr;\n let innerBaseId = baseIds[parentJsonPtr];\n if (typeof sch[schemaId] == \"string\")\n innerBaseId = addRef.call(this, sch[schemaId]);\n addAnchor.call(this, sch.$anchor);\n addAnchor.call(this, sch.$dynamicAnchor);\n baseIds[jsonPtr] = innerBaseId;\n function addRef(ref) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const _resolve = this.opts.uriResolver.resolve;\n ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref);\n if (schemaRefs.has(ref))\n throw ambiguos(ref);\n schemaRefs.add(ref);\n let schOrRef = this.refs[ref];\n if (typeof schOrRef == \"string\")\n schOrRef = this.refs[schOrRef];\n if (typeof schOrRef == \"object\") {\n checkAmbiguosRef(sch, schOrRef.schema, ref);\n }\n else if (ref !== normalizeId(fullPath)) {\n if (ref[0] === \"#\") {\n checkAmbiguosRef(sch, localRefs[ref], ref);\n localRefs[ref] = sch;\n }\n else {\n this.refs[ref] = fullPath;\n }\n }\n return ref;\n }\n function addAnchor(anchor) {\n if (typeof anchor == \"string\") {\n if (!ANCHOR.test(anchor))\n throw new Error(`invalid anchor \"${anchor}\"`);\n addRef.call(this, `#${anchor}`);\n }\n }\n });\n return localRefs;\n function checkAmbiguosRef(sch1, sch2, ref) {\n if (sch2 !== undefined && !equal(sch1, sch2))\n throw ambiguos(ref);\n }\n function ambiguos(ref) {\n return new Error(`reference \"${ref}\" resolves to more than one schema`);\n }\n}\nexports.getSchemaRefs = getSchemaRefs;\n//# sourceMappingURL=resolve.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0;\nconst boolSchema_1 = require(\"./boolSchema\");\nconst dataType_1 = require(\"./dataType\");\nconst applicability_1 = require(\"./applicability\");\nconst dataType_2 = require(\"./dataType\");\nconst defaults_1 = require(\"./defaults\");\nconst keyword_1 = require(\"./keyword\");\nconst subschema_1 = require(\"./subschema\");\nconst codegen_1 = require(\"../codegen\");\nconst names_1 = require(\"../names\");\nconst resolve_1 = require(\"../resolve\");\nconst util_1 = require(\"../util\");\nconst errors_1 = require(\"../errors\");\n// schema compilation - generates validation function, subschemaCode (below) is used for subschemas\nfunction validateFunctionCode(it) {\n if (isSchemaObj(it)) {\n checkKeywords(it);\n if (schemaCxtHasRules(it)) {\n topSchemaObjCode(it);\n return;\n }\n }\n validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it));\n}\nexports.validateFunctionCode = validateFunctionCode;\nfunction validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) {\n if (opts.code.es5) {\n gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => {\n gen.code((0, codegen_1._) `\"use strict\"; ${funcSourceUrl(schema, opts)}`);\n destructureValCxtES5(gen, opts);\n gen.code(body);\n });\n }\n else {\n gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body));\n }\n}\nfunction destructureValCxt(opts) {\n 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}}={}`;\n}\nfunction destructureValCxtES5(gen, opts) {\n gen.if(names_1.default.valCxt, () => {\n gen.var(names_1.default.instancePath, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.instancePath}`);\n gen.var(names_1.default.parentData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentData}`);\n gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentDataProperty}`);\n gen.var(names_1.default.rootData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.rootData}`);\n if (opts.dynamicRef)\n gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`);\n }, () => {\n gen.var(names_1.default.instancePath, (0, codegen_1._) `\"\"`);\n gen.var(names_1.default.parentData, (0, codegen_1._) `undefined`);\n gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `undefined`);\n gen.var(names_1.default.rootData, names_1.default.data);\n if (opts.dynamicRef)\n gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `{}`);\n });\n}\nfunction topSchemaObjCode(it) {\n const { schema, opts, gen } = it;\n validateFunction(it, () => {\n if (opts.$comment && schema.$comment)\n commentKeyword(it);\n checkNoDefault(it);\n gen.let(names_1.default.vErrors, null);\n gen.let(names_1.default.errors, 0);\n if (opts.unevaluated)\n resetEvaluated(it);\n typeAndKeywords(it);\n returnResults(it);\n });\n return;\n}\nfunction resetEvaluated(it) {\n // TODO maybe some hook to execute it in the end to check whether props/items are Name, as in assignEvaluated\n const { gen, validateName } = it;\n it.evaluated = gen.const(\"evaluated\", (0, codegen_1._) `${validateName}.evaluated`);\n gen.if((0, codegen_1._) `${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._) `${it.evaluated}.props`, (0, codegen_1._) `undefined`));\n gen.if((0, codegen_1._) `${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._) `${it.evaluated}.items`, (0, codegen_1._) `undefined`));\n}\nfunction funcSourceUrl(schema, opts) {\n const schId = typeof schema == \"object\" && schema[opts.schemaId];\n return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._) `/*# sourceURL=${schId} */` : codegen_1.nil;\n}\n// schema compilation - this function is used recursively to generate code for sub-schemas\nfunction subschemaCode(it, valid) {\n if (isSchemaObj(it)) {\n checkKeywords(it);\n if (schemaCxtHasRules(it)) {\n subSchemaObjCode(it, valid);\n return;\n }\n }\n (0, boolSchema_1.boolOrEmptySchema)(it, valid);\n}\nfunction schemaCxtHasRules({ schema, self }) {\n if (typeof schema == \"boolean\")\n return !schema;\n for (const key in schema)\n if (self.RULES.all[key])\n return true;\n return false;\n}\nfunction isSchemaObj(it) {\n return typeof it.schema != \"boolean\";\n}\nfunction subSchemaObjCode(it, valid) {\n const { schema, gen, opts } = it;\n if (opts.$comment && schema.$comment)\n commentKeyword(it);\n updateContext(it);\n checkAsyncSchema(it);\n const errsCount = gen.const(\"_errs\", names_1.default.errors);\n typeAndKeywords(it, errsCount);\n // TODO var\n gen.var(valid, (0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);\n}\nfunction checkKeywords(it) {\n (0, util_1.checkUnknownRules)(it);\n checkRefsAndKeywords(it);\n}\nfunction typeAndKeywords(it, errsCount) {\n if (it.opts.jtd)\n return schemaKeywords(it, [], false, errsCount);\n const types = (0, dataType_1.getSchemaTypes)(it.schema);\n const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types);\n schemaKeywords(it, types, !checkedTypes, errsCount);\n}\nfunction checkRefsAndKeywords(it) {\n const { schema, errSchemaPath, opts, self } = it;\n if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) {\n self.logger.warn(`$ref: keywords ignored in schema at path \"${errSchemaPath}\"`);\n }\n}\nfunction checkNoDefault(it) {\n const { schema, opts } = it;\n if (schema.default !== undefined && opts.useDefaults && opts.strictSchema) {\n (0, util_1.checkStrictMode)(it, \"default is ignored in the schema root\");\n }\n}\nfunction updateContext(it) {\n const schId = it.schema[it.opts.schemaId];\n if (schId)\n it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId);\n}\nfunction checkAsyncSchema(it) {\n if (it.schema.$async && !it.schemaEnv.$async)\n throw new Error(\"async schema in sync schema\");\n}\nfunction commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) {\n const msg = schema.$comment;\n if (opts.$comment === true) {\n gen.code((0, codegen_1._) `${names_1.default.self}.logger.log(${msg})`);\n }\n else if (typeof opts.$comment == \"function\") {\n const schemaPath = (0, codegen_1.str) `${errSchemaPath}/$comment`;\n const rootName = gen.scopeValue(\"root\", { ref: schemaEnv.root });\n gen.code((0, codegen_1._) `${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`);\n }\n}\nfunction returnResults(it) {\n const { gen, schemaEnv, validateName, ValidationError, opts } = it;\n if (schemaEnv.$async) {\n // TODO assign unevaluated\n gen.if((0, codegen_1._) `${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._) `new ${ValidationError}(${names_1.default.vErrors})`));\n }\n else {\n gen.assign((0, codegen_1._) `${validateName}.errors`, names_1.default.vErrors);\n if (opts.unevaluated)\n assignEvaluated(it);\n gen.return((0, codegen_1._) `${names_1.default.errors} === 0`);\n }\n}\nfunction assignEvaluated({ gen, evaluated, props, items }) {\n if (props instanceof codegen_1.Name)\n gen.assign((0, codegen_1._) `${evaluated}.props`, props);\n if (items instanceof codegen_1.Name)\n gen.assign((0, codegen_1._) `${evaluated}.items`, items);\n}\nfunction schemaKeywords(it, types, typeErrors, errsCount) {\n const { gen, schema, data, allErrors, opts, self } = it;\n const { RULES } = self;\n if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) {\n gen.block(() => keywordCode(it, \"$ref\", RULES.all.$ref.definition)); // TODO typecast\n return;\n }\n if (!opts.jtd)\n checkStrictTypes(it, types);\n gen.block(() => {\n for (const group of RULES.rules)\n groupKeywords(group);\n groupKeywords(RULES.post);\n });\n function groupKeywords(group) {\n if (!(0, applicability_1.shouldUseGroup)(schema, group))\n return;\n if (group.type) {\n gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers));\n iterateKeywords(it, group);\n if (types.length === 1 && types[0] === group.type && typeErrors) {\n gen.else();\n (0, dataType_2.reportTypeError)(it);\n }\n gen.endIf();\n }\n else {\n iterateKeywords(it, group);\n }\n // TODO make it \"ok\" call?\n if (!allErrors)\n gen.if((0, codegen_1._) `${names_1.default.errors} === ${errsCount || 0}`);\n }\n}\nfunction iterateKeywords(it, group) {\n const { gen, schema, opts: { useDefaults }, } = it;\n if (useDefaults)\n (0, defaults_1.assignDefaults)(it, group.type);\n gen.block(() => {\n for (const rule of group.rules) {\n if ((0, applicability_1.shouldUseRule)(schema, rule)) {\n keywordCode(it, rule.keyword, rule.definition, group.type);\n }\n }\n });\n}\nfunction checkStrictTypes(it, types) {\n if (it.schemaEnv.meta || !it.opts.strictTypes)\n return;\n checkContextTypes(it, types);\n if (!it.opts.allowUnionTypes)\n checkMultipleTypes(it, types);\n checkKeywordTypes(it, it.dataTypes);\n}\nfunction checkContextTypes(it, types) {\n if (!types.length)\n return;\n if (!it.dataTypes.length) {\n it.dataTypes = types;\n return;\n }\n types.forEach((t) => {\n if (!includesType(it.dataTypes, t)) {\n strictTypesError(it, `type \"${t}\" not allowed by context \"${it.dataTypes.join(\",\")}\"`);\n }\n });\n narrowSchemaTypes(it, types);\n}\nfunction checkMultipleTypes(it, ts) {\n if (ts.length > 1 && !(ts.length === 2 && ts.includes(\"null\"))) {\n strictTypesError(it, \"use allowUnionTypes to allow union type keyword\");\n }\n}\nfunction checkKeywordTypes(it, ts) {\n const rules = it.self.RULES.all;\n for (const keyword in rules) {\n const rule = rules[keyword];\n if (typeof rule == \"object\" && (0, applicability_1.shouldUseRule)(it.schema, rule)) {\n const { type } = rule.definition;\n if (type.length && !type.some((t) => hasApplicableType(ts, t))) {\n strictTypesError(it, `missing type \"${type.join(\",\")}\" for keyword \"${keyword}\"`);\n }\n }\n }\n}\nfunction hasApplicableType(schTs, kwdT) {\n return schTs.includes(kwdT) || (kwdT === \"number\" && schTs.includes(\"integer\"));\n}\nfunction includesType(ts, t) {\n return ts.includes(t) || (t === \"integer\" && ts.includes(\"number\"));\n}\nfunction narrowSchemaTypes(it, withTypes) {\n const ts = [];\n for (const t of it.dataTypes) {\n if (includesType(withTypes, t))\n ts.push(t);\n else if (withTypes.includes(\"integer\") && t === \"number\")\n ts.push(\"integer\");\n }\n it.dataTypes = ts;\n}\nfunction strictTypesError(it, msg) {\n const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;\n msg += ` at \"${schemaPath}\" (strictTypes)`;\n (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes);\n}\nclass KeywordCxt {\n constructor(it, def, keyword) {\n (0, keyword_1.validateKeywordUsage)(it, def, keyword);\n this.gen = it.gen;\n this.allErrors = it.allErrors;\n this.keyword = keyword;\n this.data = it.data;\n this.schema = it.schema[keyword];\n this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data;\n this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data);\n this.schemaType = def.schemaType;\n this.parentSchema = it.schema;\n this.params = {};\n this.it = it;\n this.def = def;\n if (this.$data) {\n this.schemaCode = it.gen.const(\"vSchema\", getData(this.$data, it));\n }\n else {\n this.schemaCode = this.schemaValue;\n if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) {\n throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`);\n }\n }\n if (\"code\" in def ? def.trackErrors : def.errors !== false) {\n this.errsCount = it.gen.const(\"_errs\", names_1.default.errors);\n }\n }\n result(condition, successAction, failAction) {\n this.failResult((0, codegen_1.not)(condition), successAction, failAction);\n }\n failResult(condition, successAction, failAction) {\n this.gen.if(condition);\n if (failAction)\n failAction();\n else\n this.error();\n if (successAction) {\n this.gen.else();\n successAction();\n if (this.allErrors)\n this.gen.endIf();\n }\n else {\n if (this.allErrors)\n this.gen.endIf();\n else\n this.gen.else();\n }\n }\n pass(condition, failAction) {\n this.failResult((0, codegen_1.not)(condition), undefined, failAction);\n }\n fail(condition) {\n if (condition === undefined) {\n this.error();\n if (!this.allErrors)\n this.gen.if(false); // this branch will be removed by gen.optimize\n return;\n }\n this.gen.if(condition);\n this.error();\n if (this.allErrors)\n this.gen.endIf();\n else\n this.gen.else();\n }\n fail$data(condition) {\n if (!this.$data)\n return this.fail(condition);\n const { schemaCode } = this;\n this.fail((0, codegen_1._) `${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`);\n }\n error(append, errorParams, errorPaths) {\n if (errorParams) {\n this.setParams(errorParams);\n this._error(append, errorPaths);\n this.setParams({});\n return;\n }\n this._error(append, errorPaths);\n }\n _error(append, errorPaths) {\n ;\n (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths);\n }\n $dataError() {\n (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError);\n }\n reset() {\n if (this.errsCount === undefined)\n throw new Error('add \"trackErrors\" to keyword definition');\n (0, errors_1.resetErrorsCount)(this.gen, this.errsCount);\n }\n ok(cond) {\n if (!this.allErrors)\n this.gen.if(cond);\n }\n setParams(obj, assign) {\n if (assign)\n Object.assign(this.params, obj);\n else\n this.params = obj;\n }\n block$data(valid, codeBlock, $dataValid = codegen_1.nil) {\n this.gen.block(() => {\n this.check$data(valid, $dataValid);\n codeBlock();\n });\n }\n check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) {\n if (!this.$data)\n return;\n const { gen, schemaCode, schemaType, def } = this;\n gen.if((0, codegen_1.or)((0, codegen_1._) `${schemaCode} === undefined`, $dataValid));\n if (valid !== codegen_1.nil)\n gen.assign(valid, true);\n if (schemaType.length || def.validateSchema) {\n gen.elseIf(this.invalid$data());\n this.$dataError();\n if (valid !== codegen_1.nil)\n gen.assign(valid, false);\n }\n gen.else();\n }\n invalid$data() {\n const { gen, schemaCode, schemaType, def, it } = this;\n return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema());\n function wrong$DataType() {\n if (schemaType.length) {\n /* istanbul ignore if */\n if (!(schemaCode instanceof codegen_1.Name))\n throw new Error(\"ajv implementation error\");\n const st = Array.isArray(schemaType) ? schemaType : [schemaType];\n return (0, codegen_1._) `${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`;\n }\n return codegen_1.nil;\n }\n function invalid$DataSchema() {\n if (def.validateSchema) {\n const validateSchemaRef = gen.scopeValue(\"validate$data\", { ref: def.validateSchema }); // TODO value.code for standalone\n return (0, codegen_1._) `!${validateSchemaRef}(${schemaCode})`;\n }\n return codegen_1.nil;\n }\n }\n subschema(appl, valid) {\n const subschema = (0, subschema_1.getSubschema)(this.it, appl);\n (0, subschema_1.extendSubschemaData)(subschema, this.it, appl);\n (0, subschema_1.extendSubschemaMode)(subschema, appl);\n const nextContext = { ...this.it, ...subschema, items: undefined, props: undefined };\n subschemaCode(nextContext, valid);\n return nextContext;\n }\n mergeEvaluated(schemaCxt, toName) {\n const { it, gen } = this;\n if (!it.opts.unevaluated)\n return;\n if (it.props !== true && schemaCxt.props !== undefined) {\n it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName);\n }\n if (it.items !== true && schemaCxt.items !== undefined) {\n it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName);\n }\n }\n mergeValidEvaluated(schemaCxt, valid) {\n const { it, gen } = this;\n if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {\n gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name));\n return true;\n }\n }\n}\nexports.KeywordCxt = KeywordCxt;\nfunction keywordCode(it, keyword, def, ruleType) {\n const cxt = new KeywordCxt(it, def, keyword);\n if (\"code\" in def) {\n def.code(cxt, ruleType);\n }\n else if (cxt.$data && def.validate) {\n (0, keyword_1.funcKeywordCode)(cxt, def);\n }\n else if (\"macro\" in def) {\n (0, keyword_1.macroKeywordCode)(cxt, def);\n }\n else if (def.compile || def.validate) {\n (0, keyword_1.funcKeywordCode)(cxt, def);\n }\n}\nconst JSON_POINTER = /^\\/(?:[^~]|~0|~1)*$/;\nconst RELATIVE_JSON_POINTER = /^([0-9]+)(#|\\/(?:[^~]|~0|~1)*)?$/;\nfunction getData($data, { dataLevel, dataNames, dataPathArr }) {\n let jsonPointer;\n let data;\n if ($data === \"\")\n return names_1.default.rootData;\n if ($data[0] === \"/\") {\n if (!JSON_POINTER.test($data))\n throw new Error(`Invalid JSON-pointer: ${$data}`);\n jsonPointer = $data;\n data = names_1.default.rootData;\n }\n else {\n const matches = RELATIVE_JSON_POINTER.exec($data);\n if (!matches)\n throw new Error(`Invalid JSON-pointer: ${$data}`);\n const up = +matches[1];\n jsonPointer = matches[2];\n if (jsonPointer === \"#\") {\n if (up >= dataLevel)\n throw new Error(errorMsg(\"property/index\", up));\n return dataPathArr[dataLevel - up];\n }\n if (up > dataLevel)\n throw new Error(errorMsg(\"data\", up));\n data = dataNames[dataLevel - up];\n if (!jsonPointer)\n return data;\n }\n let expr = data;\n const segments = jsonPointer.split(\"/\");\n for (const segment of segments) {\n if (segment) {\n data = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`;\n expr = (0, codegen_1._) `${expr} && ${data}`;\n }\n }\n return expr;\n function errorMsg(pointerType, up) {\n return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`;\n }\n}\nexports.getData = getData;\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nclass ValidationError extends Error {\n constructor(errors) {\n super(\"validation failed\");\n this.errors = errors;\n this.ajv = this.validation = true;\n }\n}\nexports.default = ValidationError;\n//# sourceMappingURL=validation_error.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst resolve_1 = require(\"./resolve\");\nclass MissingRefError extends Error {\n constructor(resolver, baseId, ref, msg) {\n super(msg || `can't resolve reference ${ref} from id ${baseId}`);\n this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref);\n this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef));\n }\n}\nexports.default = MissingRefError;\n//# sourceMappingURL=ref_error.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0;\nconst codegen_1 = require(\"./codegen\");\nconst validation_error_1 = require(\"../runtime/validation_error\");\nconst names_1 = require(\"./names\");\nconst resolve_1 = require(\"./resolve\");\nconst util_1 = require(\"./util\");\nconst validate_1 = require(\"./validate\");\nclass SchemaEnv {\n constructor(env) {\n var _a;\n this.refs = {};\n this.dynamicAnchors = {};\n let schema;\n if (typeof env.schema == \"object\")\n schema = env.schema;\n this.schema = env.schema;\n this.schemaId = env.schemaId;\n this.root = env.root || this;\n this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || \"$id\"]);\n this.schemaPath = env.schemaPath;\n this.localRefs = env.localRefs;\n this.meta = env.meta;\n this.$async = schema === null || schema === void 0 ? void 0 : schema.$async;\n this.refs = {};\n }\n}\nexports.SchemaEnv = SchemaEnv;\n// let codeSize = 0\n// let nodeCount = 0\n// Compiles schema in SchemaEnv\nfunction compileSchema(sch) {\n // TODO refactor - remove compilations\n const _sch = getCompilingSchema.call(this, sch);\n if (_sch)\n return _sch;\n const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); // TODO if getFullPath removed 1 tests fails\n const { es5, lines } = this.opts.code;\n const { ownProperties } = this.opts;\n const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties });\n let _ValidationError;\n if (sch.$async) {\n _ValidationError = gen.scopeValue(\"Error\", {\n ref: validation_error_1.default,\n code: (0, codegen_1._) `require(\"ajv/dist/runtime/validation_error\").default`,\n });\n }\n const validateName = gen.scopeName(\"validate\");\n sch.validateName = validateName;\n const schemaCxt = {\n gen,\n allErrors: this.opts.allErrors,\n data: names_1.default.data,\n parentData: names_1.default.parentData,\n parentDataProperty: names_1.default.parentDataProperty,\n dataNames: [names_1.default.data],\n dataPathArr: [codegen_1.nil], // TODO can its length be used as dataLevel if nil is removed?\n dataLevel: 0,\n dataTypes: [],\n definedProperties: new Set(),\n topSchemaRef: gen.scopeValue(\"schema\", this.opts.code.source === true\n ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) }\n : { ref: sch.schema }),\n validateName,\n ValidationError: _ValidationError,\n schema: sch.schema,\n schemaEnv: sch,\n rootId,\n baseId: sch.baseId || rootId,\n schemaPath: codegen_1.nil,\n errSchemaPath: sch.schemaPath || (this.opts.jtd ? \"\" : \"#\"),\n errorPath: (0, codegen_1._) `\"\"`,\n opts: this.opts,\n self: this,\n };\n let sourceCode;\n try {\n this._compilations.add(sch);\n (0, validate_1.validateFunctionCode)(schemaCxt);\n gen.optimize(this.opts.code.optimize);\n // gen.optimize(1)\n const validateCode = gen.toString();\n sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`;\n // console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount))\n if (this.opts.code.process)\n sourceCode = this.opts.code.process(sourceCode, sch);\n // console.log(\"\\n\\n\\n *** \\n\", sourceCode)\n const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode);\n const validate = makeValidate(this, this.scope.get());\n this.scope.value(validateName, { ref: validate });\n validate.errors = null;\n validate.schema = sch.schema;\n validate.schemaEnv = sch;\n if (sch.$async)\n validate.$async = true;\n if (this.opts.code.source === true) {\n validate.source = { validateName, validateCode, scopeValues: gen._values };\n }\n if (this.opts.unevaluated) {\n const { props, items } = schemaCxt;\n validate.evaluated = {\n props: props instanceof codegen_1.Name ? undefined : props,\n items: items instanceof codegen_1.Name ? undefined : items,\n dynamicProps: props instanceof codegen_1.Name,\n dynamicItems: items instanceof codegen_1.Name,\n };\n if (validate.source)\n validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated);\n }\n sch.validate = validate;\n return sch;\n }\n catch (e) {\n delete sch.validate;\n delete sch.validateName;\n if (sourceCode)\n this.logger.error(\"Error compiling schema, function code:\", sourceCode);\n // console.log(\"\\n\\n\\n *** \\n\", sourceCode, this.opts)\n throw e;\n }\n finally {\n this._compilations.delete(sch);\n }\n}\nexports.compileSchema = compileSchema;\nfunction resolveRef(root, baseId, ref) {\n var _a;\n ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref);\n const schOrFunc = root.refs[ref];\n if (schOrFunc)\n return schOrFunc;\n let _sch = resolve.call(this, root, ref);\n if (_sch === undefined) {\n const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; // TODO maybe localRefs should hold SchemaEnv\n const { schemaId } = this.opts;\n if (schema)\n _sch = new SchemaEnv({ schema, schemaId, root, baseId });\n }\n if (_sch === undefined)\n return;\n return (root.refs[ref] = inlineOrCompile.call(this, _sch));\n}\nexports.resolveRef = resolveRef;\nfunction inlineOrCompile(sch) {\n if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs))\n return sch.schema;\n return sch.validate ? sch : compileSchema.call(this, sch);\n}\n// Index of schema compilation in the currently compiled list\nfunction getCompilingSchema(schEnv) {\n for (const sch of this._compilations) {\n if (sameSchemaEnv(sch, schEnv))\n return sch;\n }\n}\nexports.getCompilingSchema = getCompilingSchema;\nfunction sameSchemaEnv(s1, s2) {\n return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;\n}\n// resolve and compile the references ($ref)\n// TODO returns AnySchemaObject (if the schema can be inlined) or validation function\nfunction resolve(root, // information about the root schema for the current schema\nref // reference to resolve\n) {\n let sch;\n while (typeof (sch = this.refs[ref]) == \"string\")\n ref = sch;\n return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);\n}\n// Resolve schema, its root and baseId\nfunction resolveSchema(root, // root object with properties schema, refs TODO below SchemaEnv is assigned to it\nref // reference to resolve\n) {\n const p = this.opts.uriResolver.parse(ref);\n const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p);\n let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, undefined);\n // TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests\n if (Object.keys(root.schema).length > 0 && refPath === baseId) {\n return getJsonPointer.call(this, p, root);\n }\n const id = (0, resolve_1.normalizeId)(refPath);\n const schOrRef = this.refs[id] || this.schemas[id];\n if (typeof schOrRef == \"string\") {\n const sch = resolveSchema.call(this, root, schOrRef);\n if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== \"object\")\n return;\n return getJsonPointer.call(this, p, sch);\n }\n if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== \"object\")\n return;\n if (!schOrRef.validate)\n compileSchema.call(this, schOrRef);\n if (id === (0, resolve_1.normalizeId)(ref)) {\n const { schema } = schOrRef;\n const { schemaId } = this.opts;\n const schId = schema[schemaId];\n if (schId)\n baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);\n return new SchemaEnv({ schema, schemaId, root, baseId });\n }\n return getJsonPointer.call(this, p, schOrRef);\n}\nexports.resolveSchema = resolveSchema;\nconst PREVENT_SCOPE_CHANGE = new Set([\n \"properties\",\n \"patternProperties\",\n \"enum\",\n \"dependencies\",\n \"definitions\",\n]);\nfunction getJsonPointer(parsedRef, { baseId, schema, root }) {\n var _a;\n if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== \"/\")\n return;\n for (const part of parsedRef.fragment.slice(1).split(\"/\")) {\n if (typeof schema === \"boolean\")\n return;\n const partSchema = schema[(0, util_1.unescapeFragment)(part)];\n if (partSchema === undefined)\n return;\n schema = partSchema;\n // TODO PREVENT_SCOPE_CHANGE could be defined in keyword def?\n const schId = typeof schema === \"object\" && schema[this.opts.schemaId];\n if (!PREVENT_SCOPE_CHANGE.has(part) && schId) {\n baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);\n }\n }\n let env;\n if (typeof schema != \"boolean\" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) {\n const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref);\n env = resolveSchema.call(this, root, $ref);\n }\n // even though resolution failed we need to return SchemaEnv to throw exception\n // so that compileAsync loads missing schema.\n const { schemaId } = this.opts;\n env = env || new SchemaEnv({ schema, schemaId, root, baseId });\n if (env.schema !== env.root.schema)\n return env;\n return undefined;\n}\n//# sourceMappingURL=index.js.map","","'use strict'\n\n/** @type {(value: string) => boolean} */\nconst isUUID = RegExp.prototype.test.bind(/^[\\da-f]{8}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{12}$/iu)\n\n/** @type {(value: string) => boolean} */\nconst 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)\n\n/** @type {(value: string) => boolean} */\nconst isHexPair = RegExp.prototype.test.bind(/^[\\da-f]{2}$/iu)\n\n/** @type {(value: string) => boolean} */\nconst isUnreserved = RegExp.prototype.test.bind(/^[\\da-z\\-._~]$/iu)\n\n/** @type {(value: string) => boolean} */\nconst isPathCharacter = RegExp.prototype.test.bind(/^[\\da-z\\-._~!$&'()*+,;=:@/]$/iu)\n\n/**\n * @param {Array<string>} input\n * @returns {string}\n */\nfunction stringArrayToHexStripped (input) {\n let acc = ''\n let code = 0\n let i = 0\n\n for (i = 0; i < input.length; i++) {\n code = input[i].charCodeAt(0)\n if (code === 48) {\n continue\n }\n if (!((code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102))) {\n return ''\n }\n acc += input[i]\n break\n }\n\n for (i += 1; i < input.length; i++) {\n code = input[i].charCodeAt(0)\n if (!((code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102))) {\n return ''\n }\n acc += input[i]\n }\n return acc\n}\n\n/**\n * @typedef {Object} GetIPV6Result\n * @property {boolean} error - Indicates if there was an error parsing the IPv6 address.\n * @property {string} address - The parsed IPv6 address.\n * @property {string} [zone] - The zone identifier, if present.\n */\n\n/**\n * @param {string} value\n * @returns {boolean}\n */\nconst nonSimpleDomain = RegExp.prototype.test.bind(/[^!\"$&'()*+,\\-.;=_`a-z{}~]/u)\n\n/**\n * @param {Array<string>} buffer\n * @returns {boolean}\n */\nfunction consumeIsZone (buffer) {\n buffer.length = 0\n return true\n}\n\n/**\n * @param {Array<string>} buffer\n * @param {Array<string>} address\n * @param {GetIPV6Result} output\n * @returns {boolean}\n */\nfunction consumeHextets (buffer, address, output) {\n if (buffer.length) {\n const hex = stringArrayToHexStripped(buffer)\n if (hex !== '') {\n address.push(hex)\n } else {\n output.error = true\n return false\n }\n buffer.length = 0\n }\n return true\n}\n\n/**\n * @param {string} input\n * @returns {GetIPV6Result}\n */\nfunction getIPV6 (input) {\n let tokenCount = 0\n const output = { error: false, address: '', zone: '' }\n /** @type {Array<string>} */\n const address = []\n /** @type {Array<string>} */\n const buffer = []\n let endipv6Encountered = false\n let endIpv6 = false\n\n let consume = consumeHextets\n\n for (let i = 0; i < input.length; i++) {\n const cursor = input[i]\n if (cursor === '[' || cursor === ']') { continue }\n if (cursor === ':') {\n if (endipv6Encountered === true) {\n endIpv6 = true\n }\n if (!consume(buffer, address, output)) { break }\n if (++tokenCount > 7) {\n // not valid\n output.error = true\n break\n }\n if (i > 0 && input[i - 1] === ':') {\n endipv6Encountered = true\n }\n address.push(':')\n continue\n } else if (cursor === '%') {\n if (!consume(buffer, address, output)) { break }\n // switch to zone detection\n consume = consumeIsZone\n } else {\n buffer.push(cursor)\n continue\n }\n }\n if (buffer.length) {\n if (consume === consumeIsZone) {\n output.zone = buffer.join('')\n } else if (endIpv6) {\n address.push(buffer.join(''))\n } else {\n address.push(stringArrayToHexStripped(buffer))\n }\n }\n output.address = address.join('')\n return output\n}\n\n/**\n * @typedef {Object} NormalizeIPv6Result\n * @property {string} host - The normalized host.\n * @property {string} [escapedHost] - The escaped host.\n * @property {boolean} isIPV6 - Indicates if the host is an IPv6 address.\n */\n\n/**\n * @param {string} host\n * @returns {NormalizeIPv6Result}\n */\nfunction normalizeIPv6 (host) {\n if (findToken(host, ':') < 2) { return { host, isIPV6: false } }\n const ipv6 = getIPV6(host)\n\n if (!ipv6.error) {\n let newHost = ipv6.address\n let escapedHost = ipv6.address\n if (ipv6.zone) {\n newHost += '%' + ipv6.zone\n escapedHost += '%25' + ipv6.zone\n }\n return { host: newHost, isIPV6: true, escapedHost }\n } else {\n return { host, isIPV6: false }\n }\n}\n\n/**\n * @param {string} str\n * @param {string} token\n * @returns {number}\n */\nfunction findToken (str, token) {\n let ind = 0\n for (let i = 0; i < str.length; i++) {\n if (str[i] === token) ind++\n }\n return ind\n}\n\n/**\n * @param {string} path\n * @returns {string}\n *\n * @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4\n */\nfunction removeDotSegments (path) {\n let input = path\n const output = []\n let nextSlash = -1\n let len = 0\n\n // eslint-disable-next-line no-cond-assign\n while (len = input.length) {\n if (len === 1) {\n if (input === '.') {\n break\n } else if (input === '/') {\n output.push('/')\n break\n } else {\n output.push(input)\n break\n }\n } else if (len === 2) {\n if (input[0] === '.') {\n if (input[1] === '.') {\n break\n } else if (input[1] === '/') {\n input = input.slice(2)\n continue\n }\n } else if (input[0] === '/') {\n if (input[1] === '.' || input[1] === '/') {\n output.push('/')\n break\n }\n }\n } else if (len === 3) {\n if (input === '/..') {\n if (output.length !== 0) {\n output.pop()\n }\n output.push('/')\n break\n }\n }\n if (input[0] === '.') {\n if (input[1] === '.') {\n if (input[2] === '/') {\n input = input.slice(3)\n continue\n }\n } else if (input[1] === '/') {\n input = input.slice(2)\n continue\n }\n } else if (input[0] === '/') {\n if (input[1] === '.') {\n if (input[2] === '/') {\n input = input.slice(2)\n continue\n } else if (input[2] === '.') {\n if (input[3] === '/') {\n input = input.slice(3)\n if (output.length !== 0) {\n output.pop()\n }\n continue\n }\n }\n }\n }\n\n // Rule 2E: Move normal path segment to output\n if ((nextSlash = input.indexOf('/', 1)) === -1) {\n output.push(input)\n break\n } else {\n output.push(input.slice(0, nextSlash))\n input = input.slice(nextSlash)\n }\n }\n\n return output.join('')\n}\n\n/**\n * Re-escape RFC 3986 gen-delims that must not appear literally in the host.\n * After the URI regex parses, these characters cannot be literal in the host\n * field, so any that appear after decoding came from percent-encoding and\n * must be restored to prevent authority structure changes.\n *\n * @param {string} host\n * @param {boolean} isIP - true for IPv4/IPv6 hosts (skip colon re-escaping)\n * @returns {string}\n */\nconst HOST_DELIMS = { '@': '%40', '/': '%2F', '?': '%3F', '#': '%23', ':': '%3A' }\nconst HOST_DELIM_RE = /[@/?#:]/g\nconst HOST_DELIM_NO_COLON_RE = /[@/?#]/g\n\nfunction reescapeHostDelimiters (host, isIP) {\n const re = isIP ? HOST_DELIM_NO_COLON_RE : HOST_DELIM_RE\n re.lastIndex = 0\n return host.replace(re, (ch) => HOST_DELIMS[ch])\n}\n\n/**\n * Normalizes percent escapes and optionally decodes only unreserved ASCII bytes.\n * Reserved delimiters such as `%2F` and `%2E` stay escaped.\n *\n * @param {string} input\n * @param {boolean} [decodeUnreserved=false]\n * @returns {string}\n */\nfunction normalizePercentEncoding (input, decodeUnreserved = false) {\n if (input.indexOf('%') === -1) {\n return input\n }\n\n let output = ''\n\n for (let i = 0; i < input.length; i++) {\n if (input[i] === '%' && i + 2 < input.length) {\n const hex = input.slice(i + 1, i + 3)\n if (isHexPair(hex)) {\n const normalizedHex = hex.toUpperCase()\n const decoded = String.fromCharCode(parseInt(normalizedHex, 16))\n\n if (decodeUnreserved && isUnreserved(decoded)) {\n output += decoded\n } else {\n output += '%' + normalizedHex\n }\n\n i += 2\n continue\n }\n }\n\n output += input[i]\n }\n\n return output\n}\n\n/**\n * Normalizes path data without turning reserved escapes into live path syntax.\n * Valid escapes are uppercased, raw unsafe characters are escaped, and only\n * unreserved bytes that are not `.` are decoded.\n *\n * @param {string} input\n * @returns {string}\n */\nfunction normalizePathEncoding (input) {\n let output = ''\n\n for (let i = 0; i < input.length; i++) {\n if (input[i] === '%' && i + 2 < input.length) {\n const hex = input.slice(i + 1, i + 3)\n if (isHexPair(hex)) {\n const normalizedHex = hex.toUpperCase()\n const decoded = String.fromCharCode(parseInt(normalizedHex, 16))\n\n if (decoded !== '.' && isUnreserved(decoded)) {\n output += decoded\n } else {\n output += '%' + normalizedHex\n }\n\n i += 2\n continue\n }\n }\n\n if (isPathCharacter(input[i])) {\n output += input[i]\n } else {\n output += escape(input[i])\n }\n }\n\n return output\n}\n\n/**\n * Escapes a component while preserving existing valid percent escapes.\n *\n * @param {string} input\n * @returns {string}\n */\nfunction escapePreservingEscapes (input) {\n let output = ''\n\n for (let i = 0; i < input.length; i++) {\n if (input[i] === '%' && i + 2 < input.length) {\n const hex = input.slice(i + 1, i + 3)\n if (isHexPair(hex)) {\n output += '%' + hex.toUpperCase()\n i += 2\n continue\n }\n }\n\n output += escape(input[i])\n }\n\n return output\n}\n\n/**\n * @param {import('../types/index').URIComponent} component\n * @returns {string|undefined}\n */\nfunction recomposeAuthority (component) {\n const uriTokens = []\n\n if (component.userinfo !== undefined) {\n uriTokens.push(component.userinfo)\n uriTokens.push('@')\n }\n\n if (component.host !== undefined) {\n let host = unescape(component.host)\n if (!isIPv4(host)) {\n const ipV6res = normalizeIPv6(host)\n if (ipV6res.isIPV6 === true) {\n host = `[${ipV6res.escapedHost}]`\n } else {\n host = reescapeHostDelimiters(host, false)\n }\n }\n uriTokens.push(host)\n }\n\n if (typeof component.port === 'number' || typeof component.port === 'string') {\n uriTokens.push(':')\n uriTokens.push(String(component.port))\n }\n\n return uriTokens.length ? uriTokens.join('') : undefined\n};\n\nmodule.exports = {\n nonSimpleDomain,\n recomposeAuthority,\n reescapeHostDelimiters,\n normalizePercentEncoding,\n normalizePathEncoding,\n escapePreservingEscapes,\n removeDotSegments,\n isIPv4,\n isUUID,\n normalizeIPv6,\n stringArrayToHexStripped\n}\n","'use strict'\n\nconst { isUUID } = require('./utils')\nconst URN_REG = /([\\da-z][\\d\\-a-z]{0,31}):((?:[\\w!$'()*+,\\-.:;=@]|%[\\da-f]{2})+)/iu\n\nconst supportedSchemeNames = /** @type {const} */ (['http', 'https', 'ws',\n 'wss', 'urn', 'urn:uuid'])\n\n/** @typedef {supportedSchemeNames[number]} SchemeName */\n\n/**\n * @param {string} name\n * @returns {name is SchemeName}\n */\nfunction isValidSchemeName (name) {\n return supportedSchemeNames.indexOf(/** @type {*} */ (name)) !== -1\n}\n\n/**\n * @callback SchemeFn\n * @param {import('../types/index').URIComponent} component\n * @param {import('../types/index').Options} options\n * @returns {import('../types/index').URIComponent}\n */\n\n/**\n * @typedef {Object} SchemeHandler\n * @property {SchemeName} scheme - The scheme name.\n * @property {boolean} [domainHost] - Indicates if the scheme supports domain hosts.\n * @property {SchemeFn} parse - Function to parse the URI component for this scheme.\n * @property {SchemeFn} serialize - Function to serialize the URI component for this scheme.\n * @property {boolean} [skipNormalize] - Indicates if normalization should be skipped for this scheme.\n * @property {boolean} [absolutePath] - Indicates if the scheme uses absolute paths.\n * @property {boolean} [unicodeSupport] - Indicates if the scheme supports Unicode.\n */\n\n/**\n * @param {import('../types/index').URIComponent} wsComponent\n * @returns {boolean}\n */\nfunction wsIsSecure (wsComponent) {\n if (wsComponent.secure === true) {\n return true\n } else if (wsComponent.secure === false) {\n return false\n } else if (wsComponent.scheme) {\n return (\n wsComponent.scheme.length === 3 &&\n (wsComponent.scheme[0] === 'w' || wsComponent.scheme[0] === 'W') &&\n (wsComponent.scheme[1] === 's' || wsComponent.scheme[1] === 'S') &&\n (wsComponent.scheme[2] === 's' || wsComponent.scheme[2] === 'S')\n )\n } else {\n return false\n }\n}\n\n/** @type {SchemeFn} */\nfunction httpParse (component) {\n if (!component.host) {\n component.error = component.error || 'HTTP URIs must have a host.'\n }\n\n return component\n}\n\n/** @type {SchemeFn} */\nfunction httpSerialize (component) {\n const secure = String(component.scheme).toLowerCase() === 'https'\n\n // normalize the default port\n if (component.port === (secure ? 443 : 80) || component.port === '') {\n component.port = undefined\n }\n\n // normalize the empty path\n if (!component.path) {\n component.path = '/'\n }\n\n // NOTE: We do not parse query strings for HTTP URIs\n // as WWW Form Url Encoded query strings are part of the HTML4+ spec,\n // and not the HTTP spec.\n\n return component\n}\n\n/** @type {SchemeFn} */\nfunction wsParse (wsComponent) {\n// indicate if the secure flag is set\n wsComponent.secure = wsIsSecure(wsComponent)\n\n // construct resouce name\n wsComponent.resourceName = (wsComponent.path || '/') + (wsComponent.query ? '?' + wsComponent.query : '')\n wsComponent.path = undefined\n wsComponent.query = undefined\n\n return wsComponent\n}\n\n/** @type {SchemeFn} */\nfunction wsSerialize (wsComponent) {\n// normalize the default port\n if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === '') {\n wsComponent.port = undefined\n }\n\n // ensure scheme matches secure flag\n if (typeof wsComponent.secure === 'boolean') {\n wsComponent.scheme = (wsComponent.secure ? 'wss' : 'ws')\n wsComponent.secure = undefined\n }\n\n // reconstruct path from resource name\n if (wsComponent.resourceName) {\n const [path, query] = wsComponent.resourceName.split('?')\n wsComponent.path = (path && path !== '/' ? path : undefined)\n wsComponent.query = query\n wsComponent.resourceName = undefined\n }\n\n // forbid fragment component\n wsComponent.fragment = undefined\n\n return wsComponent\n}\n\n/** @type {SchemeFn} */\nfunction urnParse (urnComponent, options) {\n if (!urnComponent.path) {\n urnComponent.error = 'URN can not be parsed'\n return urnComponent\n }\n const matches = urnComponent.path.match(URN_REG)\n if (matches) {\n const scheme = options.scheme || urnComponent.scheme || 'urn'\n urnComponent.nid = matches[1].toLowerCase()\n urnComponent.nss = matches[2]\n const urnScheme = `${scheme}:${options.nid || urnComponent.nid}`\n const schemeHandler = getSchemeHandler(urnScheme)\n urnComponent.path = undefined\n\n if (schemeHandler) {\n urnComponent = schemeHandler.parse(urnComponent, options)\n }\n } else {\n urnComponent.error = urnComponent.error || 'URN can not be parsed.'\n }\n\n return urnComponent\n}\n\n/** @type {SchemeFn} */\nfunction urnSerialize (urnComponent, options) {\n if (urnComponent.nid === undefined) {\n throw new Error('URN without nid cannot be serialized')\n }\n const scheme = options.scheme || urnComponent.scheme || 'urn'\n const nid = urnComponent.nid.toLowerCase()\n const urnScheme = `${scheme}:${options.nid || nid}`\n const schemeHandler = getSchemeHandler(urnScheme)\n\n if (schemeHandler) {\n urnComponent = schemeHandler.serialize(urnComponent, options)\n }\n\n const uriComponent = urnComponent\n const nss = urnComponent.nss\n uriComponent.path = `${nid || options.nid}:${nss}`\n\n options.skipEscape = true\n return uriComponent\n}\n\n/** @type {SchemeFn} */\nfunction urnuuidParse (urnComponent, options) {\n const uuidComponent = urnComponent\n uuidComponent.uuid = uuidComponent.nss\n uuidComponent.nss = undefined\n\n if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) {\n uuidComponent.error = uuidComponent.error || 'UUID is not valid.'\n }\n\n return uuidComponent\n}\n\n/** @type {SchemeFn} */\nfunction urnuuidSerialize (uuidComponent) {\n const urnComponent = uuidComponent\n // normalize UUID\n urnComponent.nss = (uuidComponent.uuid || '').toLowerCase()\n return urnComponent\n}\n\nconst http = /** @type {SchemeHandler} */ ({\n scheme: 'http',\n domainHost: true,\n parse: httpParse,\n serialize: httpSerialize\n})\n\nconst https = /** @type {SchemeHandler} */ ({\n scheme: 'https',\n domainHost: http.domainHost,\n parse: httpParse,\n serialize: httpSerialize\n})\n\nconst ws = /** @type {SchemeHandler} */ ({\n scheme: 'ws',\n domainHost: true,\n parse: wsParse,\n serialize: wsSerialize\n})\n\nconst wss = /** @type {SchemeHandler} */ ({\n scheme: 'wss',\n domainHost: ws.domainHost,\n parse: ws.parse,\n serialize: ws.serialize\n})\n\nconst urn = /** @type {SchemeHandler} */ ({\n scheme: 'urn',\n parse: urnParse,\n serialize: urnSerialize,\n skipNormalize: true\n})\n\nconst urnuuid = /** @type {SchemeHandler} */ ({\n scheme: 'urn:uuid',\n parse: urnuuidParse,\n serialize: urnuuidSerialize,\n skipNormalize: true\n})\n\nconst SCHEMES = /** @type {Record<SchemeName, SchemeHandler>} */ ({\n http,\n https,\n ws,\n wss,\n urn,\n 'urn:uuid': urnuuid\n})\n\nObject.setPrototypeOf(SCHEMES, null)\n\n/**\n * @param {string|undefined} scheme\n * @returns {SchemeHandler|undefined}\n */\nfunction getSchemeHandler (scheme) {\n return (\n scheme && (\n SCHEMES[/** @type {SchemeName} */ (scheme)] ||\n SCHEMES[/** @type {SchemeName} */(scheme.toLowerCase())])\n ) ||\n undefined\n}\n\nmodule.exports = {\n wsIsSecure,\n SCHEMES,\n isValidSchemeName,\n getSchemeHandler,\n}\n","'use strict'\n\nconst { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizePercentEncoding, normalizePathEncoding, escapePreservingEscapes, reescapeHostDelimiters, isIPv4, nonSimpleDomain } = require('./lib/utils')\nconst { SCHEMES, getSchemeHandler } = require('./lib/schemes')\n\n/**\n * @template {import('./types/index').URIComponent|string} T\n * @param {T} uri\n * @param {import('./types/index').Options} [options]\n * @returns {T}\n */\nfunction normalize (uri, options) {\n if (typeof uri === 'string') {\n uri = /** @type {T} */ (normalizeString(uri, options))\n } else if (typeof uri === 'object') {\n uri = /** @type {T} */ (parse(serialize(uri, options), options))\n }\n return uri\n}\n\n/**\n * @param {string} baseURI\n * @param {string} relativeURI\n * @param {import('./types/index').Options} [options]\n * @returns {string}\n */\nfunction resolve (baseURI, relativeURI, options) {\n const schemelessOptions = options ? Object.assign({ scheme: 'null' }, options) : { scheme: 'null' }\n const resolved = resolveComponent(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true)\n schemelessOptions.skipEscape = true\n return serialize(resolved, schemelessOptions)\n}\n\n/**\n * @param {import ('./types/index').URIComponent} base\n * @param {import ('./types/index').URIComponent} relative\n * @param {import('./types/index').Options} [options]\n * @param {boolean} [skipNormalization=false]\n * @returns {import ('./types/index').URIComponent}\n */\nfunction resolveComponent (base, relative, options, skipNormalization) {\n /** @type {import('./types/index').URIComponent} */\n const target = {}\n if (!skipNormalization) {\n base = parse(serialize(base, options), options) // normalize base component\n relative = parse(serialize(relative, options), options) // normalize relative component\n }\n options = options || {}\n\n if (!options.tolerant && relative.scheme) {\n target.scheme = relative.scheme\n // target.authority = relative.authority;\n target.userinfo = relative.userinfo\n target.host = relative.host\n target.port = relative.port\n target.path = removeDotSegments(relative.path || '')\n target.query = relative.query\n } else {\n if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) {\n // target.authority = relative.authority;\n target.userinfo = relative.userinfo\n target.host = relative.host\n target.port = relative.port\n target.path = removeDotSegments(relative.path || '')\n target.query = relative.query\n } else {\n if (!relative.path) {\n target.path = base.path\n if (relative.query !== undefined) {\n target.query = relative.query\n } else {\n target.query = base.query\n }\n } else {\n if (relative.path[0] === '/') {\n target.path = removeDotSegments(relative.path)\n } else {\n if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) {\n target.path = '/' + relative.path\n } else if (!base.path) {\n target.path = relative.path\n } else {\n target.path = base.path.slice(0, base.path.lastIndexOf('/') + 1) + relative.path\n }\n target.path = removeDotSegments(target.path)\n }\n target.query = relative.query\n }\n // target.authority = base.authority;\n target.userinfo = base.userinfo\n target.host = base.host\n target.port = base.port\n }\n target.scheme = base.scheme\n }\n\n target.fragment = relative.fragment\n\n return target\n}\n\n/**\n * @param {import ('./types/index').URIComponent|string} uriA\n * @param {import ('./types/index').URIComponent|string} uriB\n * @param {import ('./types/index').Options} options\n * @returns {boolean}\n */\nfunction equal (uriA, uriB, options) {\n const normalizedA = normalizeComparableURI(uriA, options)\n const normalizedB = normalizeComparableURI(uriB, options)\n\n return normalizedA !== undefined && normalizedB !== undefined && normalizedA.toLowerCase() === normalizedB.toLowerCase()\n}\n\n/**\n * @param {Readonly<import('./types/index').URIComponent>} cmpts\n * @param {import('./types/index').Options} [opts]\n * @returns {string}\n */\nfunction serialize (cmpts, opts) {\n const component = {\n host: cmpts.host,\n scheme: cmpts.scheme,\n userinfo: cmpts.userinfo,\n port: cmpts.port,\n path: cmpts.path,\n query: cmpts.query,\n nid: cmpts.nid,\n nss: cmpts.nss,\n uuid: cmpts.uuid,\n fragment: cmpts.fragment,\n reference: cmpts.reference,\n resourceName: cmpts.resourceName,\n secure: cmpts.secure,\n error: ''\n }\n const options = Object.assign({}, opts)\n const uriTokens = []\n\n // find scheme handler\n const schemeHandler = getSchemeHandler(options.scheme || component.scheme)\n\n // perform scheme specific serialization\n if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options)\n\n if (component.path !== undefined) {\n if (!options.skipEscape) {\n component.path = escapePreservingEscapes(component.path)\n\n if (component.scheme !== undefined) {\n component.path = component.path.split('%3A').join(':')\n }\n } else {\n component.path = normalizePercentEncoding(component.path)\n }\n }\n\n if (options.reference !== 'suffix' && component.scheme) {\n uriTokens.push(component.scheme, ':')\n }\n\n const authority = recomposeAuthority(component)\n if (authority !== undefined) {\n if (options.reference !== 'suffix') {\n uriTokens.push('//')\n }\n\n uriTokens.push(authority)\n\n if (component.path && component.path[0] !== '/') {\n uriTokens.push('/')\n }\n }\n if (component.path !== undefined) {\n let s = component.path\n\n if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {\n s = removeDotSegments(s)\n }\n\n if (\n authority === undefined &&\n s[0] === '/' &&\n s[1] === '/'\n ) {\n // don't allow the path to start with \"//\"\n s = '/%2F' + s.slice(2)\n }\n\n uriTokens.push(s)\n }\n\n if (component.query !== undefined) {\n uriTokens.push('?', component.query)\n }\n\n if (component.fragment !== undefined) {\n uriTokens.push('#', component.fragment)\n }\n return uriTokens.join('')\n}\n\nconst URI_PARSE = /^(?:([^#/:?]+):)?(?:\\/\\/((?:([^#/?@]*)@)?(\\[[^#/?\\]]+\\]|[^#/:?]*)(?::(\\d*))?))?([^#?]*)(?:\\?([^#]*))?(?:#((?:.|[\\n\\r])*))?/u\n\n/**\n * @param {import('./types/index').URIComponent} parsed\n * @param {RegExpMatchArray} matches\n * @returns {string|undefined}\n */\nfunction getParseError (parsed, matches) {\n if (matches[2] !== undefined && parsed.path && parsed.path[0] !== '/') {\n return 'URI path must start with \"/\" when authority is present.'\n }\n\n if (typeof parsed.port === 'number' && (parsed.port < 0 || parsed.port > 65535)) {\n return 'URI port is malformed.'\n }\n\n return undefined\n}\n\n/**\n * @param {string} uri\n * @param {import('./types/index').Options} [opts]\n * @returns {{ parsed: import('./types/index').URIComponent, malformedAuthorityOrPort: boolean }}\n */\nfunction parseWithStatus (uri, opts) {\n const options = Object.assign({}, opts)\n /** @type {import('./types/index').URIComponent} */\n const parsed = {\n scheme: undefined,\n userinfo: undefined,\n host: '',\n port: undefined,\n path: '',\n query: undefined,\n fragment: undefined\n }\n\n let malformedAuthorityOrPort = false\n\n let isIP = false\n if (options.reference === 'suffix') {\n if (options.scheme) {\n uri = options.scheme + ':' + uri\n } else {\n uri = '//' + uri\n }\n }\n\n const matches = uri.match(URI_PARSE)\n\n if (matches) {\n // store each component\n parsed.scheme = matches[1]\n parsed.userinfo = matches[3]\n parsed.host = matches[4]\n parsed.port = parseInt(matches[5], 10)\n parsed.path = matches[6] || ''\n parsed.query = matches[7]\n parsed.fragment = matches[8]\n\n // fix port number\n if (isNaN(parsed.port)) {\n parsed.port = matches[5]\n }\n\n const parseError = getParseError(parsed, matches)\n if (parseError !== undefined) {\n parsed.error = parsed.error || parseError\n malformedAuthorityOrPort = true\n }\n\n if (parsed.host) {\n const ipv4result = isIPv4(parsed.host)\n if (ipv4result === false) {\n const ipv6result = normalizeIPv6(parsed.host)\n parsed.host = ipv6result.host.toLowerCase()\n isIP = ipv6result.isIPV6\n } else {\n isIP = true\n }\n }\n if (parsed.scheme === undefined && parsed.userinfo === undefined && parsed.host === undefined && parsed.port === undefined && parsed.query === undefined && !parsed.path) {\n parsed.reference = 'same-document'\n } else if (parsed.scheme === undefined) {\n parsed.reference = 'relative'\n } else if (parsed.fragment === undefined) {\n parsed.reference = 'absolute'\n } else {\n parsed.reference = 'uri'\n }\n\n // check for reference errors\n if (options.reference && options.reference !== 'suffix' && options.reference !== parsed.reference) {\n parsed.error = parsed.error || 'URI is not a ' + options.reference + ' reference.'\n }\n\n // find scheme handler\n const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme)\n\n // check if scheme can't handle IRIs\n if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {\n // if host component is a domain name\n if (parsed.host && (options.domainHost || (schemeHandler && schemeHandler.domainHost)) && isIP === false && nonSimpleDomain(parsed.host)) {\n // convert Unicode IDN -> ASCII IDN\n try {\n parsed.host = URL.domainToASCII(parsed.host.toLowerCase())\n } catch (e) {\n parsed.error = parsed.error || \"Host's domain name can not be converted to ASCII: \" + e\n }\n }\n // convert IRI -> URI\n }\n\n if (!schemeHandler || (schemeHandler && !schemeHandler.skipNormalize)) {\n if (uri.indexOf('%') !== -1) {\n if (parsed.scheme !== undefined) {\n parsed.scheme = unescape(parsed.scheme)\n }\n if (parsed.host !== undefined) {\n parsed.host = reescapeHostDelimiters(unescape(parsed.host), isIP)\n }\n }\n if (parsed.path) {\n parsed.path = normalizePathEncoding(parsed.path)\n }\n if (parsed.fragment) {\n try {\n parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment))\n } catch {\n parsed.error = parsed.error || 'URI malformed'\n }\n }\n }\n\n // perform scheme specific parsing\n if (schemeHandler && schemeHandler.parse) {\n schemeHandler.parse(parsed, options)\n }\n } else {\n parsed.error = parsed.error || 'URI can not be parsed.'\n }\n return { parsed, malformedAuthorityOrPort }\n}\n\n/**\n * @param {string} uri\n * @param {import('./types/index').Options} [opts]\n * @returns\n */\nfunction parse (uri, opts) {\n return parseWithStatus(uri, opts).parsed\n}\n\n/**\n * @param {string} uri\n * @param {import('./types/index').Options} [opts]\n * @returns {string}\n */\nfunction normalizeString (uri, opts) {\n return normalizeStringWithStatus(uri, opts).normalized\n}\n\n/**\n * @param {string} uri\n * @param {import('./types/index').Options} [opts]\n * @returns {{ normalized: string, malformedAuthorityOrPort: boolean }}\n */\nfunction normalizeStringWithStatus (uri, opts) {\n const { parsed, malformedAuthorityOrPort } = parseWithStatus(uri, opts)\n return {\n normalized: malformedAuthorityOrPort ? uri : serialize(parsed, opts),\n malformedAuthorityOrPort\n }\n}\n\n/**\n * @param {import ('./types/index').URIComponent|string} uri\n * @param {import('./types/index').Options} [opts]\n * @returns {string|undefined}\n */\nfunction normalizeComparableURI (uri, opts) {\n if (typeof uri === 'string') {\n const { normalized, malformedAuthorityOrPort } = normalizeStringWithStatus(uri, opts)\n return malformedAuthorityOrPort ? undefined : normalized\n }\n\n if (typeof uri === 'object') {\n return serialize(uri, opts)\n }\n}\n\nconst fastUri = {\n SCHEMES,\n normalize,\n resolve,\n resolveComponent,\n equal,\n serialize,\n parse\n}\n\nmodule.exports = fastUri\nmodule.exports.default = fastUri\nmodule.exports.fastUri = fastUri\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst uri = require(\"fast-uri\");\nuri.code = 'require(\"ajv/dist/runtime/uri\").default';\nexports.default = uri;\n//# sourceMappingURL=uri.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0;\nvar validate_1 = require(\"./compile/validate\");\nObject.defineProperty(exports, \"KeywordCxt\", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });\nvar codegen_1 = require(\"./compile/codegen\");\nObject.defineProperty(exports, \"_\", { enumerable: true, get: function () { return codegen_1._; } });\nObject.defineProperty(exports, \"str\", { enumerable: true, get: function () { return codegen_1.str; } });\nObject.defineProperty(exports, \"stringify\", { enumerable: true, get: function () { return codegen_1.stringify; } });\nObject.defineProperty(exports, \"nil\", { enumerable: true, get: function () { return codegen_1.nil; } });\nObject.defineProperty(exports, \"Name\", { enumerable: true, get: function () { return codegen_1.Name; } });\nObject.defineProperty(exports, \"CodeGen\", { enumerable: true, get: function () { return codegen_1.CodeGen; } });\nconst validation_error_1 = require(\"./runtime/validation_error\");\nconst ref_error_1 = require(\"./compile/ref_error\");\nconst rules_1 = require(\"./compile/rules\");\nconst compile_1 = require(\"./compile\");\nconst codegen_2 = require(\"./compile/codegen\");\nconst resolve_1 = require(\"./compile/resolve\");\nconst dataType_1 = require(\"./compile/validate/dataType\");\nconst util_1 = require(\"./compile/util\");\nconst $dataRefSchema = require(\"./refs/data.json\");\nconst uri_1 = require(\"./runtime/uri\");\nconst defaultRegExp = (str, flags) => new RegExp(str, flags);\ndefaultRegExp.code = \"new RegExp\";\nconst META_IGNORE_OPTIONS = [\"removeAdditional\", \"useDefaults\", \"coerceTypes\"];\nconst EXT_SCOPE_NAMES = new Set([\n \"validate\",\n \"serialize\",\n \"parse\",\n \"wrapper\",\n \"root\",\n \"schema\",\n \"keyword\",\n \"pattern\",\n \"formats\",\n \"validate$data\",\n \"func\",\n \"obj\",\n \"Error\",\n]);\nconst removedOptions = {\n errorDataPath: \"\",\n format: \"`validateFormats: false` can be used instead.\",\n nullable: '\"nullable\" keyword is supported by default.',\n jsonPointers: \"Deprecated jsPropertySyntax can be used instead.\",\n extendRefs: \"Deprecated ignoreKeywordsWithRef can be used instead.\",\n missingRefs: \"Pass empty schema with $id that should be ignored to ajv.addSchema.\",\n processCode: \"Use option `code: {process: (code, schemaEnv: object) => string}`\",\n sourceCode: \"Use option `code: {source: true}`\",\n strictDefaults: \"It is default now, see option `strict`.\",\n strictKeywords: \"It is default now, see option `strict`.\",\n uniqueItems: '\"uniqueItems\" keyword is always validated.',\n unknownFormats: \"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).\",\n cache: \"Map is used as cache, schema object as key.\",\n serialize: \"Map is used as cache, schema object as key.\",\n ajvErrors: \"It is default now.\",\n};\nconst deprecatedOptions = {\n ignoreKeywordsWithRef: \"\",\n jsPropertySyntax: \"\",\n unicode: '\"minLength\"/\"maxLength\" account for unicode characters by default.',\n};\nconst MAX_EXPRESSION = 200;\n// eslint-disable-next-line complexity\nfunction requiredOptions(o) {\n var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0;\n const s = o.strict;\n const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize;\n const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0;\n const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp;\n const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default;\n return {\n strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true,\n strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true,\n strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : \"log\",\n strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : \"log\",\n strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false,\n code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp },\n loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION,\n loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION,\n meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true,\n messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true,\n inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true,\n schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : \"$id\",\n addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true,\n validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true,\n validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true,\n unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true,\n int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true,\n uriResolver: uriResolver,\n };\n}\nclass Ajv {\n constructor(opts = {}) {\n this.schemas = {};\n this.refs = {};\n this.formats = Object.create(null);\n this._compilations = new Set();\n this._loading = {};\n this._cache = new Map();\n opts = this.opts = { ...opts, ...requiredOptions(opts) };\n const { es5, lines } = this.opts.code;\n this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines });\n this.logger = getLogger(opts.logger);\n const formatOpt = opts.validateFormats;\n opts.validateFormats = false;\n this.RULES = (0, rules_1.getRules)();\n checkOptions.call(this, removedOptions, opts, \"NOT SUPPORTED\");\n checkOptions.call(this, deprecatedOptions, opts, \"DEPRECATED\", \"warn\");\n this._metaOpts = getMetaSchemaOptions.call(this);\n if (opts.formats)\n addInitialFormats.call(this);\n this._addVocabularies();\n this._addDefaultMetaSchema();\n if (opts.keywords)\n addInitialKeywords.call(this, opts.keywords);\n if (typeof opts.meta == \"object\")\n this.addMetaSchema(opts.meta);\n addInitialSchemas.call(this);\n opts.validateFormats = formatOpt;\n }\n _addVocabularies() {\n this.addKeyword(\"$async\");\n }\n _addDefaultMetaSchema() {\n const { $data, meta, schemaId } = this.opts;\n let _dataRefSchema = $dataRefSchema;\n if (schemaId === \"id\") {\n _dataRefSchema = { ...$dataRefSchema };\n _dataRefSchema.id = _dataRefSchema.$id;\n delete _dataRefSchema.$id;\n }\n if (meta && $data)\n this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false);\n }\n defaultMeta() {\n const { meta, schemaId } = this.opts;\n return (this.opts.defaultMeta = typeof meta == \"object\" ? meta[schemaId] || meta : undefined);\n }\n validate(schemaKeyRef, // key, ref or schema object\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents\n data // to be validated\n ) {\n let v;\n if (typeof schemaKeyRef == \"string\") {\n v = this.getSchema(schemaKeyRef);\n if (!v)\n throw new Error(`no schema with key or ref \"${schemaKeyRef}\"`);\n }\n else {\n v = this.compile(schemaKeyRef);\n }\n const valid = v(data);\n if (!(\"$async\" in v))\n this.errors = v.errors;\n return valid;\n }\n compile(schema, _meta) {\n const sch = this._addSchema(schema, _meta);\n return (sch.validate || this._compileSchemaEnv(sch));\n }\n compileAsync(schema, meta) {\n if (typeof this.opts.loadSchema != \"function\") {\n throw new Error(\"options.loadSchema should be a function\");\n }\n const { loadSchema } = this.opts;\n return runCompileAsync.call(this, schema, meta);\n async function runCompileAsync(_schema, _meta) {\n await loadMetaSchema.call(this, _schema.$schema);\n const sch = this._addSchema(_schema, _meta);\n return sch.validate || _compileAsync.call(this, sch);\n }\n async function loadMetaSchema($ref) {\n if ($ref && !this.getSchema($ref)) {\n await runCompileAsync.call(this, { $ref }, true);\n }\n }\n async function _compileAsync(sch) {\n try {\n return this._compileSchemaEnv(sch);\n }\n catch (e) {\n if (!(e instanceof ref_error_1.default))\n throw e;\n checkLoaded.call(this, e);\n await loadMissingSchema.call(this, e.missingSchema);\n return _compileAsync.call(this, sch);\n }\n }\n function checkLoaded({ missingSchema: ref, missingRef }) {\n if (this.refs[ref]) {\n throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`);\n }\n }\n async function loadMissingSchema(ref) {\n const _schema = await _loadSchema.call(this, ref);\n if (!this.refs[ref])\n await loadMetaSchema.call(this, _schema.$schema);\n if (!this.refs[ref])\n this.addSchema(_schema, ref, meta);\n }\n async function _loadSchema(ref) {\n const p = this._loading[ref];\n if (p)\n return p;\n try {\n return await (this._loading[ref] = loadSchema(ref));\n }\n finally {\n delete this._loading[ref];\n }\n }\n }\n // Adds schema to the instance\n addSchema(schema, // If array is passed, `key` will be ignored\n key, // Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.\n _meta, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.\n _validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead.\n ) {\n if (Array.isArray(schema)) {\n for (const sch of schema)\n this.addSchema(sch, undefined, _meta, _validateSchema);\n return this;\n }\n let id;\n if (typeof schema === \"object\") {\n const { schemaId } = this.opts;\n id = schema[schemaId];\n if (id !== undefined && typeof id != \"string\") {\n throw new Error(`schema ${schemaId} must be string`);\n }\n }\n key = (0, resolve_1.normalizeId)(key || id);\n this._checkUnique(key);\n this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true);\n return this;\n }\n // Add schema that will be used to validate other schemas\n // options in META_IGNORE_OPTIONS are alway set to false\n addMetaSchema(schema, key, // schema key\n _validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema\n ) {\n this.addSchema(schema, key, true, _validateSchema);\n return this;\n }\n // Validate schema against its meta-schema\n validateSchema(schema, throwOrLogError) {\n if (typeof schema == \"boolean\")\n return true;\n let $schema;\n $schema = schema.$schema;\n if ($schema !== undefined && typeof $schema != \"string\") {\n throw new Error(\"$schema must be a string\");\n }\n $schema = $schema || this.opts.defaultMeta || this.defaultMeta();\n if (!$schema) {\n this.logger.warn(\"meta-schema not available\");\n this.errors = null;\n return true;\n }\n const valid = this.validate($schema, schema);\n if (!valid && throwOrLogError) {\n const message = \"schema is invalid: \" + this.errorsText();\n if (this.opts.validateSchema === \"log\")\n this.logger.error(message);\n else\n throw new Error(message);\n }\n return valid;\n }\n // Get compiled schema by `key` or `ref`.\n // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)\n getSchema(keyRef) {\n let sch;\n while (typeof (sch = getSchEnv.call(this, keyRef)) == \"string\")\n keyRef = sch;\n if (sch === undefined) {\n const { schemaId } = this.opts;\n const root = new compile_1.SchemaEnv({ schema: {}, schemaId });\n sch = compile_1.resolveSchema.call(this, root, keyRef);\n if (!sch)\n return;\n this.refs[keyRef] = sch;\n }\n return (sch.validate || this._compileSchemaEnv(sch));\n }\n // Remove cached schema(s).\n // If no parameter is passed all schemas but meta-schemas are removed.\n // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.\n // Even if schema is referenced by other schemas it still can be removed as other schemas have local references.\n removeSchema(schemaKeyRef) {\n if (schemaKeyRef instanceof RegExp) {\n this._removeAllSchemas(this.schemas, schemaKeyRef);\n this._removeAllSchemas(this.refs, schemaKeyRef);\n return this;\n }\n switch (typeof schemaKeyRef) {\n case \"undefined\":\n this._removeAllSchemas(this.schemas);\n this._removeAllSchemas(this.refs);\n this._cache.clear();\n return this;\n case \"string\": {\n const sch = getSchEnv.call(this, schemaKeyRef);\n if (typeof sch == \"object\")\n this._cache.delete(sch.schema);\n delete this.schemas[schemaKeyRef];\n delete this.refs[schemaKeyRef];\n return this;\n }\n case \"object\": {\n const cacheKey = schemaKeyRef;\n this._cache.delete(cacheKey);\n let id = schemaKeyRef[this.opts.schemaId];\n if (id) {\n id = (0, resolve_1.normalizeId)(id);\n delete this.schemas[id];\n delete this.refs[id];\n }\n return this;\n }\n default:\n throw new Error(\"ajv.removeSchema: invalid parameter\");\n }\n }\n // add \"vocabulary\" - a collection of keywords\n addVocabulary(definitions) {\n for (const def of definitions)\n this.addKeyword(def);\n return this;\n }\n addKeyword(kwdOrDef, def // deprecated\n ) {\n let keyword;\n if (typeof kwdOrDef == \"string\") {\n keyword = kwdOrDef;\n if (typeof def == \"object\") {\n this.logger.warn(\"these parameters are deprecated, see docs for addKeyword\");\n def.keyword = keyword;\n }\n }\n else if (typeof kwdOrDef == \"object\" && def === undefined) {\n def = kwdOrDef;\n keyword = def.keyword;\n if (Array.isArray(keyword) && !keyword.length) {\n throw new Error(\"addKeywords: keyword must be string or non-empty array\");\n }\n }\n else {\n throw new Error(\"invalid addKeywords parameters\");\n }\n checkKeyword.call(this, keyword, def);\n if (!def) {\n (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd));\n return this;\n }\n keywordMetaschema.call(this, def);\n const definition = {\n ...def,\n type: (0, dataType_1.getJSONTypes)(def.type),\n schemaType: (0, dataType_1.getJSONTypes)(def.schemaType),\n };\n (0, util_1.eachItem)(keyword, definition.type.length === 0\n ? (k) => addRule.call(this, k, definition)\n : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t)));\n return this;\n }\n getKeyword(keyword) {\n const rule = this.RULES.all[keyword];\n return typeof rule == \"object\" ? rule.definition : !!rule;\n }\n // Remove keyword\n removeKeyword(keyword) {\n // TODO return type should be Ajv\n const { RULES } = this;\n delete RULES.keywords[keyword];\n delete RULES.all[keyword];\n for (const group of RULES.rules) {\n const i = group.rules.findIndex((rule) => rule.keyword === keyword);\n if (i >= 0)\n group.rules.splice(i, 1);\n }\n return this;\n }\n // Add format\n addFormat(name, format) {\n if (typeof format == \"string\")\n format = new RegExp(format);\n this.formats[name] = format;\n return this;\n }\n errorsText(errors = this.errors, // optional array of validation errors\n { separator = \", \", dataVar = \"data\" } = {} // optional options with properties `separator` and `dataVar`\n ) {\n if (!errors || errors.length === 0)\n return \"No errors\";\n return errors\n .map((e) => `${dataVar}${e.instancePath} ${e.message}`)\n .reduce((text, msg) => text + separator + msg);\n }\n $dataMetaSchema(metaSchema, keywordsJsonPointers) {\n const rules = this.RULES.all;\n metaSchema = JSON.parse(JSON.stringify(metaSchema));\n for (const jsonPointer of keywordsJsonPointers) {\n const segments = jsonPointer.split(\"/\").slice(1); // first segment is an empty string\n let keywords = metaSchema;\n for (const seg of segments)\n keywords = keywords[seg];\n for (const key in rules) {\n const rule = rules[key];\n if (typeof rule != \"object\")\n continue;\n const { $data } = rule.definition;\n const schema = keywords[key];\n if ($data && schema)\n keywords[key] = schemaOrData(schema);\n }\n }\n return metaSchema;\n }\n _removeAllSchemas(schemas, regex) {\n for (const keyRef in schemas) {\n const sch = schemas[keyRef];\n if (!regex || regex.test(keyRef)) {\n if (typeof sch == \"string\") {\n delete schemas[keyRef];\n }\n else if (sch && !sch.meta) {\n this._cache.delete(sch.schema);\n delete schemas[keyRef];\n }\n }\n }\n }\n _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) {\n let id;\n const { schemaId } = this.opts;\n if (typeof schema == \"object\") {\n id = schema[schemaId];\n }\n else {\n if (this.opts.jtd)\n throw new Error(\"schema must be object\");\n else if (typeof schema != \"boolean\")\n throw new Error(\"schema must be object or boolean\");\n }\n let sch = this._cache.get(schema);\n if (sch !== undefined)\n return sch;\n baseId = (0, resolve_1.normalizeId)(id || baseId);\n const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId);\n sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs });\n this._cache.set(sch.schema, sch);\n if (addSchema && !baseId.startsWith(\"#\")) {\n // TODO atm it is allowed to overwrite schemas without id (instead of not adding them)\n if (baseId)\n this._checkUnique(baseId);\n this.refs[baseId] = sch;\n }\n if (validateSchema)\n this.validateSchema(schema, true);\n return sch;\n }\n _checkUnique(id) {\n if (this.schemas[id] || this.refs[id]) {\n throw new Error(`schema with key or id \"${id}\" already exists`);\n }\n }\n _compileSchemaEnv(sch) {\n if (sch.meta)\n this._compileMetaSchema(sch);\n else\n compile_1.compileSchema.call(this, sch);\n /* istanbul ignore if */\n if (!sch.validate)\n throw new Error(\"ajv implementation error\");\n return sch.validate;\n }\n _compileMetaSchema(sch) {\n const currentOpts = this.opts;\n this.opts = this._metaOpts;\n try {\n compile_1.compileSchema.call(this, sch);\n }\n finally {\n this.opts = currentOpts;\n }\n }\n}\nAjv.ValidationError = validation_error_1.default;\nAjv.MissingRefError = ref_error_1.default;\nexports.default = Ajv;\nfunction checkOptions(checkOpts, options, msg, log = \"error\") {\n for (const key in checkOpts) {\n const opt = key;\n if (opt in options)\n this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);\n }\n}\nfunction getSchEnv(keyRef) {\n keyRef = (0, resolve_1.normalizeId)(keyRef); // TODO tests fail without this line\n return this.schemas[keyRef] || this.refs[keyRef];\n}\nfunction addInitialSchemas() {\n const optsSchemas = this.opts.schemas;\n if (!optsSchemas)\n return;\n if (Array.isArray(optsSchemas))\n this.addSchema(optsSchemas);\n else\n for (const key in optsSchemas)\n this.addSchema(optsSchemas[key], key);\n}\nfunction addInitialFormats() {\n for (const name in this.opts.formats) {\n const format = this.opts.formats[name];\n if (format)\n this.addFormat(name, format);\n }\n}\nfunction addInitialKeywords(defs) {\n if (Array.isArray(defs)) {\n this.addVocabulary(defs);\n return;\n }\n this.logger.warn(\"keywords option as map is deprecated, pass array\");\n for (const keyword in defs) {\n const def = defs[keyword];\n if (!def.keyword)\n def.keyword = keyword;\n this.addKeyword(def);\n }\n}\nfunction getMetaSchemaOptions() {\n const metaOpts = { ...this.opts };\n for (const opt of META_IGNORE_OPTIONS)\n delete metaOpts[opt];\n return metaOpts;\n}\nconst noLogs = { log() { }, warn() { }, error() { } };\nfunction getLogger(logger) {\n if (logger === false)\n return noLogs;\n if (logger === undefined)\n return console;\n if (logger.log && logger.warn && logger.error)\n return logger;\n throw new Error(\"logger must implement log, warn and error methods\");\n}\nconst KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;\nfunction checkKeyword(keyword, def) {\n const { RULES } = this;\n (0, util_1.eachItem)(keyword, (kwd) => {\n if (RULES.keywords[kwd])\n throw new Error(`Keyword ${kwd} is already defined`);\n if (!KEYWORD_NAME.test(kwd))\n throw new Error(`Keyword ${kwd} has invalid name`);\n });\n if (!def)\n return;\n if (def.$data && !(\"code\" in def || \"validate\" in def)) {\n throw new Error('$data keyword must have \"code\" or \"validate\" function');\n }\n}\nfunction addRule(keyword, definition, dataType) {\n var _a;\n const post = definition === null || definition === void 0 ? void 0 : definition.post;\n if (dataType && post)\n throw new Error('keyword with \"post\" flag cannot have \"type\"');\n const { RULES } = this;\n let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType);\n if (!ruleGroup) {\n ruleGroup = { type: dataType, rules: [] };\n RULES.rules.push(ruleGroup);\n }\n RULES.keywords[keyword] = true;\n if (!definition)\n return;\n const rule = {\n keyword,\n definition: {\n ...definition,\n type: (0, dataType_1.getJSONTypes)(definition.type),\n schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType),\n },\n };\n if (definition.before)\n addBeforeRule.call(this, ruleGroup, rule, definition.before);\n else\n ruleGroup.rules.push(rule);\n RULES.all[keyword] = rule;\n (_a = definition.implements) === null || _a === void 0 ? void 0 : _a.forEach((kwd) => this.addKeyword(kwd));\n}\nfunction addBeforeRule(ruleGroup, rule, before) {\n const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);\n if (i >= 0) {\n ruleGroup.rules.splice(i, 0, rule);\n }\n else {\n ruleGroup.rules.push(rule);\n this.logger.warn(`rule ${before} is not defined`);\n }\n}\nfunction keywordMetaschema(def) {\n let { metaSchema } = def;\n if (metaSchema === undefined)\n return;\n if (def.$data && this.opts.$data)\n metaSchema = schemaOrData(metaSchema);\n def.validateSchema = this.compile(metaSchema, true);\n}\nconst $dataRef = {\n $ref: \"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#\",\n};\nfunction schemaOrData(schema) {\n return { anyOf: [schema, $dataRef] };\n}\n//# sourceMappingURL=core.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst def = {\n keyword: \"id\",\n code() {\n throw new Error('NOT SUPPORTED: keyword \"id\", use \"$id\" for schema ID');\n },\n};\nexports.default = def;\n//# sourceMappingURL=id.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.callRef = exports.getValidate = void 0;\nconst ref_error_1 = require(\"../../compile/ref_error\");\nconst code_1 = require(\"../code\");\nconst codegen_1 = require(\"../../compile/codegen\");\nconst names_1 = require(\"../../compile/names\");\nconst compile_1 = require(\"../../compile\");\nconst util_1 = require(\"../../compile/util\");\nconst def = {\n keyword: \"$ref\",\n schemaType: \"string\",\n code(cxt) {\n const { gen, schema: $ref, it } = cxt;\n const { baseId, schemaEnv: env, validateName, opts, self } = it;\n const { root } = env;\n if (($ref === \"#\" || $ref === \"#/\") && baseId === root.baseId)\n return callRootRef();\n const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref);\n if (schOrEnv === undefined)\n throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref);\n if (schOrEnv instanceof compile_1.SchemaEnv)\n return callValidate(schOrEnv);\n return inlineRefSchema(schOrEnv);\n function callRootRef() {\n if (env === root)\n return callRef(cxt, validateName, env, env.$async);\n const rootName = gen.scopeValue(\"root\", { ref: root });\n return callRef(cxt, (0, codegen_1._) `${rootName}.validate`, root, root.$async);\n }\n function callValidate(sch) {\n const v = getValidate(cxt, sch);\n callRef(cxt, v, sch, sch.$async);\n }\n function inlineRefSchema(sch) {\n const schName = gen.scopeValue(\"schema\", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch });\n const valid = gen.name(\"valid\");\n const schCxt = cxt.subschema({\n schema: sch,\n dataTypes: [],\n schemaPath: codegen_1.nil,\n topSchemaRef: schName,\n errSchemaPath: $ref,\n }, valid);\n cxt.mergeEvaluated(schCxt);\n cxt.ok(valid);\n }\n },\n};\nfunction getValidate(cxt, sch) {\n const { gen } = cxt;\n return sch.validate\n ? gen.scopeValue(\"validate\", { ref: sch.validate })\n : (0, codegen_1._) `${gen.scopeValue(\"wrapper\", { ref: sch })}.validate`;\n}\nexports.getValidate = getValidate;\nfunction callRef(cxt, v, sch, $async) {\n const { gen, it } = cxt;\n const { allErrors, schemaEnv: env, opts } = it;\n const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil;\n if ($async)\n callAsyncRef();\n else\n callSyncRef();\n function callAsyncRef() {\n if (!env.$async)\n throw new Error(\"async schema referenced by sync schema\");\n const valid = gen.let(\"valid\");\n gen.try(() => {\n gen.code((0, codegen_1._) `await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`);\n addEvaluatedFrom(v); // TODO will not work with async, it has to be returned with the result\n if (!allErrors)\n gen.assign(valid, true);\n }, (e) => {\n gen.if((0, codegen_1._) `!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e));\n addErrorsFrom(e);\n if (!allErrors)\n gen.assign(valid, false);\n });\n cxt.ok(valid);\n }\n function callSyncRef() {\n cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v));\n }\n function addErrorsFrom(source) {\n const errs = (0, codegen_1._) `${source}.errors`;\n gen.assign(names_1.default.vErrors, (0, codegen_1._) `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); // TODO tagged\n gen.assign(names_1.default.errors, (0, codegen_1._) `${names_1.default.vErrors}.length`);\n }\n function addEvaluatedFrom(source) {\n var _a;\n if (!it.opts.unevaluated)\n return;\n const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated;\n // TODO refactor\n if (it.props !== true) {\n if (schEvaluated && !schEvaluated.dynamicProps) {\n if (schEvaluated.props !== undefined) {\n it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props);\n }\n }\n else {\n const props = gen.var(\"props\", (0, codegen_1._) `${source}.evaluated.props`);\n it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name);\n }\n }\n if (it.items !== true) {\n if (schEvaluated && !schEvaluated.dynamicItems) {\n if (schEvaluated.items !== undefined) {\n it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items);\n }\n }\n else {\n const items = gen.var(\"items\", (0, codegen_1._) `${source}.evaluated.items`);\n it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name);\n }\n }\n }\n}\nexports.callRef = callRef;\nexports.default = def;\n//# sourceMappingURL=ref.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst id_1 = require(\"./id\");\nconst ref_1 = require(\"./ref\");\nconst core = [\n \"$schema\",\n \"$id\",\n \"$defs\",\n \"$vocabulary\",\n { keyword: \"$comment\" },\n \"definitions\",\n id_1.default,\n ref_1.default,\n];\nexports.default = core;\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst ops = codegen_1.operators;\nconst KWDs = {\n maximum: { okStr: \"<=\", ok: ops.LTE, fail: ops.GT },\n minimum: { okStr: \">=\", ok: ops.GTE, fail: ops.LT },\n exclusiveMaximum: { okStr: \"<\", ok: ops.LT, fail: ops.GTE },\n exclusiveMinimum: { okStr: \">\", ok: ops.GT, fail: ops.LTE },\n};\nconst error = {\n message: ({ keyword, schemaCode }) => (0, codegen_1.str) `must be ${KWDs[keyword].okStr} ${schemaCode}`,\n params: ({ keyword, schemaCode }) => (0, codegen_1._) `{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`,\n};\nconst def = {\n keyword: Object.keys(KWDs),\n type: \"number\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt) {\n const { keyword, data, schemaCode } = cxt;\n cxt.fail$data((0, codegen_1._) `${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`);\n },\n};\nexports.default = def;\n//# sourceMappingURL=limitNumber.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst error = {\n message: ({ schemaCode }) => (0, codegen_1.str) `must be multiple of ${schemaCode}`,\n params: ({ schemaCode }) => (0, codegen_1._) `{multipleOf: ${schemaCode}}`,\n};\nconst def = {\n keyword: \"multipleOf\",\n type: \"number\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt) {\n const { gen, data, schemaCode, it } = cxt;\n // const bdt = bad$DataType(schemaCode, <string>def.schemaType, $data)\n const prec = it.opts.multipleOfPrecision;\n const res = gen.let(\"res\");\n const invalid = prec\n ? (0, codegen_1._) `Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}`\n : (0, codegen_1._) `${res} !== parseInt(${res})`;\n cxt.fail$data((0, codegen_1._) `(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`);\n },\n};\nexports.default = def;\n//# sourceMappingURL=multipleOf.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n// https://mathiasbynens.be/notes/javascript-encoding\n// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode\nfunction ucs2length(str) {\n const len = str.length;\n let length = 0;\n let pos = 0;\n let value;\n while (pos < len) {\n length++;\n value = str.charCodeAt(pos++);\n if (value >= 0xd800 && value <= 0xdbff && pos < len) {\n // high surrogate, and there is a next character\n value = str.charCodeAt(pos);\n if ((value & 0xfc00) === 0xdc00)\n pos++; // low surrogate\n }\n }\n return length;\n}\nexports.default = ucs2length;\nucs2length.code = 'require(\"ajv/dist/runtime/ucs2length\").default';\n//# sourceMappingURL=ucs2length.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst ucs2length_1 = require(\"../../runtime/ucs2length\");\nconst error = {\n message({ keyword, schemaCode }) {\n const comp = keyword === \"maxLength\" ? \"more\" : \"fewer\";\n return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} characters`;\n },\n params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,\n};\nconst def = {\n keyword: [\"maxLength\", \"minLength\"],\n type: \"string\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt) {\n const { keyword, data, schemaCode, it } = cxt;\n const op = keyword === \"maxLength\" ? codegen_1.operators.GT : codegen_1.operators.LT;\n const len = it.opts.unicode === false ? (0, codegen_1._) `${data}.length` : (0, codegen_1._) `${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`;\n cxt.fail$data((0, codegen_1._) `${len} ${op} ${schemaCode}`);\n },\n};\nexports.default = def;\n//# sourceMappingURL=limitLength.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst code_1 = require(\"../code\");\nconst util_1 = require(\"../../compile/util\");\nconst codegen_1 = require(\"../../compile/codegen\");\nconst error = {\n message: ({ schemaCode }) => (0, codegen_1.str) `must match pattern \"${schemaCode}\"`,\n params: ({ schemaCode }) => (0, codegen_1._) `{pattern: ${schemaCode}}`,\n};\nconst def = {\n keyword: \"pattern\",\n type: \"string\",\n schemaType: \"string\",\n $data: true,\n error,\n code(cxt) {\n const { gen, data, $data, schema, schemaCode, it } = cxt;\n const u = it.opts.unicodeRegExp ? \"u\" : \"\";\n if ($data) {\n const { regExp } = it.opts.code;\n const regExpCode = regExp.code === \"new RegExp\" ? (0, codegen_1._) `new RegExp` : (0, util_1.useFunc)(gen, regExp);\n const valid = gen.let(\"valid\");\n gen.try(() => gen.assign(valid, (0, codegen_1._) `${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false));\n cxt.fail$data((0, codegen_1._) `!${valid}`);\n }\n else {\n const regExp = (0, code_1.usePattern)(cxt, schema);\n cxt.fail$data((0, codegen_1._) `!${regExp}.test(${data})`);\n }\n },\n};\nexports.default = def;\n//# sourceMappingURL=pattern.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst error = {\n message({ keyword, schemaCode }) {\n const comp = keyword === \"maxProperties\" ? \"more\" : \"fewer\";\n return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} properties`;\n },\n params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,\n};\nconst def = {\n keyword: [\"maxProperties\", \"minProperties\"],\n type: \"object\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt) {\n const { keyword, data, schemaCode } = cxt;\n const op = keyword === \"maxProperties\" ? codegen_1.operators.GT : codegen_1.operators.LT;\n cxt.fail$data((0, codegen_1._) `Object.keys(${data}).length ${op} ${schemaCode}`);\n },\n};\nexports.default = def;\n//# sourceMappingURL=limitProperties.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst code_1 = require(\"../code\");\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst error = {\n message: ({ params: { missingProperty } }) => (0, codegen_1.str) `must have required property '${missingProperty}'`,\n params: ({ params: { missingProperty } }) => (0, codegen_1._) `{missingProperty: ${missingProperty}}`,\n};\nconst def = {\n keyword: \"required\",\n type: \"object\",\n schemaType: \"array\",\n $data: true,\n error,\n code(cxt) {\n const { gen, schema, schemaCode, data, $data, it } = cxt;\n const { opts } = it;\n if (!$data && schema.length === 0)\n return;\n const useLoop = schema.length >= opts.loopRequired;\n if (it.allErrors)\n allErrorsMode();\n else\n exitOnErrorMode();\n if (opts.strictRequired) {\n const props = cxt.parentSchema.properties;\n const { definedProperties } = cxt.it;\n for (const requiredKey of schema) {\n if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === undefined && !definedProperties.has(requiredKey)) {\n const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;\n const msg = `required property \"${requiredKey}\" is not defined at \"${schemaPath}\" (strictRequired)`;\n (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired);\n }\n }\n }\n function allErrorsMode() {\n if (useLoop || $data) {\n cxt.block$data(codegen_1.nil, loopAllRequired);\n }\n else {\n for (const prop of schema) {\n (0, code_1.checkReportMissingProp)(cxt, prop);\n }\n }\n }\n function exitOnErrorMode() {\n const missing = gen.let(\"missing\");\n if (useLoop || $data) {\n const valid = gen.let(\"valid\", true);\n cxt.block$data(valid, () => loopUntilMissing(missing, valid));\n cxt.ok(valid);\n }\n else {\n gen.if((0, code_1.checkMissingProp)(cxt, schema, missing));\n (0, code_1.reportMissingProp)(cxt, missing);\n gen.else();\n }\n }\n function loopAllRequired() {\n gen.forOf(\"prop\", schemaCode, (prop) => {\n cxt.setParams({ missingProperty: prop });\n gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error());\n });\n }\n function loopUntilMissing(missing, valid) {\n cxt.setParams({ missingProperty: missing });\n gen.forOf(missing, schemaCode, () => {\n gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties));\n gen.if((0, codegen_1.not)(valid), () => {\n cxt.error();\n gen.break();\n });\n }, codegen_1.nil);\n }\n },\n};\nexports.default = def;\n//# sourceMappingURL=required.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst error = {\n message({ keyword, schemaCode }) {\n const comp = keyword === \"maxItems\" ? \"more\" : \"fewer\";\n return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} items`;\n },\n params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,\n};\nconst def = {\n keyword: [\"maxItems\", \"minItems\"],\n type: \"array\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt) {\n const { keyword, data, schemaCode } = cxt;\n const op = keyword === \"maxItems\" ? codegen_1.operators.GT : codegen_1.operators.LT;\n cxt.fail$data((0, codegen_1._) `${data}.length ${op} ${schemaCode}`);\n },\n};\nexports.default = def;\n//# sourceMappingURL=limitItems.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n// https://github.com/ajv-validator/ajv/issues/889\nconst equal = require(\"fast-deep-equal\");\nequal.code = 'require(\"ajv/dist/runtime/equal\").default';\nexports.default = equal;\n//# sourceMappingURL=equal.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst dataType_1 = require(\"../../compile/validate/dataType\");\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst equal_1 = require(\"../../runtime/equal\");\nconst error = {\n message: ({ params: { i, j } }) => (0, codegen_1.str) `must NOT have duplicate items (items ## ${j} and ${i} are identical)`,\n params: ({ params: { i, j } }) => (0, codegen_1._) `{i: ${i}, j: ${j}}`,\n};\nconst def = {\n keyword: \"uniqueItems\",\n type: \"array\",\n schemaType: \"boolean\",\n $data: true,\n error,\n code(cxt) {\n const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt;\n if (!$data && !schema)\n return;\n const valid = gen.let(\"valid\");\n const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : [];\n cxt.block$data(valid, validateUniqueItems, (0, codegen_1._) `${schemaCode} === false`);\n cxt.ok(valid);\n function validateUniqueItems() {\n const i = gen.let(\"i\", (0, codegen_1._) `${data}.length`);\n const j = gen.let(\"j\");\n cxt.setParams({ i, j });\n gen.assign(valid, true);\n gen.if((0, codegen_1._) `${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j));\n }\n function canOptimize() {\n return itemTypes.length > 0 && !itemTypes.some((t) => t === \"object\" || t === \"array\");\n }\n function loopN(i, j) {\n const item = gen.name(\"item\");\n const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong);\n const indices = gen.const(\"indices\", (0, codegen_1._) `{}`);\n gen.for((0, codegen_1._) `;${i}--;`, () => {\n gen.let(item, (0, codegen_1._) `${data}[${i}]`);\n gen.if(wrongType, (0, codegen_1._) `continue`);\n if (itemTypes.length > 1)\n gen.if((0, codegen_1._) `typeof ${item} == \"string\"`, (0, codegen_1._) `${item} += \"_\"`);\n gen\n .if((0, codegen_1._) `typeof ${indices}[${item}] == \"number\"`, () => {\n gen.assign(j, (0, codegen_1._) `${indices}[${item}]`);\n cxt.error();\n gen.assign(valid, false).break();\n })\n .code((0, codegen_1._) `${indices}[${item}] = ${i}`);\n });\n }\n function loopN2(i, j) {\n const eql = (0, util_1.useFunc)(gen, equal_1.default);\n const outer = gen.name(\"outer\");\n gen.label(outer).for((0, codegen_1._) `;${i}--;`, () => gen.for((0, codegen_1._) `${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._) `${eql}(${data}[${i}], ${data}[${j}])`, () => {\n cxt.error();\n gen.assign(valid, false).break(outer);\n })));\n }\n },\n};\nexports.default = def;\n//# sourceMappingURL=uniqueItems.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst equal_1 = require(\"../../runtime/equal\");\nconst error = {\n message: \"must be equal to constant\",\n params: ({ schemaCode }) => (0, codegen_1._) `{allowedValue: ${schemaCode}}`,\n};\nconst def = {\n keyword: \"const\",\n $data: true,\n error,\n code(cxt) {\n const { gen, data, $data, schemaCode, schema } = cxt;\n if ($data || (schema && typeof schema == \"object\")) {\n cxt.fail$data((0, codegen_1._) `!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`);\n }\n else {\n cxt.fail((0, codegen_1._) `${schema} !== ${data}`);\n }\n },\n};\nexports.default = def;\n//# sourceMappingURL=const.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst equal_1 = require(\"../../runtime/equal\");\nconst error = {\n message: \"must be equal to one of the allowed values\",\n params: ({ schemaCode }) => (0, codegen_1._) `{allowedValues: ${schemaCode}}`,\n};\nconst def = {\n keyword: \"enum\",\n schemaType: \"array\",\n $data: true,\n error,\n code(cxt) {\n const { gen, data, $data, schema, schemaCode, it } = cxt;\n if (!$data && schema.length === 0)\n throw new Error(\"enum must have non-empty array\");\n const useLoop = schema.length >= it.opts.loopEnum;\n let eql;\n const getEql = () => (eql !== null && eql !== void 0 ? eql : (eql = (0, util_1.useFunc)(gen, equal_1.default)));\n let valid;\n if (useLoop || $data) {\n valid = gen.let(\"valid\");\n cxt.block$data(valid, loopEnum);\n }\n else {\n /* istanbul ignore if */\n if (!Array.isArray(schema))\n throw new Error(\"ajv implementation error\");\n const vSchema = gen.const(\"vSchema\", schemaCode);\n valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i)));\n }\n cxt.pass(valid);\n function loopEnum() {\n gen.assign(valid, false);\n gen.forOf(\"v\", schemaCode, (v) => gen.if((0, codegen_1._) `${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break()));\n }\n function equalCode(vSchema, i) {\n const sch = schema[i];\n return typeof sch === \"object\" && sch !== null\n ? (0, codegen_1._) `${getEql()}(${data}, ${vSchema}[${i}])`\n : (0, codegen_1._) `${data} === ${sch}`;\n }\n },\n};\nexports.default = def;\n//# sourceMappingURL=enum.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst limitNumber_1 = require(\"./limitNumber\");\nconst multipleOf_1 = require(\"./multipleOf\");\nconst limitLength_1 = require(\"./limitLength\");\nconst pattern_1 = require(\"./pattern\");\nconst limitProperties_1 = require(\"./limitProperties\");\nconst required_1 = require(\"./required\");\nconst limitItems_1 = require(\"./limitItems\");\nconst uniqueItems_1 = require(\"./uniqueItems\");\nconst const_1 = require(\"./const\");\nconst enum_1 = require(\"./enum\");\nconst validation = [\n // number\n limitNumber_1.default,\n multipleOf_1.default,\n // string\n limitLength_1.default,\n pattern_1.default,\n // object\n limitProperties_1.default,\n required_1.default,\n // array\n limitItems_1.default,\n uniqueItems_1.default,\n // any\n { keyword: \"type\", schemaType: [\"string\", \"array\"] },\n { keyword: \"nullable\", schemaType: \"boolean\" },\n const_1.default,\n enum_1.default,\n];\nexports.default = validation;\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.validateAdditionalItems = void 0;\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst error = {\n message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`,\n params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`,\n};\nconst def = {\n keyword: \"additionalItems\",\n type: \"array\",\n schemaType: [\"boolean\", \"object\"],\n before: \"uniqueItems\",\n error,\n code(cxt) {\n const { parentSchema, it } = cxt;\n const { items } = parentSchema;\n if (!Array.isArray(items)) {\n (0, util_1.checkStrictMode)(it, '\"additionalItems\" is ignored when \"items\" is not an array of schemas');\n return;\n }\n validateAdditionalItems(cxt, items);\n },\n};\nfunction validateAdditionalItems(cxt, items) {\n const { gen, schema, data, keyword, it } = cxt;\n it.items = true;\n const len = gen.const(\"len\", (0, codegen_1._) `${data}.length`);\n if (schema === false) {\n cxt.setParams({ len: items.length });\n cxt.pass((0, codegen_1._) `${len} <= ${items.length}`);\n }\n else if (typeof schema == \"object\" && !(0, util_1.alwaysValidSchema)(it, schema)) {\n const valid = gen.var(\"valid\", (0, codegen_1._) `${len} <= ${items.length}`); // TODO var\n gen.if((0, codegen_1.not)(valid), () => validateItems(valid));\n cxt.ok(valid);\n }\n function validateItems(valid) {\n gen.forRange(\"i\", items.length, len, (i) => {\n cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid);\n if (!it.allErrors)\n gen.if((0, codegen_1.not)(valid), () => gen.break());\n });\n }\n}\nexports.validateAdditionalItems = validateAdditionalItems;\nexports.default = def;\n//# sourceMappingURL=additionalItems.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.validateTuple = void 0;\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst code_1 = require(\"../code\");\nconst def = {\n keyword: \"items\",\n type: \"array\",\n schemaType: [\"object\", \"array\", \"boolean\"],\n before: \"uniqueItems\",\n code(cxt) {\n const { schema, it } = cxt;\n if (Array.isArray(schema))\n return validateTuple(cxt, \"additionalItems\", schema);\n it.items = true;\n if ((0, util_1.alwaysValidSchema)(it, schema))\n return;\n cxt.ok((0, code_1.validateArray)(cxt));\n },\n};\nfunction validateTuple(cxt, extraItems, schArr = cxt.schema) {\n const { gen, parentSchema, data, keyword, it } = cxt;\n checkStrictTuple(parentSchema);\n if (it.opts.unevaluated && schArr.length && it.items !== true) {\n it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items);\n }\n const valid = gen.name(\"valid\");\n const len = gen.const(\"len\", (0, codegen_1._) `${data}.length`);\n schArr.forEach((sch, i) => {\n if ((0, util_1.alwaysValidSchema)(it, sch))\n return;\n gen.if((0, codegen_1._) `${len} > ${i}`, () => cxt.subschema({\n keyword,\n schemaProp: i,\n dataProp: i,\n }, valid));\n cxt.ok(valid);\n });\n function checkStrictTuple(sch) {\n const { opts, errSchemaPath } = it;\n const l = schArr.length;\n const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false);\n if (opts.strictTuples && !fullTuple) {\n const msg = `\"${keyword}\" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path \"${errSchemaPath}\"`;\n (0, util_1.checkStrictMode)(it, msg, opts.strictTuples);\n }\n }\n}\nexports.validateTuple = validateTuple;\nexports.default = def;\n//# sourceMappingURL=items.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst items_1 = require(\"./items\");\nconst def = {\n keyword: \"prefixItems\",\n type: \"array\",\n schemaType: [\"array\"],\n before: \"uniqueItems\",\n code: (cxt) => (0, items_1.validateTuple)(cxt, \"items\"),\n};\nexports.default = def;\n//# sourceMappingURL=prefixItems.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst code_1 = require(\"../code\");\nconst additionalItems_1 = require(\"./additionalItems\");\nconst error = {\n message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`,\n params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`,\n};\nconst def = {\n keyword: \"items\",\n type: \"array\",\n schemaType: [\"object\", \"boolean\"],\n before: \"uniqueItems\",\n error,\n code(cxt) {\n const { schema, parentSchema, it } = cxt;\n const { prefixItems } = parentSchema;\n it.items = true;\n if ((0, util_1.alwaysValidSchema)(it, schema))\n return;\n if (prefixItems)\n (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems);\n else\n cxt.ok((0, code_1.validateArray)(cxt));\n },\n};\nexports.default = def;\n//# sourceMappingURL=items2020.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst error = {\n message: ({ params: { min, max } }) => max === undefined\n ? (0, codegen_1.str) `must contain at least ${min} valid item(s)`\n : (0, codegen_1.str) `must contain at least ${min} and no more than ${max} valid item(s)`,\n params: ({ params: { min, max } }) => max === undefined ? (0, codegen_1._) `{minContains: ${min}}` : (0, codegen_1._) `{minContains: ${min}, maxContains: ${max}}`,\n};\nconst def = {\n keyword: \"contains\",\n type: \"array\",\n schemaType: [\"object\", \"boolean\"],\n before: \"uniqueItems\",\n trackErrors: true,\n error,\n code(cxt) {\n const { gen, schema, parentSchema, data, it } = cxt;\n let min;\n let max;\n const { minContains, maxContains } = parentSchema;\n if (it.opts.next) {\n min = minContains === undefined ? 1 : minContains;\n max = maxContains;\n }\n else {\n min = 1;\n }\n const len = gen.const(\"len\", (0, codegen_1._) `${data}.length`);\n cxt.setParams({ min, max });\n if (max === undefined && min === 0) {\n (0, util_1.checkStrictMode)(it, `\"minContains\" == 0 without \"maxContains\": \"contains\" keyword ignored`);\n return;\n }\n if (max !== undefined && min > max) {\n (0, util_1.checkStrictMode)(it, `\"minContains\" > \"maxContains\" is always invalid`);\n cxt.fail();\n return;\n }\n if ((0, util_1.alwaysValidSchema)(it, schema)) {\n let cond = (0, codegen_1._) `${len} >= ${min}`;\n if (max !== undefined)\n cond = (0, codegen_1._) `${cond} && ${len} <= ${max}`;\n cxt.pass(cond);\n return;\n }\n it.items = true;\n const valid = gen.name(\"valid\");\n if (max === undefined && min === 1) {\n validateItems(valid, () => gen.if(valid, () => gen.break()));\n }\n else if (min === 0) {\n gen.let(valid, true);\n if (max !== undefined)\n gen.if((0, codegen_1._) `${data}.length > 0`, validateItemsWithCount);\n }\n else {\n gen.let(valid, false);\n validateItemsWithCount();\n }\n cxt.result(valid, () => cxt.reset());\n function validateItemsWithCount() {\n const schValid = gen.name(\"_valid\");\n const count = gen.let(\"count\", 0);\n validateItems(schValid, () => gen.if(schValid, () => checkLimits(count)));\n }\n function validateItems(_valid, block) {\n gen.forRange(\"i\", 0, len, (i) => {\n cxt.subschema({\n keyword: \"contains\",\n dataProp: i,\n dataPropType: util_1.Type.Num,\n compositeRule: true,\n }, _valid);\n block();\n });\n }\n function checkLimits(count) {\n gen.code((0, codegen_1._) `${count}++`);\n if (max === undefined) {\n gen.if((0, codegen_1._) `${count} >= ${min}`, () => gen.assign(valid, true).break());\n }\n else {\n gen.if((0, codegen_1._) `${count} > ${max}`, () => gen.assign(valid, false).break());\n if (min === 1)\n gen.assign(valid, true);\n else\n gen.if((0, codegen_1._) `${count} >= ${min}`, () => gen.assign(valid, true));\n }\n }\n },\n};\nexports.default = def;\n//# sourceMappingURL=contains.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0;\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst code_1 = require(\"../code\");\nexports.error = {\n message: ({ params: { property, depsCount, deps } }) => {\n const property_ies = depsCount === 1 ? \"property\" : \"properties\";\n return (0, codegen_1.str) `must have ${property_ies} ${deps} when property ${property} is present`;\n },\n params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._) `{property: ${property},\n missingProperty: ${missingProperty},\n depsCount: ${depsCount},\n deps: ${deps}}`, // TODO change to reference\n};\nconst def = {\n keyword: \"dependencies\",\n type: \"object\",\n schemaType: \"object\",\n error: exports.error,\n code(cxt) {\n const [propDeps, schDeps] = splitDependencies(cxt);\n validatePropertyDeps(cxt, propDeps);\n validateSchemaDeps(cxt, schDeps);\n },\n};\nfunction splitDependencies({ schema }) {\n const propertyDeps = {};\n const schemaDeps = {};\n for (const key in schema) {\n if (key === \"__proto__\")\n continue;\n const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps;\n deps[key] = schema[key];\n }\n return [propertyDeps, schemaDeps];\n}\nfunction validatePropertyDeps(cxt, propertyDeps = cxt.schema) {\n const { gen, data, it } = cxt;\n if (Object.keys(propertyDeps).length === 0)\n return;\n const missing = gen.let(\"missing\");\n for (const prop in propertyDeps) {\n const deps = propertyDeps[prop];\n if (deps.length === 0)\n continue;\n const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties);\n cxt.setParams({\n property: prop,\n depsCount: deps.length,\n deps: deps.join(\", \"),\n });\n if (it.allErrors) {\n gen.if(hasProperty, () => {\n for (const depProp of deps) {\n (0, code_1.checkReportMissingProp)(cxt, depProp);\n }\n });\n }\n else {\n gen.if((0, codegen_1._) `${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`);\n (0, code_1.reportMissingProp)(cxt, missing);\n gen.else();\n }\n }\n}\nexports.validatePropertyDeps = validatePropertyDeps;\nfunction validateSchemaDeps(cxt, schemaDeps = cxt.schema) {\n const { gen, data, keyword, it } = cxt;\n const valid = gen.name(\"valid\");\n for (const prop in schemaDeps) {\n if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop]))\n continue;\n gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => {\n const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid);\n cxt.mergeValidEvaluated(schCxt, valid);\n }, () => gen.var(valid, true) // TODO var\n );\n cxt.ok(valid);\n }\n}\nexports.validateSchemaDeps = validateSchemaDeps;\nexports.default = def;\n//# sourceMappingURL=dependencies.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst error = {\n message: \"property name must be valid\",\n params: ({ params }) => (0, codegen_1._) `{propertyName: ${params.propertyName}}`,\n};\nconst def = {\n keyword: \"propertyNames\",\n type: \"object\",\n schemaType: [\"object\", \"boolean\"],\n error,\n code(cxt) {\n const { gen, schema, data, it } = cxt;\n if ((0, util_1.alwaysValidSchema)(it, schema))\n return;\n const valid = gen.name(\"valid\");\n gen.forIn(\"key\", data, (key) => {\n cxt.setParams({ propertyName: key });\n cxt.subschema({\n keyword: \"propertyNames\",\n data: key,\n dataTypes: [\"string\"],\n propertyName: key,\n compositeRule: true,\n }, valid);\n gen.if((0, codegen_1.not)(valid), () => {\n cxt.error(true);\n if (!it.allErrors)\n gen.break();\n });\n });\n cxt.ok(valid);\n },\n};\nexports.default = def;\n//# sourceMappingURL=propertyNames.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst code_1 = require(\"../code\");\nconst codegen_1 = require(\"../../compile/codegen\");\nconst names_1 = require(\"../../compile/names\");\nconst util_1 = require(\"../../compile/util\");\nconst error = {\n message: \"must NOT have additional properties\",\n params: ({ params }) => (0, codegen_1._) `{additionalProperty: ${params.additionalProperty}}`,\n};\nconst def = {\n keyword: \"additionalProperties\",\n type: [\"object\"],\n schemaType: [\"boolean\", \"object\"],\n allowUndefined: true,\n trackErrors: true,\n error,\n code(cxt) {\n const { gen, schema, parentSchema, data, errsCount, it } = cxt;\n /* istanbul ignore if */\n if (!errsCount)\n throw new Error(\"ajv implementation error\");\n const { allErrors, opts } = it;\n it.props = true;\n if (opts.removeAdditional !== \"all\" && (0, util_1.alwaysValidSchema)(it, schema))\n return;\n const props = (0, code_1.allSchemaProperties)(parentSchema.properties);\n const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties);\n checkAdditionalProperties();\n cxt.ok((0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);\n function checkAdditionalProperties() {\n gen.forIn(\"key\", data, (key) => {\n if (!props.length && !patProps.length)\n additionalPropertyCode(key);\n else\n gen.if(isAdditional(key), () => additionalPropertyCode(key));\n });\n }\n function isAdditional(key) {\n let definedProp;\n if (props.length > 8) {\n // TODO maybe an option instead of hard-coded 8?\n const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, \"properties\");\n definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key);\n }\n else if (props.length) {\n definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._) `${key} === ${p}`));\n }\n else {\n definedProp = codegen_1.nil;\n }\n if (patProps.length) {\n definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._) `${(0, code_1.usePattern)(cxt, p)}.test(${key})`));\n }\n return (0, codegen_1.not)(definedProp);\n }\n function deleteAdditional(key) {\n gen.code((0, codegen_1._) `delete ${data}[${key}]`);\n }\n function additionalPropertyCode(key) {\n if (opts.removeAdditional === \"all\" || (opts.removeAdditional && schema === false)) {\n deleteAdditional(key);\n return;\n }\n if (schema === false) {\n cxt.setParams({ additionalProperty: key });\n cxt.error();\n if (!allErrors)\n gen.break();\n return;\n }\n if (typeof schema == \"object\" && !(0, util_1.alwaysValidSchema)(it, schema)) {\n const valid = gen.name(\"valid\");\n if (opts.removeAdditional === \"failing\") {\n applyAdditionalSchema(key, valid, false);\n gen.if((0, codegen_1.not)(valid), () => {\n cxt.reset();\n deleteAdditional(key);\n });\n }\n else {\n applyAdditionalSchema(key, valid);\n if (!allErrors)\n gen.if((0, codegen_1.not)(valid), () => gen.break());\n }\n }\n }\n function applyAdditionalSchema(key, valid, errors) {\n const subschema = {\n keyword: \"additionalProperties\",\n dataProp: key,\n dataPropType: util_1.Type.Str,\n };\n if (errors === false) {\n Object.assign(subschema, {\n compositeRule: true,\n createErrors: false,\n allErrors: false,\n });\n }\n cxt.subschema(subschema, valid);\n }\n },\n};\nexports.default = def;\n//# sourceMappingURL=additionalProperties.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst validate_1 = require(\"../../compile/validate\");\nconst code_1 = require(\"../code\");\nconst util_1 = require(\"../../compile/util\");\nconst additionalProperties_1 = require(\"./additionalProperties\");\nconst def = {\n keyword: \"properties\",\n type: \"object\",\n schemaType: \"object\",\n code(cxt) {\n const { gen, schema, parentSchema, data, it } = cxt;\n if (it.opts.removeAdditional === \"all\" && parentSchema.additionalProperties === undefined) {\n additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, \"additionalProperties\"));\n }\n const allProps = (0, code_1.allSchemaProperties)(schema);\n for (const prop of allProps) {\n it.definedProperties.add(prop);\n }\n if (it.opts.unevaluated && allProps.length && it.props !== true) {\n it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props);\n }\n const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p]));\n if (properties.length === 0)\n return;\n const valid = gen.name(\"valid\");\n for (const prop of properties) {\n if (hasDefault(prop)) {\n applyPropertySchema(prop);\n }\n else {\n gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties));\n applyPropertySchema(prop);\n if (!it.allErrors)\n gen.else().var(valid, true);\n gen.endIf();\n }\n cxt.it.definedProperties.add(prop);\n cxt.ok(valid);\n }\n function hasDefault(prop) {\n return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== undefined;\n }\n function applyPropertySchema(prop) {\n cxt.subschema({\n keyword: \"properties\",\n schemaProp: prop,\n dataProp: prop,\n }, valid);\n }\n },\n};\nexports.default = def;\n//# sourceMappingURL=properties.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst code_1 = require(\"../code\");\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst util_2 = require(\"../../compile/util\");\nconst def = {\n keyword: \"patternProperties\",\n type: \"object\",\n schemaType: \"object\",\n code(cxt) {\n const { gen, schema, data, parentSchema, it } = cxt;\n const { opts } = it;\n const patterns = (0, code_1.allSchemaProperties)(schema);\n const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p]));\n if (patterns.length === 0 ||\n (alwaysValidPatterns.length === patterns.length &&\n (!it.opts.unevaluated || it.props === true))) {\n return;\n }\n const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties;\n const valid = gen.name(\"valid\");\n if (it.props !== true && !(it.props instanceof codegen_1.Name)) {\n it.props = (0, util_2.evaluatedPropsToName)(gen, it.props);\n }\n const { props } = it;\n validatePatternProperties();\n function validatePatternProperties() {\n for (const pat of patterns) {\n if (checkProperties)\n checkMatchingProperties(pat);\n if (it.allErrors) {\n validateProperties(pat);\n }\n else {\n gen.var(valid, true); // TODO var\n validateProperties(pat);\n gen.if(valid);\n }\n }\n }\n function checkMatchingProperties(pat) {\n for (const prop in checkProperties) {\n if (new RegExp(pat).test(prop)) {\n (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`);\n }\n }\n }\n function validateProperties(pat) {\n gen.forIn(\"key\", data, (key) => {\n gen.if((0, codegen_1._) `${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => {\n const alwaysValid = alwaysValidPatterns.includes(pat);\n if (!alwaysValid) {\n cxt.subschema({\n keyword: \"patternProperties\",\n schemaProp: pat,\n dataProp: key,\n dataPropType: util_2.Type.Str,\n }, valid);\n }\n if (it.opts.unevaluated && props !== true) {\n gen.assign((0, codegen_1._) `${props}[${key}]`, true);\n }\n else if (!alwaysValid && !it.allErrors) {\n // can short-circuit if `unevaluatedProperties` is not supported (opts.next === false)\n // or if all properties were evaluated (props === true)\n gen.if((0, codegen_1.not)(valid), () => gen.break());\n }\n });\n });\n }\n },\n};\nexports.default = def;\n//# sourceMappingURL=patternProperties.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst util_1 = require(\"../../compile/util\");\nconst def = {\n keyword: \"not\",\n schemaType: [\"object\", \"boolean\"],\n trackErrors: true,\n code(cxt) {\n const { gen, schema, it } = cxt;\n if ((0, util_1.alwaysValidSchema)(it, schema)) {\n cxt.fail();\n return;\n }\n const valid = gen.name(\"valid\");\n cxt.subschema({\n keyword: \"not\",\n compositeRule: true,\n createErrors: false,\n allErrors: false,\n }, valid);\n cxt.failResult(valid, () => cxt.reset(), () => cxt.error());\n },\n error: { message: \"must NOT be valid\" },\n};\nexports.default = def;\n//# sourceMappingURL=not.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst code_1 = require(\"../code\");\nconst def = {\n keyword: \"anyOf\",\n schemaType: \"array\",\n trackErrors: true,\n code: code_1.validateUnion,\n error: { message: \"must match a schema in anyOf\" },\n};\nexports.default = def;\n//# sourceMappingURL=anyOf.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst error = {\n message: \"must match exactly one schema in oneOf\",\n params: ({ params }) => (0, codegen_1._) `{passingSchemas: ${params.passing}}`,\n};\nconst def = {\n keyword: \"oneOf\",\n schemaType: \"array\",\n trackErrors: true,\n error,\n code(cxt) {\n const { gen, schema, parentSchema, it } = cxt;\n /* istanbul ignore if */\n if (!Array.isArray(schema))\n throw new Error(\"ajv implementation error\");\n if (it.opts.discriminator && parentSchema.discriminator)\n return;\n const schArr = schema;\n const valid = gen.let(\"valid\", false);\n const passing = gen.let(\"passing\", null);\n const schValid = gen.name(\"_valid\");\n cxt.setParams({ passing });\n // TODO possibly fail straight away (with warning or exception) if there are two empty always valid schemas\n gen.block(validateOneOf);\n cxt.result(valid, () => cxt.reset(), () => cxt.error(true));\n function validateOneOf() {\n schArr.forEach((sch, i) => {\n let schCxt;\n if ((0, util_1.alwaysValidSchema)(it, sch)) {\n gen.var(schValid, true);\n }\n else {\n schCxt = cxt.subschema({\n keyword: \"oneOf\",\n schemaProp: i,\n compositeRule: true,\n }, schValid);\n }\n if (i > 0) {\n gen\n .if((0, codegen_1._) `${schValid} && ${valid}`)\n .assign(valid, false)\n .assign(passing, (0, codegen_1._) `[${passing}, ${i}]`)\n .else();\n }\n gen.if(schValid, () => {\n gen.assign(valid, true);\n gen.assign(passing, i);\n if (schCxt)\n cxt.mergeEvaluated(schCxt, codegen_1.Name);\n });\n });\n }\n },\n};\nexports.default = def;\n//# sourceMappingURL=oneOf.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst util_1 = require(\"../../compile/util\");\nconst def = {\n keyword: \"allOf\",\n schemaType: \"array\",\n code(cxt) {\n const { gen, schema, it } = cxt;\n /* istanbul ignore if */\n if (!Array.isArray(schema))\n throw new Error(\"ajv implementation error\");\n const valid = gen.name(\"valid\");\n schema.forEach((sch, i) => {\n if ((0, util_1.alwaysValidSchema)(it, sch))\n return;\n const schCxt = cxt.subschema({ keyword: \"allOf\", schemaProp: i }, valid);\n cxt.ok(valid);\n cxt.mergeEvaluated(schCxt);\n });\n },\n};\nexports.default = def;\n//# sourceMappingURL=allOf.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst util_1 = require(\"../../compile/util\");\nconst error = {\n message: ({ params }) => (0, codegen_1.str) `must match \"${params.ifClause}\" schema`,\n params: ({ params }) => (0, codegen_1._) `{failingKeyword: ${params.ifClause}}`,\n};\nconst def = {\n keyword: \"if\",\n schemaType: [\"object\", \"boolean\"],\n trackErrors: true,\n error,\n code(cxt) {\n const { gen, parentSchema, it } = cxt;\n if (parentSchema.then === undefined && parentSchema.else === undefined) {\n (0, util_1.checkStrictMode)(it, '\"if\" without \"then\" and \"else\" is ignored');\n }\n const hasThen = hasSchema(it, \"then\");\n const hasElse = hasSchema(it, \"else\");\n if (!hasThen && !hasElse)\n return;\n const valid = gen.let(\"valid\", true);\n const schValid = gen.name(\"_valid\");\n validateIf();\n cxt.reset();\n if (hasThen && hasElse) {\n const ifClause = gen.let(\"ifClause\");\n cxt.setParams({ ifClause });\n gen.if(schValid, validateClause(\"then\", ifClause), validateClause(\"else\", ifClause));\n }\n else if (hasThen) {\n gen.if(schValid, validateClause(\"then\"));\n }\n else {\n gen.if((0, codegen_1.not)(schValid), validateClause(\"else\"));\n }\n cxt.pass(valid, () => cxt.error(true));\n function validateIf() {\n const schCxt = cxt.subschema({\n keyword: \"if\",\n compositeRule: true,\n createErrors: false,\n allErrors: false,\n }, schValid);\n cxt.mergeEvaluated(schCxt);\n }\n function validateClause(keyword, ifClause) {\n return () => {\n const schCxt = cxt.subschema({ keyword }, schValid);\n gen.assign(valid, schValid);\n cxt.mergeValidEvaluated(schCxt, valid);\n if (ifClause)\n gen.assign(ifClause, (0, codegen_1._) `${keyword}`);\n else\n cxt.setParams({ ifClause: keyword });\n };\n }\n },\n};\nfunction hasSchema(it, keyword) {\n const schema = it.schema[keyword];\n return schema !== undefined && !(0, util_1.alwaysValidSchema)(it, schema);\n}\nexports.default = def;\n//# sourceMappingURL=if.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst util_1 = require(\"../../compile/util\");\nconst def = {\n keyword: [\"then\", \"else\"],\n schemaType: [\"object\", \"boolean\"],\n code({ keyword, parentSchema, it }) {\n if (parentSchema.if === undefined)\n (0, util_1.checkStrictMode)(it, `\"${keyword}\" without \"if\" is ignored`);\n },\n};\nexports.default = def;\n//# sourceMappingURL=thenElse.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst additionalItems_1 = require(\"./additionalItems\");\nconst prefixItems_1 = require(\"./prefixItems\");\nconst items_1 = require(\"./items\");\nconst items2020_1 = require(\"./items2020\");\nconst contains_1 = require(\"./contains\");\nconst dependencies_1 = require(\"./dependencies\");\nconst propertyNames_1 = require(\"./propertyNames\");\nconst additionalProperties_1 = require(\"./additionalProperties\");\nconst properties_1 = require(\"./properties\");\nconst patternProperties_1 = require(\"./patternProperties\");\nconst not_1 = require(\"./not\");\nconst anyOf_1 = require(\"./anyOf\");\nconst oneOf_1 = require(\"./oneOf\");\nconst allOf_1 = require(\"./allOf\");\nconst if_1 = require(\"./if\");\nconst thenElse_1 = require(\"./thenElse\");\nfunction getApplicator(draft2020 = false) {\n const applicator = [\n // any\n not_1.default,\n anyOf_1.default,\n oneOf_1.default,\n allOf_1.default,\n if_1.default,\n thenElse_1.default,\n // object\n propertyNames_1.default,\n additionalProperties_1.default,\n dependencies_1.default,\n properties_1.default,\n patternProperties_1.default,\n ];\n // array\n if (draft2020)\n applicator.push(prefixItems_1.default, items2020_1.default);\n else\n applicator.push(additionalItems_1.default, items_1.default);\n applicator.push(contains_1.default);\n return applicator;\n}\nexports.default = getApplicator;\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst error = {\n message: ({ schemaCode }) => (0, codegen_1.str) `must match format \"${schemaCode}\"`,\n params: ({ schemaCode }) => (0, codegen_1._) `{format: ${schemaCode}}`,\n};\nconst def = {\n keyword: \"format\",\n type: [\"number\", \"string\"],\n schemaType: \"string\",\n $data: true,\n error,\n code(cxt, ruleType) {\n const { gen, data, $data, schema, schemaCode, it } = cxt;\n const { opts, errSchemaPath, schemaEnv, self } = it;\n if (!opts.validateFormats)\n return;\n if ($data)\n validate$DataFormat();\n else\n validateFormat();\n function validate$DataFormat() {\n const fmts = gen.scopeValue(\"formats\", {\n ref: self.formats,\n code: opts.code.formats,\n });\n const fDef = gen.const(\"fDef\", (0, codegen_1._) `${fmts}[${schemaCode}]`);\n const fType = gen.let(\"fType\");\n const format = gen.let(\"format\");\n // TODO simplify\n gen.if((0, codegen_1._) `typeof ${fDef} == \"object\" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._) `${fDef}.type || \"string\"`).assign(format, (0, codegen_1._) `${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._) `\"string\"`).assign(format, fDef));\n cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt()));\n function unknownFmt() {\n if (opts.strictSchema === false)\n return codegen_1.nil;\n return (0, codegen_1._) `${schemaCode} && !${format}`;\n }\n function invalidFmt() {\n const callFormat = schemaEnv.$async\n ? (0, codegen_1._) `(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))`\n : (0, codegen_1._) `${format}(${data})`;\n const validData = (0, codegen_1._) `(typeof ${format} == \"function\" ? ${callFormat} : ${format}.test(${data}))`;\n return (0, codegen_1._) `${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`;\n }\n }\n function validateFormat() {\n const formatDef = self.formats[schema];\n if (!formatDef) {\n unknownFormat();\n return;\n }\n if (formatDef === true)\n return;\n const [fmtType, format, fmtRef] = getFormat(formatDef);\n if (fmtType === ruleType)\n cxt.pass(validCondition());\n function unknownFormat() {\n if (opts.strictSchema === false) {\n self.logger.warn(unknownMsg());\n return;\n }\n throw new Error(unknownMsg());\n function unknownMsg() {\n return `unknown format \"${schema}\" ignored in schema at path \"${errSchemaPath}\"`;\n }\n }\n function getFormat(fmtDef) {\n const code = fmtDef instanceof RegExp\n ? (0, codegen_1.regexpCode)(fmtDef)\n : opts.code.formats\n ? (0, codegen_1._) `${opts.code.formats}${(0, codegen_1.getProperty)(schema)}`\n : undefined;\n const fmt = gen.scopeValue(\"formats\", { key: schema, ref: fmtDef, code });\n if (typeof fmtDef == \"object\" && !(fmtDef instanceof RegExp)) {\n return [fmtDef.type || \"string\", fmtDef.validate, (0, codegen_1._) `${fmt}.validate`];\n }\n return [\"string\", fmtDef, fmt];\n }\n function validCondition() {\n if (typeof formatDef == \"object\" && !(formatDef instanceof RegExp) && formatDef.async) {\n if (!schemaEnv.$async)\n throw new Error(\"async format in sync schema\");\n return (0, codegen_1._) `await ${fmtRef}(${data})`;\n }\n return typeof format == \"function\" ? (0, codegen_1._) `${fmtRef}(${data})` : (0, codegen_1._) `${fmtRef}.test(${data})`;\n }\n }\n },\n};\nexports.default = def;\n//# sourceMappingURL=format.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst format_1 = require(\"./format\");\nconst format = [format_1.default];\nexports.default = format;\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.contentVocabulary = exports.metadataVocabulary = void 0;\nexports.metadataVocabulary = [\n \"title\",\n \"description\",\n \"default\",\n \"deprecated\",\n \"readOnly\",\n \"writeOnly\",\n \"examples\",\n];\nexports.contentVocabulary = [\n \"contentMediaType\",\n \"contentEncoding\",\n \"contentSchema\",\n];\n//# sourceMappingURL=metadata.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst core_1 = require(\"./core\");\nconst validation_1 = require(\"./validation\");\nconst applicator_1 = require(\"./applicator\");\nconst format_1 = require(\"./format\");\nconst metadata_1 = require(\"./metadata\");\nconst draft7Vocabularies = [\n core_1.default,\n validation_1.default,\n (0, applicator_1.default)(),\n format_1.default,\n metadata_1.metadataVocabulary,\n metadata_1.contentVocabulary,\n];\nexports.default = draft7Vocabularies;\n//# sourceMappingURL=draft7.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DiscrError = void 0;\nvar DiscrError;\n(function (DiscrError) {\n DiscrError[\"Tag\"] = \"tag\";\n DiscrError[\"Mapping\"] = \"mapping\";\n})(DiscrError || (exports.DiscrError = DiscrError = {}));\n//# sourceMappingURL=types.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst codegen_1 = require(\"../../compile/codegen\");\nconst types_1 = require(\"../discriminator/types\");\nconst compile_1 = require(\"../../compile\");\nconst ref_error_1 = require(\"../../compile/ref_error\");\nconst util_1 = require(\"../../compile/util\");\nconst error = {\n message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag\n ? `tag \"${tagName}\" must be string`\n : `value of tag \"${tagName}\" must be in oneOf`,\n params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._) `{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`,\n};\nconst def = {\n keyword: \"discriminator\",\n type: \"object\",\n schemaType: \"object\",\n error,\n code(cxt) {\n const { gen, data, schema, parentSchema, it } = cxt;\n const { oneOf } = parentSchema;\n if (!it.opts.discriminator) {\n throw new Error(\"discriminator: requires discriminator option\");\n }\n const tagName = schema.propertyName;\n if (typeof tagName != \"string\")\n throw new Error(\"discriminator: requires propertyName\");\n if (schema.mapping)\n throw new Error(\"discriminator: mapping is not supported\");\n if (!oneOf)\n throw new Error(\"discriminator: requires oneOf keyword\");\n const valid = gen.let(\"valid\", false);\n const tag = gen.const(\"tag\", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(tagName)}`);\n gen.if((0, codegen_1._) `typeof ${tag} == \"string\"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName }));\n cxt.ok(valid);\n function validateMapping() {\n const mapping = getMapping();\n gen.if(false);\n for (const tagValue in mapping) {\n gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`);\n gen.assign(valid, applyTagSchema(mapping[tagValue]));\n }\n gen.else();\n cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName });\n gen.endIf();\n }\n function applyTagSchema(schemaProp) {\n const _valid = gen.name(\"valid\");\n const schCxt = cxt.subschema({ keyword: \"oneOf\", schemaProp }, _valid);\n cxt.mergeEvaluated(schCxt, codegen_1.Name);\n return _valid;\n }\n function getMapping() {\n var _a;\n const oneOfMapping = {};\n const topRequired = hasRequired(parentSchema);\n let tagRequired = true;\n for (let i = 0; i < oneOf.length; i++) {\n let sch = oneOf[i];\n if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) {\n const ref = sch.$ref;\n sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref);\n if (sch instanceof compile_1.SchemaEnv)\n sch = sch.schema;\n if (sch === undefined)\n throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref);\n }\n const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName];\n if (typeof propSch != \"object\") {\n throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have \"properties/${tagName}\"`);\n }\n tagRequired = tagRequired && (topRequired || hasRequired(sch));\n addMappings(propSch, i);\n }\n if (!tagRequired)\n throw new Error(`discriminator: \"${tagName}\" must be required`);\n return oneOfMapping;\n function hasRequired({ required }) {\n return Array.isArray(required) && required.includes(tagName);\n }\n function addMappings(sch, i) {\n if (sch.const) {\n addMapping(sch.const, i);\n }\n else if (sch.enum) {\n for (const tagValue of sch.enum) {\n addMapping(tagValue, i);\n }\n }\n else {\n throw new Error(`discriminator: \"properties/${tagName}\" must have \"const\" or \"enum\"`);\n }\n }\n function addMapping(tagValue, i) {\n if (typeof tagValue != \"string\" || tagValue in oneOfMapping) {\n throw new Error(`discriminator: \"${tagName}\" values must be unique strings`);\n }\n oneOfMapping[tagValue] = i;\n }\n }\n },\n};\nexports.default = def;\n//# sourceMappingURL=index.js.map","","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0;\nconst core_1 = require(\"./core\");\nconst draft7_1 = require(\"./vocabularies/draft7\");\nconst discriminator_1 = require(\"./vocabularies/discriminator\");\nconst draft7MetaSchema = require(\"./refs/json-schema-draft-07.json\");\nconst META_SUPPORT_DATA = [\"/properties\"];\nconst META_SCHEMA_ID = \"http://json-schema.org/draft-07/schema\";\nclass Ajv extends core_1.default {\n _addVocabularies() {\n super._addVocabularies();\n draft7_1.default.forEach((v) => this.addVocabulary(v));\n if (this.opts.discriminator)\n this.addKeyword(discriminator_1.default);\n }\n _addDefaultMetaSchema() {\n super._addDefaultMetaSchema();\n if (!this.opts.meta)\n return;\n const metaSchema = this.opts.$data\n ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)\n : draft7MetaSchema;\n this.addMetaSchema(metaSchema, META_SCHEMA_ID, false);\n this.refs[\"http://json-schema.org/schema\"] = META_SCHEMA_ID;\n }\n defaultMeta() {\n return (this.opts.defaultMeta =\n super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined));\n }\n}\nexports.Ajv = Ajv;\nmodule.exports = exports = Ajv;\nmodule.exports.Ajv = Ajv;\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.default = Ajv;\nvar validate_1 = require(\"./compile/validate\");\nObject.defineProperty(exports, \"KeywordCxt\", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });\nvar codegen_1 = require(\"./compile/codegen\");\nObject.defineProperty(exports, \"_\", { enumerable: true, get: function () { return codegen_1._; } });\nObject.defineProperty(exports, \"str\", { enumerable: true, get: function () { return codegen_1.str; } });\nObject.defineProperty(exports, \"stringify\", { enumerable: true, get: function () { return codegen_1.stringify; } });\nObject.defineProperty(exports, \"nil\", { enumerable: true, get: function () { return codegen_1.nil; } });\nObject.defineProperty(exports, \"Name\", { enumerable: true, get: function () { return codegen_1.Name; } });\nObject.defineProperty(exports, \"CodeGen\", { enumerable: true, get: function () { return codegen_1.CodeGen; } });\nvar validation_error_1 = require(\"./runtime/validation_error\");\nObject.defineProperty(exports, \"ValidationError\", { enumerable: true, get: function () { return validation_error_1.default; } });\nvar ref_error_1 = require(\"./compile/ref_error\");\nObject.defineProperty(exports, \"MissingRefError\", { enumerable: true, get: function () { return ref_error_1.default; } });\n//# sourceMappingURL=ajv.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.formatNames = exports.fastFormats = exports.fullFormats = void 0;\nfunction fmtDef(validate, compare) {\n return { validate, compare };\n}\nexports.fullFormats = {\n // date: http://tools.ietf.org/html/rfc3339#section-5.6\n date: fmtDef(date, compareDate),\n // date-time: http://tools.ietf.org/html/rfc3339#section-5.6\n time: fmtDef(getTime(true), compareTime),\n \"date-time\": fmtDef(getDateTime(true), compareDateTime),\n \"iso-time\": fmtDef(getTime(), compareIsoTime),\n \"iso-date-time\": fmtDef(getDateTime(), compareIsoDateTime),\n // duration: https://tools.ietf.org/html/rfc3339#appendix-A\n duration: /^P(?!$)((\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+S)?)?|(\\d+W)?)$/,\n uri,\n \"uri-reference\": /^(?:[a-z][a-z0-9+\\-.]*:)?(?:\\/?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,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\\-._~!$&'\"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,\n // uri-template: https://tools.ietf.org/html/rfc6570\n \"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,\n // For the source: https://gist.github.com/dperini/729294\n // For test cases: https://mathiasbynens.be/demo/url-regex\n 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,\n 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,\n 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,\n // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html\n 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)$/,\n 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,\n regex,\n // uuid: http://tools.ietf.org/html/rfc4122\n uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,\n // JSON-pointer: https://tools.ietf.org/html/rfc6901\n // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A\n \"json-pointer\": /^(?:\\/(?:[^~/]|~0|~1)*)*$/,\n \"json-pointer-uri-fragment\": /^#(?:\\/(?:[a-z0-9_\\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,\n // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00\n \"relative-json-pointer\": /^(?:0|[1-9][0-9]*)(?:#|(?:\\/(?:[^~/]|~0|~1)*)*)$/,\n // the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types\n // byte: https://github.com/miguelmota/is-base64\n byte,\n // signed 32 bit integer\n int32: { type: \"number\", validate: validateInt32 },\n // signed 64 bit integer\n int64: { type: \"number\", validate: validateInt64 },\n // C-type float\n float: { type: \"number\", validate: validateNumber },\n // C-type double\n double: { type: \"number\", validate: validateNumber },\n // hint to the UI to hide input strings\n password: true,\n // unchecked string payload\n binary: true,\n};\nexports.fastFormats = {\n ...exports.fullFormats,\n date: fmtDef(/^\\d\\d\\d\\d-[0-1]\\d-[0-3]\\d$/, compareDate),\n time: fmtDef(/^(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)(?:\\.\\d+)?(?:z|[+-]\\d\\d(?::?\\d\\d)?)$/i, compareTime),\n \"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),\n \"iso-time\": fmtDef(/^(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)(?:\\.\\d+)?(?:z|[+-]\\d\\d(?::?\\d\\d)?)?$/i, compareIsoTime),\n \"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),\n // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js\n uri: /^(?:[a-z][a-z0-9+\\-.]*:)(?:\\/?\\/)?[^\\s]*$/i,\n \"uri-reference\": /^(?:(?:[a-z][a-z0-9+\\-.]*:)?\\/?\\/)?(?:[^\\\\\\s#][^\\s#]*)?(?:#[^\\\\\\s]*)?$/i,\n // email (sources from jsen validator):\n // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363\n // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'wilful violation')\n 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,\n};\nexports.formatNames = Object.keys(exports.fullFormats);\nfunction isLeapYear(year) {\n // https://tools.ietf.org/html/rfc3339#appendix-C\n return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n}\nconst DATE = /^(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)$/;\nconst DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\nfunction date(str) {\n // full-date from http://tools.ietf.org/html/rfc3339#section-5.6\n const matches = DATE.exec(str);\n if (!matches)\n return false;\n const year = +matches[1];\n const month = +matches[2];\n const day = +matches[3];\n return (month >= 1 &&\n month <= 12 &&\n day >= 1 &&\n day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]));\n}\nfunction compareDate(d1, d2) {\n if (!(d1 && d2))\n return undefined;\n if (d1 > d2)\n return 1;\n if (d1 < d2)\n return -1;\n return 0;\n}\nconst TIME = /^(\\d\\d):(\\d\\d):(\\d\\d(?:\\.\\d+)?)(z|([+-])(\\d\\d)(?::?(\\d\\d))?)?$/i;\nfunction getTime(strictTimeZone) {\n return function time(str) {\n const matches = TIME.exec(str);\n if (!matches)\n return false;\n const hr = +matches[1];\n const min = +matches[2];\n const sec = +matches[3];\n const tz = matches[4];\n const tzSign = matches[5] === \"-\" ? -1 : 1;\n const tzH = +(matches[6] || 0);\n const tzM = +(matches[7] || 0);\n if (tzH > 23 || tzM > 59 || (strictTimeZone && !tz))\n return false;\n if (hr <= 23 && min <= 59 && sec < 60)\n return true;\n // leap second\n const utcMin = min - tzM * tzSign;\n const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0);\n return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61;\n };\n}\nfunction compareTime(s1, s2) {\n if (!(s1 && s2))\n return undefined;\n const t1 = new Date(\"2020-01-01T\" + s1).valueOf();\n const t2 = new Date(\"2020-01-01T\" + s2).valueOf();\n if (!(t1 && t2))\n return undefined;\n return t1 - t2;\n}\nfunction compareIsoTime(t1, t2) {\n if (!(t1 && t2))\n return undefined;\n const a1 = TIME.exec(t1);\n const a2 = TIME.exec(t2);\n if (!(a1 && a2))\n return undefined;\n t1 = a1[1] + a1[2] + a1[3];\n t2 = a2[1] + a2[2] + a2[3];\n if (t1 > t2)\n return 1;\n if (t1 < t2)\n return -1;\n return 0;\n}\nconst DATE_TIME_SEPARATOR = /t|\\s/i;\nfunction getDateTime(strictTimeZone) {\n const time = getTime(strictTimeZone);\n return function date_time(str) {\n // http://tools.ietf.org/html/rfc3339#section-5.6\n const dateTime = str.split(DATE_TIME_SEPARATOR);\n return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1]);\n };\n}\nfunction compareDateTime(dt1, dt2) {\n if (!(dt1 && dt2))\n return undefined;\n const d1 = new Date(dt1).valueOf();\n const d2 = new Date(dt2).valueOf();\n if (!(d1 && d2))\n return undefined;\n return d1 - d2;\n}\nfunction compareIsoDateTime(dt1, dt2) {\n if (!(dt1 && dt2))\n return undefined;\n const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR);\n const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR);\n const res = compareDate(d1, d2);\n if (res === undefined)\n return undefined;\n return res || compareTime(t1, t2);\n}\nconst NOT_URI_FRAGMENT = /\\/|:/;\nconst 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;\nfunction uri(str) {\n // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required \".\"\n return NOT_URI_FRAGMENT.test(str) && URI.test(str);\n}\nconst BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;\nfunction byte(str) {\n BYTE.lastIndex = 0;\n return BYTE.test(str);\n}\nconst MIN_INT32 = -(2 ** 31);\nconst MAX_INT32 = 2 ** 31 - 1;\nfunction validateInt32(value) {\n return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32;\n}\nfunction validateInt64(value) {\n // JSON and javascript max Int is 2**53, so any int that passes isInteger is valid for Int64\n return Number.isInteger(value);\n}\nfunction validateNumber() {\n return true;\n}\nconst Z_ANCHOR = /[^\\\\]\\\\Z/;\nfunction regex(str) {\n if (Z_ANCHOR.test(str))\n return false;\n try {\n new RegExp(str);\n return true;\n }\n catch (e) {\n return false;\n }\n}\n//# sourceMappingURL=formats.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.formatLimitDefinition = void 0;\nconst ajv_1 = require(\"ajv\");\nconst codegen_1 = require(\"ajv/dist/compile/codegen\");\nconst ops = codegen_1.operators;\nconst KWDs = {\n formatMaximum: { okStr: \"<=\", ok: ops.LTE, fail: ops.GT },\n formatMinimum: { okStr: \">=\", ok: ops.GTE, fail: ops.LT },\n formatExclusiveMaximum: { okStr: \"<\", ok: ops.LT, fail: ops.GTE },\n formatExclusiveMinimum: { okStr: \">\", ok: ops.GT, fail: ops.LTE },\n};\nconst error = {\n message: ({ keyword, schemaCode }) => (0, codegen_1.str) `should be ${KWDs[keyword].okStr} ${schemaCode}`,\n params: ({ keyword, schemaCode }) => (0, codegen_1._) `{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`,\n};\nexports.formatLimitDefinition = {\n keyword: Object.keys(KWDs),\n type: \"string\",\n schemaType: \"string\",\n $data: true,\n error,\n code(cxt) {\n const { gen, data, schemaCode, keyword, it } = cxt;\n const { opts, self } = it;\n if (!opts.validateFormats)\n return;\n const fCxt = new ajv_1.KeywordCxt(it, self.RULES.all.format.definition, \"format\");\n if (fCxt.$data)\n validate$DataFormat();\n else\n validateFormat();\n function validate$DataFormat() {\n const fmts = gen.scopeValue(\"formats\", {\n ref: self.formats,\n code: opts.code.formats,\n });\n const fmt = gen.const(\"fmt\", (0, codegen_1._) `${fmts}[${fCxt.schemaCode}]`);\n 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)));\n }\n function validateFormat() {\n const format = fCxt.schema;\n const fmtDef = self.formats[format];\n if (!fmtDef || fmtDef === true)\n return;\n if (typeof fmtDef != \"object\" ||\n fmtDef instanceof RegExp ||\n typeof fmtDef.compare != \"function\") {\n throw new Error(`\"${keyword}\": format \"${format}\" does not define \"compare\" function`);\n }\n const fmt = gen.scopeValue(\"formats\", {\n key: format,\n ref: fmtDef,\n code: opts.code.formats ? (0, codegen_1._) `${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : undefined,\n });\n cxt.fail$data(compareCode(fmt));\n }\n function compareCode(fmt) {\n return (0, codegen_1._) `${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`;\n }\n },\n dependencies: [\"format\"],\n};\nconst formatLimitPlugin = (ajv) => {\n ajv.addKeyword(exports.formatLimitDefinition);\n return ajv;\n};\nexports.default = formatLimitPlugin;\n//# sourceMappingURL=limit.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst formats_1 = require(\"./formats\");\nconst limit_1 = require(\"./limit\");\nconst codegen_1 = require(\"ajv/dist/compile/codegen\");\nconst fullName = new codegen_1.Name(\"fullFormats\");\nconst fastName = new codegen_1.Name(\"fastFormats\");\nconst formatsPlugin = (ajv, opts = { keywords: true }) => {\n if (Array.isArray(opts)) {\n addFormats(ajv, opts, formats_1.fullFormats, fullName);\n return ajv;\n }\n const [formats, exportName] = opts.mode === \"fast\" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName];\n const list = opts.formats || formats_1.formatNames;\n addFormats(ajv, list, formats, exportName);\n if (opts.keywords)\n (0, limit_1.default)(ajv);\n return ajv;\n};\nformatsPlugin.get = (name, mode = \"full\") => {\n const formats = mode === \"fast\" ? formats_1.fastFormats : formats_1.fullFormats;\n const f = formats[name];\n if (!f)\n throw new Error(`Unknown format \"${name}\"`);\n return f;\n};\nfunction addFormats(ajv, list, fs, exportName) {\n var _a;\n var _b;\n (_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 ? _a : (_b.formats = (0, codegen_1._) `require(\"ajv-formats/dist/formats\").${exportName}`);\n for (const f of list)\n ajv.addFormat(f, fs[f]);\n}\nmodule.exports = exports = formatsPlugin;\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.default = formatsPlugin;\n//# sourceMappingURL=index.js.map","/**\n * AJV-based JSON Schema validator provider\n */\nimport Ajv from 'ajv';\nimport _addFormats from 'ajv-formats';\nfunction createDefaultAjvInstance() {\n const ajv = new Ajv({\n strict: false,\n validateFormats: true,\n validateSchema: false,\n allErrors: true\n });\n const addFormats = _addFormats;\n addFormats(ajv);\n return ajv;\n}\n/**\n * @example\n * ```typescript\n * // Use with default AJV instance (recommended)\n * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv';\n * const validator = new AjvJsonSchemaValidator();\n *\n * // Use with custom AJV instance\n * import { Ajv } from 'ajv';\n * const ajv = new Ajv({ strict: true, allErrors: true });\n * const validator = new AjvJsonSchemaValidator(ajv);\n * ```\n */\nexport class AjvJsonSchemaValidator {\n /**\n * Create an AJV validator\n *\n * @param ajv - Optional pre-configured AJV instance. If not provided, a default instance will be created.\n *\n * @example\n * ```typescript\n * // Use default configuration (recommended for most cases)\n * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv';\n * const validator = new AjvJsonSchemaValidator();\n *\n * // Or provide custom AJV instance for advanced configuration\n * import { Ajv } from 'ajv';\n * import addFormats from 'ajv-formats';\n *\n * const ajv = new Ajv({ validateFormats: true });\n * addFormats(ajv);\n * const validator = new AjvJsonSchemaValidator(ajv);\n * ```\n */\n constructor(ajv) {\n this._ajv = ajv ?? createDefaultAjvInstance();\n }\n /**\n * Create a validator for the given JSON Schema\n *\n * The validator is compiled once and can be reused multiple times.\n * If the schema has an $id, it will be cached by AJV automatically.\n *\n * @param schema - Standard JSON Schema object\n * @returns A validator function that validates input data\n */\n getValidator(schema) {\n // Check if schema has $id and is already compiled/cached\n const ajvValidator = '$id' in schema && typeof schema.$id === 'string'\n ? (this._ajv.getSchema(schema.$id) ?? this._ajv.compile(schema))\n : this._ajv.compile(schema);\n return (input) => {\n const valid = ajvValidator(input);\n if (valid) {\n return {\n valid: true,\n data: input,\n errorMessage: undefined\n };\n }\n else {\n return {\n valid: false,\n data: undefined,\n errorMessage: this._ajv.errorsText(ajvValidator.errors)\n };\n }\n };\n }\n}\n//# sourceMappingURL=ajv-provider.js.map","module.exports = isexe\nisexe.sync = sync\n\nvar fs = require('fs')\n\nfunction checkPathExt (path, options) {\n var pathext = options.pathExt !== undefined ?\n options.pathExt : process.env.PATHEXT\n\n if (!pathext) {\n return true\n }\n\n pathext = pathext.split(';')\n if (pathext.indexOf('') !== -1) {\n return true\n }\n for (var i = 0; i < pathext.length; i++) {\n var p = pathext[i].toLowerCase()\n if (p && path.substr(-p.length).toLowerCase() === p) {\n return true\n }\n }\n return false\n}\n\nfunction checkStat (stat, path, options) {\n if (!stat.isSymbolicLink() && !stat.isFile()) {\n return false\n }\n return checkPathExt(path, options)\n}\n\nfunction isexe (path, options, cb) {\n fs.stat(path, function (er, stat) {\n cb(er, er ? false : checkStat(stat, path, options))\n })\n}\n\nfunction sync (path, options) {\n return checkStat(fs.statSync(path), path, options)\n}\n","module.exports = isexe\nisexe.sync = sync\n\nvar fs = require('fs')\n\nfunction isexe (path, options, cb) {\n fs.stat(path, function (er, stat) {\n cb(er, er ? false : checkStat(stat, options))\n })\n}\n\nfunction sync (path, options) {\n return checkStat(fs.statSync(path), options)\n}\n\nfunction checkStat (stat, options) {\n return stat.isFile() && checkMode(stat, options)\n}\n\nfunction checkMode (stat, options) {\n var mod = stat.mode\n var uid = stat.uid\n var gid = stat.gid\n\n var myUid = options.uid !== undefined ?\n options.uid : process.getuid && process.getuid()\n var myGid = options.gid !== undefined ?\n options.gid : process.getgid && process.getgid()\n\n var u = parseInt('100', 8)\n var g = parseInt('010', 8)\n var o = parseInt('001', 8)\n var ug = u | g\n\n var ret = (mod & o) ||\n (mod & g) && gid === myGid ||\n (mod & u) && uid === myUid ||\n (mod & ug) && myUid === 0\n\n return ret\n}\n","var fs = require('fs')\nvar core\nif (process.platform === 'win32' || global.TESTING_WINDOWS) {\n core = require('./windows.js')\n} else {\n core = require('./mode.js')\n}\n\nmodule.exports = isexe\nisexe.sync = sync\n\nfunction isexe (path, options, cb) {\n if (typeof options === 'function') {\n cb = options\n options = {}\n }\n\n if (!cb) {\n if (typeof Promise !== 'function') {\n throw new TypeError('callback not provided')\n }\n\n return new Promise(function (resolve, reject) {\n isexe(path, options || {}, function (er, is) {\n if (er) {\n reject(er)\n } else {\n resolve(is)\n }\n })\n })\n }\n\n core(path, options || {}, function (er, is) {\n // ignore EACCES because that just means we aren't allowed to run it\n if (er) {\n if (er.code === 'EACCES' || options && options.ignoreErrors) {\n er = null\n is = false\n }\n }\n cb(er, is)\n })\n}\n\nfunction sync (path, options) {\n // my kingdom for a filtered catch\n try {\n return core.sync(path, options || {})\n } catch (er) {\n if (options && options.ignoreErrors || er.code === 'EACCES') {\n return false\n } else {\n throw er\n }\n }\n}\n","const isWindows = process.platform === 'win32' ||\n process.env.OSTYPE === 'cygwin' ||\n process.env.OSTYPE === 'msys'\n\nconst path = require('path')\nconst COLON = isWindows ? ';' : ':'\nconst isexe = require('isexe')\n\nconst getNotFoundError = (cmd) =>\n Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' })\n\nconst getPathInfo = (cmd, opt) => {\n const colon = opt.colon || COLON\n\n // If it has a slash, then we don't bother searching the pathenv.\n // just check the file itself, and that's it.\n const pathEnv = cmd.match(/\\//) || isWindows && cmd.match(/\\\\/) ? ['']\n : (\n [\n // windows always checks the cwd first\n ...(isWindows ? [process.cwd()] : []),\n ...(opt.path || process.env.PATH ||\n /* istanbul ignore next: very unusual */ '').split(colon),\n ]\n )\n const pathExtExe = isWindows\n ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM'\n : ''\n const pathExt = isWindows ? pathExtExe.split(colon) : ['']\n\n if (isWindows) {\n if (cmd.indexOf('.') !== -1 && pathExt[0] !== '')\n pathExt.unshift('')\n }\n\n return {\n pathEnv,\n pathExt,\n pathExtExe,\n }\n}\n\nconst which = (cmd, opt, cb) => {\n if (typeof opt === 'function') {\n cb = opt\n opt = {}\n }\n if (!opt)\n opt = {}\n\n const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)\n const found = []\n\n const step = i => new Promise((resolve, reject) => {\n if (i === pathEnv.length)\n return opt.all && found.length ? resolve(found)\n : reject(getNotFoundError(cmd))\n\n const ppRaw = pathEnv[i]\n const pathPart = /^\".*\"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw\n\n const pCmd = path.join(pathPart, cmd)\n const p = !pathPart && /^\\.[\\\\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd\n : pCmd\n\n resolve(subStep(p, i, 0))\n })\n\n const subStep = (p, i, ii) => new Promise((resolve, reject) => {\n if (ii === pathExt.length)\n return resolve(step(i + 1))\n const ext = pathExt[ii]\n isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {\n if (!er && is) {\n if (opt.all)\n found.push(p + ext)\n else\n return resolve(p + ext)\n }\n return resolve(subStep(p, i, ii + 1))\n })\n })\n\n return cb ? step(0).then(res => cb(null, res), cb) : step(0)\n}\n\nconst whichSync = (cmd, opt) => {\n opt = opt || {}\n\n const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)\n const found = []\n\n for (let i = 0; i < pathEnv.length; i ++) {\n const ppRaw = pathEnv[i]\n const pathPart = /^\".*\"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw\n\n const pCmd = path.join(pathPart, cmd)\n const p = !pathPart && /^\\.[\\\\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd\n : pCmd\n\n for (let j = 0; j < pathExt.length; j ++) {\n const cur = p + pathExt[j]\n try {\n const is = isexe.sync(cur, { pathExt: pathExtExe })\n if (is) {\n if (opt.all)\n found.push(cur)\n else\n return cur\n }\n } catch (ex) {}\n }\n }\n\n if (opt.all && found.length)\n return found\n\n if (opt.nothrow)\n return null\n\n throw getNotFoundError(cmd)\n}\n\nmodule.exports = which\nwhich.sync = whichSync\n","'use strict';\n\nconst pathKey = (options = {}) => {\n\tconst environment = options.env || process.env;\n\tconst platform = options.platform || process.platform;\n\n\tif (platform !== 'win32') {\n\t\treturn 'PATH';\n\t}\n\n\treturn Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path';\n};\n\nmodule.exports = pathKey;\n// TODO: Remove this for the next major release\nmodule.exports.default = pathKey;\n","'use strict';\n\nconst path = require('path');\nconst which = require('which');\nconst getPathKey = require('path-key');\n\nfunction resolveCommandAttempt(parsed, withoutPathExt) {\n const env = parsed.options.env || process.env;\n const cwd = process.cwd();\n const hasCustomCwd = parsed.options.cwd != null;\n // Worker threads do not have process.chdir()\n const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled;\n\n // If a custom `cwd` was specified, we need to change the process cwd\n // because `which` will do stat calls but does not support a custom cwd\n if (shouldSwitchCwd) {\n try {\n process.chdir(parsed.options.cwd);\n } catch (err) {\n /* Empty */\n }\n }\n\n let resolved;\n\n try {\n resolved = which.sync(parsed.command, {\n path: env[getPathKey({ env })],\n pathExt: withoutPathExt ? path.delimiter : undefined,\n });\n } catch (e) {\n /* Empty */\n } finally {\n if (shouldSwitchCwd) {\n process.chdir(cwd);\n }\n }\n\n // If we successfully resolved, ensure that an absolute path is returned\n // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it\n if (resolved) {\n resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved);\n }\n\n return resolved;\n}\n\nfunction resolveCommand(parsed) {\n return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);\n}\n\nmodule.exports = resolveCommand;\n","'use strict';\n\n// See http://www.robvanderwoude.com/escapechars.php\nconst metaCharsRegExp = /([()\\][%!^\"`<>&|;, *?])/g;\n\nfunction escapeCommand(arg) {\n // Escape meta chars\n arg = arg.replace(metaCharsRegExp, '^$1');\n\n return arg;\n}\n\nfunction escapeArgument(arg, doubleEscapeMetaChars) {\n // Convert to string\n arg = `${arg}`;\n\n // Algorithm below is based on https://qntm.org/cmd\n // It's slightly altered to disable JS backtracking to avoid hanging on specially crafted input\n // Please see https://github.com/moxystudio/node-cross-spawn/pull/160 for more information\n\n // Sequence of backslashes followed by a double quote:\n // double up all the backslashes and escape the double quote\n arg = arg.replace(/(?=(\\\\+?)?)\\1\"/g, '$1$1\\\\\"');\n\n // Sequence of backslashes followed by the end of the string\n // (which will become a double quote later):\n // double up all the backslashes\n arg = arg.replace(/(?=(\\\\+?)?)\\1$/, '$1$1');\n\n // All other backslashes occur literally\n\n // Quote the whole thing:\n arg = `\"${arg}\"`;\n\n // Escape meta chars\n arg = arg.replace(metaCharsRegExp, '^$1');\n\n // Double escape meta chars if necessary\n if (doubleEscapeMetaChars) {\n arg = arg.replace(metaCharsRegExp, '^$1');\n }\n\n return arg;\n}\n\nmodule.exports.command = escapeCommand;\nmodule.exports.argument = escapeArgument;\n","'use strict';\nmodule.exports = /^#!(.*)/;\n","'use strict';\nconst shebangRegex = require('shebang-regex');\n\nmodule.exports = (string = '') => {\n\tconst match = string.match(shebangRegex);\n\n\tif (!match) {\n\t\treturn null;\n\t}\n\n\tconst [path, argument] = match[0].replace(/#! ?/, '').split(' ');\n\tconst binary = path.split('/').pop();\n\n\tif (binary === 'env') {\n\t\treturn argument;\n\t}\n\n\treturn argument ? `${binary} ${argument}` : binary;\n};\n","'use strict';\n\nconst fs = require('fs');\nconst shebangCommand = require('shebang-command');\n\nfunction readShebang(command) {\n // Read the first 150 bytes from the file\n const size = 150;\n const buffer = Buffer.alloc(size);\n\n let fd;\n\n try {\n fd = fs.openSync(command, 'r');\n fs.readSync(fd, buffer, 0, size, 0);\n fs.closeSync(fd);\n } catch (e) { /* Empty */ }\n\n // Attempt to extract shebang (null is returned if not a shebang)\n return shebangCommand(buffer.toString());\n}\n\nmodule.exports = readShebang;\n","'use strict';\n\nconst path = require('path');\nconst resolveCommand = require('./util/resolveCommand');\nconst escape = require('./util/escape');\nconst readShebang = require('./util/readShebang');\n\nconst isWin = process.platform === 'win32';\nconst isExecutableRegExp = /\\.(?:com|exe)$/i;\nconst isCmdShimRegExp = /node_modules[\\\\/].bin[\\\\/][^\\\\/]+\\.cmd$/i;\n\nfunction detectShebang(parsed) {\n parsed.file = resolveCommand(parsed);\n\n const shebang = parsed.file && readShebang(parsed.file);\n\n if (shebang) {\n parsed.args.unshift(parsed.file);\n parsed.command = shebang;\n\n return resolveCommand(parsed);\n }\n\n return parsed.file;\n}\n\nfunction parseNonShell(parsed) {\n if (!isWin) {\n return parsed;\n }\n\n // Detect & add support for shebangs\n const commandFile = detectShebang(parsed);\n\n // We don't need a shell if the command filename is an executable\n const needsShell = !isExecutableRegExp.test(commandFile);\n\n // If a shell is required, use cmd.exe and take care of escaping everything correctly\n // Note that `forceShell` is an hidden option used only in tests\n if (parsed.options.forceShell || needsShell) {\n // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/`\n // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument\n // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called,\n // we need to double escape them\n const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);\n\n // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\\bar)\n // This is necessary otherwise it will always fail with ENOENT in those cases\n parsed.command = path.normalize(parsed.command);\n\n // Escape command & arguments\n parsed.command = escape.command(parsed.command);\n parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));\n\n const shellCommand = [parsed.command].concat(parsed.args).join(' ');\n\n parsed.args = ['/d', '/s', '/c', `\"${shellCommand}\"`];\n parsed.command = process.env.comspec || 'cmd.exe';\n parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped\n }\n\n return parsed;\n}\n\nfunction parse(command, args, options) {\n // Normalize arguments, similar to nodejs\n if (args && !Array.isArray(args)) {\n options = args;\n args = null;\n }\n\n args = args ? args.slice(0) : []; // Clone array to avoid changing the original\n options = Object.assign({}, options); // Clone object to avoid changing the original\n\n // Build our parsed object\n const parsed = {\n command,\n args,\n options,\n file: undefined,\n original: {\n command,\n args,\n },\n };\n\n // Delegate further parsing to shell or non-shell\n return options.shell ? parsed : parseNonShell(parsed);\n}\n\nmodule.exports = parse;\n","'use strict';\n\nconst isWin = process.platform === 'win32';\n\nfunction notFoundError(original, syscall) {\n return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {\n code: 'ENOENT',\n errno: 'ENOENT',\n syscall: `${syscall} ${original.command}`,\n path: original.command,\n spawnargs: original.args,\n });\n}\n\nfunction hookChildProcess(cp, parsed) {\n if (!isWin) {\n return;\n }\n\n const originalEmit = cp.emit;\n\n cp.emit = function (name, arg1) {\n // If emitting \"exit\" event and exit code is 1, we need to check if\n // the command exists and emit an \"error\" instead\n // See https://github.com/IndigoUnited/node-cross-spawn/issues/16\n if (name === 'exit') {\n const err = verifyENOENT(arg1, parsed);\n\n if (err) {\n return originalEmit.call(cp, 'error', err);\n }\n }\n\n return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params\n };\n}\n\nfunction verifyENOENT(status, parsed) {\n if (isWin && status === 1 && !parsed.file) {\n return notFoundError(parsed.original, 'spawn');\n }\n\n return null;\n}\n\nfunction verifyENOENTSync(status, parsed) {\n if (isWin && status === 1 && !parsed.file) {\n return notFoundError(parsed.original, 'spawnSync');\n }\n\n return null;\n}\n\nmodule.exports = {\n hookChildProcess,\n verifyENOENT,\n verifyENOENTSync,\n notFoundError,\n};\n","'use strict';\n\nconst cp = require('child_process');\nconst parse = require('./lib/parse');\nconst enoent = require('./lib/enoent');\n\nfunction spawn(command, args, options) {\n // Parse the arguments\n const parsed = parse(command, args, options);\n\n // Spawn the child process\n const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);\n\n // Hook into child process \"exit\" event to emit an error if the command\n // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16\n enoent.hookChildProcess(spawned, parsed);\n\n return spawned;\n}\n\nfunction spawnSync(command, args, options) {\n // Parse the arguments\n const parsed = parse(command, args, options);\n\n // Spawn the child process\n const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);\n\n // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16\n result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);\n\n return result;\n}\n\nmodule.exports = spawn;\nmodule.exports.spawn = spawn;\nmodule.exports.sync = spawnSync;\n\nmodule.exports._parse = parse;\nmodule.exports._enoent = enoent;\n","import { JSONRPCMessageSchema } from '../types.js';\n/**\n * Buffers a continuous stdio stream into discrete JSON-RPC messages.\n */\nexport class ReadBuffer {\n append(chunk) {\n this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk;\n }\n readMessage() {\n if (!this._buffer) {\n return null;\n }\n const index = this._buffer.indexOf('\\n');\n if (index === -1) {\n return null;\n }\n const line = this._buffer.toString('utf8', 0, index).replace(/\\r$/, '');\n this._buffer = this._buffer.subarray(index + 1);\n return deserializeMessage(line);\n }\n clear() {\n this._buffer = undefined;\n }\n}\nexport function deserializeMessage(line) {\n return JSONRPCMessageSchema.parse(JSON.parse(line));\n}\nexport function serializeMessage(message) {\n return JSON.stringify(message) + '\\n';\n}\n//# sourceMappingURL=stdio.js.map","import spawn from 'cross-spawn';\nimport process from 'node:process';\nimport { PassThrough } from 'node:stream';\nimport { ReadBuffer, serializeMessage } from '../shared/stdio.js';\n/**\n * Environment variables to inherit by default, if an environment is not explicitly given.\n */\nexport const DEFAULT_INHERITED_ENV_VARS = process.platform === 'win32'\n ? [\n 'APPDATA',\n 'HOMEDRIVE',\n 'HOMEPATH',\n 'LOCALAPPDATA',\n 'PATH',\n 'PROCESSOR_ARCHITECTURE',\n 'SYSTEMDRIVE',\n 'SYSTEMROOT',\n 'TEMP',\n 'USERNAME',\n 'USERPROFILE',\n 'PROGRAMFILES'\n ]\n : /* list inspired by the default env inheritance of sudo */\n ['HOME', 'LOGNAME', 'PATH', 'SHELL', 'TERM', 'USER'];\n/**\n * Returns a default environment object including only environment variables deemed safe to inherit.\n */\nexport function getDefaultEnvironment() {\n const env = {};\n for (const key of DEFAULT_INHERITED_ENV_VARS) {\n const value = process.env[key];\n if (value === undefined) {\n continue;\n }\n if (value.startsWith('()')) {\n // Skip functions, which are a security risk.\n continue;\n }\n env[key] = value;\n }\n return env;\n}\n/**\n * Client transport for stdio: this will connect to a server by spawning a process and communicating with it over stdin/stdout.\n *\n * This transport is only available in Node.js environments.\n */\nexport class StdioClientTransport {\n constructor(server) {\n this._readBuffer = new ReadBuffer();\n this._stderrStream = null;\n this._serverParams = server;\n if (server.stderr === 'pipe' || server.stderr === 'overlapped') {\n this._stderrStream = new PassThrough();\n }\n }\n /**\n * Starts the server process and prepares to communicate with it.\n */\n async start() {\n if (this._process) {\n throw new Error('StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.');\n }\n return new Promise((resolve, reject) => {\n this._process = spawn(this._serverParams.command, this._serverParams.args ?? [], {\n // merge default env with server env because mcp server needs some env vars\n env: {\n ...getDefaultEnvironment(),\n ...this._serverParams.env\n },\n stdio: ['pipe', 'pipe', this._serverParams.stderr ?? 'inherit'],\n shell: false,\n windowsHide: process.platform === 'win32',\n cwd: this._serverParams.cwd\n });\n this._process.on('error', error => {\n reject(error);\n this.onerror?.(error);\n });\n this._process.on('spawn', () => {\n resolve();\n });\n this._process.on('close', _code => {\n this._process = undefined;\n this.onclose?.();\n });\n this._process.stdin?.on('error', error => {\n this.onerror?.(error);\n });\n this._process.stdout?.on('data', chunk => {\n this._readBuffer.append(chunk);\n this.processReadBuffer();\n });\n this._process.stdout?.on('error', error => {\n this.onerror?.(error);\n });\n if (this._stderrStream && this._process.stderr) {\n this._process.stderr.pipe(this._stderrStream);\n }\n });\n }\n /**\n * The stderr stream of the child process, if `StdioServerParameters.stderr` was set to \"pipe\" or \"overlapped\".\n *\n * If stderr piping was requested, a PassThrough stream is returned _immediately_, allowing callers to\n * attach listeners before the start method is invoked. This prevents loss of any early\n * error output emitted by the child process.\n */\n get stderr() {\n if (this._stderrStream) {\n return this._stderrStream;\n }\n return this._process?.stderr ?? null;\n }\n /**\n * The child process pid spawned by this transport.\n *\n * This is only available after the transport has been started.\n */\n get pid() {\n return this._process?.pid ?? null;\n }\n processReadBuffer() {\n while (true) {\n try {\n const message = this._readBuffer.readMessage();\n if (message === null) {\n break;\n }\n this.onmessage?.(message);\n }\n catch (error) {\n this.onerror?.(error);\n }\n }\n }\n async close() {\n if (this._process) {\n const processToClose = this._process;\n this._process = undefined;\n const closePromise = new Promise(resolve => {\n processToClose.once('close', () => {\n resolve();\n });\n });\n try {\n processToClose.stdin?.end();\n }\n catch {\n // ignore\n }\n await Promise.race([closePromise, new Promise(resolve => setTimeout(resolve, 2000).unref())]);\n if (processToClose.exitCode === null) {\n try {\n processToClose.kill('SIGTERM');\n }\n catch {\n // ignore\n }\n await Promise.race([closePromise, new Promise(resolve => setTimeout(resolve, 2000).unref())]);\n }\n if (processToClose.exitCode === null) {\n try {\n processToClose.kill('SIGKILL');\n }\n catch {\n // ignore\n }\n }\n }\n this._readBuffer.clear();\n }\n send(message) {\n return new Promise(resolve => {\n if (!this._process?.stdin) {\n throw new Error('Not connected');\n }\n const json = serializeMessage(message);\n if (this._process.stdin.write(json)) {\n resolve();\n }\n else {\n this._process.stdin.once('drain', resolve);\n }\n });\n }\n}\n//# sourceMappingURL=stdio.js.map","import { z } from \"zod\";\nimport { executeAction, getActionCredentialRequirements, getRunSignal, getWorkflowRunHandle, normalizeCredentialList, registerWorkflowRunGetter, runWithMcpCredentialContext } from \"@keystrokehq/action\";\nimport { captureConsole, logSystem, withSpan } from \"@keystrokehq/tracing\";\nimport { resolveActionCredentials } from \"@keystrokehq/credentials\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n//#region src/run-canceled-error.ts\nvar RunCanceledError = class extends Error {\n\tconstructor(runId) {\n\t\tsuper(runId ? `Workflow run ${runId} was canceled` : \"Workflow run was canceled\");\n\t\tthis.name = \"RunCanceledError\";\n\t}\n};\nfunction isRunCanceledError(error) {\n\treturn error instanceof RunCanceledError;\n}\n//#endregion\n//#region src/workflow-definition.ts\nconst zodSchema = z.custom((v) => v instanceof z.ZodType, \"must be a Zod schema\");\n/** Runtime validation for an unbranded workflow definition. */\nconst workflowCoreSchema = z.object({\n\tslug: z.string().trim().min(1),\n\tname: z.string().optional(),\n\tdescription: z.string().optional(),\n\tsubscription: z.object({ mode: z.enum([\"system\", \"subscribable\"]).optional() }).optional(),\n\tinput: zodSchema,\n\toutput: zodSchema,\n\trun: z.function()\n});\nconst WORKFLOW = Symbol.for(\"keystroke.workflow\");\n/**\n* Validates brand + shape via `workflowCoreSchema` so discovery and guards\n* reject malformed definitions.\n*/\nfunction isWorkflow(value) {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tif (!(WORKFLOW in value) || value[WORKFLOW] !== true) return false;\n\treturn workflowCoreSchema.safeParse(value).success;\n}\n//#endregion\n//#region src/define-workflow.ts\nfunction defineWorkflow(def) {\n\tconst result = workflowCoreSchema.safeParse(def);\n\tif (!result.success) throw new Error(`Invalid workflow definition: ${formatIssues(result.error.issues)}`);\n\treturn {\n\t\t...result.data,\n\t\t[WORKFLOW]: true\n\t};\n}\nfunction formatIssues(issues) {\n\treturn issues.map((issue) => {\n\t\treturn `${issue.path.length > 0 ? `${issue.path.join(\".\")}: ` : \"\"}${issue.message}`;\n\t}).join(\"; \");\n}\n//#endregion\n//#region src/replay/error.ts\nfunction serializeWorkflowError(error) {\n\tif (error instanceof Error) return {\n\t\tname: error.name,\n\t\tmessage: error.message\n\t};\n\treturn { message: String(error) };\n}\n/** Rebuild an Error from a recorded error so replay re-raises the same failure. */\nfunction deserializeWorkflowError(data) {\n\tconst serialized = data;\n\tconst error = new Error(serialized?.message ?? \"Workflow step failed\");\n\tif (serialized?.name) error.name = serialized.name;\n\treturn error;\n}\n//#endregion\n//#region src/replay/duration.ts\nconst UNIT_MS = {\n\tms: 1,\n\ts: 1e3,\n\tm: 6e4,\n\th: 36e5,\n\td: 864e5\n};\n/** Resolve a sleep duration to an absolute resume time. */\nfunction resolveResumeAt(duration, now = /* @__PURE__ */ new Date()) {\n\tif (duration instanceof Date) return duration;\n\tif (typeof duration === \"number\") return new Date(now.getTime() + Math.max(0, duration));\n\treturn new Date(now.getTime() + parseDurationToMs(duration));\n}\nfunction parseDurationToMs(value) {\n\tconst match = /^(\\d+(?:\\.\\d+)?)\\s*(ms|s|m|h|d)$/.exec(value.trim());\n\tif (!match) throw new Error(`Invalid sleep duration \"${value}\". Use a number of ms, a Date, or a string like \"5s\", \"10m\", \"1h\".`);\n\tconst amount = Number(match[1]);\n\tconst unit = match[2];\n\treturn Math.round(amount * UNIT_MS[unit]);\n}\n//#endregion\n//#region src/replay/events-consumer.ts\n/** Indexes replay events by correlationId for O(1) cache-hit checks during replay. */\nvar EventsConsumer = class {\n\tbyCorrelationId = /* @__PURE__ */ new Map();\n\tconstructor(events) {\n\t\tfor (const event of events) {\n\t\t\tif (!event.correlationId) continue;\n\t\t\tconst list = this.byCorrelationId.get(event.correlationId);\n\t\t\tif (list) list.push(event);\n\t\t\telse this.byCorrelationId.set(event.correlationId, [event]);\n\t\t}\n\t}\n\tevents(correlationId) {\n\t\treturn this.byCorrelationId.get(correlationId) ?? [];\n\t}\n\thasEventType(correlationId, type) {\n\t\treturn this.events(correlationId).some((event) => event.type === type);\n\t}\n\t/**\n\t* Cache lookup for a step. Returns the recorded output on a `step_completed`,\n\t* re-raises the recorded error on a terminal `step_failed` (so a permanently\n\t* failed step is not re-executed), and otherwise reports a miss — including\n\t* when only `step_retrying` events exist (the step re-runs on the next pass).\n\t*/\n\tgetStepResult(correlationId) {\n\t\tconst events = this.events(correlationId);\n\t\tconst failed = events.find((event) => event.type === \"step_failed\");\n\t\tif (failed) throw deserializeWorkflowError(failed.data);\n\t\tconst completed = events.find((event) => event.type === \"step_completed\");\n\t\tif (completed) return {\n\t\t\tcompleted: true,\n\t\t\tresult: completed.data\n\t\t};\n\t\treturn { completed: false };\n\t}\n\t/** Number of prior `step_retrying` events recorded for a step (= failed attempts so far). */\n\tcountRetrying(correlationId) {\n\t\treturn this.events(correlationId).filter((event) => event.type === \"step_retrying\").length;\n\t}\n\tisSleepCompleted(correlationId) {\n\t\treturn this.hasEventType(correlationId, \"sleep_completed\");\n\t}\n\t/** Returns the persisted resumeAt for a scheduled-but-not-completed sleep, if any. */\n\tgetSleepResumeAt(correlationId) {\n\t\tconst scheduled = this.events(correlationId).find((event) => event.type === \"sleep_scheduled\");\n\t\tif (!scheduled) return;\n\t\tconst data = scheduled.data;\n\t\treturn data?.resumeAt ? new Date(data.resumeAt) : void 0;\n\t}\n\tgetHookToken(correlationId) {\n\t\treturn (this.events(correlationId).find((event) => event.type === \"hook_created\")?.data)?.token;\n\t}\n\tgetHookResult(correlationId) {\n\t\tconst resumed = this.events(correlationId).find((event) => event.type === \"hook_resumed\");\n\t\tif (!resumed) return { resolved: false };\n\t\treturn {\n\t\t\tresolved: true,\n\t\t\tpayload: resumed.data?.payload\n\t\t};\n\t}\n};\n//#endregion\n//#region src/replay/suspension.ts\n/** A promise that never settles — returned by a suspending primitive so the body parks. */\nfunction createPendingPromise() {\n\treturn new Promise(() => {});\n}\n/**\n* Collects pending items requested within a single tick and resolves once, so\n* parallel suspensions (e.g. Promise.all of two sleeps) batch into one suspension.\n*/\nvar SuspensionCoordinator = class {\n\titems = /* @__PURE__ */ new Map();\n\tscheduled = false;\n\tresolve;\n\tpromise;\n\tconstructor() {\n\t\tthis.promise = new Promise((resolve) => {\n\t\t\tthis.resolve = resolve;\n\t\t});\n\t}\n\trequest(item) {\n\t\tthis.items.set(item.correlationId, item);\n\t\tif (!this.scheduled) {\n\t\t\tthis.scheduled = true;\n\t\t\tqueueMicrotask(() => {\n\t\t\t\tthis.resolve([...this.items.values()]);\n\t\t\t});\n\t\t}\n\t}\n\twaitForSuspension() {\n\t\treturn this.promise;\n\t}\n};\n//#endregion\n//#region src/replay/replay-context.ts\nfunction createReplayState(params) {\n\treturn {\n\t\trunId: params.runId,\n\t\tconsumer: params.consumer,\n\t\tcoordinator: params.coordinator,\n\t\teventLog: params.eventLog,\n\t\tnewEvents: [],\n\t\tnow: params.now ?? /* @__PURE__ */ new Date(),\n\t\thookBaseUrl: params.hookBaseUrl,\n\t\tsleepCounter: 0,\n\t\thookCounter: 0,\n\t\tstepOccurrences: /* @__PURE__ */ new Map(),\n\t\tstepCorrelationIds: /* @__PURE__ */ new Set()\n\t};\n}\n/**\n* Allocate the correlation id for a step. An explicit `.stepId(x)` maps to\n* `step:x` (and must be unique within a run); otherwise the key is\n* `step:<actionKey>#<occurrence>` so that two calls to the same action get\n* distinct, replay-stable ids and inserting an unrelated call never shifts the\n* ids of later calls (unlike a single global ordinal).\n*/\nfunction nextStepCorrelationId(state, actionKey, explicitId) {\n\tif (explicitId !== void 0) {\n\t\tconst correlationId = `step:${explicitId}`;\n\t\tif (state.stepCorrelationIds.has(correlationId)) throw new Error(`Duplicate step id \"${explicitId}\" in workflow run ${state.runId}`);\n\t\tstate.stepCorrelationIds.add(correlationId);\n\t\treturn correlationId;\n\t}\n\tconst occurrence = state.stepOccurrences.get(actionKey) ?? 0;\n\tstate.stepOccurrences.set(actionKey, occurrence + 1);\n\tconst correlationId = `step:${actionKey}#${occurrence}`;\n\tstate.stepCorrelationIds.add(correlationId);\n\treturn correlationId;\n}\nfunction createSleep(state) {\n\treturn function sleep(duration) {\n\t\tconst correlationId = `sleep#${state.sleepCounter++}`;\n\t\tif (state.consumer.isSleepCompleted(correlationId)) return Promise.resolve();\n\t\tconst scheduledResumeAt = state.consumer.getSleepResumeAt(correlationId);\n\t\tconst resumeAt = scheduledResumeAt ?? resolveResumeAt(duration, state.now);\n\t\tif (scheduledResumeAt && resumeAt.getTime() <= state.now.getTime()) {\n\t\t\tstate.newEvents.push({\n\t\t\t\tid: `sleep_completed:${state.runId}:${correlationId}`,\n\t\t\t\trunId: state.runId,\n\t\t\t\ttype: \"sleep_completed\",\n\t\t\t\tcorrelationId\n\t\t\t});\n\t\t\treturn Promise.resolve();\n\t\t}\n\t\tif (!scheduledResumeAt) state.newEvents.push({\n\t\t\tid: `sleep_scheduled:${state.runId}:${correlationId}`,\n\t\t\trunId: state.runId,\n\t\t\ttype: \"sleep_scheduled\",\n\t\t\tcorrelationId,\n\t\t\tdata: { resumeAt: resumeAt.toISOString() }\n\t\t});\n\t\tstate.coordinator.request({\n\t\t\tkind: \"sleep\",\n\t\t\tcorrelationId,\n\t\t\tresumeAt\n\t\t});\n\t\treturn createPendingPromise();\n\t};\n}\nfunction createHook(state) {\n\treturn function hook(options) {\n\t\tconst correlationId = `hook#${state.hookCounter++}`;\n\t\tconst token = options?.token ?? state.consumer.getHookToken(correlationId) ?? `hook_${crypto.randomUUID()}`;\n\t\treturn {\n\t\t\ttoken,\n\t\t\tresumeUrl: state.hookBaseUrl ? `${state.hookBaseUrl}/hooks/${token}/resume` : `/hooks/${token}/resume`,\n\t\t\tthen(onFulfilled, onRejected) {\n\t\t\t\tconst result = state.consumer.getHookResult(correlationId);\n\t\t\t\tif (result.resolved) {\n\t\t\t\t\tconst payload = options?.schema ? options.schema.parse(result.payload) : result.payload;\n\t\t\t\t\treturn Promise.resolve(payload).then(onFulfilled, onRejected);\n\t\t\t\t}\n\t\t\t\tif (!state.consumer.hasEventType(correlationId, \"hook_created\")) state.newEvents.push({\n\t\t\t\t\tid: `hook_created:${state.runId}:${correlationId}`,\n\t\t\t\t\trunId: state.runId,\n\t\t\t\t\ttype: \"hook_created\",\n\t\t\t\t\tcorrelationId,\n\t\t\t\t\tdata: { token }\n\t\t\t\t});\n\t\t\t\tstate.coordinator.request({\n\t\t\t\t\tkind: \"hook\",\n\t\t\t\t\tcorrelationId,\n\t\t\t\t\ttoken\n\t\t\t\t});\n\t\t\t\treturn createPendingPromise().then(onFulfilled, onRejected);\n\t\t\t}\n\t\t};\n\t};\n}\n//#endregion\n//#region src/run-durable-step.ts\n/**\n* Shared durable-step shell: resolve a stable `correlation_id`, short-circuit\n* from the event log on a cache hit, otherwise execute and append\n* `step_completed` immediately (per-step crash durability). A thrown step\n* appends `step_retrying` (non-fatal, re-run on the next attempt) and\n* rethrows; the terminal `step_failed` is written by the job handler once the\n* queue exhausts retries.\n*/\nasync function runDurableStep(state, options) {\n\tconst { runId, consumer, eventLog } = state;\n\tgetRunSignal().throwIfAborted();\n\tconst correlationId = nextStepCorrelationId(state, options.key, options.id);\n\tconst cached = consumer.getStepResult(correlationId);\n\tconst metadata = {\n\t\trunId,\n\t\t[options.metadataKey]: options.key,\n\t\tcorrelationId\n\t};\n\tif (cached.completed) {\n\t\tawait withSpan({\n\t\t\tkind: options.kind,\n\t\t\tname: options.key,\n\t\t\trefId: `${runId}:${correlationId}`,\n\t\t\tmetadata: {\n\t\t\t\t...metadata,\n\t\t\t\treplayed: true\n\t\t\t}\n\t\t}, async () => {\n\t\t\tawait logSystem(\"info\", options.replayMessage, metadata);\n\t\t});\n\t\treturn options.parseCached ? options.parseCached(cached.result) : cached.result;\n\t}\n\treturn withSpan({\n\t\tkind: options.kind,\n\t\tname: options.key,\n\t\trefId: `${runId}:${correlationId}`,\n\t\tmetadata\n\t}, async () => captureConsole(async () => {\n\t\ttry {\n\t\t\tconst result = await options.execute(correlationId);\n\t\t\tawait eventLog.append({\n\t\t\t\tid: `step_completed:${runId}:${correlationId}`,\n\t\t\t\trunId,\n\t\t\t\ttype: \"step_completed\",\n\t\t\t\tcorrelationId,\n\t\t\t\tdata: result\n\t\t\t});\n\t\t\treturn result;\n\t\t} catch (error) {\n\t\t\tconst attempt = consumer.countRetrying(correlationId);\n\t\t\tawait eventLog.append({\n\t\t\t\tid: `step_retrying:${runId}:${correlationId}:${attempt}`,\n\t\t\t\trunId,\n\t\t\t\ttype: \"step_retrying\",\n\t\t\t\tcorrelationId,\n\t\t\t\tdata: serializeWorkflowError(error)\n\t\t\t});\n\t\t\tstate.failedCorrelationId = correlationId;\n\t\t\tthrow error;\n\t\t}\n\t}));\n}\n//#endregion\n//#region src/create-action-runner.ts\nfunction withCredentialScopeOverride(requirements, scope) {\n\tif (!requirements || !scope) return requirements;\n\treturn normalizeCredentialList(requirements).map((requirement) => ({\n\t\t...requirement,\n\t\tscope\n\t}));\n}\n/** Builds the per-run action runner; durability lives in {@link runDurableStep}. */\nfunction createActionRunner(state, options = {}) {\n\treturn (action, input, runOptions) => runDurableStep(state, {\n\t\tkind: \"action\",\n\t\tkey: action.slug,\n\t\tid: runOptions?.id,\n\t\tmetadataKey: \"actionKey\",\n\t\treplayMessage: \"action replayed from checkpoint\",\n\t\tparseCached: (cached) => action.output.parse(cached),\n\t\texecute: async (correlationId) => {\n\t\t\tconst requirements = withCredentialScopeOverride(getActionCredentialRequirements(action), runOptions?.credentialScope);\n\t\t\tconst credentials = requirements?.length ? await resolveActionCredentials(requirements, {\n\t\t\t\tresolveCredentials: options.resolveCredentials,\n\t\t\t\tcontext: options.credentialContext,\n\t\t\t\toauthAdapter: options.oauthAdapter,\n\t\t\t\tconsumer: {\n\t\t\t\t\tkind: \"action\",\n\t\t\t\t\tname: action.slug,\n\t\t\t\t\tid: correlationId\n\t\t\t\t}\n\t\t\t}) : {};\n\t\t\treturn runWithMcpCredentialContext({\n\t\t\t\t...options.mcpCredentialContext,\n\t\t\t\tconsumerId: correlationId\n\t\t\t}, () => executeAction(action, input, credentials));\n\t\t}\n\t});\n}\n//#endregion\n//#region src/create-agent-step-runner.ts\n/**\n* Builds the per-run agent runner: each `agent.prompt()` in a workflow body\n* becomes a durable step keyed `step:<agentKey>#<occurrence>` (same scheme as\n* actions). The actual prompt execution is delegated to `runAgent`, supplied\n* by the host (server) via `executeWorkflow({ runAgent })`.\n*/\nfunction createAgentStepRunner(state, runAgent) {\n\treturn (agent, input, options) => {\n\t\tconst slug = agent.slug;\n\t\treturn runDurableStep(state, {\n\t\t\tkind: \"agent_session\",\n\t\t\tkey: slug,\n\t\t\tid: options?.id,\n\t\t\tmetadataKey: \"agentKey\",\n\t\t\treplayMessage: \"agent step replayed from checkpoint\",\n\t\t\texecute: (_correlationId) => runAgent(agent, input, options?.runPrompt)\n\t\t});\n\t};\n}\n//#endregion\n//#region src/create-llm-step-runner.ts\n/**\n* Builds the per-run LLM runner: each `promptLlm()` in a workflow body becomes a\n* durable step keyed `step:promptLlm#<occurrence>`. The actual LLM call is\n* delegated to `runLlm`, supplied by the host (server) via `executeWorkflow({ runLlm })`.\n*/\nfunction createLlmStepRunner(state, runLlm) {\n\treturn (opts) => runDurableStep(state, {\n\t\tkind: \"llm\",\n\t\tkey: \"promptLlm\",\n\t\tid: opts.stepId,\n\t\tmetadataKey: \"llmKey\",\n\t\treplayMessage: \"llm step replayed from checkpoint\",\n\t\tparseCached: (cached) => opts.outputSchema ? opts.outputSchema.parse(cached) : cached,\n\t\texecute: (_correlationId) => runLlm(opts)\n\t});\n}\n//#endregion\n//#region src/run-context.ts\nconst storage = new AsyncLocalStorage();\nregisterWorkflowRunGetter(() => {\n\tconst store = storage.getStore();\n\tif (!store) return;\n\treturn {\n\t\tactionRunner: store.actionRunner,\n\t\tagentRunner: store.agentRunner,\n\t\tllmRunner: store.llmRunner\n\t};\n});\nfunction runWithWorkflowContext(store, fn) {\n\treturn storage.run(store, fn);\n}\n//#endregion\n//#region src/replay/memory-event-log.ts\n/** In-memory durable log for inline execution and tests. */\nvar MemoryEventLog = class {\n\tevents = [];\n\tids = /* @__PURE__ */ new Set();\n\tasync append(event) {\n\t\tconst id = event.id ?? crypto.randomUUID();\n\t\tif (this.ids.has(id)) return false;\n\t\tthis.ids.add(id);\n\t\tthis.events.push({\n\t\t\tid,\n\t\t\trunId: event.runId,\n\t\t\tseq: this.events.length,\n\t\t\ttype: event.type,\n\t\t\tcorrelationId: event.correlationId ?? null,\n\t\t\tdata: event.data ?? null\n\t\t});\n\t\treturn true;\n\t}\n\tasync listReplay(runId) {\n\t\treturn this.events.filter((event) => event.runId === runId).map((event) => ({ ...event }));\n\t}\n};\n//#endregion\n//#region src/execute-workflow.ts\n/**\n* The single way to run a workflow: replay its event log from the top, execute\n* un-cached primitives, and either complete/fail or suspend at the first\n* un-satisfied sleep/hook. New events (sleep_scheduled/sleep_completed/\n* hook_created/run_completed/run_failed) are flushed before returning.\n*\n* Durability comes entirely from the log — a suspended run resumes by calling\n* this again with the same `runId` and event log once the sleep is due or the\n* hook is resumed.\n*/\nasync function executeWorkflow(workflow, input, options = {}) {\n\tconst runId = options.runId ?? crypto.randomUUID();\n\tconst eventLog = options.eventLog ?? new MemoryEventLog();\n\tconst signal = getRunSignal();\n\tconst consumer = new EventsConsumer(await eventLog.listReplay(runId));\n\tconst coordinator = new SuspensionCoordinator();\n\tconst state = createReplayState({\n\t\trunId,\n\t\tconsumer,\n\t\tcoordinator,\n\t\teventLog,\n\t\thookBaseUrl: options.hookBaseUrl,\n\t\tnow: options.now\n\t});\n\tconst actionRunner = createActionRunner(state, {\n\t\tresolveCredentials: options.resolveCredentials,\n\t\tcredentialContext: options.credentialContext,\n\t\toauthAdapter: options.oauthAdapter,\n\t\tmcpCredentialContext: { assignmentTarget: {\n\t\t\ttype: \"workflow\",\n\t\t\tkey: workflow.slug\n\t\t} }\n\t});\n\tconst ctx = {\n\t\trunId,\n\t\tsleep: createSleep(state),\n\t\thook: createHook(state),\n\t\t...options.context\n\t};\n\tconst agentRunner = options.runAgent ? createAgentStepRunner(state, options.runAgent) : void 0;\n\tconst llmRunner = options.runLlm ? createLlmStepRunner(state, options.runLlm) : void 0;\n\tconst validatedInput = workflow.input.parse(input);\n\tconst bodyPromise = runWithWorkflowContext({\n\t\tactionRunner,\n\t\tagentRunner,\n\t\tllmRunner,\n\t\trunId\n\t}, () => captureConsole(async () => workflow.run(validatedInput, ctx)));\n\tlet onAbort;\n\tconst waitForAbort = signal.aborted ? Promise.resolve({ type: \"canceled\" }) : new Promise((resolve) => {\n\t\tonAbort = () => resolve({ type: \"canceled\" });\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t});\n\tconst outcome = await Promise.race([\n\t\tbodyPromise.then((output) => ({\n\t\t\ttype: \"done\",\n\t\t\toutput\n\t\t}), (error) => ({\n\t\t\ttype: \"error\",\n\t\t\terror\n\t\t})),\n\t\tcoordinator.waitForSuspension().then((items) => ({\n\t\t\ttype: \"suspended\",\n\t\t\titems\n\t\t})),\n\t\twaitForAbort\n\t]);\n\tif (onAbort) signal.removeEventListener(\"abort\", onAbort);\n\tlet result;\n\tif (outcome.type === \"suspended\") {\n\t\tbodyPromise.catch(() => {});\n\t\tresult = {\n\t\t\tstatus: \"suspended\",\n\t\t\titems: outcome.items\n\t\t};\n\t} else if (outcome.type === \"done\") {\n\t\tconst output = workflow.output.parse(outcome.output);\n\t\tstate.newEvents.push({\n\t\t\tid: `run_completed:${runId}`,\n\t\t\trunId,\n\t\t\ttype: \"run_completed\",\n\t\t\tdata: { output }\n\t\t});\n\t\tresult = {\n\t\t\tstatus: \"completed\",\n\t\t\toutput\n\t\t};\n\t} else if (outcome.type === \"canceled\" || isRunCanceledError(outcome.error)) {\n\t\tbodyPromise.catch(() => {});\n\t\tstate.newEvents.push({\n\t\t\tid: `run_canceled:${runId}`,\n\t\t\trunId,\n\t\t\ttype: \"run_canceled\"\n\t\t});\n\t\tresult = { status: \"canceled\" };\n\t} else result = {\n\t\tstatus: \"failed\",\n\t\terror: outcome.error,\n\t\tfailedCorrelationId: state.failedCorrelationId\n\t};\n\tfor (const event of state.newEvents) await eventLog.append(event);\n\treturn result;\n}\n//#endregion\n//#region src/prompt-llm.ts\nfunction promptLlm(prompt, opts) {\n\tconst handle = getWorkflowRunHandle();\n\tif (!handle?.llmRunner) throw new Error(\"promptLlm must run inside a workflow with an injected llm executor (executeWorkflow({ runLlm })).\");\n\treturn handle.llmRunner({\n\t\tprompt,\n\t\t...opts\n\t});\n}\n//#endregion\nexport { MemoryEventLog, RunCanceledError, defineWorkflow, deserializeWorkflowError, executeWorkflow, isRunCanceledError, isWorkflow, promptLlm, serializeWorkflowError };\n\n//# sourceMappingURL=index.mjs.map","import { parseCronExpression } from \"cron-schedule\";\nimport { z } from \"zod\";\nimport { isWorkflow } from \"@keystrokehq/workflow\";\n//#region src/cron/cron-schedule.ts\n/**\n* Validates and brands a cron expression. Accepts anything the `cron-schedule`\n* engine accepts (5/6 fields, named months/weekdays, `@daily`-style nicknames)\n* so authoring validation never rejects a schedule the scheduler can run. The\n* `.brand()` makes `CronSchedule` nominally distinct from a plain `string`, so\n* a raw string can't be passed where a validated schedule is expected.\n*/\nconst cronScheduleSchema = z.string().trim().min(1, \"cron schedule must be a non-empty string\").refine(isParseableCron, \"must be a valid cron expression\").brand();\n/** Parse/validate an arbitrary value into a branded `CronSchedule` (throws on failure). */\nfunction parseCronSchedule(value) {\n\treturn cronScheduleSchema.parse(value);\n}\n/**\n* Resolves the effective schedule for an attachment, applying overrides by\n* precedence: per-attachment override → global override → the authored\n* schedule. Pure string precedence — no cron parsing.\n*/\nfunction resolveCronSchedule(attachmentId, schedule, options) {\n\treturn options.attachmentScheduleOverrides?.[attachmentId] ?? options.cronScheduleOverride ?? schedule;\n}\n/** Parse a schedule into a `cron-schedule` `Cron` instance (throws on invalid input). */\nfunction parseTriggerSchedule(schedule) {\n\treturn toCron(schedule);\n}\n/** The next time the schedule fires at or after `from`. */\nfunction nextTriggerRunAt(schedule, from = /* @__PURE__ */ new Date()) {\n\treturn toCron(schedule).getNextDate(from);\n}\n/**\n* Single touchpoint for the `cron-schedule` library — every parse, validation,\n* and next-run calculation in this package goes through here.\n*/\nfunction toCron(schedule) {\n\treturn parseCronExpression(schedule);\n}\nfunction isParseableCron(value) {\n\ttry {\n\t\ttoCron(value);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n//#endregion\n//#region src/attachment-definition.ts\nconst zodSchema = z.custom((v) => v instanceof z.ZodType, \"must be a Zod schema\");\nconst workflowSchema = z.custom((v) => isWorkflow(v), \"must be defineWorkflow(...)\");\nconst agentSchema = z.custom((v) => typeof v === \"object\" && v !== null && typeof v.slug === \"string\" && v.slug.trim().length > 0 && typeof v.prompt === \"function\", \"must be defineAgent(...)\");\nconst promptSchema = z.union([z.string(), z.function()]);\n/** backwards-compat: normalize legacy `key` fields to canonical `slug` before validation. */\nfunction normalizeLegacySlugFields(value) {\n\tif (typeof value !== \"object\" || value === null) return value;\n\tconst next = { ...value };\n\tif (typeof next.slug !== \"string\" && typeof next.key === \"string\") next.slug = next.key;\n\tdelete next.key;\n\tif (typeof next.source === \"object\" && next.source !== null) next.source = normalizeLegacySlugFields(next.source);\n\treturn next;\n}\nconst slugField = z.string().trim().min(1);\nconst optionalTextField = z.string().optional();\nconst baseSourceShape = {\n\tslug: slugField,\n\tname: optionalTextField,\n\tdescription: optionalTextField,\n\tattach: z.function()\n};\nconst webhookSourceSchema = z.object({\n\tkind: z.literal(\"webhook\"),\n\t...baseSourceShape,\n\tendpoint: z.string().min(1),\n\trequest: zodSchema,\n\tfilter: zodSchema.optional(),\n\tpasses: z.function()\n});\nconst cronSourceSchema = z.object({\n\tkind: z.literal(\"cron\"),\n\t...baseSourceShape,\n\tschedule: cronScheduleSchema\n});\nconst pollSourceSchema = z.object({\n\tkind: z.literal(\"poll\"),\n\t...baseSourceShape,\n\tid: z.string().optional(),\n\tschedule: cronScheduleSchema,\n\trun: z.function(),\n\tfilters: z.array(z.function()),\n\tpasses: z.function()\n});\n/** Runtime validation for a trigger source (webhook | cron | poll). */\nconst triggerSourceSchema = z.preprocess(normalizeLegacySlugFields, z.discriminatedUnion(\"kind\", [\n\twebhookSourceSchema,\n\tcronSourceSchema,\n\tpollSourceSchema\n]));\nconst workflowAttachmentSchema = z.object({\n\tslug: slugField,\n\tname: optionalTextField,\n\tdescription: optionalTextField,\n\tsource: triggerSourceSchema,\n\ttarget: z.literal(\"workflow\"),\n\tworkflow: workflowSchema,\n\ttransform: z.function().optional()\n});\nconst agentAttachmentSchema = z.object({\n\tslug: slugField,\n\tname: optionalTextField,\n\tdescription: optionalTextField,\n\tsource: triggerSourceSchema,\n\ttarget: z.literal(\"agent\"),\n\tagent: agentSchema,\n\tprompt: promptSchema\n});\nconst triggerAttachmentCoreSchemaBase = z.discriminatedUnion(\"target\", [workflowAttachmentSchema, agentAttachmentSchema]);\n/** Runtime validation for an unbranded trigger attachment. */\nconst triggerAttachmentCoreSchema = z.preprocess(normalizeLegacySlugFields, triggerAttachmentCoreSchemaBase);\nconst TRIGGER_ATTACHMENT = Symbol.for(\"keystroke.triggerAttachment\");\n/**\n* Validates brand + shape via `triggerAttachmentCoreSchema` so server discovery\n* rejects unbranded or malformed attachments.\n*/\nfunction isTriggerAttachment(value) {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tif (!(TRIGGER_ATTACHMENT in value) || value[TRIGGER_ATTACHMENT] !== true) return false;\n\treturn triggerAttachmentCoreSchema.safeParse(value).success;\n}\nfunction isWorkflowTriggerAttachment(attachment) {\n\treturn attachment.target === \"workflow\";\n}\nfunction isAgentTriggerAttachment(attachment) {\n\treturn attachment.target === \"agent\";\n}\n//#endregion\n//#region src/trigger-slug.ts\n/** Resolve slug from authoring options (`slug` preferred, `key` fallback). */\nfunction resolveAuthoringSlug(input, label = \"trigger\") {\n\tconst slug = input.slug?.trim() || input.key?.trim();\n\tif (!slug) throw new Error(`${label} requires a non-empty slug`);\n\treturn slug;\n}\n/** Composite attachment slug `{sourceSlug}:{targetSlug}`. */\nfunction attachmentSlugFrom(sourceSlug, targetSlug) {\n\treturn `${sourceSlug}:${targetSlug}`;\n}\n/** Read slug from a trigger source (`slug` preferred, legacy `key` fallback). */\nfunction sourceSlugFrom(source) {\n\tconst slug = source.slug?.trim() || source.key?.trim();\n\tif (!slug) throw new Error(\"Trigger source requires slug or legacy key\");\n\treturn slug;\n}\n/** Read slug from a trigger attachment (`slug` preferred, legacy `key` fallback). */\nfunction attachmentSlugFromRecord(attachment) {\n\tconst slug = attachment.slug?.trim() || attachment.key?.trim();\n\tif (!slug) throw new Error(\"Trigger attachment requires slug or legacy key\");\n\treturn slug;\n}\n/** Source slug prefix from a composite attachment slug. */\nfunction triggerSourceSlugFromAttachmentSlug(attachmentSlug) {\n\tconst separator = attachmentSlug.indexOf(\":\");\n\treturn separator === -1 ? attachmentSlug : attachmentSlug.slice(0, separator);\n}\n/** Target slug suffix from a composite attachment slug. */\nfunction triggerTargetSlugFromAttachmentSlug(attachmentSlug) {\n\tconst separator = attachmentSlug.indexOf(\":\");\n\treturn separator === -1 ? attachmentSlug : attachmentSlug.slice(separator + 1);\n}\n//#endregion\n//#region src/attachment-slug.ts\nfunction workflowSlugFromDefinition(workflow) {\n\tconst slug = workflow.slug?.trim();\n\tif (!slug) throw new Error(\"Workflow definition requires a non-empty slug\");\n\treturn slug;\n}\nfunction agentSlugFromAgent(agent) {\n\tconst slug = agent.slug?.trim();\n\tif (!slug) throw new Error(\"Agent definition requires a non-empty slug\");\n\treturn slug;\n}\n/** @deprecated Use {@link attachmentSlugFrom}. */\nconst attachmentKeyFrom = attachmentSlugFrom;\n/** @deprecated Use {@link workflowSlugFromDefinition}. */\nconst workflowKeyFromDefinition = workflowSlugFromDefinition;\n/** @deprecated Use {@link agentSlugFromAgent}. */\nconst agentKeyFromAgent = agentSlugFromAgent;\n//#endregion\n//#region src/attach-options.ts\nfunction isAgentAttachOptions(options) {\n\treturn \"agent\" in options;\n}\n//#endregion\n//#region src/define-trigger-attachment.ts\n/**\n* Internal helper used by source `.attach()` factories. Validates the\n* attachment shape against `triggerAttachmentCoreSchema` and applies the\n* `TRIGGER_ATTACHMENT` brand.\n*/\nfunction defineTriggerAttachment(input) {\n\tconst result = triggerAttachmentCoreSchema.safeParse(input);\n\tif (!result.success) throw new Error(`Invalid trigger attachment: ${formatIssues(result.error.issues)}`);\n\treturn {\n\t\t...result.data,\n\t\t[TRIGGER_ATTACHMENT]: true\n\t};\n}\nfunction formatIssues(issues) {\n\treturn issues.map((issue) => {\n\t\treturn `${issue.path.length > 0 ? `${issue.path.join(\".\")}: ` : \"\"}${issue.message}`;\n\t}).join(\"; \");\n}\n//#endregion\n//#region src/trigger-meta.ts\nfunction triggerMetaFromSource(source) {\n\treturn {\n\t\t...source.name !== void 0 ? { name: source.name } : {},\n\t\t...source.description !== void 0 ? { description: source.description } : {}\n\t};\n}\nfunction triggerMetaFromAttachment(attachment) {\n\tconst name = attachment.name ?? attachment.source.name;\n\tconst description = attachment.description ?? attachment.source.description;\n\treturn {\n\t\t...name !== void 0 ? { name } : {},\n\t\t...description !== void 0 ? { description } : {}\n\t};\n}\nfunction triggerMetaRecordFromAttachment(attachment) {\n\tconst meta = triggerMetaFromAttachment(attachment);\n\treturn {\n\t\tname: meta.name ?? null,\n\t\tdescription: meta.description ?? null\n\t};\n}\n//#endregion\n//#region src/attach-from-source.ts\n/**\n* Hidden link from a chained `.attach(...)` result back to every attachment in the\n* same chain. Lets discovery expand a single default export into all fan-out targets.\n*/\nconst TRIGGER_ATTACHMENT_SIBLINGS = Symbol.for(\"keystroke.triggerAttachmentSiblings\");\nfunction buildAttachment(source, sourceSlug, options) {\n\tconst meta = triggerMetaFromSource(source);\n\tif (isAgentAttachOptions(options)) return defineTriggerAttachment({\n\t\tslug: attachmentSlugFrom(sourceSlug, agentSlugFromAgent(options.agent)),\n\t\t...meta,\n\t\tsource,\n\t\ttarget: \"agent\",\n\t\tagent: options.agent,\n\t\tprompt: options.prompt\n\t});\n\treturn defineTriggerAttachment({\n\t\tslug: attachmentSlugFrom(sourceSlug, workflowSlugFromDefinition(options.workflow)),\n\t\t...meta,\n\t\tsource,\n\t\ttarget: \"workflow\",\n\t\tworkflow: options.workflow,\n\t\ttransform: options.transform\n\t});\n}\nfunction chainableAttachment(source, sourceSlug, options, siblings) {\n\tconst attachment = buildAttachment(source, sourceSlug, options);\n\tconst group = [...siblings, attachment];\n\tObject.defineProperty(attachment, TRIGGER_ATTACHMENT_SIBLINGS, {\n\t\tvalue: group,\n\t\tenumerable: false,\n\t\tconfigurable: true\n\t});\n\tObject.defineProperty(attachment, \"attach\", {\n\t\tvalue: (next) => chainableAttachment(source, sourceSlug, next, group),\n\t\tenumerable: false,\n\t\tconfigurable: true\n\t});\n\treturn attachment;\n}\nfunction attachFromSource(source, sourceSlug, options) {\n\treturn chainableAttachment(source, sourceSlug, options, []);\n}\n/**\n* Flatten a trigger module's default export into its individual attachments —\n* a single `.attach(...)`, a `.attach(...).attach(...)` chain, or an array of either.\n*/\nfunction triggerAttachmentsFromExport(value) {\n\tif (Array.isArray(value)) return value.flatMap(triggerAttachmentsFromExport);\n\tif (value && typeof value === \"object\") {\n\t\tconst siblings = value[TRIGGER_ATTACHMENT_SIBLINGS];\n\t\tif (Array.isArray(siblings)) return siblings;\n\t}\n\treturn isTriggerAttachment(value) ? [value] : [];\n}\n//#endregion\n//#region src/trigger-match-schema.ts\nfunction matchShapeAndFilter(shape, filter, payload) {\n\tconst shaped = shape.safeParse(payload);\n\tif (!shaped.success) return { matched: false };\n\tif (filter && !filter.safeParse(shaped.data).success) return {\n\t\tmatched: true,\n\t\tdata: shaped.data,\n\t\tfilterRejected: true\n\t};\n\treturn {\n\t\tmatched: true,\n\t\tdata: shaped.data,\n\t\tfilterRejected: false\n\t};\n}\nfunction passesShapeAndFilter(shape, filter, payload) {\n\tconst result = matchShapeAndFilter(shape, filter, payload);\n\treturn result.matched && !result.filterRejected;\n}\nfunction matchWebhookPayload(raw, schemas) {\n\tconst matches = [];\n\tconst filterRejected = [];\n\tif (typeof z.fromJSONSchema !== \"function\") throw new Error(\"z.fromJSONSchema is required for JSON schema matching\");\n\tfor (const schema of schemas) {\n\t\tconst result = matchShapeAndFilter(z.fromJSONSchema(schema.requestSchema), schema.filterSchema ? z.fromJSONSchema(schema.filterSchema) : void 0, raw);\n\t\tif (!result.matched) continue;\n\t\tconst entry = {\n\t\t\tattachmentSlug: schema.attachmentSlug,\n\t\t\tdata: result.data\n\t\t};\n\t\tif (result.filterRejected) {\n\t\t\tfilterRejected.push(entry);\n\t\t\tcontinue;\n\t\t}\n\t\tmatches.push(entry);\n\t}\n\treturn {\n\t\tmatches,\n\t\tfilterRejected\n\t};\n}\n/** Live Zod validation for webhook `request` + optional Zod `filter` (in-process paths). */\nfunction passesTriggerMatch(shape, filter, payload) {\n\treturn passesShapeAndFilter(shape, filter, payload);\n}\n//#endregion\n//#region src/sources/webhook-source.ts\nfunction normalizeWebhookEndpoint(endpoint) {\n\treturn endpoint.replace(/^\\/+|\\/+$/g, \"\").replace(/^triggers\\/?/, \"\");\n}\nfunction webhookObjectSchema(schema) {\n\tif (schema instanceof z.ZodObject) return schema.loose();\n\treturn schema;\n}\n/**\n* Defines a webhook trigger source — fires its attached workflow when a request\n* hits `/triggers/{endpoint}` and satisfies `request` plus any optional `filter`.\n*\n* @param options.slug - Stable trigger source slug; attachment slug is `{slug}:{targetSlug}`.\n* @param options.key - **Deprecated.** Accepted for backwards-compatible definitions.\n* @param options.endpoint - Shared route suffix under `/triggers/` (e.g. `\"stripe\"`).\n*/\nfunction defineWebhookSource(options) {\n\tconst sourceSlug = resolveAuthoringSlug(options, \"defineWebhookSource\");\n\tconst endpoint = normalizeWebhookEndpoint(options.endpoint);\n\tif (!endpoint) throw new Error(\"defineWebhookSource requires a non-empty endpoint\");\n\tconst request = webhookObjectSchema(options.request);\n\tconst filter = options.filter ? webhookObjectSchema(options.filter) : void 0;\n\tconst source = {\n\t\tkind: \"webhook\",\n\t\tslug: sourceSlug,\n\t\t...options.name !== void 0 ? { name: options.name } : {},\n\t\t...options.description !== void 0 ? { description: options.description } : {},\n\t\tendpoint,\n\t\trequest,\n\t\tfilter,\n\t\tpasses(payload) {\n\t\t\treturn passesTriggerMatch(request, filter, payload);\n\t\t},\n\t\tattach(attachOptions) {\n\t\t\treturn attachFromSource(source, sourceSlug, attachOptions);\n\t\t}\n\t};\n\treturn source;\n}\n//#endregion\n//#region src/sources/cron-source.ts\n/**\n* Defines a cron trigger source — fires its attached workflow on a schedule.\n*\n* @param options.slug - Stable trigger source slug; attachment slug is `{slug}:{targetSlug}`.\n* @param options.key - **Deprecated.** Accepted for backwards-compatible definitions.\n* @param options.name - Optional human-readable name shown in the platform.\n* @param options.description - Optional short description shown in the platform.\n* @param options.schedule - A cron expression. Pass a 5-field literal (e.g.\n* `\"0 9 * * *\"`) for compile-time shape checking, or wrap with\n* `parseCronSchedule(...)` for 6-field, named (`MON`), or `@daily`-style\n* schedules. Validated at runtime; throws if the expression is invalid.\n* @example\n* defineCronSource({ slug: \"morning\", schedule: \"0 9 * * *\" }).attach({ workflow });\n*/\nfunction defineCronSource(options) {\n\tconst sourceSlug = resolveAuthoringSlug(options, \"defineCronSource\");\n\tconst schedule = parseCronSchedule(options.schedule);\n\tconst source = {\n\t\tkind: \"cron\",\n\t\tslug: sourceSlug,\n\t\t...options.name !== void 0 ? { name: options.name } : {},\n\t\t...options.description !== void 0 ? { description: options.description } : {},\n\t\tschedule,\n\t\tattach(attachOptions) {\n\t\t\treturn attachFromSource(source, sourceSlug, attachOptions);\n\t\t}\n\t};\n\treturn source;\n}\n//#endregion\n//#region src/sources/poll-source.ts\n/**\n* Defines a poll trigger source — runs `run` on a schedule and, when the result\n* passes any `.filter(...)`, fires the attached workflow with it.\n*\n* @param options.slug - Stable trigger source slug; attachment slug is `{slug}:{targetSlug}`.\n* @param options.key - **Deprecated.** Accepted for backwards-compatible definitions.\n* @param options.id - Optional group id; poll sources sharing an id poll together.\n* @param options.schedule - Cron expression for the poll cadence (see `defineCronSource`).\n* @param options.run - Produces the payload checked by `filter` and passed to the workflow.\n* @param options.filter - Source-level predicate; the workflow only fires when it returns true.\n* @example\n* definePollSource({ slug: \"inbox\", schedule: \"0 * * * *\", run: fetchInbox })\n* .filter((r) => r.length > 0)\n* .attach({ workflow });\n*/\nfunction definePollSource(options) {\n\tconst sourceSlug = resolveAuthoringSlug(options, \"definePollSource\");\n\tconst schedule = parseCronSchedule(options.schedule);\n\tconst filters = [];\n\tif (options.filter) filters.push(options.filter);\n\tconst source = {\n\t\tkind: \"poll\",\n\t\tslug: sourceSlug,\n\t\t...options.name !== void 0 ? { name: options.name } : {},\n\t\t...options.description !== void 0 ? { description: options.description } : {},\n\t\tid: options.id,\n\t\tschedule,\n\t\trun: options.run,\n\t\tfilters,\n\t\tpasses(payload) {\n\t\t\treturn source.filters.every((candidate) => candidate(payload));\n\t\t},\n\t\tattach(attachOptions) {\n\t\t\treturn attachFromSource(source, sourceSlug, attachOptions);\n\t\t}\n\t};\n\tconst chain = source;\n\tchain.filter = (fn) => {\n\t\tsource.filters.push(fn);\n\t\treturn chain;\n\t};\n\treturn chain;\n}\n//#endregion\n//#region src/ephemeral-match.ts\nfunction emptyObjectSchema() {\n\treturn {\n\t\ttype: \"object\",\n\t\tproperties: {},\n\t\trequired: []\n\t};\n}\nfunction setConstAtPath(schema, path, value) {\n\tconst [head, ...rest] = path;\n\tif (!head) return;\n\tif (!schema.required.includes(head)) schema.required.push(head);\n\tif (rest.length === 0) {\n\t\tschema.properties[head] = { const: value };\n\t\treturn;\n\t}\n\tconst existing = schema.properties[head];\n\tconst child = existing && typeof existing === \"object\" && existing.type === \"object\" ? existing : emptyObjectSchema();\n\tschema.properties[head] = child;\n\tsetConstAtPath(child, rest, value);\n}\n/**\n* Compiles a shallow `match` object into a JSON Schema usable as a stored webhook\n* `requestSchema`. Dots in keys are treated as path separators; an empty match\n* produces a schema that accepts any JSON object payload.\n*/\nfunction matchToJsonSchema(match) {\n\tconst schema = emptyObjectSchema();\n\tfor (const [path, value] of Object.entries(match)) setConstAtPath(schema, path.split(\".\").filter((segment) => segment.length > 0), value);\n\tif (schema.required.length === 0) return { type: \"object\" };\n\treturn schema;\n}\n//#endregion\n//#region src/interpolate-prompt.ts\nfunction resolvePath(payload, path) {\n\tlet current = payload;\n\tfor (const segment of path) {\n\t\tif (current === null || typeof current !== \"object\") return;\n\t\tcurrent = current[segment];\n\t}\n\treturn current;\n}\n/**\n* Resolves `{{path}}` / `{{payload.path}}` dot-path tokens in an ephemeral trigger\n* prompt against the webhook payload. Unresolved tokens are left untouched so the\n* agent can see what failed to bind.\n*/\nfunction interpolatePrompt(template, payload) {\n\treturn template.replace(/\\{\\{\\s*([\\w.$-]+)\\s*\\}\\}/g, (token, rawPath) => {\n\t\tconst segments = rawPath.split(\".\");\n\t\tif (segments[0] === \"payload\") segments.shift();\n\t\tconst value = segments.length === 0 ? payload : resolvePath(payload, segments);\n\t\tif (value === void 0) return token;\n\t\treturn typeof value === \"string\" ? value : JSON.stringify(value);\n\t});\n}\n//#endregion\n//#region src/resolve-agent-prompt.ts\n/** Resolves the agent prompt for a validated trigger payload. */\nfunction resolveAgentPrompt(attachment, payload) {\n\tconst prompt = attachment.prompt;\n\tif (typeof prompt === \"function\") return prompt(payload ?? {});\n\treturn prompt;\n}\n//#endregion\n//#region src/resolve-attachment-input.ts\nfunction applyAttachmentTransform(attachment, payload) {\n\treturn attachment.transform ? attachment.transform(payload) : payload;\n}\n/**\n* Applies attachment `transform` to a payload that already passed source validation.\n* Webhook payloads are matched at ingress via persisted Zod JSON schemas.\n*/\nfunction resolveAttachmentTransform(attachment, payload) {\n\tif (isAgentTriggerAttachment(attachment)) return payload;\n\treturn applyAttachmentTransform(attachment, payload);\n}\n/** Applies poll source filters and attachment `transform`. Webhook ingress already matched Zod schemas. */\nfunction resolveAttachmentInput(attachment, payload) {\n\tconst source = attachment.source;\n\tif (source.kind === \"poll\" && !source.passes(payload)) return;\n\tif (isAgentTriggerAttachment(attachment)) return payload;\n\treturn applyAttachmentTransform(attachment, payload);\n}\n//#endregion\nexport { TRIGGER_ATTACHMENT, TRIGGER_ATTACHMENT_SIBLINGS, agentKeyFromAgent, agentSlugFromAgent, attachFromSource, attachmentKeyFrom, attachmentSlugFrom, attachmentSlugFromRecord, cronScheduleSchema, defineCronSource, definePollSource, defineWebhookSource, interpolatePrompt, isAgentTriggerAttachment, isTriggerAttachment, isWorkflowTriggerAttachment, matchToJsonSchema, matchWebhookPayload, nextTriggerRunAt, normalizeWebhookEndpoint, parseCronSchedule, parseTriggerSchedule, resolveAgentPrompt, resolveAttachmentInput, resolveAttachmentTransform, resolveAuthoringSlug, resolveCronSchedule, sourceSlugFrom, triggerAttachmentsFromExport, triggerMetaFromAttachment, triggerMetaFromSource, triggerMetaRecordFromAttachment, triggerSourceSlugFromAttachmentSlug, triggerTargetSlugFromAttachmentSlug, workflowKeyFromDefinition, workflowSlugFromDefinition };\n\n//# sourceMappingURL=index.mjs.map","import { a as discoverModuleFileEntries, c as walkTypeScriptFiles, l as entryIdFromFile, o as moduleFileKeyFromPath, s as discoverEntries, t as validateUniqueModuleKeys } from \"./discovery-CWjr_liZ.mjs\";\nimport { pathToFileURL } from \"node:url\";\nimport { resolveAppRoot, runWithAppRoot } from \"@keystrokehq/sandbox\";\nimport { dirname, join, relative, sep } from \"node:path\";\nimport { PromptResponseSchema, ROUTE_MANIFEST_REL_PATH, normalizeCredentialList, parseStoredRouteManifest } from \"@keystrokehq/shared\";\nimport { createHash } from \"node:crypto\";\nimport { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from \"node:fs\";\nimport { z } from \"zod\";\nimport { attachmentSlugFromRecord, sourceSlugFrom, triggerAttachmentsFromExport, triggerMetaFromAttachment } from \"@keystrokehq/trigger\";\n//#region src/guards/agent.ts\nfunction isManifestAgent(value) {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tconst agent = value;\n\treturn typeof agent.slug === \"string\" && agent.slug.trim().length > 0 && typeof agent.buildRuntime === \"function\" && typeof agent.model === \"string\" && typeof agent.systemPrompt === \"string\";\n}\nfunction validateManifestAgent(value, filePath) {\n\tif (!isManifestAgent(value)) throw new Error(`${filePath} must default-export defineAgent(...)`);\n\treturn value;\n}\n//#endregion\n//#region src/routes.ts\nfunction normalizeWebhookEndpoint(endpoint) {\n\treturn endpoint.replace(/^\\/+|\\/+$/g, \"\").replace(/^triggers\\/?/, \"\");\n}\nfunction agentRouteFromKey(key) {\n\treturn `/agents/${key}`;\n}\nfunction workflowRouteFromKey(key) {\n\treturn `/workflows/${key}`;\n}\nfunction pollRouteFromSourceSlug(sourceSlug) {\n\treturn `/triggers/${sourceSlug}/poll`;\n}\n/** @deprecated Use {@link pollRouteFromSourceSlug}. */\nconst pollRouteFromKey = pollRouteFromSourceSlug;\nfunction pollGroupRouteFromId(pollId) {\n\treturn `/triggers/polls/${pollId}/run`;\n}\nfunction webhookRouteFromEndpoint(endpoint) {\n\tconst normalized = normalizeWebhookEndpoint(endpoint);\n\tif (!normalized) throw new Error(\"Webhook endpoint must not be empty\");\n\treturn `/triggers/${normalized}`;\n}\n//#endregion\n//#region src/agents/discover.ts\nasync function discoverAgentEntries(agentsDir, options) {\n\tconst files = await discoverModuleFileEntries(agentsDir, {\n\t\tnestedEntry: \"agent\",\n\t\tduplicateLabel: \"agent module file\"\n\t});\n\tconst entries = [];\n\tfor (const { filePath, moduleFile } of files) {\n\t\tconst agent = await importAgentDefinition(filePath, options);\n\t\tentries.push({\n\t\t\tkey: agent.slug,\n\t\t\troute: agentRouteFromKey(agent.slug),\n\t\t\tfilePath,\n\t\t\tmoduleFile\n\t\t});\n\t}\n\treturn entries;\n}\nasync function importAgentDefinition(filePath, options) {\n\tconst appRoot = resolveAppRoot(filePath);\n\tconst href = pathToFileURL(filePath).href;\n\treturn runWithAppRoot(appRoot, async () => {\n\t\treturn validateManifestAgent((await (options?.reload ? import(`${href}?keystroke=${Date.now()}`) : import(href))).default, filePath);\n\t});\n}\n//#endregion\n//#region src/guards/action.ts\nconst ACTION = Symbol.for(\"keystroke.action\");\nfunction isManifestAction(value) {\n\tif (typeof value !== \"object\" || value === null) return false;\n\treturn ACTION in value && value[ACTION] === true;\n}\nfunction getManifestActionCredentialRequirements(action) {\n\treturn Array.isArray(action.credentials) ? action.credentials : void 0;\n}\n//#endregion\n//#region src/agents/count-agent-credentials.ts\nfunction actionSlug(tool) {\n\tconst record = tool;\n\treturn typeof record.slug === \"string\" ? record.slug : void 0;\n}\n/** App-kind slugs required by the agent's tools (same as `credential_instances.app_slug`). */\nfunction collectAgentAppSlugs(agent) {\n\tconst slugs = /* @__PURE__ */ new Set();\n\tfor (const tool of agent.tools ?? []) {\n\t\tconst record = tool;\n\t\tconst requirements = isManifestAction(tool) ? getManifestActionCredentialRequirements(tool) : \"credentials\" in record && Array.isArray(record.credentials) ? record.credentials : void 0;\n\t\tif (!requirements?.length) continue;\n\t\tfor (const requirement of normalizeCredentialList(requirements)) slugs.add(requirement.key);\n\t}\n\treturn [...slugs].sort();\n}\nfunction collectAgentToolSlugs(agent) {\n\tconst slugs = [];\n\tfor (const tool of agent.tools ?? []) {\n\t\tconst slug = actionSlug(tool);\n\t\tif (slug) slugs.push(slug);\n\t}\n\treturn slugs;\n}\nfunction countAgentCredentials(agent) {\n\treturn collectAgentAppSlugs(agent).length;\n}\n//#endregion\n//#region src/agents/agent-manifest-entry.ts\n/** Single source of truth for the `kind: \"agent\"` route-manifest entry shape. */\nfunction agentManifestEntry(agent, options) {\n\treturn {\n\t\tkind: \"agent\",\n\t\tslug: agent.slug,\n\t\tmoduleFile: options.moduleFile,\n\t\tname: agent.name,\n\t\tdescription: agent.description,\n\t\tmodel: agent.model,\n\t\tsystemPrompt: agent.systemPrompt,\n\t\ttoolCount: agent.tools?.length ?? 0,\n\t\tcredentialCount: countAgentCredentials(agent),\n\t\tappSlugs: collectAgentAppSlugs(agent),\n\t\ttoolSlugs: collectAgentToolSlugs(agent)\n\t};\n}\n//#endregion\n//#region src/skills/discover-manifest-entries.ts\nconst SKIP_DIRS = new Set([\".git\", \"node_modules\"]);\nfunction toPosix$1(path) {\n\treturn path.split(sep).join(\"/\");\n}\nfunction parseSkillFrontmatter(raw) {\n\tconst match = raw.match(/^---\\s*\\n([\\s\\S]*?)\\n---/);\n\tif (!match) return {};\n\tconst out = {};\n\tfor (const line of match[1]?.split(\"\\n\") ?? []) {\n\t\tconst trimmed = line.trim();\n\t\tif (!trimmed || trimmed.startsWith(\"#\")) continue;\n\t\tconst colon = trimmed.indexOf(\":\");\n\t\tif (colon < 0) continue;\n\t\tconst key = trimmed.slice(0, colon).trim();\n\t\tlet value = trimmed.slice(colon + 1).trim();\n\t\tif (value.startsWith(\"\\\"\") && value.endsWith(\"\\\"\") || value.startsWith(\"'\") && value.endsWith(\"'\")) value = value.slice(1, -1);\n\t\tif (key === \"name\") out.name = value;\n\t\telse if (key === \"description\") out.description = value;\n\t}\n\treturn out;\n}\nfunction walkSkillFiles(root, dir, out) {\n\tfor (const name of readdirSync(dir).sort()) {\n\t\tconst absolute = join(dir, name);\n\t\tconst stats = statSync(absolute);\n\t\tif (stats.isDirectory()) {\n\t\t\tif (SKIP_DIRS.has(name)) continue;\n\t\t\twalkSkillFiles(root, absolute, out);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!stats.isFile() || name !== \"SKILL.md\") continue;\n\t\tconst moduleFile = toPosix$1(relative(root, absolute));\n\t\tconst slug = toPosix$1(relative(join(root, \"src\", \"skills\"), absolute)).replace(/\\/?SKILL\\.md$/, \"\");\n\t\tif (!slug) continue;\n\t\tconst frontmatter = parseSkillFrontmatter(readFileSync(absolute, \"utf8\"));\n\t\tout.push({\n\t\t\tslug,\n\t\t\tname: frontmatter.name,\n\t\t\tdescription: frontmatter.description,\n\t\t\tmoduleFile\n\t\t});\n\t}\n}\n/** Discover skill metadata from src/skills SKILL.md files for the route manifest. */\nfunction discoverSkillManifestEntries(projectRoot) {\n\tconst skillsDir = join(projectRoot, \"src\", \"skills\");\n\tif (!statSync(skillsDir, { throwIfNoEntry: false })?.isDirectory()) return [];\n\tconst entries = [];\n\twalkSkillFiles(projectRoot, skillsDir, entries);\n\treturn entries;\n}\n//#endregion\n//#region src/openapi/schema-to-json.ts\nfunction schemaToJson(schema) {\n\treturn z.toJSONSchema(schema, { target: \"openapi-3.0\" });\n}\n//#endregion\n//#region src/openapi/serialize-manifest.ts\nfunction collectIntegrationKeys(integrations) {\n\treturn integrations.map((integration) => integration.key);\n}\nfunction serializeRouteManifest(manifest) {\n\tconst entries = [];\n\tfor (const entry of manifest) switch (entry.kind) {\n\t\tcase \"health\":\n\t\t\tentries.push(entry);\n\t\t\tbreak;\n\t\tcase \"agent\":\n\t\t\tentries.push({\n\t\t\t\tkind: entry.kind,\n\t\t\t\tslug: entry.slug,\n\t\t\t\tmoduleFile: entry.moduleFile,\n\t\t\t\tname: entry.name,\n\t\t\t\tdescription: entry.description,\n\t\t\t\tmodel: entry.model,\n\t\t\t\tsystemPrompt: entry.systemPrompt,\n\t\t\t\ttoolCount: entry.toolCount,\n\t\t\t\tcredentialCount: entry.credentialCount,\n\t\t\t\tappSlugs: entry.appSlugs,\n\t\t\t\ttoolSlugs: entry.toolSlugs\n\t\t\t});\n\t\t\tbreak;\n\t\tcase \"workflow\":\n\t\t\tentries.push({\n\t\t\t\tkind: entry.kind,\n\t\t\t\tslug: entry.slug,\n\t\t\t\tname: entry.name,\n\t\t\t\tdescription: entry.description,\n\t\t\t\tsubscribable: entry.subscribable,\n\t\t\t\tmoduleFile: entry.moduleFile,\n\t\t\t\trequestSchema: schemaToJson(entry.request)\n\t\t\t});\n\t\t\tbreak;\n\t\tcase \"trigger-webhook\":\n\t\t\tentries.push({\n\t\t\t\tkind: entry.kind,\n\t\t\t\tendpoint: entry.endpoint,\n\t\t\t\tattachmentIds: entry.attachmentIds,\n\t\t\t\tmoduleFile: entry.moduleFile,\n\t\t\t\tattachmentSchemas: Object.fromEntries(Object.entries(entry.attachmentSchemas).map(([attachmentSlug, schemas]) => [attachmentSlug, {\n\t\t\t\t\trequestSchema: schemaToJson(schemas.request),\n\t\t\t\t\t...schemas.filter ? { filterSchema: schemaToJson(schemas.filter) } : {}\n\t\t\t\t}])),\n\t\t\t\t...entry.attachmentMeta ? { attachmentMeta: entry.attachmentMeta } : {}\n\t\t\t});\n\t\t\tbreak;\n\t\tcase \"trigger-poll\":\n\t\t\tentries.push({\n\t\t\t\tkind: entry.kind,\n\t\t\t\tattachmentId: entry.attachmentId,\n\t\t\t\tattachmentIds: entry.attachmentIds,\n\t\t\t\tmoduleFile: entry.moduleFile,\n\t\t\t\tschedule: entry.schedule,\n\t\t\t\t...entry.name !== void 0 ? { name: entry.name } : {},\n\t\t\t\t...entry.description !== void 0 ? { description: entry.description } : {}\n\t\t\t});\n\t\t\tbreak;\n\t\tcase \"trigger-poll-group\":\n\t\t\tentries.push({\n\t\t\t\tkind: entry.kind,\n\t\t\t\tpollId: entry.pollId,\n\t\t\t\tattachmentIds: entry.attachmentIds,\n\t\t\t\tmoduleFile: entry.moduleFile,\n\t\t\t\tschedule: entry.schedule\n\t\t\t});\n\t\t\tbreak;\n\t\tcase \"cron-schedule\":\n\t\t\tentries.push(entry);\n\t\t\tbreak;\n\t\tdefault: break;\n\t}\n\treturn entries;\n}\nfunction toStoredRouteManifest(manifest, options) {\n\treturn {\n\t\tversion: 2,\n\t\tentries: serializeRouteManifest(manifest),\n\t\tskills: options?.skills ?? [],\n\t\tintegrations: options?.integrations\n\t};\n}\nfunction buildStoredRouteManifestFromContext(ctx) {\n\tconst integrations = ctx.options?.integrations ?? ctx.options?.plugins?.map((plugin) => ({\n\t\tkey: plugin.name,\n\t\tmount: plugin.register\n\t})) ?? [];\n\treturn toStoredRouteManifest(ctx.manifest, {\n\t\tintegrations: collectIntegrationKeys(integrations),\n\t\tskills: ctx.skills ?? (ctx.projectRoot ? discoverSkillManifestEntries(ctx.projectRoot) : void 0) ?? []\n\t});\n}\nfunction findWorkflowManifestEntry(manifest, workflowSlug) {\n\treturn manifest.entries.find((entry) => entry.kind === \"workflow\" && entry.slug === workflowSlug);\n}\nfunction findWebhookManifestEntryByEndpoint(manifest, endpoint) {\n\treturn manifest.entries.find((entry) => entry.kind === \"trigger-webhook\" && entry.endpoint === endpoint);\n}\n/** @deprecated Use {@link findWebhookManifestEntryByEndpoint}. */\nfunction findWebhookManifestEntryByPath(manifest, route) {\n\treturn findWebhookManifestEntryByEndpoint(manifest, route.replace(/^\\/triggers\\//, \"\").replace(/^\\/+|\\/+$/g, \"\"));\n}\n//#endregion\n//#region src/persist.ts\nfunction persistStoredRouteManifest(projectRoot, manifest) {\n\tconst path = join(projectRoot, ROUTE_MANIFEST_REL_PATH);\n\tmkdirSync(dirname(path), { recursive: true });\n\twriteFileSync(path, `${JSON.stringify(manifest, null, 2)}\\n`);\n}\n//#endregion\n//#region src/guards/workflow.ts\nconst WORKFLOW = Symbol.for(\"keystroke.workflow\");\nfunction isManifestWorkflow(value) {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tif (!(WORKFLOW in value) || value[WORKFLOW] !== true) return false;\n\tconst workflow = value;\n\treturn typeof workflow.slug === \"string\" && workflow.slug.trim().length > 0 && workflow.input instanceof Object && \"safeParse\" in workflow.input && workflow.output instanceof Object && \"safeParse\" in workflow.output;\n}\nfunction validateManifestWorkflow(value, filePath) {\n\tif (!isManifestWorkflow(value)) throw new Error(`${filePath} must default-export defineWorkflow(...)`);\n\treturn value;\n}\n//#endregion\n//#region src/guards/trigger.ts\nconst TRIGGER_ATTACHMENT = Symbol.for(\"keystroke.triggerAttachment\");\nconst zodSchema = z.custom((value) => value instanceof z.ZodType, \"must be a Zod schema\");\nconst cronScheduleSchema = z.string().trim().min(1, \"cron schedule must be a non-empty string\");\nconst workflowSchema = z.custom((value) => isManifestWorkflow(value), \"must be defineWorkflow(...)\");\nconst agentSchema = z.custom((value) => typeof value === \"object\" && value !== null && typeof value.slug === \"string\" && value.slug.trim().length > 0 && typeof value.prompt === \"function\", \"must be defineAgent(...)\");\nconst promptSchema = z.union([z.string(), z.function()]);\n/** backwards-compat: normalize legacy `key` fields to canonical `slug` before validation. */\nfunction normalizeLegacySlugFields(value) {\n\tif (typeof value !== \"object\" || value === null) return value;\n\tconst next = { ...value };\n\tif (typeof next.slug !== \"string\" && typeof next.key === \"string\") next.slug = next.key;\n\tdelete next.key;\n\tif (typeof next.source === \"object\" && next.source !== null) next.source = normalizeLegacySlugFields(next.source);\n\treturn next;\n}\nconst slugField = z.string().trim().min(1);\nconst optionalTextField = z.string().optional();\nconst baseSourceShape = {\n\tslug: slugField,\n\tname: optionalTextField,\n\tdescription: optionalTextField,\n\tattach: z.function()\n};\nconst webhookSourceSchema = z.object({\n\tkind: z.literal(\"webhook\"),\n\t...baseSourceShape,\n\tendpoint: z.string().min(1),\n\trequest: zodSchema,\n\tfilter: zodSchema.optional(),\n\tpasses: z.function()\n});\nconst cronSourceSchema = z.object({\n\tkind: z.literal(\"cron\"),\n\t...baseSourceShape,\n\tschedule: cronScheduleSchema\n});\nconst pollSourceSchema = z.object({\n\tkind: z.literal(\"poll\"),\n\t...baseSourceShape,\n\tid: z.string().optional(),\n\tschedule: cronScheduleSchema,\n\trun: z.function(),\n\tfilters: z.array(z.function()),\n\tpasses: z.function()\n});\nconst triggerSourceSchema = z.preprocess(normalizeLegacySlugFields, z.discriminatedUnion(\"kind\", [\n\twebhookSourceSchema,\n\tcronSourceSchema,\n\tpollSourceSchema\n]));\nconst workflowAttachmentSchema = z.object({\n\tslug: slugField,\n\tname: optionalTextField,\n\tdescription: optionalTextField,\n\tsource: triggerSourceSchema,\n\ttarget: z.literal(\"workflow\"),\n\tworkflow: workflowSchema,\n\ttransform: z.function().optional()\n});\nconst agentAttachmentSchema = z.object({\n\tslug: slugField,\n\tname: optionalTextField,\n\tdescription: optionalTextField,\n\tsource: triggerSourceSchema,\n\ttarget: z.literal(\"agent\"),\n\tagent: agentSchema,\n\tprompt: promptSchema\n});\nconst triggerAttachmentCoreSchema = z.preprocess(normalizeLegacySlugFields, z.discriminatedUnion(\"target\", [workflowAttachmentSchema, agentAttachmentSchema]));\nfunction isManifestTriggerAttachment(value) {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tif (!(TRIGGER_ATTACHMENT in value) || value[TRIGGER_ATTACHMENT] !== true) return false;\n\treturn triggerAttachmentCoreSchema.safeParse(value).success;\n}\nfunction validateManifestTriggerAttachment(value, filePath) {\n\tif (!isManifestTriggerAttachment(value)) throw new Error(`${filePath} must default-export a trigger attachment from .attach({ workflow }) or .attach({ agent, prompt })`);\n\treturn value;\n}\n//#endregion\n//#region src/triggers/discover.ts\nfunction shouldDiscoverTriggerFile(triggersDir, filePath) {\n\treturn !relative(triggersDir, filePath).split(sep).includes(\"sources\");\n}\nasync function discoverTriggerAttachments(triggersDir, options) {\n\tconst files = await discoverModuleFileEntries(triggersDir, {\n\t\tnestedEntry: \"trigger\",\n\t\tduplicateLabel: \"trigger module file\",\n\t\tshouldDiscoverFile: (filePath) => shouldDiscoverTriggerFile(triggersDir, filePath)\n\t});\n\tconst attachments = [];\n\tfor (const { filePath, moduleFile } of files) for (const attachment of await importTriggerAttachments(filePath, options)) attachments.push({\n\t\tslug: attachmentSlugFromRecord(attachment),\n\t\tfilePath,\n\t\tmoduleFile,\n\t\tattachment\n\t});\n\treturn attachments;\n}\nfunction validateImportedTriggerAttachment(def, filePath) {\n\treturn validateManifestTriggerAttachment(def, filePath);\n}\nasync function loadTriggerModuleDefault(filePath, options) {\n\tconst href = pathToFileURL(filePath).href;\n\treturn (await (options?.reload ? import(`${href}?keystroke=${Date.now()}`) : import(href))).default;\n}\n/**\n* Import every attachment a trigger file declares — a single `.attach(...)`, a\n* `.attach(...).attach(...)` chain, or an array of either.\n*/\nasync function importTriggerAttachments(filePath, options) {\n\tconst candidates = triggerAttachmentsFromExport(await loadTriggerModuleDefault(filePath, options));\n\tif (candidates.length === 0) return [validateImportedTriggerAttachment(void 0, filePath)];\n\treturn candidates.map((candidate) => validateImportedTriggerAttachment(candidate, filePath));\n}\nasync function importTriggerAttachment(filePath, options) {\n\treturn validateImportedTriggerAttachment(await loadTriggerModuleDefault(filePath, options), filePath);\n}\n//#endregion\n//#region src/triggers/poll/groups.ts\nfunction pollGroupId(discovered) {\n\tconst source = discovered.attachment.source;\n\tif (source.kind !== \"poll\") throw new Error(`Attachment \"${discovered.slug}\" is not a poll trigger`);\n\treturn source.id ?? sourceSlugFrom(source);\n}\nfunction buildPollGroups(attachments) {\n\tconst byId = /* @__PURE__ */ new Map();\n\tfor (const discovered of attachments) {\n\t\tif (discovered.attachment.source.kind !== \"poll\") continue;\n\t\tconst id = pollGroupId(discovered);\n\t\tconst group = byId.get(id) ?? [];\n\t\tgroup.push(discovered);\n\t\tbyId.set(id, group);\n\t}\n\treturn [...byId.entries()].map(([id, groupAttachments]) => ({\n\t\tid,\n\t\tattachments: groupAttachments\n\t}));\n}\nfunction validatePollGroups(groups) {\n\tfor (const group of groups) {\n\t\tif (group.attachments.length <= 1) continue;\n\t\tif (new Set(group.attachments.map((discovered) => {\n\t\t\tconst source = discovered.attachment.source;\n\t\t\tif (source.kind !== \"poll\") throw new Error(`Poll group \"${group.id}\" has non-poll attachment ${discovered.slug}`);\n\t\t\treturn source.schedule;\n\t\t})).size > 1) {\n\t\t\tconst slugs = group.attachments.map((discovered) => discovered.slug).join(\", \");\n\t\t\tthrow new Error(`Poll group \"${group.id}\" has attachments with different schedules (${slugs})`);\n\t\t}\n\t}\n}\nfunction matchesPollRunTarget(attachmentSlug, workflowKey, target) {\n\tif (!target?.workflows?.length && !target?.attachments?.length) return true;\n\tif (target.attachments?.length && !target.attachments.includes(attachmentSlug)) return false;\n\tif (target.workflows?.length && !target.workflows.includes(workflowKey)) return false;\n\treturn true;\n}\n//#endregion\n//#region src/triggers/webhook/build-webhook-bindings.ts\nfunction buildWebhookBindingsByRoute(attachments, handlerOptionsFor) {\n\tconst webhookBindingsByRoute = /* @__PURE__ */ new Map();\n\tfor (const discovered of attachments) {\n\t\tconst source = discovered.attachment.source;\n\t\tif (source.kind !== \"webhook\") continue;\n\t\tconst route = webhookRouteFromEndpoint(source.endpoint);\n\t\tconst bindings = webhookBindingsByRoute.get(route) ?? [];\n\t\tbindings.push({\n\t\t\tdiscovered,\n\t\t\toptions: handlerOptionsFor(discovered.slug)\n\t\t});\n\t\twebhookBindingsByRoute.set(route, bindings);\n\t}\n\treturn webhookBindingsByRoute;\n}\n//#endregion\n//#region src/triggers/webhook/webhook-schemas.ts\nfunction webhookSchemaEntriesFromBindings(bindings) {\n\treturn bindings.flatMap((binding) => {\n\t\tconst source = binding.discovered.attachment.source;\n\t\tif (source.kind !== \"webhook\") return [];\n\t\treturn [{\n\t\t\tattachmentSlug: binding.discovered.slug,\n\t\t\trequest: source.request,\n\t\t\t...source.filter ? { filter: source.filter } : {}\n\t\t}];\n\t});\n}\nfunction webhookAttachmentSchemasFromBindings(bindings) {\n\treturn webhookSchemaEntriesFromBindings(bindings).map((entry) => ({\n\t\tattachmentSlug: entry.attachmentSlug,\n\t\trequestSchema: schemaToJson(entry.request),\n\t\t...entry.filter ? { filterSchema: schemaToJson(entry.filter) } : {}\n\t}));\n}\nfunction webhookMatchSchemaForBindings(bindings) {\n\tconst schemas = bindings.flatMap((binding) => {\n\t\tconst source = binding.discovered.attachment.source;\n\t\treturn source.kind === \"webhook\" ? [source.request] : [];\n\t});\n\tif (schemas.length === 0) throw new Error(\"Webhook bindings require at least one webhook source\");\n\tif (schemas.length === 1) return schemas[0];\n\treturn z.union(schemas);\n}\nfunction webhookManifestAttachmentSchemasFromBindings(bindings) {\n\treturn Object.fromEntries(webhookSchemaEntriesFromBindings(bindings).map((entry) => [entry.attachmentSlug, {\n\t\trequest: entry.request,\n\t\t...entry.filter ? { filter: entry.filter } : {}\n\t}]));\n}\n//#endregion\n//#region src/workflows/discover.ts\nasync function discoverWorkflowEntries(workflowsDir, options) {\n\tconst files = await discoverModuleFileEntries(workflowsDir, {\n\t\tnestedEntry: \"workflow\",\n\t\tduplicateLabel: \"workflow module file\"\n\t});\n\tconst entries = [];\n\tfor (const { filePath, moduleFile } of files) {\n\t\tconst definition = await importWorkflowDefinition(filePath, options);\n\t\tentries.push({\n\t\t\tkey: definition.slug,\n\t\t\troute: workflowRouteFromKey(definition.slug),\n\t\t\tfilePath,\n\t\t\tmoduleFile\n\t\t});\n\t}\n\treturn entries;\n}\nfunction validateImportedWorkflowDefinition(def, filePath) {\n\treturn validateManifestWorkflow(def, filePath);\n}\nasync function importWorkflowDefinition(filePath, options) {\n\tconst href = pathToFileURL(filePath).href;\n\treturn validateImportedWorkflowDefinition((await (options?.reload ? import(`${href}?keystroke=${Date.now()}`) : import(href))).default, filePath);\n}\nasync function discoverWorkflows(workflowsDir, options) {\n\tconst entries = await discoverWorkflowEntries(workflowsDir, options);\n\tconst workflows = [];\n\tfor (const entry of entries) {\n\t\tconst definition = await importWorkflowDefinition(entry.filePath, options);\n\t\tworkflows.push({\n\t\t\tkey: definition.slug,\n\t\t\troute: workflowRouteFromKey(definition.slug),\n\t\t\tfilePath: entry.filePath,\n\t\t\tdefinition\n\t\t});\n\t}\n\treturn workflows;\n}\n//#endregion\n//#region src/build-stored-manifest.ts\nfunction resolveDistModuleDirs(projectRoot) {\n\tconst distBase = join(projectRoot, \"dist\");\n\tif (!existsSync(distBase)) throw new Error(`Build output missing at ${distBase}. Run keystroke build before emitting the route manifest.`);\n\treturn {\n\t\tagentsDir: join(distBase, \"agents\"),\n\t\tworkflowsDir: join(distBase, \"workflows\"),\n\t\ttriggersDir: join(distBase, \"triggers\")\n\t};\n}\nfunction toPosix(path) {\n\treturn path.split(sep).join(\"/\");\n}\nfunction hashFileContents(absPath) {\n\ttry {\n\t\treturn createHash(\"sha256\").update(readFileSync(absPath)).digest(\"hex\");\n\t} catch {\n\t\treturn;\n\t}\n}\n/**\n* Resolve manifest moduleFile values to project-root-relative source paths.\n*\n* Discovery runs over compiled `dist/` modules, so the raw moduleFile is a\n* dist-relative `.mjs` path. Dist entries are named by their source entry id\n* (`team/escalation.mjs` ← `src/agents/team/escalation/agent.ts`), so walking\n* the matching source dir by the same id rules recovers the source path. Falls\n* back to the dist-relative value when no source file matches (e.g. building\n* a dist-only artifact with no `src/`).\n*/\nvar SourceModuleFileResolver = class {\n\tprojectRoot;\n\tmapsByKind = /* @__PURE__ */ new Map();\n\tconstructor(projectRoot) {\n\t\tthis.projectRoot = projectRoot;\n\t}\n\tasync sourceMapFor(kindDir, nestedEntry) {\n\t\tconst existing = this.mapsByKind.get(kindDir);\n\t\tif (existing) return existing;\n\t\tconst map = /* @__PURE__ */ new Map();\n\t\tconst sourceDir = join(this.projectRoot, \"src\", kindDir);\n\t\tfor (const filePath of await walkTypeScriptFiles(sourceDir)) {\n\t\t\tconst id = entryIdFromFile(sourceDir, filePath, { nestedEntry });\n\t\t\tif (id) map.set(id, toPosix(relative(this.projectRoot, filePath)));\n\t\t}\n\t\tthis.mapsByKind.set(kindDir, map);\n\t\treturn map;\n\t}\n\tasync resolve(kindDir, nestedEntry, distDir, distFilePath) {\n\t\tconst fallback = toPosix(relative(distDir, distFilePath));\n\t\tconst id = entryIdFromFile(distDir, distFilePath, { nestedEntry });\n\t\tif (!id) return fallback;\n\t\treturn (await this.sourceMapFor(kindDir, nestedEntry)).get(id) ?? fallback;\n\t}\n\t/**\n\t* Like `resolve`, but also returns the sha256 of the resolved source file. The hash\n\t* is only present when a real `src/` file is matched (absent for dist-only artifacts),\n\t* and feeds the trigger overview change-detection (`triggers.triggerHash`).\n\t*/\n\tasync resolveSource(kindDir, nestedEntry, distDir, distFilePath) {\n\t\tconst fallback = toPosix(relative(distDir, distFilePath));\n\t\tconst id = entryIdFromFile(distDir, distFilePath, { nestedEntry });\n\t\tif (!id) return { moduleFile: fallback };\n\t\tconst sourceRel = (await this.sourceMapFor(kindDir, nestedEntry)).get(id);\n\t\tif (!sourceRel) return { moduleFile: fallback };\n\t\tconst sourceHash = hashFileContents(join(this.projectRoot, sourceRel));\n\t\treturn {\n\t\t\tmoduleFile: sourceRel,\n\t\t\t...sourceHash ? { sourceHash } : {}\n\t\t};\n\t}\n};\n/** Build a stored route manifest from compiled dist/ modules without starting a server. */\nasync function buildStoredRouteManifestForProject(projectRoot, options) {\n\tconst previousRoot = process.env.KEYSTROKE_ROOT;\n\tprocess.env.KEYSTROKE_ROOT = projectRoot;\n\tconst reload = options?.reloadModules ? { reload: true } : void 0;\n\ttry {\n\t\tconst dirs = resolveDistModuleDirs(projectRoot);\n\t\tconst sourcePaths = new SourceModuleFileResolver(projectRoot);\n\t\tconst manifest = [{ kind: \"health\" }];\n\t\tconst agentEntries = await discoverAgentEntries(dirs.agentsDir, reload);\n\t\tfor (const entry of agentEntries) {\n\t\t\tconst agent = await importAgentDefinition(entry.filePath, reload);\n\t\t\tconst moduleFile = await sourcePaths.resolve(\"agents\", \"agent\", dirs.agentsDir, entry.filePath);\n\t\t\tmanifest.push(agentManifestEntry(agent, { moduleFile }));\n\t\t}\n\t\tconst workflows = await discoverWorkflows(dirs.workflowsDir, reload);\n\t\tfor (const workflow of workflows) {\n\t\t\tconst moduleFile = await sourcePaths.resolve(\"workflows\", \"workflow\", dirs.workflowsDir, workflow.filePath);\n\t\t\tmanifest.push({\n\t\t\t\tkind: \"workflow\",\n\t\t\t\tslug: workflow.definition.slug,\n\t\t\t\tname: workflow.definition.name,\n\t\t\t\tdescription: workflow.definition.description,\n\t\t\t\tsubscribable: workflow.definition.subscription?.mode === \"subscribable\",\n\t\t\t\tmoduleFile,\n\t\t\t\trequest: workflow.definition.input\n\t\t\t});\n\t\t}\n\t\tconst attachments = await discoverTriggerAttachments(dirs.triggersDir, reload);\n\t\tconst discoveredBySlug = new Map(attachments.map((attachment) => [attachment.slug, attachment]));\n\t\tconst cronByTriggerSlug = /* @__PURE__ */ new Map();\n\t\tconst pollByGroupId = /* @__PURE__ */ new Map();\n\t\tfor (const discovered of attachments) {\n\t\t\tconst source = discovered.attachment.source;\n\t\t\tif (source.kind === \"cron\") {\n\t\t\t\tconst triggerSlug = sourceSlugFrom(source);\n\t\t\t\tconst group = cronByTriggerSlug.get(triggerSlug) ?? [];\n\t\t\t\tgroup.push(discovered);\n\t\t\t\tcronByTriggerSlug.set(triggerSlug, group);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (source.kind === \"poll\") {\n\t\t\t\tconst groupId = pollGroupId(discovered);\n\t\t\t\tconst group = pollByGroupId.get(groupId) ?? [];\n\t\t\t\tgroup.push(discovered);\n\t\t\t\tpollByGroupId.set(groupId, group);\n\t\t\t}\n\t\t}\n\t\tfor (const [triggerSlug, group] of cronByTriggerSlug) {\n\t\t\tconst first = group[0];\n\t\t\tconst source = first.attachment.source;\n\t\t\tif (source.kind !== \"cron\") continue;\n\t\t\tconst meta = triggerMetaFromAttachment(first.attachment);\n\t\t\tconst { moduleFile, sourceHash } = await sourcePaths.resolveSource(\"triggers\", \"trigger\", dirs.triggersDir, first.filePath);\n\t\t\tmanifest.push({\n\t\t\t\tkind: \"cron-schedule\",\n\t\t\t\tattachmentId: triggerSlug,\n\t\t\t\tattachmentIds: group.map((attachment) => attachment.slug),\n\t\t\t\tmoduleFile,\n\t\t\t\t...sourceHash ? { sourceHash } : {},\n\t\t\t\tschedule: source.schedule,\n\t\t\t\t...meta\n\t\t\t});\n\t\t}\n\t\tfor (const [groupId, group] of pollByGroupId) {\n\t\t\tconst first = group[0];\n\t\t\tconst source = first.attachment.source;\n\t\t\tif (source.kind !== \"poll\") continue;\n\t\t\tconst meta = triggerMetaFromAttachment(first.attachment);\n\t\t\tconst { moduleFile, sourceHash } = await sourcePaths.resolveSource(\"triggers\", \"trigger\", dirs.triggersDir, first.filePath);\n\t\t\tmanifest.push({\n\t\t\t\tkind: \"trigger-poll\",\n\t\t\t\tattachmentId: groupId,\n\t\t\t\tattachmentIds: group.map((attachment) => attachment.slug),\n\t\t\t\tmoduleFile,\n\t\t\t\t...sourceHash ? { sourceHash } : {},\n\t\t\t\tschedule: source.schedule,\n\t\t\t\t...meta,\n\t\t\t\tresponse: PromptResponseSchema\n\t\t\t});\n\t\t}\n\t\tfor (const discovered of discoveredBySlug.values()) {\n\t\t\tconst source = discovered.attachment.source;\n\t\t\tif (source.kind !== \"webhook\") continue;\n\t\t\tconst { moduleFile, sourceHash } = await sourcePaths.resolveSource(\"triggers\", \"trigger\", dirs.triggersDir, discovered.filePath);\n\t\t\tconst route = webhookRouteFromEndpoint(source.endpoint);\n\t\t\tconst bindings = buildWebhookBindingsByRoute(discoveredBySlug.values(), () => ({\n\t\t\t\texecution: { attachmentSlug: discovered.slug },\n\t\t\t\tattachmentSlug: discovered.slug\n\t\t\t})).get(route) ?? [{\n\t\t\t\tdiscovered,\n\t\t\t\toptions: { attachmentSlug: discovered.slug }\n\t\t\t}];\n\t\t\tconst attachmentMeta = Object.fromEntries(bindings.flatMap(({ discovered: row }) => {\n\t\t\t\tconst meta = triggerMetaFromAttachment(row.attachment);\n\t\t\t\treturn Object.keys(meta).length > 0 ? [[row.slug, meta]] : [];\n\t\t\t}));\n\t\t\tmanifest.push({\n\t\t\t\tkind: \"trigger-webhook\",\n\t\t\t\tendpoint: source.endpoint,\n\t\t\t\tattachmentIds: bindings.map(({ discovered: row }) => row.slug),\n\t\t\t\tmoduleFile,\n\t\t\t\t...sourceHash ? { sourceHash } : {},\n\t\t\t\trequest: webhookMatchSchemaForBindings(bindings),\n\t\t\t\tattachmentSchemas: webhookManifestAttachmentSchemasFromBindings(bindings),\n\t\t\t\t...Object.keys(attachmentMeta).length > 0 ? { attachmentMeta } : {},\n\t\t\t\tresponse: PromptResponseSchema\n\t\t\t});\n\t\t}\n\t\treturn buildStoredRouteManifestFromContext({\n\t\t\tmanifest,\n\t\t\toptions: {},\n\t\t\tprojectRoot,\n\t\t\tskills: discoverSkillManifestEntries(projectRoot)\n\t\t});\n\t} finally {\n\t\tif (previousRoot === void 0) delete process.env.KEYSTROKE_ROOT;\n\t\telse process.env.KEYSTROKE_ROOT = previousRoot;\n\t}\n}\n/** Write `dist/.keystroke/route-manifest.json` for the project. */\nasync function emitStoredRouteManifestForProject(projectRoot) {\n\tpersistStoredRouteManifest(projectRoot, await buildStoredRouteManifestForProject(projectRoot));\n}\n//#endregion\n//#region src/openapi/manifest.ts\nfunction schedulesFromManifest(manifest) {\n\tconst schedules = [];\n\tfor (const entry of manifest) {\n\t\tif (entry.kind === \"cron-schedule\") {\n\t\t\tschedules.push({\n\t\t\t\tattachmentId: entry.attachmentId,\n\t\t\t\ttype: \"cron\",\n\t\t\t\tschedule: entry.schedule\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (entry.kind === \"trigger-poll\") schedules.push({\n\t\t\tattachmentId: entry.attachmentId,\n\t\t\ttype: \"poll\",\n\t\t\tschedule: entry.schedule\n\t\t});\n\t}\n\treturn schedules;\n}\n//#endregion\n//#region src/load-route-manifest.ts\nfunction routeManifestPathForProjectRoot(projectRoot) {\n\treturn join(projectRoot, ROUTE_MANIFEST_REL_PATH);\n}\nfunction readRouteManifest(projectRoot) {\n\tconst path = routeManifestPathForProjectRoot(projectRoot);\n\tif (!existsSync(path)) throw new Error(`${ROUTE_MANIFEST_REL_PATH} not found — start the project server once to emit the manifest`);\n\tconst raw = readFileSync(path, \"utf8\");\n\treturn parseStoredRouteManifest(JSON.parse(raw));\n}\n//#endregion\nexport { agentManifestEntry, agentRouteFromKey, buildPollGroups, buildStoredRouteManifestForProject, buildStoredRouteManifestFromContext, buildWebhookBindingsByRoute, collectAgentAppSlugs, collectAgentToolSlugs, countAgentCredentials, discoverAgentEntries, discoverEntries, discoverModuleFileEntries, discoverSkillManifestEntries, discoverTriggerAttachments, discoverWorkflowEntries, discoverWorkflows, emitStoredRouteManifestForProject, entryIdFromFile, findWebhookManifestEntryByEndpoint, findWebhookManifestEntryByPath, findWorkflowManifestEntry, importAgentDefinition, importTriggerAttachment, importTriggerAttachments, importWorkflowDefinition, matchesPollRunTarget, moduleFileKeyFromPath, persistStoredRouteManifest, pollGroupId, pollGroupRouteFromId, pollRouteFromKey, pollRouteFromSourceSlug, readRouteManifest, routeManifestPathForProjectRoot, schedulesFromManifest, schemaToJson, serializeRouteManifest, toStoredRouteManifest, validateImportedTriggerAttachment, validateImportedWorkflowDefinition, validatePollGroups, validateUniqueModuleKeys, walkTypeScriptFiles, webhookAttachmentSchemasFromBindings, webhookManifestAttachmentSchemasFromBindings, webhookMatchSchemaForBindings, webhookRouteFromEndpoint, workflowRouteFromKey };\n\n//# sourceMappingURL=index.mjs.map"],"x_google_ignoreList":[0,1,2,3,4,5,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,30,31,32,33,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGA,MAAa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