{"version":3,"file":"dist-aOn-HftZ.mjs","names":["storage","Qt","z.enum","z.enum","SKIP_DIRS$1","z.enum","z.object","z.string","z.array","z.union","z.literal","z.boolean","z.custom","z.string","z.object","z.array","z.number","z.object","z.string","z.boolean","zodSchema","z.custom","z.ZodType","z.object","z.string","z.array","z.function","ACTION","z.custom","#values","#wildcard","#isWildcardValue","#hasLastChar","#hasQuestionMarkChar","#date","#dstStart","#dstEnd","#isLeapYear","#verbMap","#getUTC","exports","#second","#minute","#hour","#month","#dayOfWeek","#dayOfMonth","#handleSingleRange","#handleMultipleRanges","#options","#tz","#startDate","#endDate","#currentDate","#fields","#matchSchedule","#dstTransitionDayKey","#isDstTransitionDay","#getMinOrMax","#isLastWeekdayOfMonthMatch","#findSchedule","#matchDayOfMonth","#checkDstTransition","#validateTimeSpan","#matchHour","#moveToNextMinute","#moveToNextSecond","#getRawFields","#parseField","#parseNthDay","#parseWildcard","#parseHashed","#parseSequence","#isValidConstraintChar","#parseRepeat","#parseRange","#validateRange","#validateRepeatInterval","#createRange","#parseContent","#parseEntry","exports","zodSchema","z.custom","z.ZodType","z.object","z.string","z.enum","z.function","WORKFLOW","isWorkflow","ForeignKeyBuilder","ForeignKey","uniqueKeyName","ForeignKeyBuilder","uniqueKeyName","CheckBuilder","Check","check","customType","integer","numeric","real","text","InlineForeignKeys","IndexBuilderOn","IndexBuilder","Index","index","uniqueIndex","primaryKey","PrimaryKeyBuilder","PrimaryKey","text","text$1","integer$1","index","index$1","integer","assert","util","exports","net_1","events_1","events_1","net_1","tls_1","Buffer","require","text","integer","index","text$1","integer$1","index$1","uniqueIndex","uniqueIndex$1","primaryKey","primaryKey$1","check","check$1","require","toPosix","storage","crypto","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","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","schema","z4mini.safeParse","v3Schema","v4Schema","Ajv","node_process","node_process","z.record","z.string","z.unknown","z.object","z.enum","z.string","z.boolean","cronScheduleSchema","z.string","CronExpressionParser","z.lazy","z.union","z.number","z.boolean","z.null","z.array","z.record","zodSchema","z.custom","z.ZodType","workflowSchema","isWorkflow","agentSchema","promptSchema","z.function","normalizeLegacySlugFields","slugField","requiredTextField","optionalTextField","baseSourceShape","webhookSourceSchema","z.object","z.literal","cronSourceSchema","pollSourceSchema","triggerSourceSchema","z.preprocess","z.discriminatedUnion","workflowAttachmentSchema","agentAttachmentSchema","triggerAttachmentCoreSchema","TRIGGER_ATTACHMENT","normalizeCredentialList$1","zodToStoredJsonSchema$1","z.custom","z.ZodType","z.string","z.union","z.function","z.object","z.literal","z.array","z.preprocess","z.discriminatedUnion","attachmentSlugFromRecord$1"],"sources":["../../../packages/telemetry/dist/index.mjs","../../../node_modules/.pnpm/just-bash@3.0.1/node_modules/just-bash/dist/bundle/chunks/chunk-G5EVRAOO.js","../../../node_modules/.pnpm/just-bash@3.0.1/node_modules/just-bash/dist/bundle/index.js","../../../packages/browser/dist/index.mjs","../../../packages/manifest/dist/discovery-C6Un-m9-.mjs","../../../packages/workflow-canvas/dist/index.mjs","../../../packages/sandbox/dist/sizes-CeGfTo5B.mjs","../../../packages/sandbox/dist/resolve-sandbox-definition-Bgbd2rfm.mjs","../../../packages/sandbox/dist/files-Ds9QSoth.mjs","../../../packages/sandbox/dist/with-exec-timeout-D45q6sQP.mjs","../../../packages/sandbox/dist/index.mjs","../../../packages/action/dist/define-action-CrYCWt9v.mjs","../../../packages/app/dist/index.mjs","../../../packages/agent/dist/agent-model-id-D8Vimsri.mjs","../../../packages/agent/dist/validate-agent-model-ids-D2ODPNKe.mjs","../../../node_modules/.pnpm/cron-parser@5.5.0/node_modules/cron-parser/dist/fields/types.js","../../../node_modules/.pnpm/cron-parser@5.5.0/node_modules/cron-parser/dist/fields/CronField.js","../../../node_modules/.pnpm/cron-parser@5.5.0/node_modules/cron-parser/dist/fields/CronDayOfMonth.js","../../../node_modules/.pnpm/cron-parser@5.5.0/node_modules/cron-parser/dist/fields/CronDayOfWeek.js","../../../node_modules/.pnpm/cron-parser@5.5.0/node_modules/cron-parser/dist/fields/CronHour.js","../../../node_modules/.pnpm/cron-parser@5.5.0/node_modules/cron-parser/dist/fields/CronMinute.js","../../../node_modules/.pnpm/luxon@3.7.2/node_modules/luxon/build/node/luxon.js","../../../node_modules/.pnpm/cron-parser@5.5.0/node_modules/cron-parser/dist/CronDate.js","../../../node_modules/.pnpm/cron-parser@5.5.0/node_modules/cron-parser/dist/fields/CronMonth.js","../../../node_modules/.pnpm/cron-parser@5.5.0/node_modules/cron-parser/dist/fields/CronSecond.js","../../../node_modules/.pnpm/cron-parser@5.5.0/node_modules/cron-parser/dist/fields/index.js","../../../node_modules/.pnpm/cron-parser@5.5.0/node_modules/cron-parser/dist/CronFieldCollection.js","../../../node_modules/.pnpm/cron-parser@5.5.0/node_modules/cron-parser/dist/CronExpression.js","../../../node_modules/.pnpm/cron-parser@5.5.0/node_modules/cron-parser/dist/utils/random.js","../../../node_modules/.pnpm/cron-parser@5.5.0/node_modules/cron-parser/dist/CronExpressionParser.js","../../../node_modules/.pnpm/cron-parser@5.5.0/node_modules/cron-parser/dist/CronFileParser.js","../../../node_modules/.pnpm/cron-parser@5.5.0/node_modules/cron-parser/dist/index.js","../../../packages/workflow/dist/define-workflow-BBoZgWI5.mjs","../../../packages/tracing/dist/index.mjs","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/entity.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/column.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/column-builder.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/table.utils.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/foreign-keys.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/tracing-utils.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/unique-constraint.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/utils/array.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/common.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/enum.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/subquery.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/tracing.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/view-common.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/table.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/sql/sql.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/checks.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/utils.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/int.common.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/bigint.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/bigserial.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/boolean.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/char.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/cidr.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/custom.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/date.common.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/date.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/double-precision.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/inet.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/integer.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/interval.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/json.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/jsonb.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/line.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/macaddr.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/macaddr8.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/numeric.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/point.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/postgis_extension/utils.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/postgis_extension/geometry.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/real.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/serial.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/smallint.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/smallserial.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/text.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/time.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/timestamp.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/uuid.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/varchar.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/vector_extension/bit.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/vector_extension/halfvec.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/vector_extension/sparsevec.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/vector_extension/vector.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/columns/all.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/table.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/indexes.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/policies.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/pg-core/primary-keys.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/sqlite-core/checks.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/sqlite-core/foreign-keys.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/sqlite-core/unique-constraint.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/sqlite-core/columns/common.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/sqlite-core/columns/blob.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/sqlite-core/columns/custom.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/sqlite-core/columns/integer.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/sqlite-core/columns/numeric.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/sqlite-core/columns/real.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/sqlite-core/columns/text.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/sqlite-core/columns/all.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/sqlite-core/table.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/sqlite-core/indexes.js","../../../node_modules/.pnpm/drizzle-orm@0.45.2_@opentelemetry+api@1.9.1_@types+better-sqlite3@7.6.13_@types+pg@8.20_77911661b3ede76946c974aead4d265f/node_modules/drizzle-orm/sqlite-core/primary-keys.js","../../../packages/platform-database/dist/mcp-oauth-SRTcHMWZ.mjs","../../../node_modules/.pnpm/@ioredis+commands@1.10.0/node_modules/@ioredis/commands/built/commands.json","../../../node_modules/.pnpm/@ioredis+commands@1.10.0/node_modules/@ioredis/commands/built/index.js","../../../node_modules/.pnpm/standard-as-callback@2.1.0/node_modules/standard-as-callback/built/utils.js","../../../node_modules/.pnpm/standard-as-callback@2.1.0/node_modules/standard-as-callback/built/index.js","../../../node_modules/.pnpm/redis-errors@1.2.0/node_modules/redis-errors/lib/old.js","../../../node_modules/.pnpm/redis-errors@1.2.0/node_modules/redis-errors/lib/modern.js","../../../node_modules/.pnpm/redis-errors@1.2.0/node_modules/redis-errors/index.js","../../../node_modules/.pnpm/cluster-key-slot@1.1.1/node_modules/cluster-key-slot/lib/index.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/utils/defaults.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/utils/isArguments.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/utils/lodash.js","../../../node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js","../../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/common.js","../../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/browser.js","../../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/node.js","../../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/index.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/utils/debug.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/constants/TLSProfiles.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/utils/index.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/utils/argumentParsers.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/Command.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/errors/ClusterAllFailedError.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/ScanStream.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/autoPipelining.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/Script.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/utils/Commander.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/Pipeline.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/tracing.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/transaction.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/utils/applyMixin.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/cluster/ClusterOptions.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/cluster/util.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/cluster/ClusterSubscriber.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/cluster/ConnectionPool.js","../../../node_modules/.pnpm/denque@2.1.0/node_modules/denque/index.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/cluster/DelayQueue.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/cluster/ShardedSubscriber.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/cluster/ClusterSubscriberGroup.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/cluster/index.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/connectors/AbstractConnector.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/connectors/StandaloneConnector.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/connectors/SentinelConnector/SentinelIterator.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/connectors/SentinelConnector/FailoverDetector.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/connectors/SentinelConnector/index.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/connectors/index.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/errors/MaxRetriesPerRequestError.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/errors/index.js","../../../node_modules/.pnpm/redis-parser@3.0.0/node_modules/redis-parser/lib/parser.js","../../../node_modules/.pnpm/redis-parser@3.0.0/node_modules/redis-parser/index.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/SubscriptionSet.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/DataHandler.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/redis/event_handler.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/redis/RedisOptions.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/Redis.js","../../../node_modules/.pnpm/ioredis@5.11.1/node_modules/ioredis/built/index.js","../../../packages/platform-database/dist/sanitize-message-JfOafIe_.mjs","../../../packages/platform-database/dist/runtime/index.mjs","../../../packages/storage/dist/map-in-batches.mjs","../../../packages/storage/dist/collect-artifact-modules-CApdro3d.mjs","../../../packages/platform-database/dist/index.mjs","../../../node_modules/.pnpm/eventsource-parser@3.0.8/node_modules/eventsource-parser/dist/index.js","../../../node_modules/.pnpm/eventsource-parser@3.0.8/node_modules/eventsource-parser/dist/stream.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/types.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/shared/auth-utils.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/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js","../../../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/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js","../../../packages/mcp/dist/index.mjs","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/identity.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/visit.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/doc/directives.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/doc/anchors.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/doc/applyReviver.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/toJS.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/Node.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/Alias.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/Scalar.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/doc/createNode.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/Collection.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/stringifyComment.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/foldFlowLines.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/stringifyString.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/stringify.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/stringifyPair.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/log.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/merge.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/addPairToJSMap.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/Pair.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/stringifyCollection.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/YAMLMap.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/common/map.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/YAMLSeq.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/common/seq.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/common/string.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/common/null.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/core/bool.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/stringifyNumber.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/core/float.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/core/int.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/core/schema.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/json/schema.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/binary.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/pairs.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/omap.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/bool.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/float.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/int.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/set.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/timestamp.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/schema.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/tags.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/Schema.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/stringifyDocument.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/doc/Document.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/errors.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/resolve-props.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/util-contains-newline.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/util-flow-indent-check.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/util-map-includes.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/resolve-block-map.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/resolve-block-seq.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/resolve-end.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/resolve-flow-collection.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/compose-collection.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/resolve-block-scalar.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/resolve-flow-scalar.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/compose-scalar.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/util-empty-scalar-position.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/compose-node.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/compose-doc.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/composer.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/cst-scalar.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/cst-stringify.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/cst-visit.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/cst.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/lexer.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/line-counter.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/parser.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/public-api.js","../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/index.js","../../../packages/credentials/dist/index.mjs","../../../packages/workflow/dist/index.mjs","../../../packages/trigger/dist/index.mjs","../../../packages/manifest/dist/index.mjs"],"sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\n//#region src/context.ts\nconst storage = new AsyncLocalStorage();\nfunction getTelemetryContext() {\n\treturn storage.getStore();\n}\nfunction runWithTelemetryContext(context, fn) {\n\treturn storage.run({ ...context }, fn);\n}\n/** Patch the active store when present (no-op outside `runWithTelemetryContext`). */\nfunction setTelemetryContext(patch) {\n\tconst current = storage.getStore();\n\tif (!current) return;\n\tif (patch.actorId !== void 0) current.actorId = patch.actorId;\n\tif (patch.analyticsId !== void 0) current.analyticsId = patch.analyticsId;\n\tif (patch.organizationId !== void 0) current.organizationId = patch.organizationId;\n\tif (patch.projectId !== void 0) current.projectId = patch.projectId;\n\tif (patch.sessionId !== void 0) current.sessionId = patch.sessionId;\n\tif (patch.client !== void 0) current.client = patch.client;\n}\n//#endregion\n//#region src/expected-error.ts\n/**\n* Returns true when an error is an expected client/control-flow failure that\n* should not become an Error Tracking issue.\n*/\nfunction isExpectedError(error) {\n\tif (!error || typeof error !== \"object\") return false;\n\tconst status = readStatus(error);\n\tif (status !== void 0 && (status === 0 || status >= 400 && status < 500)) return true;\n\tif (\"name\" in error && typeof error.name === \"string\") {\n\t\tif (error.name === \"AbortError\" || error.name === \"CanceledError\" || error.name === \"CancelledError\" || error.name === \"RunTimeoutError\") return true;\n\t}\n\treturn false;\n}\nfunction readStatus(error) {\n\tif (\"status\" in error && typeof error.status === \"number\") return error.status;\n\tif (\"statusCode\" in error && typeof error.statusCode === \"number\") return error.statusCode;\n}\n//#endregion\n//#region src/telemetry.ts\nconst EVENT_NAME_PATTERN = /^[a-z][a-z0-9_]*(:[a-z][a-z0-9_]*)?$/;\nlet sink;\nfunction configureTelemetry(options) {\n\tsink = options.sink;\n}\nfunction resetTelemetryForTests() {\n\tsink = void 0;\n}\nasync function flushTelemetry() {\n\tawait sink?.flush?.();\n}\nasync function shutdownTelemetry() {\n\tconst current = sink;\n\tsink = void 0;\n\tawait current?.shutdown?.();\n}\nasync function captureException(input) {\n\tif (isExpectedError(input.error) || !sink?.captureException) return;\n\tconst context = getTelemetryContext();\n\tconst actorId = input.actorId ?? context?.actorId;\n\tconst analyticsId = input.analyticsId ?? context?.analyticsId;\n\tconst organizationId = input.organizationId ?? context?.organizationId;\n\tconst projectId = input.projectId ?? context?.projectId;\n\tconst sessionId = input.sessionId ?? context?.sessionId;\n\tconst enriched = {\n\t\terror: input.error,\n\t\t...actorId ? { actorId } : {},\n\t\t...analyticsId ? { analyticsId } : {},\n\t\t...organizationId ? { organizationId } : {},\n\t\t...projectId ? { projectId } : {},\n\t\t...sessionId ? { sessionId } : {},\n\t\t...input.operation ? { operation: input.operation } : {},\n\t\t...input.properties ? { properties: input.properties } : {}\n\t};\n\ttry {\n\t\tawait sink.captureException(enriched);\n\t} catch (error) {\n\t\tconsole.error(\"[telemetry] captureException sink failed\", error);\n\t}\n}\nasync function event(input) {\n\tif (!EVENT_NAME_PATTERN.test(input.name)) {\n\t\tconsole.error(`[telemetry] rejected invalid event name: ${input.name}`);\n\t\treturn;\n\t}\n\tconst actorId = input.actorId.trim();\n\tif (!actorId) {\n\t\tconsole.error(\"[telemetry] rejected event without actorId\");\n\t\treturn;\n\t}\n\tif (!sink?.event) return;\n\ttry {\n\t\tawait sink.event({\n\t\t\t...input,\n\t\t\tactorId,\n\t\t\ttimestamp: input.timestamp ?? /* @__PURE__ */ new Date(),\n\t\t\tuuid: input.uuid ?? globalThis.crypto.randomUUID()\n\t\t});\n\t} catch (error) {\n\t\tconsole.error(\"[telemetry] event sink failed\", error);\n\t}\n}\nasync function groupIdentify(input) {\n\tconst groupType = input.groupType.trim();\n\tconst groupKey = input.groupKey.trim();\n\tif (!groupType || !groupKey) {\n\t\tconsole.error(\"[telemetry] rejected groupIdentify without groupType/groupKey\");\n\t\treturn;\n\t}\n\tif (!sink?.groupIdentify) return;\n\ttry {\n\t\tawait sink.groupIdentify({\n\t\t\tgroupType,\n\t\t\tgroupKey,\n\t\t\t...input.properties ? { properties: input.properties } : {}\n\t\t});\n\t} catch (error) {\n\t\tconsole.error(\"[telemetry] groupIdentify sink failed\", error);\n\t}\n}\nasync function alias(input) {\n\tconst distinctId = input.distinctId.trim();\n\tconst aliasId = input.alias.trim();\n\tif (!distinctId || !aliasId) {\n\t\tconsole.error(\"[telemetry] rejected alias without distinctId/alias\");\n\t\treturn;\n\t}\n\tif (!sink?.alias) return;\n\ttry {\n\t\tawait sink.alias({\n\t\t\tdistinctId,\n\t\t\talias: aliasId\n\t\t});\n\t} catch (error) {\n\t\tconsole.error(\"[telemetry] alias sink failed\", error);\n\t}\n}\nfunction contextAttributes(attributes) {\n\tconst context = getTelemetryContext();\n\tconst merged = {\n\t\t...context?.actorId ? { actor_id: context.actorId } : {},\n\t\t...context?.analyticsId ? { analytics_id: context.analyticsId } : {},\n\t\t...context?.organizationId ? { organization_id: context.organizationId } : {},\n\t\t...context?.projectId ? { project_id: context.projectId } : {},\n\t\t...context?.sessionId ? { session_id: context.sessionId } : {},\n\t\t...attributes\n\t};\n\treturn Object.keys(merged).length > 0 ? merged : void 0;\n}\nfunction emitLog(level, message, attributes) {\n\tconst merged = contextAttributes(attributes);\n\tconst line = merged ? `${message} ${JSON.stringify(merged)}` : message;\n\t(level === \"debug\" ? console.debug : level === \"info\" ? console.info : level === \"warn\" ? console.warn : console.error)(line);\n\tif (!sink?.log) return;\n\tconst input = {\n\t\tlevel,\n\t\tmessage,\n\t\tattributes: merged\n\t};\n\tsink.log(input).catch((error) => {\n\t\tconsole.error(\"[telemetry] log sink failed\", error);\n\t});\n}\nconst log = {\n\tdebug: (message, attributes) => emitLog(\"debug\", message, attributes),\n\tinfo: (message, attributes) => emitLog(\"info\", message, attributes),\n\twarn: (message, attributes) => emitLog(\"warn\", message, attributes),\n\terror: (message, attributes) => emitLog(\"error\", message, attributes)\n};\n//#endregion\nexport { alias, captureException, configureTelemetry, event, flushTelemetry, getTelemetryContext, groupIdentify, isExpectedError, log, resetTelemetryForTests, runWithTelemetryContext, setTelemetryContext, shutdownTelemetry };\n\n//# sourceMappingURL=index.mjs.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{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","import { z } from \"zod\";\nimport { homedir } from \"node:os\";\nimport { isAbsolute, join } from \"node:path\";\nimport { spawn } from \"node:child_process\";\nimport { existsSync, mkdirSync, readFileSync, rmSync } from \"node:fs\";\nimport { defineCommand } from \"just-bash\";\n//#region src/types.ts\n/** Provider for agent-browser (`local` = Chromium on host; `browseruse` = Browser Use cloud). */\nconst BrowserProviderSchema = z.enum([\"local\", \"browseruse\"]);\n//#endregion\n//#region src/resolve.ts\nconst DEFAULT_MAC_CHROME = \"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome\";\n/** Resolve provider from explicit input or env (worker / local). */\nfunction resolveBrowserProvider(input) {\n\tif (input?.provider) return input.provider;\n\tconst fromEnv = process.env.AGENT_BROWSER_PROVIDER?.trim().toLowerCase();\n\tif (fromEnv === \"browseruse\" || fromEnv === \"browser-use\") return \"browseruse\";\n\tif ((input?.browserUseApiKey ?? process.env.BROWSER_USE_API_KEY) && process.env.PLATFORM_URL && process.env.WORKER_INTERNAL_TOKEN) return \"browseruse\";\n\tif (fromEnv === \"local\") return \"local\";\n\treturn \"local\";\n}\n/** Durable profile directory for an agent slug. */\nfunction agentBrowserProfilePath(profilesRoot, agentSlug) {\n\treturn join(profilesRoot, agentSlug.replace(/[^a-zA-Z0-9._-]/g, \"_\"));\n}\n/** Default profiles root under ~/.keystroke/browser-profiles. */\nfunction defaultBrowserProfilesRoot() {\n\treturn join(homedir(), \".keystroke\", \"browser-profiles\");\n}\n/** agent-browser session id for a Keystroke session. */\nfunction agentBrowserSessionName(sessionId) {\n\treturn `ks-${sessionId.replace(/[^a-zA-Z0-9_-]/g, \"_\").slice(0, 64)}`;\n}\nfunction resolveBrowserContext(input) {\n\tconst provider = resolveBrowserProvider({\n\t\t...input.provider ? { provider: input.provider } : {},\n\t\t...input.browserUseApiKey ? { browserUseApiKey: input.browserUseApiKey } : {}\n\t});\n\tconst browserUseApiKey = input.browserUseApiKey ?? process.env.BROWSER_USE_API_KEY;\n\tconst executablePath = input.executablePath ?? process.env.AGENT_BROWSER_EXECUTABLE_PATH ?? (provider === \"local\" && process.platform === \"darwin\" ? DEFAULT_MAC_CHROME : void 0);\n\treturn {\n\t\tagentSlug: input.agentSlug,\n\t\t...input.profileOwnerId ? { profileOwnerId: input.profileOwnerId } : {},\n\t\tsessionId: input.sessionId,\n\t\tprofilePath: agentBrowserProfilePath(input.profilesRoot, input.agentSlug),\n\t\tprovider,\n\t\tstate: {\n\t\t\tscreenshotStorageKeys: [],\n\t\t\tpendingToolImages: []\n\t\t},\n\t\t...browserUseApiKey ? { browserUseApiKey } : {},\n\t\t...executablePath ? { executablePath } : {},\n\t\t...input.sessionRoot ? { sessionRoot: input.sessionRoot } : {},\n\t\t...input.cloudProfileId ? { cloudProfileId: input.cloudProfileId } : {},\n\t\t...input.record ? { record: true } : {},\n\t\t...input.mediaHooks ? { mediaHooks: input.mediaHooks } : {}\n\t};\n}\n/** Env vars passed to every agent-browser spawn. */\nfunction browserProcessEnv(context) {\n\tconst env = {\n\t\t...process.env,\n\t\tAGENT_BROWSER_SESSION: agentBrowserSessionName(context.sessionId),\n\t\tAGENT_BROWSER_PROFILE: context.profilePath\n\t};\n\tdelete env.NODE_OPTIONS;\n\tif (context.provider === \"browseruse\") {\n\t\tif (context.state.cdpUrl) delete env.AGENT_BROWSER_PROVIDER;\n\t\telse env.AGENT_BROWSER_PROVIDER = \"browseruse\";\n\t\tif (context.browserUseApiKey) env.BROWSER_USE_API_KEY = context.browserUseApiKey;\n\t\tif (context.cloudProfileId) env.AGENT_BROWSER_CLOUD_PROFILE_ID = context.cloudProfileId;\n\t} else {\n\t\tdelete env.AGENT_BROWSER_PROVIDER;\n\t\tif (context.executablePath) env.AGENT_BROWSER_EXECUTABLE_PATH = context.executablePath;\n\t}\n\treturn env;\n}\n//#endregion\n//#region src/browser-use.ts\nconst BROWSER_USE_API = \"https://api.browser-use.com/api/v4\";\nasync function browserUseFetch(apiKey, path, init) {\n\treturn fetch(`${BROWSER_USE_API}${path}`, {\n\t\t...init,\n\t\theaders: {\n\t\t\t\"X-Browser-Use-API-Key\": apiKey,\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t...init?.headers ?? {}\n\t\t}\n\t});\n}\n/** Create a Browser Use cloud browser (for CLI open / live view). */\nasync function createBrowserUseSession(options) {\n\tconst body = {};\n\tif (options.timeout !== void 0) body.timeout = options.timeout;\n\tif (options.profileId) body.profileId = options.profileId;\n\tif (options.record) body.browserSettings = { record: true };\n\tif (options.proxyCountryCode) body.proxyCountryCode = options.proxyCountryCode;\n\tconst res = await browserUseFetch(options.apiKey, \"/browsers\", {\n\t\tmethod: \"POST\",\n\t\tbody: JSON.stringify(body)\n\t});\n\tif (!res.ok) {\n\t\tconst text = await res.text();\n\t\tthrow new Error(`Browser Use create failed (${res.status}): ${text}`);\n\t}\n\treturn await res.json();\n}\n/** Navigate a cloud browser without leaving a persistent agent-browser daemon attached. */\nasync function navigateBrowserUseSession(cdpUrl, url) {\n\tconst socket = new WebSocket(cdpUrl.replace(/^http:/, \"ws:\").replace(/^https:/, \"wss:\"));\n\tlet nextId = 1;\n\tlet pageSessionId;\n\tconst pending = /* @__PURE__ */ new Map();\n\tawait new Promise((resolve, reject) => {\n\t\tsocket.addEventListener(\"open\", () => resolve(), { once: true });\n\t\tsocket.addEventListener(\"error\", () => reject(/* @__PURE__ */ new Error(\"Browser Use CDP connection failed\")), { once: true });\n\t});\n\tsocket.addEventListener(\"message\", (event) => {\n\t\tconst message = JSON.parse(String(event.data));\n\t\tif (!message.id) return;\n\t\tconst request = pending.get(message.id);\n\t\tif (!request) return;\n\t\tpending.delete(message.id);\n\t\tif (message.error) request.reject(new Error(message.error.message ?? \"Browser Use CDP request failed\"));\n\t\telse request.resolve(message);\n\t});\n\tconst send = (method, params, sessionId) => {\n\t\tconst id = nextId++;\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tpending.set(id, {\n\t\t\t\tresolve,\n\t\t\t\treject\n\t\t\t});\n\t\t\tsocket.send(JSON.stringify({\n\t\t\t\tid,\n\t\t\t\tmethod,\n\t\t\t\t...params ? { params } : {},\n\t\t\t\t...sessionId ? { sessionId } : {}\n\t\t\t}));\n\t\t});\n\t};\n\ttry {\n\t\tconst page = ((await send(\"Target.getTargets\")).result?.targetInfos ?? []).find((target) => target.type === \"page\");\n\t\tif (!page) throw new Error(\"Browser Use page target not found\");\n\t\tpageSessionId = (await send(\"Target.attachToTarget\", {\n\t\t\ttargetId: page.targetId,\n\t\t\tflatten: true\n\t\t})).result?.sessionId;\n\t\tif (!pageSessionId) throw new Error(\"Browser Use page attachment failed\");\n\t\tawait send(\"Page.navigate\", { url }, pageSessionId);\n\t} finally {\n\t\tfor (const request of pending.values()) request.reject(/* @__PURE__ */ new Error(\"Browser Use CDP connection closed\"));\n\t\tpending.clear();\n\t\tsocket.close();\n\t}\n}\nasync function getBrowserUseSession(options) {\n\tconst res = await browserUseFetch(options.apiKey, `/browsers/${options.sessionId}`);\n\tif (!res.ok) {\n\t\tconst text = await res.text();\n\t\tthrow new Error(`Browser Use get failed (${res.status}): ${text}`);\n\t}\n\treturn await res.json();\n}\nasync function stopBrowserUseSession(options) {\n\tconst res = await browserUseFetch(options.apiKey, `/browsers/${options.sessionId}`, {\n\t\tmethod: \"PATCH\",\n\t\tbody: JSON.stringify({ action: \"stop\" })\n\t});\n\tif (!res.ok && res.status !== 404) {\n\t\tconst text = await res.text();\n\t\tthrow new Error(`Browser Use stop failed (${res.status}): ${text}`);\n\t}\n}\n/** Create or update a Browser Use profile for an agent (returns id). */\nasync function ensureBrowserUseProfile(options) {\n\tfor (const userId of [options.userId ?? options.name, options.legacyUserId].filter((value, index, all) => Boolean(value) && all.indexOf(value) === index)) {\n\t\tconst list = await browserUseFetch(options.apiKey, `/profiles?userId=${encodeURIComponent(userId)}`);\n\t\tif (list.ok) {\n\t\t\tconst data = await list.json();\n\t\t\tconst existing = (data.items ?? (Array.isArray(data) ? data : [])).find((profile) => profile.name === options.name);\n\t\t\tif (existing?.id) return existing.id;\n\t\t}\n\t}\n\tconst res = await browserUseFetch(options.apiKey, \"/profiles\", {\n\t\tmethod: \"POST\",\n\t\tbody: JSON.stringify({\n\t\t\tname: options.name,\n\t\t\tuserId: options.userId ?? options.name\n\t\t})\n\t});\n\tif (!res.ok) {\n\t\tconst text = await res.text();\n\t\tthrow new Error(`Browser Use profile create failed (${res.status}): ${text}`);\n\t}\n\treturn (await res.json()).id;\n}\nasync function deleteBrowserUseProfile(options) {\n\tconst res = await browserUseFetch(options.apiKey, `/profiles/${options.profileId}`, { method: \"DELETE\" });\n\tif (!res.ok && res.status !== 404) {\n\t\tconst text = await res.text();\n\t\tthrow new Error(`Browser Use profile delete failed (${res.status}): ${text}`);\n\t}\n}\n/** Download a remote recording URL to bytes. */\nasync function fetchRecordingBytes(recordingUrl) {\n\tconst res = await fetch(recordingUrl);\n\tif (!res.ok) throw new Error(`Failed to download recording (${res.status})`);\n\treturn new Uint8Array(await res.arrayBuffer());\n}\nfunction browserSessionMetaFromUse(options) {\n\treturn {\n\t\tagentSlug: options.agentSlug,\n\t\tsessionId: options.sessionId,\n\t\tprovider: \"browseruse\",\n\t\t...options.use.liveUrl ? { liveUrl: options.use.liveUrl } : {},\n\t\tbrowserUseSessionId: options.use.id,\n\t\t...options.cloudProfileId ? { cloudProfileId: options.cloudProfileId } : {},\n\t\tupdatedAt: (/* @__PURE__ */ new Date()).toISOString()\n\t};\n}\n//#endregion\n//#region src/media.ts\n/** Max screenshot bytes returned inline on the bash tool result (matches chat attachments). */\nconst BROWSER_TOOL_IMAGE_MAX_BYTES = 10 * 1024 * 1024;\nconst ANSI_SGR_RE = /\\u001b\\[[0-9;]*m/g;\n/** Strip SGR color codes so path regexes can match agent-browser stdout. */\nfunction stripAnsi(text) {\n\treturn text.replace(ANSI_SGR_RE, \"\");\n}\n/** True when argv invokes the screenshot subcommand (ignores global flags). */\nfunction isScreenshotCommand(args) {\n\treturn args.some((arg) => arg === \"screenshot\");\n}\n/** Resolve the path arg for `screenshot [path]`, if provided. */\nfunction screenshotOutputPath(args, cwd) {\n\tconst idx = args.findIndex((arg) => arg === \"screenshot\");\n\tif (idx < 0) return;\n\tfor (let i = idx + 1; i < args.length; i++) {\n\t\tconst arg = args[i];\n\t\tif (!arg || arg.startsWith(\"-\")) continue;\n\t\treturn isAbsolute(arg) ? arg : join(cwd, arg);\n\t}\n}\nfunction mimeTypeForScreenshotPath(path) {\n\tconst lower = path.toLowerCase();\n\tif (lower.endsWith(\".jpg\") || lower.endsWith(\".jpeg\")) return \"image/jpeg\";\n\tif (lower.endsWith(\".webp\")) return \"image/webp\";\n\treturn \"image/png\";\n}\n/** Parse a screenshot path from JSON stdout (`{\"path\":\"...\"}`) when no path arg was given. */\nfunction screenshotPathFromStdout(stdout) {\n\tconst trimmed = stripAnsi(stdout).trim();\n\tif (!trimmed) return;\n\ttry {\n\t\tconst parsed = JSON.parse(trimmed);\n\t\tif (typeof parsed.path === \"string\" && parsed.path.length > 0) return parsed.path;\n\t} catch {}\n\treturn trimmed.match(/(?:^|\\s)(\\/[^\\s]+\\.(?:png|jpe?g|webp))\\b/i)?.[1];\n}\n/** Take and clear screenshots queued for the next bash tool result. */\nfunction drainPendingToolImages(context) {\n\tconst images = context.state.pendingToolImages;\n\tcontext.state.pendingToolImages = [];\n\treturn images;\n}\n/**\n* Ensure a Browser Use stealth session exists for this Keystroke session.\n* Returns CDP argv prefix (`--cdp <url>`) when cloud; empty for local.\n*/\nasync function ensureCloudBrowserSession(context) {\n\tif (context.provider !== \"browseruse\" || !context.browserUseApiKey) return [];\n\tif (context.state.cdpUrl) return [\"--cdp\", context.state.cdpUrl];\n\tcontext.state.ensurePending ??= ensureCloudBrowserSessionOnce(context).finally(() => {\n\t\tcontext.state.ensurePending = void 0;\n\t});\n\treturn context.state.ensurePending;\n}\nasync function ensureCloudBrowserSessionOnce(context) {\n\tconst apiKey = context.browserUseApiKey;\n\tif (!context.state.hydrated) {\n\t\tcontext.state.hydrated = true;\n\t\tconst [meta, profileId] = await Promise.all([context.mediaHooks?.loadMeta?.().catch(() => null), context.mediaHooks?.loadProfileId?.().catch(() => void 0)]);\n\t\tcontext.cloudProfileId ??= profileId ?? meta?.cloudProfileId;\n\t\tif (!profileId && context.cloudProfileId) await context.mediaHooks?.persistProfileId?.(context.cloudProfileId);\n\t\tcontext.state.resumeState ??= meta?.resumeState;\n\t\tcontext.state.screenshotStorageKeys = meta?.screenshotStorageKeys ?? [];\n\t\tconst browserUseSessionId = context.state.browserUseSessionId ?? meta?.browserUseSessionId;\n\t\tif (browserUseSessionId) {\n\t\t\tconst session = await getBrowserUseSession({\n\t\t\t\tapiKey,\n\t\t\t\tsessionId: browserUseSessionId\n\t\t\t}).catch(() => null);\n\t\t\tif (session?.status === \"active\" && session.cdpUrl) {\n\t\t\t\tcontext.state.browserUseSessionId = session.id;\n\t\t\t\tcontext.state.cdpUrl = session.cdpUrl;\n\t\t\t\tcontext.state.liveUrl = session.liveUrl || void 0;\n\t\t\t\tcontext.state.timeoutAt = session.timeoutAt || void 0;\n\t\t\t\tawait context.mediaHooks?.persistMeta({\n\t\t\t\t\tbrowserUseSessionId: session.id,\n\t\t\t\t\tliveUrl: session.liveUrl ?? null,\n\t\t\t\t\t...session.timeoutAt ? { timeoutAt: session.timeoutAt } : {}\n\t\t\t\t}).catch(() => void 0);\n\t\t\t\treturn [\"--cdp\", session.cdpUrl];\n\t\t\t}\n\t\t\tawait markCloudBrowserStale(context);\n\t\t}\n\t}\n\tif (!context.cloudProfileId) {\n\t\tcontext.cloudProfileId = await ensureBrowserUseProfile({\n\t\t\tapiKey,\n\t\t\tname: `keystroke-agent-${context.agentSlug}`,\n\t\t\tuserId: context.profileOwnerId ?? context.agentSlug,\n\t\t\t...context.profileOwnerId ? { legacyUserId: context.agentSlug } : {}\n\t\t});\n\t\tawait context.mediaHooks?.persistProfileId?.(context.cloudProfileId);\n\t}\n\tconst session = await createBrowserUseSession({\n\t\tapiKey,\n\t\tprofileId: context.cloudProfileId,\n\t\ttimeout: 15,\n\t\t...context.record ? { record: true } : {}\n\t});\n\tif (!session.cdpUrl) throw new Error(\"Browser Use session missing cdpUrl\");\n\tcontext.state.hydrated = true;\n\tcontext.state.browserUseSessionId = session.id;\n\tcontext.state.cdpUrl = session.cdpUrl;\n\tcontext.state.liveUrl = session.liveUrl || void 0;\n\tcontext.state.startedAt = session.startedAt || (/* @__PURE__ */ new Date()).toISOString();\n\tcontext.state.timeoutAt = session.timeoutAt || void 0;\n\tawait context.mediaHooks?.persistMeta({\n\t\tprovider: \"browseruse\",\n\t\tbrowserUseSessionId: session.id,\n\t\tliveUrl: session.liveUrl ?? null,\n\t\tbrowserStartedAt: context.state.startedAt,\n\t\t...session.timeoutAt ? { timeoutAt: session.timeoutAt } : {}\n\t}).catch(() => void 0);\n\treturn [\"--cdp\", session.cdpUrl];\n}\nasync function markCloudBrowserStale(context) {\n\tcontext.state.hydrated = false;\n\tcontext.state.browserUseSessionId = void 0;\n\tcontext.state.cdpUrl = void 0;\n\tcontext.state.liveUrl = void 0;\n\tcontext.state.timeoutAt = void 0;\n\tawait context.mediaHooks?.persistMeta({\n\t\tbrowserUseSessionId: null,\n\t\tliveUrl: null\n\t}).catch(() => void 0);\n}\nfunction parseTabs(stdout) {\n\tconst parsed = JSON.parse(stripAnsi(stdout));\n\tconst tabs = (parsed.tabs ?? parsed.data?.tabs ?? []).flatMap((tab) => typeof tab.url === \"string\" && /^https?:\\/\\//.test(tab.url) ? [{\n\t\turl: tab.url,\n\t\t...typeof tab.title === \"string\" ? { title: tab.title } : {},\n\t\tactive: tab.active === true\n\t}] : []);\n\tif (tabs.length > 0 && !tabs.some((tab) => tab.active)) tabs[0].active = true;\n\treturn tabs;\n}\n/** Best-effort tab manifest and active screenshot for cold resume. */\nasync function captureBrowserResumeState(context) {\n\tif (!context.state.cdpUrl) return;\n\tconst prefix = [\"--cdp\", context.state.cdpUrl];\n\tconst listed = await runAgentBrowser({\n\t\tcontext,\n\t\targs: [\n\t\t\t...prefix,\n\t\t\t\"--json\",\n\t\t\t\"tab\",\n\t\t\t\"list\"\n\t\t]\n\t});\n\tif (listed.exitCode !== 0) return;\n\tconst tabs = parseTabs(listed.stdout);\n\tif (tabs.length === 0) return;\n\tlet lastScreenshotStorageKey = context.state.resumeState?.lastScreenshotStorageKey;\n\tif (!context.mediaHooks?.uploadScreenshot) {\n\t\tconst resumeState = {\n\t\t\ttabs,\n\t\t\t...lastScreenshotStorageKey ? { lastScreenshotStorageKey } : {},\n\t\t\tcapturedAt: (/* @__PURE__ */ new Date()).toISOString()\n\t\t};\n\t\tcontext.state.resumeState = resumeState;\n\t\treturn;\n\t}\n\tif (context.mediaHooks?.uploadScreenshot) {\n\t\tconst path = join(context.sessionRoot ?? process.cwd(), \".keystroke-browser-resume.png\");\n\t\tconst shot = await runAgentBrowser({\n\t\t\tcontext,\n\t\t\targs: [\n\t\t\t\t...prefix,\n\t\t\t\t\"screenshot\",\n\t\t\t\tpath\n\t\t\t]\n\t\t});\n\t\tconst screenshotPath = existsSync(path) ? path : screenshotPathFromStdout(shot.stdout);\n\t\tif (shot.exitCode === 0 && screenshotPath && existsSync(screenshotPath)) {\n\t\t\tconst key = await context.mediaHooks.uploadScreenshot(new Uint8Array(readFileSync(screenshotPath)), \"image/png\").catch(() => void 0);\n\t\t\tif (key) {\n\t\t\t\tlastScreenshotStorageKey = key;\n\t\t\t\tcontext.state.screenshotStorageKeys = [...context.state.screenshotStorageKeys, key];\n\t\t\t}\n\t\t\trmSync(screenshotPath, { force: true });\n\t\t}\n\t}\n\tconst resumeState = {\n\t\ttabs,\n\t\t...lastScreenshotStorageKey ? { lastScreenshotStorageKey } : {},\n\t\tcapturedAt: (/* @__PURE__ */ new Date()).toISOString()\n\t};\n\tcontext.state.resumeState = resumeState;\n\tawait context.mediaHooks?.persistMeta({ resumeState }).catch(() => void 0);\n}\n/**\n* After a successful screenshot command:\n* - queue base64 image parts for the bash tool (model + chat timeline)\n* - upload to org browser-media when hooks are set (Browser panel)\n*/\nasync function maybeUploadScreenshot(context, options) {\n\tif (options.exitCode !== 0 || !isScreenshotCommand(options.args)) return;\n\tconst path = screenshotOutputPath(options.args, options.cwd) ?? screenshotPathFromStdout(options.stdout);\n\tif (!path || !existsSync(path)) return;\n\tconst bytes = new Uint8Array(readFileSync(path));\n\tconst contentType = mimeTypeForScreenshotPath(path);\n\tif (bytes.byteLength > 0 && bytes.byteLength <= 10485760) context.state.pendingToolImages = [...context.state.pendingToolImages, {\n\t\tdata: Buffer.from(bytes).toString(\"base64\"),\n\t\tmimeType: contentType\n\t}];\n\tif (!context.mediaHooks?.uploadScreenshot) return;\n\tconst key = await context.mediaHooks.uploadScreenshot(bytes, contentType);\n\tif (key) {\n\t\tcontext.state.screenshotStorageKeys = [...context.state.screenshotStorageKeys, key];\n\t\tawait context.mediaHooks.persistMeta({ screenshotStorageKeys: context.state.screenshotStorageKeys }).catch(() => void 0);\n\t}\n}\n/** Stop Browser Use session and persist recording to org storage when enabled. */\nasync function finalizeCloudBrowserSession(context) {\n\tconst apiKey = context.browserUseApiKey;\n\tconst buSessionId = context.state.browserUseSessionId;\n\tif (!apiKey || !buSessionId) return;\n\tcontext.state.browserUseSessionId = void 0;\n\tcontext.state.cdpUrl = void 0;\n\tcontext.state.liveUrl = void 0;\n\tcontext.state.timeoutAt = void 0;\n\tcontext.state.hydrated = false;\n\tawait context.mediaHooks?.persistMeta({\n\t\tbrowserUseSessionId: null,\n\t\tliveUrl: null\n\t}).catch(() => void 0);\n\tawait new Promise((resolve) => setTimeout(resolve, 2100));\n\tawait stopBrowserUseSession({\n\t\tapiKey,\n\t\tsessionId: buSessionId\n\t}).catch(() => void 0);\n\tconst stopped = await getBrowserUseSession({\n\t\tapiKey,\n\t\tsessionId: buSessionId\n\t}).catch(() => null);\n\tawait context.mediaHooks?.settleUsage?.({\n\t\tbrowserUseSessionId: buSessionId,\n\t\t...stopped?.startedAt ?? context.state.startedAt ? { startedAt: stopped?.startedAt ?? context.state.startedAt } : {},\n\t\t...stopped?.finishedAt ? { finishedAt: stopped.finishedAt } : {}\n\t}).then(() => context.mediaHooks?.persistMeta({ browserUsageSettledAt: (/* @__PURE__ */ new Date()).toISOString() })).catch((err) => console.error(\"[usage] browser settlement failed:\", err));\n\tif (context.record && context.mediaHooks?.uploadRecording) {\n\t\tlet recordingUrl;\n\t\tfor (let attempt = 0; attempt < 5; attempt++) {\n\t\t\trecordingUrl = (await getBrowserUseSession({\n\t\t\t\tapiKey,\n\t\t\t\tsessionId: buSessionId\n\t\t\t}).catch(() => null))?.recordingUrl;\n\t\t\tif (recordingUrl) break;\n\t\t\tawait new Promise((r) => setTimeout(r, 1e3));\n\t\t}\n\t\tif (recordingUrl) {\n\t\t\tconst bytes = await fetchRecordingBytes(recordingUrl).catch(() => null);\n\t\t\tif (bytes) {\n\t\t\t\tconst key = await context.mediaHooks.uploadRecording(bytes, \"video/mp4\");\n\t\t\t\tif (key) {\n\t\t\t\t\tcontext.state.recordingStorageKey = key;\n\t\t\t\t\tawait context.mediaHooks.persistMeta({ recordingStorageKey: key }).catch(() => void 0);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tcontext.state.startedAt = void 0;\n}\n//#endregion\n//#region src/run.ts\n/** Spawn host `agent-browser` with the given context. */\nfunction runAgentBrowser(options) {\n\tconst { context, args, signal } = options;\n\tmkdirSync(context.profilePath, { recursive: true });\n\tconst cwd = options.cwd ?? context.sessionRoot ?? process.cwd();\n\treturn new Promise((resolve) => {\n\t\tconst child = spawn(\"agent-browser\", args, {\n\t\t\tenv: browserProcessEnv(context),\n\t\t\tcwd,\n\t\t\tstdio: [\n\t\t\t\t\"ignore\",\n\t\t\t\t\"pipe\",\n\t\t\t\t\"pipe\"\n\t\t\t],\n\t\t\tsignal\n\t\t});\n\t\tlet stdout = \"\";\n\t\tlet stderr = \"\";\n\t\tchild.stdout.setEncoding(\"utf8\");\n\t\tchild.stderr.setEncoding(\"utf8\");\n\t\tchild.stdout.on(\"data\", (chunk) => {\n\t\t\tstdout += chunk;\n\t\t});\n\t\tchild.stderr.on(\"data\", (chunk) => {\n\t\t\tstderr += chunk;\n\t\t});\n\t\tchild.on(\"error\", (err) => {\n\t\t\tresolve({\n\t\t\t\tstdout: \"\",\n\t\t\t\tstderr: err.message,\n\t\t\t\texitCode: 127\n\t\t\t});\n\t\t});\n\t\tchild.on(\"close\", (code) => {\n\t\t\tresolve({\n\t\t\t\tstdout,\n\t\t\t\tstderr,\n\t\t\t\texitCode: code ?? 1\n\t\t\t});\n\t\t});\n\t});\n}\n/** Stop the live browser for this Keystroke session (daemon + cloud browser). */\nasync function disposeAgentBrowser(context) {\n\tconst result = await runAgentBrowser({\n\t\tcontext,\n\t\targs: [\"close\"]\n\t});\n\tawait finalizeCloudBrowserSession(context);\n\treturn result;\n}\n//#endregion\n//#region src/command.ts\n/**\n* just-bash custom command that proxies `agent-browser …` to the host CLI.\n* Register via `new Bash({ customCommands: [createAgentBrowserCommand(ctx)] })`.\n*/\nfunction createAgentBrowserCommand(context) {\n\treturn defineCommand(\"agent-browser\", async (args) => {\n\t\tconst cdpPrefix = await ensureCloudBrowserSession(context);\n\t\tconst effectiveArgs = args.includes(\"--cdp\") || cdpPrefix.length === 0 ? args : [...cdpPrefix, ...args];\n\t\tconst result = await runAgentBrowser({\n\t\t\tcontext,\n\t\t\targs: effectiveArgs\n\t\t});\n\t\tawait maybeUploadScreenshot(context, {\n\t\t\targs: effectiveArgs,\n\t\t\tcwd: context.sessionRoot ?? process.cwd(),\n\t\t\tstdout: result.stdout,\n\t\t\texitCode: result.exitCode\n\t\t});\n\t\tif (result.exitCode !== 0 && context.provider === \"browseruse\" && /(?:cdp|websocket|browser).*(?:closed|disconnect|expired)|target closed|econnreset/i.test(`${result.stderr}\\n${result.stdout}`)) {\n\t\t\tawait markCloudBrowserStale(context);\n\t\t\treturn {\n\t\t\t\t...result,\n\t\t\t\tstderr: `${result.stderr}\\nBrowser expired during this command. It will resume from the last saved pages on the next browser command. Verify page state before repeating the action.`.trim()\n\t\t\t};\n\t\t}\n\t\treturn result;\n\t});\n}\n//#endregion\n//#region src/system-prompt.ts\n/** System-prompt injection when `defineAgent({ browser: true })`. */\nfunction browserSystemPromptInjection(agentSlug) {\n\treturn [\n\t\t\"Browser automation is available via `agent-browser` in the bash tool.\",\n\t\t\"Workflow: `agent-browser open <url>` → `agent-browser snapshot -i` → act with `@ref` (`click`, `fill`, `type`) → re-snapshot after navigation or DOM changes.\",\n\t\t\"Prefer snapshot + refs over screenshots. Use `agent-browser screenshot` only when the accessibility tree is insufficient — the PNG is returned as an image on the bash tool result so you can see it.\",\n\t\t\"Load detailed command help with `agent-browser skills get core` when needed.\",\n\t\t`This agent's durable login profile is bound to slug \"${agentSlug}\". If a site requires login (X, LinkedIn, etc.), ask the human to run:`,\n\t\t`  keystroke agents browser open ${agentSlug} --url <login-url>`,\n\t\t\"Then retry after they confirm they are signed in. Prefer agent-browser over web_fetch for interactive pages.\"\n\t].join(\"\\n\");\n}\n//#endregion\n//#region src/open-login.ts\n/**\n* Open a Browser Use live session on the durable profile for an agent slug.\n* Used by platform `browser/open` and by the CLI when a local API key is set.\n*/\nasync function openCloudBrowserLogin(options) {\n\tconst url = options.url ?? \"about:blank\";\n\tconst cloudProfileId = options.cloudProfileId ?? await ensureBrowserUseProfile({\n\t\tapiKey: options.apiKey,\n\t\tname: `keystroke-agent-${options.agentSlug}`,\n\t\tuserId: options.profileOwnerId ?? options.agentSlug,\n\t\t...options.profileOwnerId ? { legacyUserId: options.agentSlug } : {}\n\t});\n\tconst session = await createBrowserUseSession({\n\t\tapiKey: options.apiKey,\n\t\tprofileId: cloudProfileId,\n\t\ttimeout: options.timeout ?? 15,\n\t\t...options.record ? { record: true } : {}\n\t});\n\tconst sessionId = options.sessionId ?? `cli-${Date.now()}`;\n\tif (url !== \"about:blank\" && session.cdpUrl) await navigateBrowserUseSession(session.cdpUrl, url);\n\treturn {\n\t\tsessionId,\n\t\tbrowserUseSessionId: session.id,\n\t\tcloudProfileId,\n\t\turl,\n\t\t...session.liveUrl ? { liveUrl: session.liveUrl } : {},\n\t\t...session.cdpUrl ? { cdpUrl: session.cdpUrl } : {},\n\t\t...session.startedAt ? { startedAt: session.startedAt } : {},\n\t\t...session.timeoutAt ? { timeoutAt: session.timeoutAt } : {}\n\t};\n}\n//#endregion\nexport { BROWSER_TOOL_IMAGE_MAX_BYTES, BrowserProviderSchema, agentBrowserProfilePath, agentBrowserSessionName, browserProcessEnv, browserSessionMetaFromUse, browserSystemPromptInjection, captureBrowserResumeState, createAgentBrowserCommand, createBrowserUseSession, defaultBrowserProfilesRoot, deleteBrowserUseProfile, disposeAgentBrowser, drainPendingToolImages, ensureBrowserUseProfile, ensureCloudBrowserSession, fetchRecordingBytes, finalizeCloudBrowserSession, getBrowserUseSession, isScreenshotCommand, markCloudBrowserStale, maybeUploadScreenshot, navigateBrowserUseSession, openCloudBrowserLogin, resolveBrowserContext, resolveBrowserProvider, runAgentBrowser, screenshotOutputPath, screenshotPathFromStdout, stopBrowserUseSession, stripAnsi };\n\n//# sourceMappingURL=index.mjs.map","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/validate-unique-module-keys.ts\n/**\n* Slugs are unique per (project, primitive kind), mirroring the per-table\n* `(project_id, slug)` unique index in the database. An agent, a workflow, and a\n* trigger may all share the same slug because they live in separate tables and\n* are routed by type (`/agents/{slug}` vs `/workflows/{slug}`); two of the same\n* kind may not.\n*\n* Single pass over `entries` (O(n)) — keyed on `kind + key` so cross-kind slug\n* reuse is allowed without a nested scan.\n*/\nfunction validateUniqueModuleKeys(entries) {\n\tconst byScopedKey = /* @__PURE__ */ new Map();\n\tfor (const entry of entries) {\n\t\tconst scopedKey = `${entry.kind}\\u0000${entry.key}`;\n\t\tconst existing = byScopedKey.get(scopedKey);\n\t\tif (existing) existing.filePaths.push(entry.filePath);\n\t\telse byScopedKey.set(scopedKey, {\n\t\t\tkind: entry.kind,\n\t\t\tkey: entry.key,\n\t\t\tfilePaths: [entry.filePath]\n\t\t});\n\t}\n\tfor (const { kind, key, filePaths } of byScopedKey.values()) {\n\t\tif (filePaths.length <= 1) continue;\n\t\tthrow new Error(`Duplicate ${kind} slug \"${key}\": ${filePaths.join(\", \")}`);\n\t}\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\nexport { discoverModuleFileEntries as a, walkTypeScriptFiles as c, validateUniqueModuleKeys as i, entryIdFromFile as l, readKeystrokeIgnoreDirective as n, moduleFileKeyFromPath as o, shouldSkipKeystrokeModuleFile as r, discoverEntries as s, parseKeystrokeIgnoreDirective as t };\n\n//# sourceMappingURL=discovery-C6Un-m9-.mjs.map","import ts from \"typescript\";\nimport { createHash } from \"node:crypto\";\n//#region src/call-site-id.ts\n/** Root segment for statements in the workflow `run` body. */\nconst RUN_BODY_SEGMENT = \"run-body\";\n/** Join path segments for hashing / debugging. */\nfunction formatCallSitePath(path) {\n\treturn path.join(\">\");\n}\n/**\n* Deterministic id for a durable call site from its structural path. The Phase 5\n* build transform must compute the same path + id for each invocation.\n*/\nfunction callSiteId(path) {\n\treturn createHash(\"sha256\").update(formatCallSitePath(path)).digest(\"hex\").slice(0, 16);\n}\n/** Id for an opaque code-block node at a structural location. */\nfunction codeBlockSiteId(path) {\n\treturn callSiteId([...path, \"code-block\"]);\n}\n//#endregion\n//#region src/classify-call.ts\n/** Unwrap `await`/parenthesized wrappers down to the inner expression. */\nfunction unwrap(expr) {\n\tlet current = expr;\n\twhile (ts.isAwaitExpression(current) || ts.isParenthesizedExpression(current)) current = current.expression;\n\treturn current;\n}\n/** Leftmost identifier text of a property-access / call chain (`a.b().c` → \"a\"). */\nfunction baseIdentifierText(expr) {\n\tlet current = expr;\n\twhile (true) {\n\t\tif (ts.isPropertyAccessExpression(current)) {\n\t\t\tcurrent = current.expression;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ts.isCallExpression(current)) {\n\t\t\tcurrent = current.expression;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ts.isNonNullExpression(current) || ts.isParenthesizedExpression(current)) {\n\t\t\tcurrent = current.expression;\n\t\t\tcontinue;\n\t\t}\n\t\tbreak;\n\t}\n\treturn ts.isIdentifier(current) ? current.text : void 0;\n}\nfunction isContainerScope(node) {\n\treturn ts.isBlock(node) || ts.isSourceFile(node) || ts.isCaseBlock(node);\n}\nfunction isLoopScope(node) {\n\treturn ts.isForStatement(node) || ts.isForInStatement(node) || ts.isForOfStatement(node);\n}\nfunction bindingScope(node) {\n\tif (ts.isParameter(node)) {\n\t\tconst body = node.parent.body;\n\t\tif (body && ts.isBlock(body)) return body;\n\t}\n\tif (ts.isVariableDeclaration(node) && ts.isVariableDeclarationList(node.parent) && (node.parent.flags & ts.NodeFlags.BlockScoped) !== 0 && isLoopScope(node.parent.parent)) return node.parent.parent;\n\tlet current = node.parent;\n\twhile (current) {\n\t\tif (isContainerScope(current)) return current;\n\t\tcurrent = current.parent;\n\t}\n}\nfunction localBindings(identifier) {\n\tconst scopes = /* @__PURE__ */ new Set();\n\tlet current = identifier;\n\twhile (current) {\n\t\tif (isContainerScope(current) || isLoopScope(current)) scopes.add(current);\n\t\tcurrent = current.parent;\n\t}\n\tconst sourceFile = identifier.getSourceFile();\n\tconst bindingsByScope = /* @__PURE__ */ new Map();\n\tconst collect = (node) => {\n\t\tif ((ts.isVariableDeclaration(node) || ts.isParameter(node)) && ts.isIdentifier(node.name) && node.name.text === identifier.text) {\n\t\t\tconst scope = bindingScope(node);\n\t\t\tif (scope && scopes.has(scope)) {\n\t\t\t\tconst bindings = bindingsByScope.get(scope) ?? [];\n\t\t\t\tbindings.push(node);\n\t\t\t\tbindingsByScope.set(scope, bindings);\n\t\t\t}\n\t\t}\n\t\tts.forEachChild(node, collect);\n\t};\n\tcollect(sourceFile);\n\tconst visible = /* @__PURE__ */ new Map();\n\tcurrent = identifier.parent;\n\twhile (current) {\n\t\tif (scopes.has(current)) {\n\t\t\tconst binding = bindingsByScope.get(current)?.at(-1);\n\t\t\tif (binding) visible.set(current, binding);\n\t\t}\n\t\tcurrent = current.parent;\n\t}\n\treturn visible;\n}\nfunction importedBrainFactoryNames(sourceFile) {\n\tconst names = /* @__PURE__ */ new Set();\n\tfor (const statement of sourceFile.statements) {\n\t\tif (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier) || ![\"@keystrokehq/keystroke/brain\", \"@keystrokehq/workflow\"].includes(statement.moduleSpecifier.text)) continue;\n\t\tconst bindings = statement.importClause?.namedBindings;\n\t\tif (!bindings || !ts.isNamedImports(bindings)) continue;\n\t\tfor (const specifier of bindings.elements) if ((specifier.propertyName ?? specifier.name).text === \"brain\") names.add(specifier.name.text);\n\t}\n\treturn names;\n}\nfunction resolvesToBrainFactory(identifier) {\n\treturn importedBrainFactoryNames(identifier.getSourceFile()).has(identifier.text) && localBindings(identifier).size === 0;\n}\nfunction isBrainFactoryCall(expression) {\n\tconst value = unwrap(expression);\n\treturn ts.isCallExpression(value) && ts.isIdentifier(value.expression) && resolvesToBrainFactory(value.expression);\n}\nfunction resolvesToBrainHandleAlias(identifier) {\n\tfor (const binding of localBindings(identifier).values()) {\n\t\tif (!ts.isVariableDeclaration(binding) || !binding.initializer) return false;\n\t\treturn isBrainFactoryCall(binding.initializer);\n\t}\n\treturn false;\n}\n/**\n* Classify an expression as a durable step invocation, or return null. Handles\n* the closed grammar: `x.run(...)`, `x.scope(...).run(...)`,\n* `x.run(...).scope(...)`, `x.prompt(...)`, `promptLlm(...)`, `brain(...).operation(...)`, and\n* `ctx.sleep(...)` / `ctx.hook(...)`. Step identity is the structural\n* {@link callSiteId}; there is no user-authored step id.\n*/\nfunction classifyCall(expression, ctxParamName) {\n\tconst expr = unwrap(expression);\n\tif (!ts.isCallExpression(expr)) return null;\n\tconst callee = expr.expression;\n\tif (ts.isIdentifier(callee)) {\n\t\tif (callee.text === \"promptLlm\") return {\n\t\t\tkey: \"promptLlm\",\n\t\t\tcallKind: \"llm\"\n\t\t};\n\t\tif (callee.text === \"sleep\") return {\n\t\t\tkey: \"sleep\",\n\t\t\tcallKind: \"wait\"\n\t\t};\n\t\tif (callee.text === \"hook\") return {\n\t\t\tkey: \"hook\",\n\t\t\tcallKind: \"hook\"\n\t\t};\n\t\treturn null;\n\t}\n\tif (!ts.isPropertyAccessExpression(callee)) return null;\n\tconst method = callee.name.text;\n\tconst base = baseIdentifierText(callee.expression);\n\tif (new Set([\n\t\t\"uploadDocument\",\n\t\t\"updateMetadata\",\n\t\t\"delete\",\n\t\t\"deleteMany\",\n\t\t\"list\",\n\t\t\"search\",\n\t\t\"read\"\n\t]).has(method) && (isBrainFactoryCall(callee.expression) || ts.isIdentifier(callee.expression) && resolvesToBrainHandleAlias(callee.expression))) return {\n\t\tkey: `brain.${method}`,\n\t\tcallKind: \"brain\"\n\t};\n\tswitch (method) {\n\t\tcase \"run\":\n\t\t\tif (!base) return null;\n\t\t\treturn {\n\t\t\t\tkey: base,\n\t\t\t\tcallKind: \"workflow-step\",\n\t\t\t\timportName: base\n\t\t\t};\n\t\tcase \"prompt\":\n\t\t\tif (!base) return null;\n\t\t\treturn {\n\t\t\t\tkey: base,\n\t\t\t\tcallKind: \"agent\",\n\t\t\t\timportName: base\n\t\t\t};\n\t\tcase \"sleep\":\n\t\t\tif (base !== ctxParamName) return null;\n\t\t\treturn {\n\t\t\t\tkey: \"sleep\",\n\t\t\t\tcallKind: \"wait\"\n\t\t\t};\n\t\tcase \"hook\":\n\t\t\tif (base !== ctxParamName) return null;\n\t\t\treturn {\n\t\t\t\tkey: \"hook\",\n\t\t\t\tcallKind: \"hook\"\n\t\t\t};\n\t\tcase \"scope\": return classifyCall(callee.expression, ctxParamName);\n\t\tcase \"__site\": return classifyCall(callee.expression, ctxParamName);\n\t\tdefault: return null;\n\t}\n}\n/** Detect `Promise.all([...])` and return its element expressions. */\nfunction asPromiseAll(expression) {\n\tconst expr = unwrap(expression);\n\tif (!ts.isCallExpression(expr) || !ts.isPropertyAccessExpression(expr.expression)) return null;\n\tconst callee = expr.expression;\n\tif (!ts.isIdentifier(callee.expression) || callee.expression.text !== \"Promise\" || callee.name.text !== \"all\") return null;\n\tconst [arg] = expr.arguments;\n\tif (!arg || !ts.isArrayLiteralExpression(arg)) return null;\n\treturn [...arg.elements];\n}\n//#endregion\n//#region src/deferred-steps.ts\n/**\n* `const approval = ctx.hook(...)` / `ctx.sleep(...)` without an immediate `await` on\n* the initializer — the durable step should appear at the later `await approval` site.\n*/\nfunction deferredHookSleepCall(initializer, ctxParamName) {\n\tif (ts.isAwaitExpression(initializer)) return null;\n\tconst inner = unwrap(initializer);\n\tif (!ts.isCallExpression(inner)) return null;\n\tconst step = classifyCall(initializer, ctxParamName);\n\tif (!step || step.callKind !== \"hook\" && step.callKind !== \"wait\") return null;\n\treturn inner;\n}\nfunction isAwaitIdentifier(expression, varName) {\n\tconst inner = unwrap(expression);\n\treturn ts.isIdentifier(inner) && inner.text === varName;\n}\n/** Whether a statement is `await <varName>` (expr stmt or var decl initializer). */\nfunction statementAwaitingIdentifier(statement, varName) {\n\tif (ts.isExpressionStatement(statement)) return isAwaitIdentifier(statement.expression, varName);\n\tif (ts.isVariableStatement(statement)) {\n\t\tfor (const decl of statement.declarationList.declarations) if (decl.initializer && isAwaitIdentifier(decl.initializer, varName)) return true;\n\t}\n\tif (ts.isIfStatement(statement)) return statementAwaitingIdentifier(statement.thenStatement, varName) || (statement.elseStatement ? statementAwaitingIdentifier(statement.elseStatement, varName) : false);\n\tif (ts.isBlock(statement)) return statement.statements.some((inner) => statementAwaitingIdentifier(inner, varName));\n\tif (ts.isForStatement(statement) || ts.isForOfStatement(statement) || ts.isForInStatement(statement) || ts.isWhileStatement(statement) || ts.isDoStatement(statement)) return statementAwaitingIdentifier(statement.statement, varName);\n\tif (ts.isTryStatement(statement)) return statementAwaitingIdentifier(statement.tryBlock, varName) || (statement.catchClause ? statementAwaitingIdentifier(statement.catchClause.block, varName) : false) || (statement.finallyBlock ? statementAwaitingIdentifier(statement.finallyBlock, varName) : false);\n\treturn false;\n}\n/**\n* Path of the first later statement in the same block that `await`s `varName`, or null\n* when the handle is never awaited (falls back to inline placement at the decl site).\n*/\nfunction findDeferredAwaitPath(statements, fromIndex, blockPath, varName) {\n\tfor (let index = fromIndex + 1; index < statements.length; index++) {\n\t\tconst statement = statements[index];\n\t\tif (statementAwaitingIdentifier(statement, varName)) return [...blockPath, `stmt:${index}`];\n\t}\n\treturn null;\n}\n//#endregion\n//#region src/walk-call-sites.ts\n/**\n* The single structural traversal shared by every consumer of {@link callSiteId}:\n* the graph producer's golden map ({@link computeCallSiteIds}), the contained-id\n* collector ({@link collectContainedCallSiteIds}), and — mirrored, not shared —\n* the graph builder itself. Assigning call paths in one place keeps the\n* cross-package `callSiteId` invariant from drifting: any construct handled here\n* (ternary prongs, deferred hook/sleep, loops, switch, try, `Promise.all`,\n* same-file helper expansion) is handled identically for the map and the set.\n*/\nfunction walkCallSites(root, basePath, options, visit) {\n\tconst state = {\n\t\tctxParamName: options.ctxParamName,\n\t\tlocalFunctions: options.localFunctions,\n\t\tcallCounters: /* @__PURE__ */ new Map(),\n\t\twalked: /* @__PURE__ */ new Set(),\n\t\tvisit\n\t};\n\tif (ts.isBlock(root)) walkStatements([...root.statements], basePath, state);\n\telse if (ts.isStatement(root)) walkStatement(root, basePath, state);\n\telse if (ts.isExpression(root)) walkExpression(root, basePath, state);\n\telse ts.forEachChild(root, (child) => {\n\t\tif (ts.isStatement(child)) walkStatement(child, basePath, state);\n\t\telse if (ts.isExpression(child)) walkExpression(child, basePath, state);\n\t});\n}\nfunction nextCallPath(state, basePath) {\n\tconst key = basePath.join(\">\");\n\tconst index = state.callCounters.get(key) ?? 0;\n\tstate.callCounters.set(key, index + 1);\n\treturn [...basePath, `call:${index}`];\n}\nfunction peekCallPath(state, basePath) {\n\tconst key = basePath.join(\">\");\n\tconst index = state.callCounters.get(key) ?? 0;\n\treturn [...basePath, `call:${index}`];\n}\nfunction reserveCallPath(state, callPath) {\n\tconst callSegment = callPath.at(-1);\n\tif (!callSegment?.startsWith(\"call:\")) return;\n\tconst index = Number.parseInt(callSegment.slice(5), 10);\n\tif (Number.isNaN(index)) return;\n\tconst key = callPath.slice(0, -1).join(\">\");\n\tconst current = state.callCounters.get(key) ?? 0;\n\tstate.callCounters.set(key, Math.max(current, index + 1));\n}\nfunction walkStatements(statements, path, state) {\n\tstatements.forEach((statement, index) => {\n\t\twalkStatement(statement, [...path, `stmt:${index}`], state, statements, index);\n\t});\n}\nfunction walkStatement(statement, path, state, statements = [], statementIndex = 0) {\n\tif (ts.isReturnStatement(statement)) {\n\t\tif (statement.expression) walkExpression(statement.expression, path, state);\n\t\treturn;\n\t}\n\tif (ts.isExpressionStatement(statement)) {\n\t\twalkExpression(statement.expression, path, state);\n\t\treturn;\n\t}\n\tif (ts.isVariableStatement(statement)) {\n\t\tfor (const decl of statement.declarationList.declarations) {\n\t\t\tif (!decl.initializer) continue;\n\t\t\tconst deferredCall = deferredHookSleepCall(decl.initializer, state.ctxParamName);\n\t\t\tif (deferredCall && ts.isIdentifier(decl.name) && statements.length > 0) {\n\t\t\t\tconst awaitPath = findDeferredAwaitPath(statements, statementIndex, path.slice(0, -1), decl.name.text);\n\t\t\t\tif (awaitPath) {\n\t\t\t\t\tconst callPath = peekCallPath(state, awaitPath);\n\t\t\t\t\tstate.visit(deferredCall, callPath);\n\t\t\t\t\treserveCallPath(state, callPath);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\twalkExpression(decl.initializer, path, state);\n\t\t}\n\t\treturn;\n\t}\n\tif (ts.isIfStatement(statement)) {\n\t\tconst conditions = [];\n\t\tlet elseBranch;\n\t\tlet current = statement;\n\t\twhile (current) {\n\t\t\tconditions.push({\n\t\t\t\thandle: `cond-${conditions.length}`,\n\t\t\t\tbranch: current.thenStatement\n\t\t\t});\n\t\t\tconst next = current.elseStatement;\n\t\t\tif (next && ts.isIfStatement(next)) {\n\t\t\t\tcurrent = next;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\telseBranch = next;\n\t\t\tcurrent = void 0;\n\t\t}\n\t\tfor (const { handle, branch } of conditions) walkStatement(branch, [...path, `if:${handle}`], state);\n\t\tif (elseBranch) walkStatement(elseBranch, [...path, \"if:else\"], state);\n\t\treturn;\n\t}\n\tif (ts.isForStatement(statement) || ts.isForOfStatement(statement) || ts.isForInStatement(statement) || ts.isWhileStatement(statement) || ts.isDoStatement(statement)) {\n\t\twalkStatement(statement.statement, [...path, \"loop\"], state);\n\t\treturn;\n\t}\n\tif (ts.isSwitchStatement(statement)) {\n\t\tfor (const [index, clause] of statement.caseBlock.clauses.entries()) {\n\t\t\tconst handle = ts.isCaseClause(clause) ? `case-${index}` : \"default\";\n\t\t\twalkStatements([...clause.statements], [...path, `switch:${handle}`], state);\n\t\t}\n\t\treturn;\n\t}\n\tif (ts.isBlock(statement)) {\n\t\twalkStatements([...statement.statements], path, state);\n\t\treturn;\n\t}\n\tif (ts.isTryStatement(statement)) {\n\t\twalkStatements([...statement.tryBlock.statements], [...path, \"try\"], state);\n\t\tif (statement.catchClause?.block) walkStatements([...statement.catchClause.block.statements], [...path, \"catch\"], state);\n\t\tif (statement.finallyBlock) walkStatements([...statement.finallyBlock.statements], [...path, \"finally\"], state);\n\t}\n}\nfunction walkExpression(expression, path, state) {\n\tconst parallel = asPromiseAll(expression);\n\tif (parallel) {\n\t\tparallel.forEach((element, index) => {\n\t\t\twalkExpression(element, [...path, `parallel:${index}`], state);\n\t\t});\n\t\treturn;\n\t}\n\tif (classifyCall(expression, state.ctxParamName)) {\n\t\tconst node = unwrap(expression);\n\t\tif (ts.isCallExpression(node)) state.visit(node, nextCallPath(state, path));\n\t\treturn;\n\t}\n\tif (ts.isConditionalExpression(expression)) {\n\t\twalkExpression(expression.whenTrue, [...path, \"cond:then\"], state);\n\t\twalkExpression(expression.whenFalse, [...path, \"cond:else\"], state);\n\t\treturn;\n\t}\n\tif (ts.isCallExpression(expression) && ts.isIdentifier(expression.expression)) {\n\t\tconst helperName = expression.expression.text;\n\t\tconst helperBody = state.localFunctions.get(helperName);\n\t\tif (helperBody) {\n\t\t\tif (state.walked.has(helperName)) return;\n\t\t\tstate.walked.add(helperName);\n\t\t\tconst helperPath = [`helper:${helperName}`];\n\t\t\tif (ts.isBlock(helperBody)) walkStatements([...helperBody.statements], helperPath, state);\n\t\t\telse if (ts.isExpression(helperBody)) walkExpression(helperBody, helperPath, state);\n\t\t\treturn;\n\t\t}\n\t}\n\tts.forEachChild(expression, (child) => {\n\t\tif (ts.isExpression(child)) walkExpression(child, path, state);\n\t});\n}\n/** Convenience: collect all callSiteIds reachable from `root`. */\nfunction collectCallSiteIds(root, basePath, options) {\n\tconst out = /* @__PURE__ */ new Set();\n\twalkCallSites(root, basePath, options, (_call, callPath) => {\n\t\tout.add(callSiteId(callPath));\n\t});\n\treturn [...out];\n}\n//#endregion\n//#region src/collect-call-site-ids.ts\n/**\n* Collect durable call-site ids hidden inside an off-grammar subtree (a\n* `code-block` node's `containedCallSiteIds`). Uses the same {@link walkCallSites}\n* traversal as {@link computeCallSiteIds}, so the ids attributed to a code-block\n* always match the ids the build transform injects at those call sites.\n*/\nfunction collectContainedCallSiteIds(node, ctxParamName, localFunctions, basePath = [RUN_BODY_SEGMENT]) {\n\treturn collectCallSiteIds(node, basePath, {\n\t\tctxParamName,\n\t\tlocalFunctions\n\t});\n}\n//#endregion\n//#region src/local-functions.ts\n/**\n* Index same-file helper functions by name (top-level `function foo()` and\n* `const foo = () => {}` / function-expression consts) so step detection can\n* descend into a local helper a workflow calls. Cross-file helpers are\n* intentionally absent (single-file boundary).\n*/\nfunction collectLocalFunctions(sourceFile) {\n\tconst byName = /* @__PURE__ */ new Map();\n\tfor (const statement of sourceFile.statements) {\n\t\tif (ts.isFunctionDeclaration(statement) && statement.name && statement.body) {\n\t\t\tbyName.set(statement.name.text, statement.body);\n\t\t\tcontinue;\n\t\t}\n\t\tif (ts.isVariableStatement(statement)) {\n\t\t\tfor (const decl of statement.declarationList.declarations) if (ts.isIdentifier(decl.name) && decl.initializer && (ts.isArrowFunction(decl.initializer) || ts.isFunctionExpression(decl.initializer))) byName.set(decl.name.text, decl.initializer.body);\n\t\t}\n\t}\n\treturn byName;\n}\n//#endregion\n//#region src/helper-usage.ts\n/**\n* Count textual invocations of each same-file helper across the workflow `run`\n* body and every other same-file helper body. A helper invoked from more than\n* one call site cannot be inlined as distinct real step nodes: the build injects\n* one `callSiteId` per physical call site in the helper body, so every invocation\n* shares those ids and folds occurrences at runtime (like a loop). Rendering it as\n* one shared subgraph produces misleading cross-branch / self-loop edges, so a\n* multiply-invoked helper collapses to a per-call-site `code-block` instead.\n*/\nfunction sharedHelperNames(located, localFunctions) {\n\tconst counts = /* @__PURE__ */ new Map();\n\tconst tally = (root) => {\n\t\tconst visit = (node) => {\n\t\t\tif (ts.isCallExpression(node) && ts.isIdentifier(node.expression)) {\n\t\t\t\tconst name = node.expression.text;\n\t\t\t\tif (localFunctions.has(name)) counts.set(name, (counts.get(name) ?? 0) + 1);\n\t\t\t}\n\t\t\tts.forEachChild(node, visit);\n\t\t};\n\t\tvisit(root);\n\t};\n\ttally(located.body);\n\tfor (const body of localFunctions.values()) tally(body);\n\tconst shared = /* @__PURE__ */ new Set();\n\tfor (const [name, count] of counts) if (count >= 2) shared.add(name);\n\treturn shared;\n}\n//#endregion\n//#region src/condition-label.ts\n/** Split camelCase identifiers into sentence case (`hasBreaking` → `Has breaking`). */\nfunction prettifyCamelCaseIdentifier(name) {\n\treturn name.replace(/([a-z0-9])([A-Z])/g, \"$1 $2\").replace(/([A-Z]+)([A-Z][a-z])/g, \"$1 $2\").split(/\\s+/).map((word, index) => {\n\t\tconst lower = word.toLowerCase();\n\t\treturn index === 0 ? lower.charAt(0).toUpperCase() + lower.slice(1) : lower;\n\t}).join(\" \");\n}\nfunction unwrapParenthesized(expression) {\n\tlet current = expression;\n\twhile (ts.isParenthesizedExpression(current)) current = current.expression;\n\treturn current;\n}\nfunction identifierNameFromExpression(expression) {\n\tconst unwrapped = unwrapParenthesized(expression);\n\tif (ts.isPropertyAccessExpression(unwrapped) || ts.isPropertyAccessChain(unwrapped)) return unwrapped.name.text;\n\tif (ts.isIdentifier(unwrapped)) return unwrapped.text;\n}\n/**\n* Human-readable label for an `if`/`switch` condition. Member access and bare\n* identifiers prettify (`changes.hasBreaking` → `Has breaking`); everything\n* else falls back to normalized source text.\n*/\nfunction formatConditionLabel(expression, sourceFile) {\n\tconst identifierName = identifierNameFromExpression(expression);\n\tif (identifierName) return prettifyCamelCaseIdentifier(identifierName);\n\treturn expression.getText(sourceFile).replace(/\\s+/g, \" \").trim();\n}\n//#endregion\n//#region src/input-bindings.ts\n/**\n* Find the input-object argument of a durable call. Descends through the\n* build-injected `.__site(...)` and user `.scope(...)` wrappers to the\n* `.run({...})` / `.prompt({...})` / `promptLlm({...})` call and returns its\n* first argument (the input object literal), or undefined.\n*/\nfunction extractStepInputArg(expression) {\n\treturn unwrapToCall(expression)?.arguments[0];\n}\nfunction combineField(base, path) {\n\tif (base && path) return `${base}.${path}`;\n\treturn base ?? path;\n}\n/** Leftmost identifier + the dotted property path of a `a.b.c` chain (`{ base: \"a\", path: \"b.c\" }`). */\nfunction propertyAccessParts(expr) {\n\tconst parts = [];\n\tlet current = expr;\n\twhile (ts.isPropertyAccessExpression(current)) {\n\t\tparts.unshift(current.name.text);\n\t\tcurrent = current.expression;\n\t}\n\tif (!ts.isIdentifier(current)) return null;\n\treturn {\n\t\tbase: current.text,\n\t\tpath: parts.join(\".\")\n\t};\n}\nfunction referenceToken(source) {\n\treturn {\n\t\tkind: \"reference\",\n\t\tsourceNodeId: source.nodeId,\n\t\t...source.field ? { field: source.field } : {}\n\t};\n}\nfunction resolveIdentifier(name, scope) {\n\tif (name === scope.inputParamName) return {\n\t\tkind: \"reference\",\n\t\tsourceNodeId: scope.entryNodeId\n\t};\n\tconst source = scope.bindings.get(name);\n\tif (source) return referenceToken(source);\n\treturn {\n\t\tkind: \"variable\",\n\t\ttext: name\n\t};\n}\n/** The callee's source name for a call expression (`buildPrompt`, `jobs.map`); never its args. */\nfunction calleeName(call, sourceFile) {\n\tconst callee = call.expression;\n\tif (ts.isIdentifier(callee)) return callee.text;\n\tif (ts.isPropertyAccessExpression(callee)) {\n\t\tconst parts = propertyAccessParts(callee);\n\t\tif (parts) return `${parts.base}.${parts.path}`;\n\t}\n\treturn callee.getText(sourceFile);\n}\nfunction resolvePropertyAccess(expr, scope, sourceFile) {\n\tconst parts = propertyAccessParts(expr);\n\tif (!parts) return {\n\t\tkind: \"variable\",\n\t\ttext: expr.getText(sourceFile)\n\t};\n\tif (parts.base === scope.inputParamName) return {\n\t\tkind: \"reference\",\n\t\tsourceNodeId: scope.entryNodeId,\n\t\tfield: parts.path\n\t};\n\tconst source = scope.bindings.get(parts.base);\n\tif (source) {\n\t\tconst field = combineField(source.field, parts.path);\n\t\treturn {\n\t\t\tkind: \"reference\",\n\t\t\tsourceNodeId: source.nodeId,\n\t\t\t...field ? { field } : {}\n\t\t};\n\t}\n\treturn {\n\t\tkind: \"variable\",\n\t\ttext: expr.getText(sourceFile)\n\t};\n}\n/** Tokenize one value expression into a binding (literal text and/or upstream references). */\nfunction tokensFromExpression(expr, scope, sourceFile) {\n\tconst value = unwrap(expr);\n\tif (ts.isStringLiteralLike(value)) return { tokens: [{\n\t\tkind: \"text\",\n\t\ttext: value.text\n\t}] };\n\tif (ts.isNumericLiteral(value)) return { tokens: [{\n\t\tkind: \"text\",\n\t\ttext: value.text\n\t}] };\n\tif (value.kind === ts.SyntaxKind.TrueKeyword) return { tokens: [{\n\t\tkind: \"text\",\n\t\ttext: \"true\"\n\t}] };\n\tif (value.kind === ts.SyntaxKind.FalseKeyword) return { tokens: [{\n\t\tkind: \"text\",\n\t\ttext: \"false\"\n\t}] };\n\tif (value.kind === ts.SyntaxKind.NullKeyword) return { tokens: [{\n\t\tkind: \"text\",\n\t\ttext: \"null\"\n\t}] };\n\tif (ts.isIdentifier(value)) return { tokens: [resolveIdentifier(value.text, scope)] };\n\tif (ts.isPropertyAccessExpression(value)) return { tokens: [resolvePropertyAccess(value, scope, sourceFile)] };\n\tif (ts.isTemplateExpression(value)) {\n\t\tconst tokens = [];\n\t\tif (value.head.text) tokens.push({\n\t\t\tkind: \"text\",\n\t\t\ttext: value.head.text\n\t\t});\n\t\tfor (const span of value.templateSpans) {\n\t\t\ttokens.push(...tokensFromExpression(span.expression, scope, sourceFile).tokens);\n\t\t\tif (span.literal.text) tokens.push({\n\t\t\t\tkind: \"text\",\n\t\t\t\ttext: span.literal.text\n\t\t\t});\n\t\t}\n\t\treturn {\n\t\t\ttokens,\n\t\t\t...value.getText(sourceFile).includes(\"\\n\") ? { multiline: true } : {}\n\t\t};\n\t}\n\tif (ts.isObjectLiteralExpression(value) || ts.isArrayLiteralExpression(value)) return {\n\t\ttokens: [{\n\t\t\tkind: \"text\",\n\t\t\ttext: value.getText(sourceFile)\n\t\t}],\n\t\tmultiline: true\n\t};\n\tif (ts.isCallExpression(value)) return { tokens: [{\n\t\tkind: \"call\",\n\t\tname: calleeName(value, sourceFile)\n\t}] };\n\treturn { tokens: [{\n\t\tkind: \"variable\",\n\t\ttext: value.getText(sourceFile)\n\t}] };\n}\n/**\n* Capture per-field call-site bindings from a step's input-object argument. Each\n* property becomes a {@link WorkflowCanvasRawBinding} (literal text and/or\n* references to upstream node outputs). Returns undefined when the argument isn't\n* an object literal (e.g. `a.run(payload)`), or has no bindable properties.\n*/\nfunction inputBindingsFromCall(expression, scope, sourceFile) {\n\tconst arg = extractStepInputArg(expression);\n\tif (!arg || !ts.isObjectLiteralExpression(arg)) return;\n\tconst bindings = {};\n\tfor (const prop of arg.properties) {\n\t\tif (ts.isShorthandPropertyAssignment(prop)) {\n\t\t\tbindings[prop.name.text] = { tokens: [resolveIdentifier(prop.name.text, scope)] };\n\t\t\tcontinue;\n\t\t}\n\t\tif (ts.isPropertyAssignment(prop)) {\n\t\t\tconst key = ts.isIdentifier(prop.name) || ts.isStringLiteralLike(prop.name) ? prop.name.text : void 0;\n\t\t\tif (!key) continue;\n\t\t\tbindings[key] = tokensFromExpression(prop.initializer, scope, sourceFile);\n\t\t}\n\t}\n\treturn Object.keys(bindings).length > 0 ? bindings : void 0;\n}\n/**\n* Capture static `promptLlm(prompt, options)` config from an llm call site. Reads\n* literal `model`/`thinkingLevel` (strings) and `maxTokens`/`temperature` (numbers),\n* plus the PRESENCE of `system`/`outputSchema` (usually expressions, not literals).\n* Returns undefined when no options object literal or no recognizable fields.\n*/\nfunction llmOptionsFromCall(expression) {\n\tconst optionsArg = unwrapToCall(expression)?.arguments[1];\n\tif (!optionsArg || !ts.isObjectLiteralExpression(optionsArg)) return;\n\tconst options = {};\n\tfor (const prop of optionsArg.properties) {\n\t\tif (!ts.isPropertyAssignment(prop)) continue;\n\t\tconst key = ts.isIdentifier(prop.name) || ts.isStringLiteralLike(prop.name) ? prop.name.text : void 0;\n\t\tif (!key) continue;\n\t\tconst value = unwrap(prop.initializer);\n\t\tswitch (key) {\n\t\t\tcase \"model\":\n\t\t\t\tif (ts.isStringLiteralLike(value)) options.model = value.text;\n\t\t\t\tbreak;\n\t\t\tcase \"thinkingLevel\":\n\t\t\t\tif (ts.isStringLiteralLike(value)) options.thinkingLevel = value.text;\n\t\t\t\tbreak;\n\t\t\tcase \"maxTokens\":\n\t\t\t\tif (ts.isNumericLiteral(value)) options.maxTokens = Number(value.text);\n\t\t\t\tbreak;\n\t\t\tcase \"temperature\":\n\t\t\t\tif (ts.isNumericLiteral(value)) options.temperature = Number(value.text);\n\t\t\t\tbreak;\n\t\t\tcase \"system\":\n\t\t\t\toptions.hasSystemPrompt = true;\n\t\t\t\tbreak;\n\t\t\tcase \"outputSchema\":\n\t\t\t\toptions.hasOutputSchema = true;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\treturn Object.keys(options).length > 0 ? options : void 0;\n}\n/** Descend wrapper calls (`.scope`/`.__site`) to the underlying durable call. */\nfunction unwrapToCall(expression) {\n\tlet expr = unwrap(expression);\n\twhile (ts.isCallExpression(expr) && ts.isPropertyAccessExpression(expr.expression)) {\n\t\tconst method = expr.expression.name.text;\n\t\tif (method === \"scope\" || method === \"__site\") {\n\t\t\texpr = unwrap(expr.expression.expression);\n\t\t\tcontinue;\n\t\t}\n\t\tbreak;\n\t}\n\treturn ts.isCallExpression(expr) ? expr : void 0;\n}\n/**\n* Tokenize a `promptLlm(prompt, options)` call's options object into per-field\n* bindings (model/system/outputSchema/maxTokens/…), the same token model used for\n* action inputs — so a `model: CLASSIFY_MODEL` renders as a variable chip and a\n* `system: dailySystem()` as a call chip, instead of being dropped. Returns\n* undefined when there's no options object literal.\n*/\nfunction llmOptionBindingsFromCall(expression, scope, sourceFile) {\n\tconst optionsArg = unwrapToCall(expression)?.arguments[1];\n\tif (!optionsArg || !ts.isObjectLiteralExpression(optionsArg)) return;\n\tconst bindings = {};\n\tfor (const prop of optionsArg.properties) {\n\t\tif (ts.isShorthandPropertyAssignment(prop)) {\n\t\t\tbindings[prop.name.text] = { tokens: [resolveIdentifier(prop.name.text, scope)] };\n\t\t\tcontinue;\n\t\t}\n\t\tif (ts.isPropertyAssignment(prop)) {\n\t\t\tconst key = ts.isIdentifier(prop.name) || ts.isStringLiteralLike(prop.name) ? prop.name.text : void 0;\n\t\t\tif (!key) continue;\n\t\t\tbindings[key] = tokensFromExpression(prop.initializer, scope, sourceFile);\n\t\t}\n\t}\n\treturn Object.keys(bindings).length > 0 ? bindings : void 0;\n}\n/** Statically-evaluate a literal initializer to a scalar, or undefined if not literal. */\nfunction literalConstantValue(initializer) {\n\tconst value = unwrap(initializer);\n\tif (ts.isStringLiteralLike(value)) return value.text;\n\tif (ts.isNumericLiteral(value)) return Number(value.text);\n\tif (ts.isPrefixUnaryExpression(value) && value.operator === ts.SyntaxKind.MinusToken && ts.isNumericLiteral(value.operand)) return -Number(value.operand.text);\n\tif (value.kind === ts.SyntaxKind.TrueKeyword) return true;\n\tif (value.kind === ts.SyntaxKind.FalseKeyword) return false;\n}\n/**\n* Collect top-level `const NAME = <literal scalar>` declarations from the workflow\n* source so the platform can resolve `variable` value tokens (e.g. a model pinned to\n* a named const) to their concrete value. Scalars only — computed or non-literal\n* consts (and anything function-local) are intentionally skipped.\n*/\nfunction collectTopLevelConstants(sourceFile) {\n\tconst constants = {};\n\tfor (const statement of sourceFile.statements) {\n\t\tif (!ts.isVariableStatement(statement) || !(statement.declarationList.flags & ts.NodeFlags.Const)) continue;\n\t\tfor (const decl of statement.declarationList.declarations) {\n\t\t\tif (!ts.isIdentifier(decl.name) || !decl.initializer) continue;\n\t\t\tconst value = literalConstantValue(decl.initializer);\n\t\t\tif (value !== void 0) constants[decl.name.text] = value;\n\t\t}\n\t}\n\treturn constants;\n}\n/**\n* Record the producer outputs a variable declaration binds, so later call sites\n* can reference them. Handles `const x = await a.run()` (→ `x` = the node) and\n* `const { text } = await a.prompt()` (→ `text` = the node's `text` field).\n*/\nfunction recordDeclarationBinding(name, nodeId, scope) {\n\tif (ts.isIdentifier(name)) {\n\t\tscope.bindings.set(name.text, { nodeId });\n\t\treturn;\n\t}\n\tif (ts.isObjectBindingPattern(name)) for (const element of name.elements) {\n\t\tif (!ts.isIdentifier(element.name)) continue;\n\t\tconst field = element.propertyName && ts.isIdentifier(element.propertyName) ? element.propertyName.text : element.name.text;\n\t\tscope.bindings.set(element.name.text, {\n\t\t\tnodeId,\n\t\t\tfield\n\t\t});\n\t}\n}\n//#endregion\n//#region src/build-graph.ts\nconst ENTRY_NODE_ID = \"entry\";\nconst MAX_LABEL_LENGTH = 60;\nfunction truncate(text) {\n\tconst collapsed = text.replace(/\\s+/g, \" \").trim();\n\treturn collapsed.length > MAX_LABEL_LENGTH ? `${collapsed.slice(0, MAX_LABEL_LENGTH - 1)}…` : collapsed;\n}\n/** First-party + integration packages live under this scope; `<app>` is the slug. */\nconst APP_PACKAGE_SCOPE = \"@keystrokehq/\";\nfunction appSlugFromSpecifier(specifier) {\n\tif (!specifier.startsWith(APP_PACKAGE_SCOPE)) return;\n\treturn specifier.slice(13).split(\"/\")[0] || void 0;\n}\nfunction collectAppImportsBySymbol(sourceFile) {\n\tconst bySymbol = /* @__PURE__ */ new Map();\n\tfor (const statement of sourceFile.statements) {\n\t\tif (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) continue;\n\t\tconst appSlug = appSlugFromSpecifier(statement.moduleSpecifier.text);\n\t\tconst clause = statement.importClause;\n\t\tif (!appSlug || !clause) continue;\n\t\tif (clause.name) bySymbol.set(clause.name.text, appSlug);\n\t\tif (clause.namedBindings && ts.isNamedImports(clause.namedBindings)) for (const element of clause.namedBindings.elements) bySymbol.set(element.name.text, appSlug);\n\t}\n\treturn bySymbol;\n}\nfunction stepLabel(info) {\n\tswitch (info.callKind) {\n\t\tcase \"wait\": return \"Sleep\";\n\t\tcase \"hook\": return \"Wait for signal\";\n\t\tcase \"llm\": return info.key === \"promptLlm\" ? \"LLM prompt\" : info.key;\n\t\tcase \"brain\": return info.key.replace(\"brain.\", \"Brain \");\n\t\tcase \"agent\":\n\t\tcase \"workflow-step\": return info.key;\n\t}\n}\nvar GraphBuilder = class {\n\tsourceFile;\n\tresolveSlug;\n\tnodes = [];\n\tedges = [];\n\tnodeIds = /* @__PURE__ */ new Set();\n\tcallCounters = /* @__PURE__ */ new Map();\n\tstructuralCount = 0;\n\tedgeCount = 0;\n\texitId = null;\n\t/** >0 while walking inside a branch (if/switch/loop/try), so a `return` there\n\t* is modeled as its own local \"Output\" terminal instead of a long edge to the\n\t* single shared exit (which reads as crossing the whole graph). */\n\tinBranchDepth = 0;\n\t/** True while inlining a helper called in VALUE position (`const x = await f()`),\n\t* so a `return` inside it is a value handoff to the caller (its expression's\n\t* frontier), NOT the workflow's terminal output. False for the run body and for\n\t* helpers dispatched in tail position (`return f()`), whose returns ARE outputs. */\n\treturnAsValue = false;\n\tappImportsBySymbol;\n\tlocalFunctions;\n\t/** Same-file helpers invoked from >1 call site — collapsed to a code-block per site. */\n\tsharedHelpers = /* @__PURE__ */ new Set();\n\t/** First open endpoints per expanded helper (for deduped re-entry). */\n\thelperEntryByName = /* @__PURE__ */ new Map();\n\thelperExitByName = /* @__PURE__ */ new Map();\n\t/** Lexical symbol table for resolving call-site value references to upstream nodes. */\n\tbindingScope = {\n\t\tbindings: /* @__PURE__ */ new Map(),\n\t\tentryNodeId: ENTRY_NODE_ID\n\t};\n\t/** Hook/sleep handles created in a var decl but awaited later in the run body. */\n\tpendingDeferredSteps = /* @__PURE__ */ new Map();\n\tconstructor(sourceFile, resolveSlug) {\n\t\tthis.sourceFile = sourceFile;\n\t\tthis.resolveSlug = resolveSlug;\n\t\tthis.appImportsBySymbol = collectAppImportsBySymbol(sourceFile);\n\t\tthis.localFunctions = collectLocalFunctions(sourceFile);\n\t}\n\tsubtreeHasStep(node, ctxParamName, visiting = /* @__PURE__ */ new Set()) {\n\t\tlet found = false;\n\t\tconst visit = (current) => {\n\t\t\tif (found) return;\n\t\t\tif ((ts.isCallExpression(current) || ts.isAwaitExpression(current)) && classifyCall(current, ctxParamName)) {\n\t\t\t\tfound = true;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (ts.isCallExpression(current) && ts.isIdentifier(current.expression)) {\n\t\t\t\tconst helperBody = this.localFunctions.get(current.expression.text);\n\t\t\t\tif (helperBody && !visiting.has(current.expression.text)) {\n\t\t\t\t\tvisiting.add(current.expression.text);\n\t\t\t\t\tif (this.subtreeHasStep(helperBody, ctxParamName, visiting)) {\n\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tts.forEachChild(current, visit);\n\t\t};\n\t\tvisit(node);\n\t\treturn found;\n\t}\n\t/**\n\t* Whether a helper called in VALUE position is safe to inline as real step nodes.\n\t* Only straight-line helpers qualify — a block of variable/expression statements\n\t* with at most a single trailing `return` (no `if`/`switch`/loop/`try`/`throw`),\n\t* or a concise non-ternary expression body. Helpers with internal control flow or\n\t* multiple returns are genuinely ambiguous as values (which `return` is \"the\"\n\t* result?), so they collapse to a single `code-block` instead (run attribution is\n\t* preserved via `containedCallSiteIds`). Helpers dispatched in tail position\n\t* (`return f()`) are inlined regardless — there their returns ARE the output.\n\t*/\n\tisLinearValueHelper(helperBody) {\n\t\tif (!ts.isBlock(helperBody)) return ts.isExpression(helperBody) && !ts.isConditionalExpression(helperBody);\n\t\tlet returnCount = 0;\n\t\tconst statements = helperBody.statements;\n\t\tfor (const [index, statement] of statements.entries()) {\n\t\t\tif (ts.isVariableStatement(statement) || ts.isExpressionStatement(statement)) continue;\n\t\t\tif (ts.isReturnStatement(statement)) {\n\t\t\t\treturnCount += 1;\n\t\t\t\tif (returnCount > 1 || index !== statements.length - 1) return false;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\tbuild(located) {\n\t\tthis.sharedHelpers = sharedHelperNames(located, this.localFunctions);\n\t\tthis.bindingScope = {\n\t\t\tbindings: /* @__PURE__ */ new Map(),\n\t\t\tentryNodeId: ENTRY_NODE_ID,\n\t\t\t...located.inputParamName ? { inputParamName: located.inputParamName } : {}\n\t\t};\n\t\tconst incoming = [{ nodeId: this.addNode(\"entry\", { label: \"Start\" }, \"entry\") }];\n\t\tconst runPath = [RUN_BODY_SEGMENT];\n\t\tconst { body, ctxParamName } = located;\n\t\tconst open = ts.isBlock(body) ? this.walkStatements([...body.statements], incoming, ctxParamName, void 0, runPath) : this.walkConcise(body, incoming, ctxParamName, runPath);\n\t\tif (open.length > 0) this.connect(open, this.getExit());\n\t\tconst constants = collectTopLevelConstants(this.sourceFile);\n\t\treturn {\n\t\t\tnodes: this.nodes,\n\t\t\tedges: this.edges,\n\t\t\t...Object.keys(constants).length > 0 ? { constants } : {}\n\t\t};\n\t}\n\tpush(node) {\n\t\tthis.nodes.push(node);\n\t\tthis.nodeIds.add(node.id);\n\t\treturn node.id;\n\t}\n\taddNode(nodeType, data, id, parentId) {\n\t\tconst node = {\n\t\t\tid,\n\t\t\tnodeType,\n\t\t\tdata\n\t\t};\n\t\tif (parentId) node.parentId = parentId;\n\t\treturn this.push(node);\n\t}\n\tnextCallPath(basePath) {\n\t\tconst key = formatCallSitePath(basePath);\n\t\tconst index = this.callCounters.get(key) ?? 0;\n\t\tthis.callCounters.set(key, index + 1);\n\t\treturn [...basePath, `call:${index}`];\n\t}\n\tpeekCallPath(basePath) {\n\t\tconst key = formatCallSitePath(basePath);\n\t\tconst index = this.callCounters.get(key) ?? 0;\n\t\treturn [...basePath, `call:${index}`];\n\t}\n\t/** Reserve a precomputed call index so a later materialization does not shift ids. */\n\treserveCallPath(callPath) {\n\t\tconst callSegment = callPath.at(-1);\n\t\tif (!callSegment?.startsWith(\"call:\")) return;\n\t\tconst index = Number.parseInt(callSegment.slice(5), 10);\n\t\tif (Number.isNaN(index)) return;\n\t\tconst key = formatCallSitePath(callPath.slice(0, -1));\n\t\tconst current = this.callCounters.get(key) ?? 0;\n\t\tthis.callCounters.set(key, Math.max(current, index + 1));\n\t}\n\taddStructural(label, parentId) {\n\t\tconst id = `merge-${this.structuralCount++}`;\n\t\treturn this.addNode(\"merge\", { label }, id, parentId);\n\t}\n\taddErrorNode(label, parentId) {\n\t\tconst id = `error-${this.structuralCount++}`;\n\t\treturn this.addNode(\"error\", { label }, id, parentId);\n\t}\n\t/** A local terminal output node for an early `return` inside a branch. */\n\taddOutputNode(parentId) {\n\t\tconst id = `output-${this.structuralCount++}`;\n\t\treturn this.addNode(\"exit\", { label: \"Output\" }, id, parentId);\n\t}\n\taddDecision(label, outputs, parentId) {\n\t\tconst id = `decision-${this.structuralCount++}`;\n\t\treturn this.addNode(\"decision\", {\n\t\t\tlabel,\n\t\t\toutputs\n\t\t}, id, parentId);\n\t}\n\taddCodeBlock(label, path, parentId, containedCallSiteIds) {\n\t\tconst id = codeBlockSiteId(path);\n\t\tif (this.nodeIds.has(id)) return id;\n\t\tconst data = {\n\t\t\tlabel,\n\t\t\t...containedCallSiteIds?.length ? { containedCallSiteIds } : {}\n\t\t};\n\t\treturn this.addNode(\"code-block\", data, id, parentId);\n\t}\n\taddStep(info, expression, callPath, parentId) {\n\t\tconst id = callSiteId(callPath);\n\t\tif (this.nodeIds.has(id)) return id;\n\t\tconst data = {\n\t\t\tlabel: stepLabel(info),\n\t\t\tcallKind: info.callKind\n\t\t};\n\t\tconst appSlug = info.importName ? this.appImportsBySymbol.get(info.importName) : void 0;\n\t\tif (appSlug) data.appSlug = appSlug;\n\t\tif (info.importName && this.resolveSlug) {\n\t\t\tconst resolved = this.resolveSlug(info.importName, this.sourceFile);\n\t\t\tif (resolved) {\n\t\t\t\tdata.slug = resolved.slug;\n\t\t\t\tif (resolved.description) data.description = resolved.description;\n\t\t\t\tif (resolved.name) data.label = resolved.name;\n\t\t\t}\n\t\t}\n\t\tif (info.callKind === \"llm\") {\n\t\t\tconst llmOptions = llmOptionsFromCall(expression);\n\t\t\tif (llmOptions) data.llmOptions = llmOptions;\n\t\t\tconst optionBindings = llmOptionBindingsFromCall(expression, this.bindingScope, this.sourceFile);\n\t\t\tif (optionBindings) data.inputBindings = optionBindings;\n\t\t} else if (info.callKind !== \"wait\" && info.callKind !== \"hook\") {\n\t\t\tconst inputBindings = inputBindingsFromCall(expression, this.bindingScope, this.sourceFile);\n\t\t\tif (inputBindings) data.inputBindings = inputBindings;\n\t\t}\n\t\treturn this.addNode(\"step\", data, id, parentId);\n\t}\n\taddGroup(groupKind, label, parentId) {\n\t\tconst nodeType = groupKind === \"loop\" ? \"loop\" : \"parallel\";\n\t\tconst groupId = `${nodeType}-${this.structuralCount++}`;\n\t\tconst groupNode = {\n\t\t\tid: groupId,\n\t\t\tnodeType,\n\t\t\tdata: {\n\t\t\t\tlabel,\n\t\t\t\tgroupKind\n\t\t\t}\n\t\t};\n\t\tif (parentId) groupNode.parentId = parentId;\n\t\tthis.push(groupNode);\n\t\tconst groupStartId = `${groupId}-start`;\n\t\tthis.push({\n\t\t\tid: groupStartId,\n\t\t\tnodeType: \"loop-start\",\n\t\t\tdata: { label: \"Start\" },\n\t\t\tparentId: groupId\n\t\t});\n\t\treturn {\n\t\t\tgroupId,\n\t\t\tgroupStartId\n\t\t};\n\t}\n\tgetExit() {\n\t\tif (this.exitId === null) this.exitId = this.addNode(\"exit\", { label: \"Output\" }, \"exit\");\n\t\treturn this.exitId;\n\t}\n\taddEdge(source, target, endpoint) {\n\t\tconst edge = {\n\t\t\tid: `edge-${this.edgeCount++}`,\n\t\t\tsource,\n\t\t\ttarget\n\t\t};\n\t\tif (endpoint?.label) edge.label = endpoint.label;\n\t\tif (endpoint?.sourceHandle) edge.sourceHandle = endpoint.sourceHandle;\n\t\tif (endpoint?.branchKind) edge.data = { branchKind: endpoint.branchKind };\n\t\tthis.edges.push(edge);\n\t}\n\tconnect(incoming, target) {\n\t\tfor (const endpoint of incoming) this.addEdge(endpoint.nodeId, target, endpoint);\n\t}\n\twalkHelperCall(helperName, helperBody, incoming, ctxParamName, parentId, visiting, tailPosition) {\n\t\tconst cachedExit = this.helperExitByName.get(helperName);\n\t\tconst cachedEntry = this.helperEntryByName.get(helperName);\n\t\tif (cachedEntry && cachedExit) {\n\t\t\tthis.connect(incoming, cachedEntry);\n\t\t\treturn cachedExit.map((nodeId) => ({ nodeId }));\n\t\t}\n\t\tif (visiting.has(helperName)) return incoming;\n\t\tvisiting.add(helperName);\n\t\tconst helperPath = [`helper:${helperName}`];\n\t\tconst nodesBefore = this.nodes.length;\n\t\tconst previousReturnAsValue = this.returnAsValue;\n\t\tthis.returnAsValue = !tailPosition;\n\t\tconst result = ts.isBlock(helperBody) ? this.walkStatements([...helperBody.statements], incoming, ctxParamName, parentId, helperPath, visiting) : this.walkValue(helperBody, incoming, ctxParamName, parentId, helperPath, visiting);\n\t\tthis.returnAsValue = previousReturnAsValue;\n\t\tconst firstNewStep = this.nodes.slice(nodesBefore).find((n) => n.nodeType === \"step\");\n\t\tif (firstNewStep) {\n\t\t\tthis.helperEntryByName.set(helperName, firstNewStep.id);\n\t\t\tthis.helperExitByName.set(helperName, result.map((endpoint) => endpoint.nodeId));\n\t\t}\n\t\tvisiting.delete(helperName);\n\t\treturn result;\n\t}\n\ttryMaterializeDeferredAwait(expression, incoming, parentId) {\n\t\tlet current = expression;\n\t\twhile (ts.isAwaitExpression(current) || ts.isParenthesizedExpression(current)) current = current.expression;\n\t\tif (!ts.isIdentifier(current)) return null;\n\t\tconst pending = this.pendingDeferredSteps.get(current.text);\n\t\tif (!pending) return null;\n\t\tthis.pendingDeferredSteps.delete(current.text);\n\t\tconst id = this.addStep(pending.step, pending.expression, pending.callPath, parentId);\n\t\tthis.reserveCallPath(pending.callPath);\n\t\tthis.connect(incoming, id);\n\t\treturn [{ nodeId: id }];\n\t}\n\ttryWalkLocalHelper(expression, incoming, ctxParamName, parentId, path, visiting, tailPosition) {\n\t\tlet current = expression;\n\t\twhile (ts.isAwaitExpression(current) || ts.isParenthesizedExpression(current)) current = current.expression;\n\t\tif (!ts.isCallExpression(current) || !ts.isIdentifier(current.expression)) return null;\n\t\tconst helperName = current.expression.text;\n\t\tconst helperBody = this.localFunctions.get(helperName);\n\t\tif (!helperBody || !this.subtreeHasStep(helperBody, ctxParamName)) return null;\n\t\tif (this.sharedHelpers.has(helperName)) return null;\n\t\tif (!tailPosition && !this.isLinearValueHelper(helperBody)) return null;\n\t\treturn this.walkHelperCall(helperName, helperBody, incoming, ctxParamName, parentId, visiting, tailPosition);\n\t}\n\twalkStatements(statements, incoming, ctxParamName, parentId, path, visiting = /* @__PURE__ */ new Set()) {\n\t\tlet frontier = incoming;\n\t\tfor (const [index, statement] of statements.entries()) frontier = this.walkStatement(statement, frontier, ctxParamName, parentId, [...path, `stmt:${index}`], visiting, statements, index);\n\t\treturn frontier;\n\t}\n\twalkStatement(statement, incoming, ctxParamName, parentId, path, visiting = /* @__PURE__ */ new Set(), statements = [], statementIndex = 0) {\n\t\tif (ts.isReturnStatement(statement)) return this.walkReturn(statement, incoming, ctxParamName, parentId, path, visiting);\n\t\tif (ts.isThrowStatement(statement)) {\n\t\t\tconst id = this.addErrorNode(\"Error\", parentId);\n\t\t\tthis.connect(incoming, id);\n\t\t\treturn [];\n\t\t}\n\t\tif (ts.isExpressionStatement(statement)) return this.walkValue(statement.expression, incoming, ctxParamName, parentId, path, visiting);\n\t\tif (ts.isVariableStatement(statement)) {\n\t\t\tlet frontier = incoming;\n\t\t\tfor (const decl of statement.declarationList.declarations) {\n\t\t\t\tif (!decl.initializer) continue;\n\t\t\t\tconst deferredCall = deferredHookSleepCall(decl.initializer, ctxParamName);\n\t\t\t\tif (deferredCall && ts.isIdentifier(decl.name) && statements.length > 0) {\n\t\t\t\t\tconst awaitPath = findDeferredAwaitPath(statements, statementIndex, path.slice(0, -1), decl.name.text);\n\t\t\t\t\tif (awaitPath) {\n\t\t\t\t\t\tconst step = classifyCall(decl.initializer, ctxParamName);\n\t\t\t\t\t\tif (step) {\n\t\t\t\t\t\t\tconst callPath = this.peekCallPath(awaitPath);\n\t\t\t\t\t\t\tthis.pendingDeferredSteps.set(decl.name.text, {\n\t\t\t\t\t\t\t\tstep,\n\t\t\t\t\t\t\t\texpression: deferredCall,\n\t\t\t\t\t\t\t\tcallPath\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\trecordDeclarationBinding(decl.name, callSiteId(callPath), this.bindingScope);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst isStep = classifyCall(decl.initializer, ctxParamName) !== null;\n\t\t\t\tfrontier = this.walkValue(decl.initializer, frontier, ctxParamName, parentId, path, visiting);\n\t\t\t\tif (isStep && frontier.length === 1) recordDeclarationBinding(decl.name, frontier[0].nodeId, this.bindingScope);\n\t\t\t}\n\t\t\treturn frontier;\n\t\t}\n\t\tif (ts.isIfStatement(statement)) return this.walkIf(statement, incoming, ctxParamName, parentId, path, visiting);\n\t\tif (ts.isForStatement(statement) || ts.isForOfStatement(statement) || ts.isForInStatement(statement) || ts.isWhileStatement(statement) || ts.isDoStatement(statement)) return this.walkLoop(statement, incoming, ctxParamName, parentId, path, visiting);\n\t\tif (ts.isSwitchStatement(statement)) return this.walkSwitch(statement, incoming, ctxParamName, parentId, path, visiting);\n\t\tif (ts.isBlock(statement)) return this.walkStatements([...statement.statements], incoming, ctxParamName, parentId, path, visiting);\n\t\tif (ts.isTryStatement(statement)) return this.walkTry(statement, incoming, ctxParamName, parentId, path, visiting);\n\t\tif (this.subtreeHasStep(statement, ctxParamName)) {\n\t\t\tconst contained = collectContainedCallSiteIds(statement, ctxParamName, this.localFunctions, path);\n\t\t\tconst id = this.addCodeBlock(truncate(statement.getText(this.sourceFile)), path, parentId, contained);\n\t\t\tthis.connect(incoming, id);\n\t\t\treturn [{ nodeId: id }];\n\t\t}\n\t\treturn incoming;\n\t}\n\twalkValue(expression, incoming, ctxParamName, parentId, path, visiting = /* @__PURE__ */ new Set(), tailPosition = false) {\n\t\tconst helperWalk = this.tryWalkLocalHelper(expression, incoming, ctxParamName, parentId, path, visiting, tailPosition);\n\t\tif (helperWalk) return helperWalk;\n\t\tif (ts.isConditionalExpression(expression) && this.subtreeHasStep(expression, ctxParamName)) return this.walkConditional(expression, incoming, ctxParamName, parentId, path, visiting, tailPosition);\n\t\tconst parallel = asPromiseAll(expression);\n\t\tif (parallel) return this.walkParallel(parallel, incoming, ctxParamName, parentId, path, visiting);\n\t\tconst deferredAwait = this.tryMaterializeDeferredAwait(expression, incoming, parentId);\n\t\tif (deferredAwait) return deferredAwait;\n\t\tconst step = classifyCall(expression, ctxParamName);\n\t\tif (step) {\n\t\t\tconst id = this.addStep(step, expression, this.nextCallPath(path), parentId);\n\t\t\tthis.connect(incoming, id);\n\t\t\treturn [{ nodeId: id }];\n\t\t}\n\t\tif (this.subtreeHasStep(expression, ctxParamName)) {\n\t\t\tconst contained = collectContainedCallSiteIds(expression, ctxParamName, this.localFunctions, path);\n\t\t\tconst id = this.addCodeBlock(truncate(expression.getText(this.sourceFile)), path, parentId, contained);\n\t\t\tthis.connect(incoming, id);\n\t\t\treturn [{ nodeId: id }];\n\t\t}\n\t\treturn incoming;\n\t}\n\twalkConcise(expression, incoming, ctxParamName, path) {\n\t\tconst frontier = this.walkValue(expression, incoming, ctxParamName, void 0, path, void 0, true);\n\t\tthis.connect(frontier, this.getExit());\n\t\treturn [];\n\t}\n\twalkReturn(statement, incoming, ctxParamName, parentId, path, visiting) {\n\t\tif (this.returnAsValue) return statement.expression ? this.walkValue(statement.expression, incoming, ctxParamName, parentId, path, visiting) : incoming;\n\t\tlet frontier = incoming;\n\t\tif (statement.expression) frontier = this.walkValue(statement.expression, frontier, ctxParamName, parentId, path, visiting, true);\n\t\tconst target = this.inBranchDepth > 0 ? this.addOutputNode(parentId) : this.getExit();\n\t\tthis.connect(frontier, target);\n\t\treturn [];\n\t}\n\twalkParallel(elements, incoming, ctxParamName, parentId, path, visiting) {\n\t\tconst { groupId, groupStartId } = this.addGroup(\"parallel\", \"Parallel\", parentId);\n\t\tthis.connect(incoming, groupId);\n\t\tfor (const [index, element] of elements.entries()) {\n\t\t\tconst branchPath = [...path, `parallel:${index}`];\n\t\t\tif (!classifyCall(element, ctxParamName) && !this.subtreeHasStep(element, ctxParamName)) continue;\n\t\t\tthis.walkValue(element, [{\n\t\t\t\tnodeId: groupStartId,\n\t\t\t\tbranchKind: \"parallel-branch\"\n\t\t\t}], ctxParamName, groupId, branchPath, visiting);\n\t\t}\n\t\treturn [{ nodeId: groupId }];\n\t}\n\twalkIf(statement, incoming, ctxParamName, parentId, path, visiting) {\n\t\tthis.inBranchDepth++;\n\t\tconst conditions = [];\n\t\tlet elseBranch;\n\t\tlet current = statement;\n\t\twhile (current) {\n\t\t\tconditions.push({\n\t\t\t\thandle: `cond-${conditions.length}`,\n\t\t\t\tlabel: truncate(formatConditionLabel(current.expression, this.sourceFile)),\n\t\t\t\tbranch: current.thenStatement\n\t\t\t});\n\t\t\tconst next = current.elseStatement;\n\t\t\tif (next && ts.isIfStatement(next)) {\n\t\t\t\tcurrent = next;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\telseBranch = next;\n\t\t\tcurrent = void 0;\n\t\t}\n\t\tconst outputs = [...conditions.map(({ handle, label }) => ({\n\t\t\tid: handle,\n\t\t\tlabel\n\t\t})), {\n\t\t\tid: \"else\",\n\t\t\tlabel: \"Else\"\n\t\t}];\n\t\tconst decisionId = this.addDecision(truncate(formatConditionLabel(statement.expression, this.sourceFile)), outputs, parentId);\n\t\tthis.connect(incoming, decisionId);\n\t\tconst branchOpens = conditions.map(({ handle, branch }) => this.walkStatement(branch, [{\n\t\t\tnodeId: decisionId,\n\t\t\tbranchKind: \"then\",\n\t\t\tsourceHandle: handle\n\t\t}], ctxParamName, parentId, [...path, `if:${handle}`], visiting));\n\t\tconst elseOpen = elseBranch ? this.walkStatement(elseBranch, [{\n\t\t\tnodeId: decisionId,\n\t\t\tbranchKind: \"else\",\n\t\t\tsourceHandle: \"else\"\n\t\t}], ctxParamName, parentId, [...path, \"if:else\"], visiting) : [{\n\t\t\tnodeId: decisionId,\n\t\t\tbranchKind: \"else\",\n\t\t\tsourceHandle: \"else\"\n\t\t}];\n\t\tthis.inBranchDepth--;\n\t\treturn this.mergeBranches([...branchOpens, elseOpen], parentId);\n\t}\n\twalkConditional(expression, incoming, ctxParamName, parentId, path, visiting, tailPosition) {\n\t\tconst label = truncate(formatConditionLabel(expression.condition, this.sourceFile));\n\t\tconst outputs = [{\n\t\t\tid: \"cond-0\",\n\t\t\tlabel\n\t\t}, {\n\t\t\tid: \"else\",\n\t\t\tlabel: \"Else\"\n\t\t}];\n\t\tconst decisionId = this.addDecision(label, outputs, parentId);\n\t\tthis.connect(incoming, decisionId);\n\t\tconst thenOpen = this.walkValue(expression.whenTrue, [{\n\t\t\tnodeId: decisionId,\n\t\t\tbranchKind: \"then\",\n\t\t\tsourceHandle: \"cond-0\"\n\t\t}], ctxParamName, parentId, [...path, \"cond:then\"], visiting, tailPosition);\n\t\tconst elseOpen = this.walkValue(expression.whenFalse, [{\n\t\t\tnodeId: decisionId,\n\t\t\tbranchKind: \"else\",\n\t\t\tsourceHandle: \"else\"\n\t\t}], ctxParamName, parentId, [...path, \"cond:else\"], visiting, tailPosition);\n\t\treturn this.mergeBranches([thenOpen, elseOpen], parentId);\n\t}\n\twalkLoop(statement, incoming, ctxParamName, parentId, path, visiting) {\n\t\tthis.inBranchDepth++;\n\t\tconst label = ts.isForOfStatement(statement) ? \"For each item\" : \"Loop\";\n\t\tconst { groupId, groupStartId } = this.addGroup(\"loop\", label, parentId);\n\t\tthis.connect(incoming, groupId);\n\t\tthis.walkStatement(statement.statement, [{ nodeId: groupStartId }], ctxParamName, groupId, [...path, \"loop\"], visiting);\n\t\tthis.inBranchDepth--;\n\t\treturn [{ nodeId: groupId }];\n\t}\n\twalkSwitch(statement, incoming, ctxParamName, parentId, path, visiting) {\n\t\tthis.inBranchDepth++;\n\t\tconst clauses = statement.caseBlock.clauses;\n\t\tconst outputs = clauses.map((clause, index) => ts.isCaseClause(clause) ? {\n\t\t\tid: `case-${index}`,\n\t\t\tlabel: truncate(clause.expression.getText(this.sourceFile))\n\t\t} : {\n\t\t\tid: \"default\",\n\t\t\tlabel: \"default\"\n\t\t});\n\t\tconst decisionId = this.addDecision(truncate(formatConditionLabel(statement.expression, this.sourceFile)), outputs, parentId);\n\t\tthis.connect(incoming, decisionId);\n\t\tconst branches = clauses.map((clause, index) => {\n\t\t\tconst handle = ts.isCaseClause(clause) ? `case-${index}` : \"default\";\n\t\t\treturn this.walkStatements([...clause.statements], [{\n\t\t\t\tnodeId: decisionId,\n\t\t\t\tsourceHandle: outputs[index].id,\n\t\t\t\tbranchKind: ts.isCaseClause(clause) ? \"then\" : \"else\"\n\t\t\t}], ctxParamName, parentId, [...path, `switch:${handle}`], visiting);\n\t\t});\n\t\tthis.inBranchDepth--;\n\t\treturn this.mergeBranches(branches, parentId);\n\t}\n\twalkTry(statement, incoming, ctxParamName, parentId, path, visiting) {\n\t\tthis.inBranchDepth++;\n\t\tconst beforeTry = this.nodes.length;\n\t\tconst tryOpen = this.walkStatements([...statement.tryBlock.statements], incoming, ctxParamName, parentId, [...path, \"try\"], visiting);\n\t\tconst protectedEntry = this.nodes[beforeTry];\n\t\tconst protectedEntryId = protectedEntry?.id;\n\t\tconst protectedEntryIsStep = protectedEntry?.nodeType === \"step\";\n\t\tlet frontier = tryOpen;\n\t\tconst catchBlock = statement.catchClause?.block;\n\t\tif (catchBlock && this.subtreeHasStep(catchBlock, ctxParamName)) if (protectedEntryId && protectedEntryIsStep) {\n\t\t\tconst errorOpen = this.walkStatements([...catchBlock.statements], [{\n\t\t\t\tnodeId: protectedEntryId,\n\t\t\t\tsourceHandle: \"error\",\n\t\t\t\tbranchKind: \"error\",\n\t\t\t\tlabel: \"on error\"\n\t\t\t}], ctxParamName, parentId, [...path, \"catch\"], visiting);\n\t\t\tfrontier = this.mergeBranches([tryOpen, errorOpen], parentId);\n\t\t} else frontier = this.walkStatements([...catchBlock.statements], tryOpen, ctxParamName, parentId, [...path, \"catch\"], visiting);\n\t\tif (statement.finallyBlock) frontier = this.walkStatements([...statement.finallyBlock.statements], frontier, ctxParamName, parentId, [...path, \"finally\"], visiting);\n\t\tthis.inBranchDepth--;\n\t\treturn frontier;\n\t}\n\tmergeBranches(branches, parentId) {\n\t\tconst open = branches.flat();\n\t\tif (open.length === 0) return [];\n\t\tconst mergeId = this.addStructural(\"Merge\", parentId);\n\t\tthis.connect(open, mergeId);\n\t\treturn [{ nodeId: mergeId }];\n\t}\n};\n/** Build a workflow-canvas graph (entry → control flow → exit) from a located workflow. */\nfunction buildGraph(sourceFile, located, options) {\n\treturn new GraphBuilder(sourceFile, options?.resolveSlug).build(located);\n}\n//#endregion\n//#region src/locate-workflow.ts\nfunction isDefineWorkflowCallee(expr) {\n\tif (ts.isIdentifier(expr)) return expr.text === \"defineWorkflow\";\n\tif (ts.isPropertyAccessExpression(expr)) return expr.name.text === \"defineWorkflow\";\n\treturn false;\n}\nfunction readRunParamCtxName(params) {\n\tconst ctxParam = params[1];\n\tif (ctxParam && ts.isIdentifier(ctxParam.name)) return ctxParam.name.text;\n}\nfunction readRunParamInputName(params) {\n\tconst inputParam = params[0];\n\tif (inputParam && ts.isIdentifier(inputParam.name)) return inputParam.name.text;\n}\nfunction readWorkflowObject(obj) {\n\tlet slug;\n\tlet body;\n\tlet ctxParamName;\n\tlet inputParamName;\n\tfor (const prop of obj.properties) {\n\t\tconst name = prop.name && (ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name)) ? prop.name.text : void 0;\n\t\tif (name === \"slug\" && ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.initializer)) {\n\t\t\tslug = prop.initializer.text;\n\t\t\tcontinue;\n\t\t}\n\t\tif (name !== \"run\") continue;\n\t\tif (ts.isMethodDeclaration(prop) && prop.body) {\n\t\t\tbody = prop.body;\n\t\t\tinputParamName = readRunParamInputName(prop.parameters);\n\t\t\tctxParamName = readRunParamCtxName(prop.parameters);\n\t\t\tcontinue;\n\t\t}\n\t\tif (ts.isPropertyAssignment(prop)) {\n\t\t\tconst init = prop.initializer;\n\t\t\tif (ts.isArrowFunction(init) || ts.isFunctionExpression(init)) {\n\t\t\t\tbody = init.body;\n\t\t\t\tinputParamName = readRunParamInputName(init.parameters);\n\t\t\t\tctxParamName = readRunParamCtxName(init.parameters);\n\t\t\t}\n\t\t}\n\t}\n\tif (!body) return null;\n\treturn {\n\t\tslug,\n\t\tbody,\n\t\tinputParamName,\n\t\tctxParamName\n\t};\n}\n/**\n* Find the `defineWorkflow({ ... })` call in a source file and extract its `run`\n* body. Returns null when the file has no recognizable workflow definition.\n*/\nfunction locateWorkflow(sourceFile) {\n\tlet located = null;\n\tconst visit = (node) => {\n\t\tif (located) return;\n\t\tif (ts.isCallExpression(node) && isDefineWorkflowCallee(node.expression)) {\n\t\t\tconst [arg] = node.arguments;\n\t\t\tif (arg && ts.isObjectLiteralExpression(arg)) {\n\t\t\t\tlocated = readWorkflowObject(arg);\n\t\t\t\tif (located) return;\n\t\t\t}\n\t\t}\n\t\tts.forEachChild(node, visit);\n\t};\n\tvisit(sourceFile);\n\treturn located;\n}\n//#endregion\n//#region src/compute-call-site-ids.ts\n/**\n* Maps each durable call site in a workflow `run` body to its deterministic\n* {@link callSiteId} — the SAME id the graph producer mints for the corresponding\n* step node. The Phase 5 build transform consumes this to inject the id into the\n* compiled call so the runtime emits `step:<callSiteId>#<occurrence>`, lining run\n* events and credential consumers up 1:1 with canvas nodes.\n*\n* Keyed by the outermost durable {@link ts.CallExpression} (after unwrapping\n* `await`/parens) — i.e. the node the transform rewrites: `x.run(i)`,\n* `x.scope(s).run(i)`, `x.run(i).scope(s)`, `promptLlm(i, opts)`,\n* `ctx.sleep(d)`, `ctx.hook(opts)`.\n*\n* Shares the {@link walkCallSites} traversal with the contained-id collector so\n* the structural `callSiteId` invariant cannot drift between the two.\n*/\nfunction computeCallSiteIds(sourceFile) {\n\tconst located = locateWorkflow(sourceFile);\n\tconst map = /* @__PURE__ */ new Map();\n\tif (!located) return map;\n\twalkCallSites(located.body, [RUN_BODY_SEGMENT], {\n\t\tctxParamName: located.ctxParamName,\n\t\tlocalFunctions: collectLocalFunctions(sourceFile)\n\t}, (call, callPath) => {\n\t\tmap.set(call, callSiteId(callPath));\n\t});\n\treturn map;\n}\n//#endregion\n//#region src/locate-poll-source.ts\nfunction isDefinePollSourceCallee(expr) {\n\tif (ts.isIdentifier(expr)) return expr.text === \"definePollSource\";\n\tif (ts.isPropertyAccessExpression(expr)) return expr.name.text === \"definePollSource\";\n\treturn false;\n}\nfunction readPollObject(obj) {\n\tlet slug;\n\tlet body;\n\tfor (const prop of obj.properties) {\n\t\tconst name = prop.name && (ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name)) ? prop.name.text : void 0;\n\t\tif (name === \"slug\" && ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.initializer)) {\n\t\t\tslug = prop.initializer.text;\n\t\t\tcontinue;\n\t\t}\n\t\tif (name !== \"run\") continue;\n\t\tif (ts.isMethodDeclaration(prop) && prop.body) {\n\t\t\tbody = prop.body;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ts.isPropertyAssignment(prop)) {\n\t\t\tconst init = prop.initializer;\n\t\t\tif (ts.isArrowFunction(init) || ts.isFunctionExpression(init)) body = init.body;\n\t\t}\n\t}\n\tif (!body) return null;\n\treturn {\n\t\tslug,\n\t\tbody\n\t};\n}\nfunction locatePollSources(sourceFile) {\n\tconst located = [];\n\tconst visit = (node) => {\n\t\tif (ts.isCallExpression(node) && isDefinePollSourceCallee(node.expression)) {\n\t\t\tconst [arg] = node.arguments;\n\t\t\tif (arg && ts.isObjectLiteralExpression(arg)) {\n\t\t\t\tconst poll = readPollObject(arg);\n\t\t\t\tif (poll) {\n\t\t\t\t\tlocated.push(poll);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tts.forEachChild(node, visit);\n\t};\n\tvisit(sourceFile);\n\treturn located;\n}\nfunction nodeContains(ancestor, target) {\n\tlet found = false;\n\tconst walk = (node) => {\n\t\tif (found || node === target) {\n\t\t\tfound = node === target || found;\n\t\t\treturn;\n\t\t}\n\t\tts.forEachChild(node, walk);\n\t};\n\twalk(ancestor);\n\treturn found;\n}\nfunction isInsidePollRunBody(sourceFile, located, call) {\n\tif (ts.isBlock(located.body)) return nodeContains(located.body, call);\n\treturn located.body === call || nodeContains(located.body, call);\n}\n//#endregion\n//#region src/diagnose.ts\n/**\n* Static reliability checks over a single workflow (or would-be helper) source\n* file. ERRORS block a deploy (they produce an invisible/misleading canvas):\n* durable steps outside a workflow file, and steps nested as call arguments.\n* WARNINGS explain each degraded (opaque code-block) construct so the author can\n* opt into the supported grammar.\n*/\nfunction diagnoseWorkflowSource(source, fileName) {\n\tconst sourceFile = ts.createSourceFile(fileName, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n\tconst located = locateWorkflow(sourceFile);\n\tif (!located) return crossFileStepDiagnostics(sourceFile, fileName, locatePollSources(sourceFile));\n\tconst shared = sharedHelperNames(located, collectLocalFunctions(sourceFile));\n\treturn [\n\t\t...nestedStepArgDiagnostics(sourceFile, fileName, located.ctxParamName),\n\t\t...stepInputSpreadDiagnostics(sourceFile, fileName, located.ctxParamName),\n\t\t...opaqueCodeBlockDiagnostics(sourceFile, located, fileName, shared)\n\t];\n}\nfunction lineColumn(sourceFile, node) {\n\tconst { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile));\n\treturn {\n\t\tline: line + 1,\n\t\tcolumn: character + 1\n\t};\n}\nfunction snippet(sourceFile, node) {\n\tconst text = node.getText(sourceFile).replace(/\\s+/g, \" \").trim();\n\treturn text.length > 80 ? `${text.slice(0, 79)}…` : text;\n}\n/** Imported identifier name → its module specifier (`@keystrokehq/gmail/actions`, `../actions/x`). */\nfunction collectImportsBySymbol(sourceFile) {\n\tconst bySymbol = /* @__PURE__ */ new Map();\n\tfor (const statement of sourceFile.statements) {\n\t\tif (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) continue;\n\t\tconst specifier = statement.moduleSpecifier.text;\n\t\tconst clause = statement.importClause;\n\t\tif (!clause) continue;\n\t\tif (clause.name) bySymbol.set(clause.name.text, specifier);\n\t\tif (clause.namedBindings) {\n\t\t\tif (ts.isNamedImports(clause.namedBindings)) for (const element of clause.namedBindings.elements) bySymbol.set(element.name.text, specifier);\n\t\t\telse if (ts.isNamespaceImport(clause.namedBindings)) bySymbol.set(clause.namedBindings.name.text, specifier);\n\t\t}\n\t}\n\treturn bySymbol;\n}\n/**\n* Durable steps come from either an integration package (`@keystrokehq/<app>/...`)\n* or the project's own actions/agents (imported by relative path). Third-party\n* packages (drizzle `db.run()`, etc.) use bare, non-`@keystrokehq` specifiers, so\n* excluding those avoids false positives while still catching real project steps.\n*/\nfunction isStepBearingSpecifier(specifier) {\n\tif (!specifier) return false;\n\treturn specifier.startsWith(\"@keystrokehq/\") || specifier.startsWith(\".\");\n}\n/** Whether `call` is the object of a `.scope(...)`/`.__site(...)` chain (an inner link). */\nfunction isChainedInnerCall(call) {\n\tconst parent = call.parent;\n\treturn ts.isPropertyAccessExpression(parent) && (parent.name.text === \"scope\" || parent.name.text === \"__site\") && parent.expression === call;\n}\nfunction forEachDurableRoot(sourceFile, ctxParamName, visit) {\n\tconst walk = (node) => {\n\t\tif (ts.isCallExpression(node) && classifyCall(node, ctxParamName) && !isChainedInnerCall(node)) visit(node);\n\t\tts.forEachChild(node, walk);\n\t};\n\twalk(sourceFile);\n}\nfunction isFunctionLike(node) {\n\treturn ts.isArrowFunction(node) || ts.isFunctionExpression(node) || ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node);\n}\n/** Durable step calls in a file that is not a workflow — invisible + un-injected. */\nfunction crossFileStepDiagnostics(sourceFile, fileName, polls = []) {\n\tconst importsBySymbol = collectImportsBySymbol(sourceFile);\n\tconst out = [];\n\tconst seen = /* @__PURE__ */ new Set();\n\tforEachDurableRoot(sourceFile, void 0, (call) => {\n\t\tconst info = classifyCall(call, void 0);\n\t\tif (!info) return;\n\t\tif (!(info.callKind === \"llm\" || info.callKind === \"brain\" || (info.callKind === \"workflow-step\" || info.callKind === \"agent\") && info.importName !== void 0 && isStepBearingSpecifier(importsBySymbol.get(info.importName)))) return;\n\t\tif (polls.some((poll) => isInsidePollRunBody(sourceFile, poll, call))) return;\n\t\tconst { line, column } = lineColumn(sourceFile, call);\n\t\tconst dedupe = `${line}:${column}`;\n\t\tif (seen.has(dedupe)) return;\n\t\tseen.add(dedupe);\n\t\tout.push({\n\t\t\tseverity: \"error\",\n\t\t\tcode: \"cross-file-step\",\n\t\t\tfileName,\n\t\t\tline,\n\t\t\tcolumn,\n\t\t\tmessage: `Durable step call \\`${snippet(sourceFile, call)}\\` is outside a workflow file. Steps only run and render on the canvas when they live in a \\`defineWorkflow\\` file (its \\`run\\` body or a same-file helper). This step is invisible to the canvas and cannot be attributed to runs. Move it into the workflow, or keep this module pure (return data; let the workflow call the step).`\n\t\t});\n\t});\n\treturn out;\n}\n/** Durable step calls nested as an argument to another call — the inner step is dropped. */\nfunction nestedStepArgDiagnostics(sourceFile, fileName, ctxParamName) {\n\tconst out = [];\n\tconst seen = /* @__PURE__ */ new Set();\n\tforEachDurableRoot(sourceFile, ctxParamName, (call) => {\n\t\tlet node = call;\n\t\tlet parent = node.parent;\n\t\twhile (parent && !ts.isSourceFile(parent)) {\n\t\t\tif (isFunctionLike(parent)) return;\n\t\t\tif (ts.isCallExpression(parent) && parent.arguments.includes(node)) {\n\t\t\t\tif (asPromiseAll(parent)) return;\n\t\t\t\tconst { line, column } = lineColumn(sourceFile, call);\n\t\t\t\tconst dedupe = `${line}:${column}`;\n\t\t\t\tif (!seen.has(dedupe)) {\n\t\t\t\t\tseen.add(dedupe);\n\t\t\t\t\tout.push({\n\t\t\t\t\t\tseverity: \"error\",\n\t\t\t\t\t\tcode: \"nested-step-arg\",\n\t\t\t\t\t\tfileName,\n\t\t\t\t\t\tline,\n\t\t\t\t\t\tcolumn,\n\t\t\t\t\t\tmessage: `Durable step call \\`${snippet(sourceFile, call)}\\` is nested as an argument to \\`${snippet(sourceFile, parent.expression)}(…)\\`. The nested step is dropped from the canvas (and un-attributable in runs). Assign it to a variable first, then pass the variable: \\`const r = await step.run(…); other.run({ x: r });\\`.`\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (ts.isStatement(parent)) return;\n\t\t\tnode = parent;\n\t\t\tparent = parent.parent;\n\t\t}\n\t});\n\treturn out;\n}\n/** Spread / computed keys in a step input object — silently missing from the inspector. */\nfunction stepInputSpreadDiagnostics(sourceFile, fileName, ctxParamName) {\n\tconst out = [];\n\tforEachDurableRoot(sourceFile, ctxParamName, (call) => {\n\t\tconst arg = extractStepInputArg(call);\n\t\tif (!arg || !ts.isObjectLiteralExpression(arg)) return;\n\t\tfor (const prop of arg.properties) {\n\t\t\tconst isSpread = ts.isSpreadAssignment(prop);\n\t\t\tconst isComputed = ts.isPropertyAssignment(prop) && ts.isComputedPropertyName(prop.name);\n\t\t\tif (!isSpread && !isComputed) continue;\n\t\t\tconst { line, column } = lineColumn(sourceFile, prop);\n\t\t\tout.push({\n\t\t\t\tseverity: \"warning\",\n\t\t\t\tcode: \"step-input-spread\",\n\t\t\t\tfileName,\n\t\t\t\tline,\n\t\t\t\tcolumn,\n\t\t\t\tmessage: `${isSpread ? \"Spread\" : \"Computed-key\"} property \\`${snippet(sourceFile, prop)}\\` in a step input isn't shown in the step inspector. List the fields explicitly so each input renders as a value chip.`\n\t\t\t});\n\t\t}\n\t});\n\treturn out;\n}\nfunction opaqueCodeBlockReason(label, shared) {\n\tif (/\\bPromise\\.(race|allSettled|any)\\b/.test(label)) return \"Promise.race/allSettled/any isn't modeled as branches; it renders opaque.\";\n\tif (/\\bPromise\\.all\\b/.test(label)) return \"Promise.all over a computed array (e.g. `.map(...)`) can't be shown as parallel branches. Pass an array literal of explicit step calls, or use a for-of loop.\";\n\tif (/\\.(map|forEach|filter|reduce|flatMap)\\s*\\(/.test(label)) return \"Array-method iteration (`.map`/`.filter`/`.forEach`) containing steps renders as one opaque block. Use a for-of loop to render an explicit loop.\";\n\tconst helperMatch = label.match(/(?:await\\s+)?([A-Za-z0-9_$]+)\\s*\\(/);\n\tif (helperMatch && shared.has(helperMatch[1])) return `Helper \\`${helperMatch[1]}\\` is called from more than one site, so each call renders as an opaque block (its steps share one id and can't be shown individually). Inline it, or call the steps directly in \\`run()\\`.`;\n\treturn \"This construct is outside the supported grammar and renders as an opaque block; the steps inside it aren't shown individually.\";\n}\n/** One warning per opaque code-block the producer emits, with an explicit reason. */\nfunction opaqueCodeBlockDiagnostics(sourceFile, located, fileName, shared) {\n\tlet graph;\n\ttry {\n\t\tgraph = buildGraph(sourceFile, located);\n\t} catch {\n\t\treturn [];\n\t}\n\treturn graph.nodes.filter((node) => node.nodeType === \"code-block\").map((node) => {\n\t\tconst label = node.data.label ?? \"\";\n\t\treturn {\n\t\t\tseverity: \"warning\",\n\t\t\tcode: \"opaque-code-block\",\n\t\t\tfileName,\n\t\t\tmessage: `Renders as an opaque code block: \\`${label}\\`. ${opaqueCodeBlockReason(label, shared)}`\n\t\t};\n\t});\n}\n//#endregion\n//#region src/index.ts\n/**\n* Deterministic deploy-time producer: parse a workflow's TypeScript source and\n* emit its control-flow skeleton (entry → steps/branches/loops → exit) as a\n* {@link WorkflowCanvasGraph}.\n*/\nfunction buildWorkflowCanvasGraph(source, options = {}) {\n\tconst sourceFile = ts.createSourceFile(options.fileName ?? \"workflow.ts\", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n\tconst located = locateWorkflow(sourceFile);\n\tif (!located) return null;\n\treturn buildGraph(sourceFile, located, { resolveSlug: options.resolveSlug });\n}\n//#endregion\nexport { RUN_BODY_SEGMENT, buildWorkflowCanvasGraph, callSiteId, classifyCall, codeBlockSiteId, collectLocalFunctions, computeCallSiteIds, diagnoseWorkflowSource, formatCallSitePath, locateWorkflow, sharedHelperNames, unwrap };\n\n//# sourceMappingURL=index.mjs.map","import { dirname, join } from \"node:path\";\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport { z } from \"zod\";\n//#region src/sandbox-dirs.ts\n/** @deprecated Use {@link resolveSessionRoot}. Kept for tests migrating off session-only layout. */\nfunction resolveSandboxRoot(workspacesRoot, sessionId) {\n\treturn resolveSessionRoot(workspacesRoot, sessionId);\n}\nfunction resolveAgentRoot(workspacesRoot, agentId) {\n\treturn join(workspacesRoot, \"agents\", agentId);\n}\nfunction resolveSessionRoot(workspacesRoot, sessionId) {\n\treturn join(workspacesRoot, \"sessions\", sessionId);\n}\nasync function ensureWorkspaceDir(workspaceRoot) {\n\tawait mkdir(workspaceRoot, { recursive: true });\n}\n/**\n* Seed a workspace file only when it does not already exist. Materialization\n* re-runs on every agent turn for the same session, so unconditionally writing\n* would clobber edits the agent made to definition/skill files in earlier turns.\n* Writing with the `wx` flag makes the seed idempotent and non-destructive: the\n* first turn (or a fresh mounted bucket fork) seeds the files; later turns leave\n* existing files untouched. Returns whether the file was written.\n*/\nasync function writeWorkspaceFileIfAbsent(filePath, content) {\n\tawait mkdir(dirname(filePath), { recursive: true });\n\ttry {\n\t\tawait writeFile(filePath, content, { flag: \"wx\" });\n\t\treturn true;\n\t} catch (error) {\n\t\tif (error.code === \"EEXIST\") return false;\n\t\tthrow error;\n\t}\n}\n//#endregion\n//#region src/files/sizes.ts\n/**\n* Author-facing VM size presets (legacy).\n* Hosted Modal ignores `size` (small request + burst). Local microsandbox still maps\n* presets to guest CPU/RAM via {@link resolveSandboxResources}.\n*/\nconst SandboxSizeSchema = z.enum([\n\t\"small\",\n\t\"medium\",\n\t\"large\"\n]);\nconst DEFAULT_SANDBOX_SIZE = \"small\";\n/** Default bash / VM exec timeout (3 minutes). */\nconst DEFAULT_EXEC_TIMEOUT_MS = 18e4;\n/** Hard cap for a single bash / exec call (10 minutes). */\nconst MAX_EXEC_TIMEOUT_MS = 6e5;\nconst SIZE_RESOURCES = {\n\tsmall: {\n\t\tcpu: 1,\n\t\tmemoryGiB: 1,\n\t\tdiskGiB: 3,\n\t\tmemoryMiB: 1024\n\t},\n\tmedium: {\n\t\tcpu: 2,\n\t\tmemoryGiB: 4,\n\t\tdiskGiB: 8,\n\t\tmemoryMiB: 4096\n\t},\n\tlarge: {\n\t\tcpu: 4,\n\t\tmemoryGiB: 8,\n\t\tdiskGiB: 10,\n\t\tmemoryMiB: 8192\n\t}\n};\nfunction normalizeSandboxSize(size) {\n\treturn size ?? \"small\";\n}\nfunction resolveSandboxResources(size) {\n\treturn SIZE_RESOURCES[normalizeSandboxSize(size)];\n}\n/** Default command timeout in seconds (always 180 regardless of size). */\nfunction defaultCommandTimeoutSeconds(_size) {\n\treturn DEFAULT_EXEC_TIMEOUT_MS / 1e3;\n}\n/** Default command timeout in milliseconds. */\nfunction defaultCommandTimeoutMs(_size) {\n\treturn DEFAULT_EXEC_TIMEOUT_MS;\n}\n/** Clamp an optional exec timeout; falls back to 180s (not size-aware). */\nfunction resolveExecTimeoutMs(requestedMs, _size) {\n\tif (requestedMs === void 0 || !Number.isFinite(requestedMs) || requestedMs <= 0) return DEFAULT_EXEC_TIMEOUT_MS;\n\treturn Math.min(Math.floor(requestedMs), MAX_EXEC_TIMEOUT_MS);\n}\n//#endregion\nexport { defaultCommandTimeoutMs as a, resolveExecTimeoutMs as c, resolveAgentRoot as d, resolveSandboxRoot as f, SandboxSizeSchema as i, resolveSandboxResources as l, writeWorkspaceFileIfAbsent as m, DEFAULT_SANDBOX_SIZE as n, defaultCommandTimeoutSeconds as o, resolveSessionRoot as p, MAX_EXEC_TIMEOUT_MS as r, normalizeSandboxSize as s, DEFAULT_EXEC_TIMEOUT_MS as t, ensureWorkspaceDir as u };\n\n//# sourceMappingURL=sizes-CeGfTo5B.mjs.map","import { createRequire } from \"node:module\";\nimport { basename, join, relative } from \"node:path\";\nimport { existsSync, readFileSync, readdirSync, statSync } from \"node:fs\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\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 isEmptyManifest(manifest) {\n\treturn Object.keys(manifest.skills).length === 0 && Object.keys(manifest.files).length === 0;\n}\nfunction loadAssetManifest(appRoot) {\n\tconst built = loadBuiltManifest(appRoot);\n\tif (built && !isEmptyManifest(built)) return built;\n\tconst fromDisk = packAssetDirs(appRoot);\n\tif (!isEmptyManifest(fromDisk)) return fromDisk;\n\treturn built ?? fromDisk;\n}\nfunction resolveAppRoot(options) {\n\treturn options.appRoot ?? getBoundAppRoot() ?? process.env.KEYSTROKE_ROOT ?? process.cwd();\n}\nfunction normalizeProjectFileRef(ref) {\n\tconst normalized = ref.trim().replaceAll(\"\\\\\", \"/\");\n\tif (!normalized) throw new Error(\"sandbox files ref must be a non-empty path under src/files/\");\n\tif (normalized.startsWith(\"/\") || normalized.startsWith(\"src/files/\") || normalized === \"src/files\") throw new Error(`sandbox files ref \"${ref}\" must be relative to src/files/ (e.g. \"support\" or \"support/guide.md\")`);\n\tif (normalized.split(\"/\").some((part) => part === \".\" || part === \"..\")) throw new Error(`sandbox files ref \"${ref}\" must not contain \".\" or \"..\"`);\n\treturn normalized;\n}\nfunction toSandboxFiles(entries) {\n\treturn entries.map((entry) => ({\n\t\tpath: entry.path,\n\t\tfile: entry.file\n\t}));\n}\nfunction loadProjectFileRef(ref, options) {\n\tconst normalized = normalizeProjectFileRef(ref);\n\tconst manifest = loadAssetManifest(resolveAppRoot(options));\n\tconst setFiles = manifest.files[normalized];\n\tif (setFiles?.length) return toSandboxFiles(setFiles);\n\tconst slash = normalized.indexOf(\"/\");\n\tif (slash === -1) throw new Error(`Unknown file set \"${normalized}\" — expected src/files/${normalized}/`);\n\tconst setKey = normalized.slice(0, slash);\n\tconst relativePath = normalized.slice(slash + 1);\n\tconst files = manifest.files[setKey];\n\tif (!files?.length) throw new Error(`Unknown file set \"${setKey}\" — expected src/files/${setKey}/`);\n\tconst exact = files.filter((entry) => entry.path === relativePath);\n\tif (exact.length) return toSandboxFiles(exact);\n\tconst prefix = relativePath.endsWith(\"/\") ? relativePath : `${relativePath}/`;\n\tconst nested = files.filter((entry) => entry.path.startsWith(prefix));\n\tif (nested.length) return toSandboxFiles(nested);\n\tthrow new Error(`Unknown file \"${normalized}\" — expected src/files/${normalized} (file or directory)`);\n}\n/** Reject destinations where one path is a file and another nests under it as a directory. */\nfunction assertNoPathPrefixConflicts(paths) {\n\tconst pathSet = new Set(paths);\n\tfor (const path of pathSet) {\n\t\tlet separator = path.indexOf(\"/\");\n\t\twhile (separator !== -1) {\n\t\t\tconst parent = path.slice(0, separator);\n\t\t\tif (pathSet.has(parent)) throw new Error(`Conflicting sandbox files: \"${parent}\" cannot be both a file and a parent of \"${path}\"`);\n\t\t\tseparator = path.indexOf(\"/\", separator + 1);\n\t\t}\n\t}\n}\nfunction mergeSandboxFiles(entries) {\n\tconst byPath = /* @__PURE__ */ new Map();\n\tfor (const entry of entries) {\n\t\tconst existing = byPath.get(entry.path);\n\t\tif (!existing) {\n\t\t\tbyPath.set(entry.path, entry);\n\t\t\tcontinue;\n\t\t}\n\t\tif (existing.file !== entry.file || existing.dir !== entry.dir) throw new Error(`Conflicting sandbox files for path \"${entry.path}\"`);\n\t}\n\tassertNoPathPrefixConflicts(byPath.keys());\n\treturn [...byPath.values()];\n}\nfunction resolveLegacyTrueSlug(options) {\n\tconst projectSlug = options.projectSlug?.trim();\n\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\treturn projectSlug;\n}\nfunction isProjectFileRefs(files) {\n\treturn files === true || typeof files === \"string\" || Array.isArray(files) && typeof files[0] === \"string\";\n}\nfunction resolveSandboxFiles(files, options) {\n\tif (files === void 0) return;\n\tif (isProjectFileRefs(files)) return mergeSandboxFiles((files === true ? [resolveLegacyTrueSlug(options)] : typeof files === \"string\" ? [files] : files).flatMap((ref) => loadProjectFileRef(ref, options)));\n\treturn files;\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...input.size !== void 0 ? { size: input.size } : {},\n\t\t...resolvedFiles !== void 0 ? { files: resolvedFiles } : {},\n\t\t...input.credentials !== void 0 ? { credentials: input.credentials } : {},\n\t\t...input.env !== void 0 ? { env: input.env } : {},\n\t\t...input.git !== void 0 ? { git: input.git } : {},\n\t\t...input.setup !== void 0 ? { setup: input.setup } : {}\n\t};\n}\n//#endregion\nexport { packAssetDirs as a, runWithAppRoot as i, resolveSandboxDefinition as n, packDirFromDisk as o, getBoundAppRoot as r, loadAssetManifest as t };\n\n//# sourceMappingURL=resolve-sandbox-definition-Bgbd2rfm.mjs.map","import { d as resolveAgentRoot, i as SandboxSizeSchema, m as writeWorkspaceFileIfAbsent, u as ensureWorkspaceDir } from \"./sizes-CeGfTo5B.mjs\";\nimport \"./resolve-sandbox-definition-Bgbd2rfm.mjs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { z } from \"zod\";\nimport { credentialInputSchema, normalizeCredentialList } from \"@keystrokehq/shared/action-runtime\";\nimport { existsSync, statSync } from \"node:fs\";\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/**\n* Author-facing project file refs under `src/files/`.\n* - `true` — legacy: agent slug set (`src/files/<agent-slug>/`) at resolve time\n* - string — one set directory or file path\n* - string[] — multiple sets and/or file paths\n*/\nconst SandboxProjectFilesSchema = z.union([\n\tz.literal(true),\n\tz.string().trim().min(1),\n\tz.array(z.string().trim().min(1)).min(1)\n]);\n/** Author-facing sandbox files: project refs under `src/files/`, or inline entries. */\nconst SandboxFilesInputSchema = z.union([SandboxProjectFilesSchema, z.array(SandboxFileSchema)]);\nconst GITHUB_REPOSITORY_PATTERN = /^[A-Za-z0-9_.-]+\\/[A-Za-z0-9_.-]+$/;\nconst SANDBOX_ENV_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;\nconst DEFAULT_GIT_USER_NAME = \"Keystroke Agent\";\nconst DEFAULT_GIT_USER_EMAIL = \"agent@keystroke.local\";\nconst DEFAULT_GIT_CLONE_PATH = \"/workspace/session/repo\";\nconst GIT_TOKEN_ENV_KEYS = [\"GH_TOKEN\", \"GITHUB_TOKEN\"];\nconst SandboxGitUserSchema = z.object({\n\tname: z.string().trim().min(1),\n\temail: z.string().trim().min(1)\n});\nconst SandboxGitCloneSchema = z.object({\n\trepository: z.string().trim().min(1).regex(GITHUB_REPOSITORY_PATTERN, \"repository must be \\\"owner/repo\\\"\"),\n\tcredential: z.string().trim().min(1),\n\t/** Branch or tag to check out. Ignored when `commit` is set. */\n\tbranch: z.string().trim().min(1).optional(),\n\t/**\n\t* Full 40-character commit SHA. Checked out after clone/fetch.\n\t* Prefer this over `branch` when pinning an exact revision.\n\t* Abbreviated SHAs are rejected — `git fetch origin <sha>` requires the full object id.\n\t*/\n\tcommit: z.string().trim().regex(/^[0-9a-f]{40}$/i, \"commit must be a full 40-character hex SHA\").optional(),\n\t/**\n\t* When true (default), use a shallow clone/fetch (`--depth 1`).\n\t* Set `false` for full history.\n\t*/\n\tshallow: z.boolean().optional(),\n\tpath: z.string().trim().min(1).optional()\n});\nconst SandboxGitSchema = z.object({\n\tclone: SandboxGitCloneSchema,\n\tuser: SandboxGitUserSchema.optional()\n});\nconst SandboxEnvFnSchema = z.custom((value) => typeof value === \"function\", \"env must be a function\");\n/** Author-facing first-session setup commands (`defineSandbox({ setup })`). */\nconst SandboxSetupSchema = z.array(z.string().trim().min(1)).min(1);\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\t/**\n\t* Legacy VM size preset. Requires `mode: \"vm\"`. Hosted Modal ignores this;\n\t* microsandbox may still map it to guest resources.\n\t*/\n\tsize: SandboxSizeSchema.optional(),\n\tcredentials: z.array(credentialInputSchema).optional(),\n\tenv: SandboxEnvFnSchema.optional(),\n\tgit: SandboxGitSchema.optional(),\n\t/**\n\t* One-shot install commands when the session sandbox is first created\n\t* (like Cursor `install` — not for starting long-lived servers).\n\t*/\n\tsetup: SandboxSetupSchema.optional()\n}).superRefine((value, ctx) => {\n\tif ((value.size !== void 0 || value.credentials !== void 0 || value.env !== void 0 || value.git !== void 0 || value.setup !== void 0) && value.mode !== \"vm\") ctx.addIssue({\n\t\tcode: \"custom\",\n\t\tmessage: \"sandbox size, credentials, env, git, and setup require mode: \\\"vm\\\"\",\n\t\tpath: [\"mode\"]\n\t});\n\tif ((value.env !== void 0 || value.git !== void 0) && !value.credentials?.length) ctx.addIssue({\n\t\tcode: \"custom\",\n\t\tmessage: \"sandbox env and git require a non-empty credentials list\",\n\t\tpath: [\"credentials\"]\n\t});\n\tif (value.credentials) {\n\t\tconst keys = value.credentials.map((item) => item.key);\n\t\tconst seen = /* @__PURE__ */ new Set();\n\t\tfor (const key of keys) {\n\t\t\tif (seen.has(key)) ctx.addIssue({\n\t\t\t\tcode: \"custom\",\n\t\t\t\tmessage: `duplicate sandbox credential key \"${key}\"`,\n\t\t\t\tpath: [\"credentials\"]\n\t\t\t});\n\t\t\tseen.add(key);\n\t\t}\n\t\tif (value.git && !seen.has(value.git.clone.credential)) ctx.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tmessage: `git.clone.credential \"${value.git.clone.credential}\" must be declared in credentials`,\n\t\t\tpath: [\n\t\t\t\t\"git\",\n\t\t\t\t\"clone\",\n\t\t\t\t\"credential\"\n\t\t\t]\n\t\t});\n\t}\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\tsize: SandboxSizeSchema.optional(),\n\tfiles: z.array(SandboxFileSchema).optional(),\n\tcredentials: z.array(credentialInputSchema).optional(),\n\tenv: SandboxEnvFnSchema.optional(),\n\tgit: SandboxGitSchema.optional(),\n\tsetup: SandboxSetupSchema.optional()\n});\n/** Validate author sandbox env output after the callback runs. */\nfunction validateSandboxEnvOutput(env, options = {}) {\n\tconst result = {};\n\tfor (const [key, value] of Object.entries(env)) {\n\t\tif (!SANDBOX_ENV_NAME_PATTERN.test(key)) throw new Error(`Invalid sandbox env name \"${key}\"`);\n\t\tif (typeof value !== \"string\") throw new Error(`Sandbox env \"${key}\" must be a string`);\n\t\tif (options.rejectGitTokenKeys && GIT_TOKEN_ENV_KEYS.includes(key)) throw new Error(`Sandbox env must not set ${key} when git bootstrap is configured — it is injected automatically`);\n\t\tresult[key] = value;\n\t}\n\treturn result;\n}\n/** Parse and validate an author sandbox definition. */\nfunction parseSandboxDefinitionInput(input) {\n\treturn SandboxDefinitionInputSchema.parse(input);\n}\n/** Normalize git user with Keystroke defaults. */\nfunction resolveSandboxGitUser(user) {\n\treturn {\n\t\tname: user?.name?.trim() || \"Keystroke Agent\",\n\t\temail: user?.email?.trim() || \"agent@keystroke.local\"\n\t};\n}\n/** Normalize credential list when present on a sandbox definition. */\nfunction normalizeSandboxCredentials(credentials) {\n\tif (!credentials?.length) return;\n\treturn normalizeCredentialList(credentials);\n}\n//#endregion\n//#region src/files/define-sandbox.ts\nfunction defineSandbox(def) {\n\tparseSandboxDefinitionInput(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/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 { normalizeSandboxCredentials as C, validateSandboxEnvOutput as E, SandboxSetupSchema as S, resolveSandboxGitUser as T, SandboxGitCloneSchema as _, defineSandbox as a, SandboxModeSchema as b, DEFAULT_GIT_USER_NAME as c, SANDBOX_ENV_NAME_PATTERN as d, SandboxDefinitionInputSchema as f, SandboxFilesInputSchema as g, SandboxFileSchema as h, flattenSandboxFiles as i, GITHUB_REPOSITORY_PATTERN as l, SandboxFileContentSchema as m, resolveAppRootFromModule as n, DEFAULT_GIT_CLONE_PATH as o, SandboxDefinitionSchema as p, materializeSandbox as r, DEFAULT_GIT_USER_EMAIL as s, resolveAppRoot as t, GIT_TOKEN_ENV_KEYS as u, SandboxGitSchema as v, parseSandboxDefinitionInput as w, SandboxProjectFilesSchema as x, SandboxGitUserSchema as y };\n\n//# sourceMappingURL=files-Ds9QSoth.mjs.map","import { posix } from \"node:path\";\nimport { z } from \"zod\";\nimport { randomUUID } from \"node:crypto\";\nimport { defineTool } from \"@keystrokehq/shared/action-runtime\";\n//#region src/exec-job-types.ts\n/** Soft foreground wait for bash / bash_job wait (never cancels). */\nconst DEFAULT_EXEC_SOFT_WAIT_MS = 3e4;\n/**\n* Hard ceiling on a single soft wait slice. Long enough that a quiet build\n* does not force a poll every 30s (Codex caps empty polls at 300s too);\n* `bash` itself still defaults to {@link DEFAULT_EXEC_SOFT_WAIT_MS}.\n*/\nconst MAX_EXEC_SOFT_WAIT_MS = 3e5;\n/** Max stdout+stderr bytes returned per wait snapshot (delta). */\nconst DEFAULT_EXEC_JOB_DELTA_BYTES = 32 * 1024;\n/** Guest path prefix for per-job logs under the session mount. */\nconst EXEC_JOB_LOG_DIR = \"/workspace/session/tool-output\";\nfunction execJobLogPath(jobId) {\n\treturn `${EXEC_JOB_LOG_DIR}/bash-${jobId}.log`;\n}\n/**\n* Slice a bounded output delta from `offset`. With `tailBias` (terminal\n* snapshots), oversized remainders return the last `maxBytes` instead of the\n* next front slice — the end of a build log is where the errors are; the\n* skipped middle stays available at the job's log path.\n*/\nfunction sliceOutputDelta(text, offset, maxBytes, options) {\n\tconst buf = Buffer.from(text, \"utf8\");\n\tconst safeOffset = Math.max(0, Math.min(offset, buf.byteLength));\n\tif (safeOffset >= buf.byteLength) return {\n\t\tdelta: \"\",\n\t\tnextOffset: buf.byteLength,\n\t\ttruncated: false,\n\t\tskippedBytes: 0\n\t};\n\tconst remaining = buf.subarray(safeOffset);\n\tif (remaining.byteLength <= maxBytes) return {\n\t\tdelta: remaining.toString(\"utf8\"),\n\t\tnextOffset: buf.byteLength,\n\t\ttruncated: false,\n\t\tskippedBytes: 0\n\t};\n\tif (options?.tailBias) {\n\t\tif (maxBytes <= 0) return {\n\t\t\tdelta: \"\",\n\t\t\tnextOffset: safeOffset,\n\t\t\ttruncated: true,\n\t\t\tskippedBytes: 0\n\t\t};\n\t\tconst tailStart = buf.byteLength - maxBytes;\n\t\treturn {\n\t\t\tdelta: buf.subarray(tailStart).toString(\"utf8\"),\n\t\t\tnextOffset: buf.byteLength,\n\t\t\ttruncated: false,\n\t\t\tskippedBytes: tailStart - safeOffset\n\t\t};\n\t}\n\treturn {\n\t\tdelta: remaining.subarray(0, maxBytes).toString(\"utf8\"),\n\t\tnextOffset: safeOffset + maxBytes,\n\t\ttruncated: true,\n\t\tskippedBytes: 0\n\t};\n}\nfunction resolveSoftWaitMs(requestedMs) {\n\tif (requestedMs === void 0 || !Number.isFinite(requestedMs) || requestedMs < 0) return DEFAULT_EXEC_SOFT_WAIT_MS;\n\treturn Math.min(Math.floor(requestedMs), MAX_EXEC_SOFT_WAIT_MS);\n}\n/** Build a terminal ExecResult from a settled job snapshot (for sync exec adapters). */\nfunction execResultFromSnapshot(snapshot) {\n\tif (snapshot.state === \"failed\") return {\n\t\tstdout: snapshot.stdout,\n\t\tstderr: snapshot.stderr || snapshot.error || \"Exec job failed\",\n\t\texitCode: snapshot.exitCode ?? 1\n\t};\n\tif (snapshot.state === \"cancelled\") return {\n\t\tstdout: snapshot.stdout,\n\t\tstderr: snapshot.stderr || \"Command cancelled\",\n\t\texitCode: snapshot.exitCode ?? 130\n\t};\n\treturn {\n\t\tstdout: snapshot.stdout,\n\t\tstderr: snapshot.stderr,\n\t\texitCode: snapshot.exitCode ?? 0\n\t};\n}\n//#endregion\n//#region src/in-memory-exec-jobs.ts\nfunction isTerminalState(state) {\n\treturn state === \"completed\" || state === \"cancelled\" || state === \"failed\";\n}\nfunction toSnapshot(job, deltaBytes, advanceDelivered) {\n\tconst tailBias = isTerminalState(job.state);\n\tconst stdoutSlice = sliceOutputDelta(job.stdout, job.deliveredStdoutOffset, deltaBytes, { tailBias });\n\tconst stderrBudget = Math.max(0, deltaBytes - Buffer.byteLength(stdoutSlice.delta, \"utf8\"));\n\tconst stderrSlice = sliceOutputDelta(job.stderr, job.deliveredStderrOffset, stderrBudget, { tailBias });\n\tif (advanceDelivered) {\n\t\tjob.deliveredStdoutOffset = stdoutSlice.nextOffset;\n\t\tjob.deliveredStderrOffset = stderrSlice.nextOffset;\n\t}\n\tconst skippedBytes = stdoutSlice.skippedBytes + stderrSlice.skippedBytes;\n\treturn {\n\t\tjobId: job.jobId,\n\t\tstate: job.state,\n\t\t...job.description !== void 0 ? { description: job.description } : {},\n\t\tstdout: stdoutSlice.delta,\n\t\tstderr: stderrSlice.delta,\n\t\tstdoutOffset: stdoutSlice.nextOffset,\n\t\tstderrOffset: stderrSlice.nextOffset,\n\t\t...job.exitCode !== void 0 ? { exitCode: job.exitCode } : {},\n\t\telapsedMs: Date.now() - job.startedAt,\n\t\toutputPath: job.outputPath,\n\t\toutputTruncated: stdoutSlice.truncated || stderrSlice.truncated,\n\t\t...skippedBytes > 0 ? { skippedBytes } : {},\n\t\t...job.error !== void 0 ? { error: job.error } : {}\n\t};\n}\nasync function persistLog(writeLog, job) {\n\tif (!writeLog) return;\n\tconst parts = [];\n\tif (job.stdout) parts.push(job.stdout);\n\tif (job.stderr) parts.push(job.stderr);\n\tif (job.exitCode !== void 0 && job.exitCode !== 0) parts.push(`[exit ${job.exitCode}]`);\n\tif (job.error) parts.push(job.error);\n\ttry {\n\t\tawait writeLog(job.outputPath, parts.join(\"\\n\"));\n\t} catch {}\n}\n/**\n* In-process tracked exec jobs for just-bash (and similar cooperative runners).\n* Cancellation is AbortSignal-based and may surface as `cancel_requested` until\n* the underlying run settles — never claim `cancelled` early.\n*/\nfunction createInMemoryExecJobs(options) {\n\tconst jobs = /* @__PURE__ */ new Map();\n\tconst deltaBytes = options.deltaBytes ?? 32768;\n\tlet disposing = false;\n\tconst getJob = (jobId) => {\n\t\tconst job = jobs.get(jobId);\n\t\tif (!job) throw new Error(`Unknown exec job: ${jobId}`);\n\t\treturn job;\n\t};\n\treturn {\n\t\tasync startExec(script, startOptions) {\n\t\t\tif (disposing) throw new Error(\"Sandbox is disposing; cannot start exec jobs\");\n\t\t\tconst jobId = startOptions?.jobId?.trim() || randomUUID();\n\t\t\tif (jobs.get(jobId)) return { jobId };\n\t\t\tlet settle;\n\t\t\tconst settled = new Promise((resolve) => {\n\t\t\t\tsettle = resolve;\n\t\t\t});\n\t\t\tconst controller = new AbortController();\n\t\t\tif (startOptions?.signal) if (startOptions.signal.aborted) controller.abort(startOptions.signal.reason);\n\t\t\telse startOptions.signal.addEventListener(\"abort\", () => {\n\t\t\t\tcontroller.abort(startOptions.signal?.reason);\n\t\t\t}, { once: true });\n\t\t\tconst job = {\n\t\t\t\tjobId,\n\t\t\t\tscript,\n\t\t\t\t...startOptions?.description !== void 0 ? { description: startOptions.description } : {},\n\t\t\t\tstartedAt: Date.now(),\n\t\t\t\tcontroller,\n\t\t\t\tstate: controller.signal.aborted ? \"cancel_requested\" : \"running\",\n\t\t\t\tstdout: \"\",\n\t\t\t\tstderr: \"\",\n\t\t\t\toutputPath: execJobLogPath(jobId),\n\t\t\t\tdeliveredStdoutOffset: 0,\n\t\t\t\tdeliveredStderrOffset: 0,\n\t\t\t\tsettled,\n\t\t\t\tsettle\n\t\t\t};\n\t\t\tjobs.set(jobId, job);\n\t\t\ttry {\n\t\t\t\tawait options.beforeStart?.(script);\n\t\t\t} catch (error) {\n\t\t\t\tjobs.delete(jobId);\n\t\t\t\tjob.settle();\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tif (options.writeLog) try {\n\t\t\t\tawait options.writeLog(job.outputPath, \"[running] Output is captured when the command settles. For live progress, have the command append to a session file (e.g. >> session/name.log).\\n\");\n\t\t\t} catch {}\n\t\t\tconst runOptions = {\n\t\t\t\t...startOptions?.cwd !== void 0 ? { cwd: startOptions.cwd } : {},\n\t\t\t\t...startOptions?.env !== void 0 ? { env: startOptions.env } : {},\n\t\t\t\t...startOptions?.stdin !== void 0 ? { stdin: startOptions.stdin } : {},\n\t\t\t\tsignal: controller.signal\n\t\t\t};\n\t\t\t(async () => {\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await options.run(script, runOptions, controller.signal);\n\t\t\t\t\tjob.stdout = result.stdout;\n\t\t\t\t\tjob.stderr = result.stderr;\n\t\t\t\t\tjob.exitCode = result.exitCode;\n\t\t\t\t\tif (job.state === \"cancel_requested\" || controller.signal.aborted) job.state = \"cancelled\";\n\t\t\t\t\telse job.state = \"completed\";\n\t\t\t\t\tawait persistLog(options.writeLog, job);\n\t\t\t\t\tawait options.afterTerminal?.(script, result);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\t\tjob.error = message;\n\t\t\t\t\tjob.stderr = job.stderr ? `${job.stderr}\\n${message}` : message;\n\t\t\t\t\tjob.exitCode = job.exitCode ?? 1;\n\t\t\t\t\tif (job.state === \"cancel_requested\" || controller.signal.aborted) job.state = \"cancelled\";\n\t\t\t\t\telse job.state = \"failed\";\n\t\t\t\t\tawait persistLog(options.writeLog, job);\n\t\t\t\t\tawait options.afterTerminal?.(script, {\n\t\t\t\t\t\tstdout: job.stdout,\n\t\t\t\t\t\tstderr: job.stderr,\n\t\t\t\t\t\texitCode: job.exitCode\n\t\t\t\t\t});\n\t\t\t\t} finally {\n\t\t\t\t\tjob.settle();\n\t\t\t\t}\n\t\t\t})();\n\t\t\treturn { jobId };\n\t\t},\n\t\tasync waitExec(jobId, waitOptions) {\n\t\t\tconst job = getJob(jobId);\n\t\t\tconst waitMs = resolveSoftWaitMs(waitOptions?.waitMs);\n\t\t\tif (job.state === \"running\" || job.state === \"cancel_requested\") await Promise.race([job.settled, new Promise((resolve) => {\n\t\t\t\tconst timer = setTimeout(resolve, waitMs);\n\t\t\t\tconst onAbort = () => {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\tresolve();\n\t\t\t\t};\n\t\t\t\tif (waitOptions?.signal) {\n\t\t\t\t\tif (waitOptions.signal.aborted) {\n\t\t\t\t\t\tonAbort();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\twaitOptions.signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\t}\n\t\t\t})]);\n\t\t\tif (waitOptions?.stdoutOffset !== void 0) job.deliveredStdoutOffset = waitOptions.stdoutOffset;\n\t\t\tif (waitOptions?.stderrOffset !== void 0) job.deliveredStderrOffset = waitOptions.stderrOffset;\n\t\t\treturn toSnapshot(job, deltaBytes, true);\n\t\t},\n\t\tasync cancelExec(jobId) {\n\t\t\tconst job = getJob(jobId);\n\t\t\tif (job.state === \"running\") {\n\t\t\t\tjob.state = \"cancel_requested\";\n\t\t\t\tjob.controller.abort();\n\t\t\t} else if (job.state === \"cancel_requested\" && !job.controller.signal.aborted) job.controller.abort();\n\t\t\treturn toSnapshot(job, deltaBytes, false);\n\t\t},\n\t\tasync listExec() {\n\t\t\treturn [...jobs.values()].sort((a, b) => b.startedAt - a.startedAt).map((job) => ({\n\t\t\t\tjobId: job.jobId,\n\t\t\t\tstate: job.state,\n\t\t\t\t...job.description !== void 0 ? { description: job.description } : {},\n\t\t\t\telapsedMs: Date.now() - job.startedAt,\n\t\t\t\t...job.exitCode !== void 0 ? { exitCode: job.exitCode } : {},\n\t\t\t\toutputPath: job.outputPath\n\t\t\t}));\n\t\t},\n\t\tasync disposeJobs() {\n\t\t\tdisposing = true;\n\t\t\tconst active = [...jobs.values()].filter((job) => job.state === \"running\" || job.state === \"cancel_requested\");\n\t\t\tfor (const job of active) {\n\t\t\t\tif (job.state === \"running\") job.state = \"cancel_requested\";\n\t\t\t\tjob.controller.abort();\n\t\t\t}\n\t\t\tawait Promise.all(active.map((job) => job.settled));\n\t\t}\n\t};\n}\n//#endregion\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/sandbox-path.ts\nfunction resolveSandboxPath(path, options) {\n\tif (posix.isAbsolute(path)) return posix.normalize(path);\n\tconst cwd = options?.cwd ? posix.isAbsolute(options.cwd) ? options.cwd : posix.resolve(WORKSPACE_MOUNT, options.cwd) : WORKSPACE_MOUNT;\n\treturn posix.resolve(cwd, path);\n}\n//#endregion\n//#region src/tools/helpers/format-exec.ts\n/** Model-facing text for a job snapshot (bounded deltas + status footer). */\nfunction formatExecJobSnapshot(snapshot) {\n\tconst parts = [];\n\tif (snapshot.stdout) parts.push(snapshot.stdout);\n\tif (snapshot.stderr) parts.push(snapshot.stderr);\n\tif (snapshot.state === \"completed\") {\n\t\tif (snapshot.exitCode !== void 0 && snapshot.exitCode !== 0) parts.push(`[exit ${snapshot.exitCode}]`);\n\t} else if (snapshot.state === \"cancelled\") parts.push(`[cancelled${snapshot.exitCode !== void 0 ? ` exit ${snapshot.exitCode}` : \"\"}]`);\n\telse if (snapshot.state === \"failed\") parts.push(`[failed${snapshot.error ? `: ${snapshot.error}` : \"\"}]`);\n\telse if (snapshot.state === \"cancel_requested\") parts.push(`[cancel_requested] Cancellation requested; command may still be stopping. Use bash_job to wait. Log: ${snapshot.outputPath}`);\n\telse parts.push(`[running jobId=${snapshot.jobId}] Still running after ${snapshot.elapsedMs}ms. Use bash_job to wait or cancel. Log: ${snapshot.outputPath}`);\n\tif (snapshot.outputTruncated) parts.push(`[output truncated; full log at ${snapshot.outputPath}]`);\n\tif (snapshot.skippedBytes) parts.push(`[skipped ${snapshot.skippedBytes} earlier bytes; full log at ${snapshot.outputPath}]`);\n\treturn parts.join(\"\\n\").trim() || \"(no output)\";\n}\n/** Model-facing text for bash_job action=list. */\nfunction formatExecJobList(summaries) {\n\tif (summaries.length === 0) return \"(no bash jobs in this session)\";\n\treturn summaries.map((job) => {\n\t\treturn [\n\t\t\t`jobId=${job.jobId}`,\n\t\t\t`state=${job.state}`,\n\t\t\t...job.exitCode !== void 0 ? [`exit=${job.exitCode}`] : [],\n\t\t\t`elapsedMs=${job.elapsedMs}`,\n\t\t\t...job.description ? [`description=${JSON.stringify(job.description)}`] : [],\n\t\t\t`log=${job.outputPath}`\n\t\t].join(\" \");\n\t}).join(\"\\n\");\n}\n//#endregion\n//#region src/tools/bash-job-tool.ts\n/**\n* Observe, cancel, or list tracked bash jobs started by the bash tool.\n* Soft waits never cancel; cancel is cooperative on just-bash and hard on Modal.\n*/\nfunction createBashJobTool(runtime) {\n\treturn defineTool({\n\t\tname: \"bash_job\",\n\t\tlabel: \"Bash job\",\n\t\tdescription: [\n\t\t\t\"Wait for, cancel, or list bash jobs started by the bash tool.\",\n\t\t\t`action=wait: soft-wait up to waitMs (default ${DEFAULT_EXEC_SOFT_WAIT_MS}ms, max ${MAX_EXEC_SOFT_WAIT_MS}ms); never cancels. Size waitMs to the expected runtime.`,\n\t\t\t\"If still running, call bash_job again. Returns bounded output deltas; full log path is in the result.\",\n\t\t\t\"action=cancel: request cancellation (Modal kills the process group; just-bash may report cancel_requested until it stops).\",\n\t\t\t\"action=list: list this session's jobs (running and finished) with states and log paths — use it to recover a lost jobId.\"\n\t\t].join(\" \"),\n\t\tparameters: z.object({\n\t\t\taction: z.enum([\n\t\t\t\t\"wait\",\n\t\t\t\t\"cancel\",\n\t\t\t\t\"list\"\n\t\t\t]).describe(\"wait for completion, request cancellation, or list session jobs\"),\n\t\t\tjobId: z.string().min(1).optional().describe(\"Job id returned by bash (required for wait and cancel)\"),\n\t\t\twaitMs: z.number().int().min(0).max(MAX_EXEC_SOFT_WAIT_MS).optional().describe(`Soft wait budget in ms for action=wait (default ${DEFAULT_EXEC_SOFT_WAIT_MS}, max ${MAX_EXEC_SOFT_WAIT_MS})`)\n\t\t}),\n\t\tasync execute(_id, params, signal) {\n\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\tconst { jobId, action, waitMs } = params;\n\t\t\tif (action === \"list\") {\n\t\t\t\tconst summaries = await runtime.listExec();\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: formatExecJobList(summaries)\n\t\t\t\t\t}],\n\t\t\t\t\tdetails: { jobs: summaries }\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (!jobId) throw new Error(`bash_job action=${action} requires a jobId`);\n\t\t\tif (action === \"cancel\") {\n\t\t\t\tawait runtime.cancelExec(jobId);\n\t\t\t\tconst settled = await runtime.waitExec(jobId, {\n\t\t\t\t\twaitMs: resolveSoftWaitMs(waitMs ?? 3e4),\n\t\t\t\t\t...signal ? { signal } : {}\n\t\t\t\t});\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: formatExecJobSnapshot(settled)\n\t\t\t\t\t}],\n\t\t\t\t\tdetails: settled\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst snapshot = await runtime.waitExec(jobId, {\n\t\t\t\twaitMs: resolveSoftWaitMs(waitMs),\n\t\t\t\t...signal ? { signal } : {}\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: formatExecJobSnapshot(snapshot)\n\t\t\t\t}],\n\t\t\t\tdetails: snapshot\n\t\t\t};\n\t\t}\n\t});\n}\nconst bashDescriptionSchema = z.string().trim().min(1).max(80).describe(\"Short UI label for this command (prefer 2–5 words)\");\nfunction createBashTool(runtime, options = {}) {\n\tconst scriptHint = options.codemode ?? true ? \"Use js-exec for JS/TS scripts; call your host tools by exact name with bracket notation — await tools[\\\"tool-name\\\"](args) (names are hyphenated, so dot notation will not work). You can only call tools you already have.\" : \"Use node or python via bash for scripts when needed.\";\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\t`Waits up to ${DEFAULT_EXEC_SOFT_WAIT_MS}ms by default; if still running, returns a jobId — use bash_job to wait, cancel, or list jobs.`,\n\t\t\t\"Set background=true to return a jobId immediately for long-running work (servers, builds).\",\n\t\t\t\"For long multi-step scripts, append progress to a session file (cmd >> session/name.log 2>&1) so read can tail it mid-run.\",\n\t\t\t\"Required description: prefer 2–5 words for the UI.\",\n\t\t\tscriptHint\n\t\t].join(\" \"),\n\t\tparameters: z.object({\n\t\t\tcommand: z.string().describe(\"Bash script or command to run in the sandbox\"),\n\t\t\tdescription: bashDescriptionSchema,\n\t\t\tbackground: z.boolean().optional().describe(\"When true, return a jobId immediately without waiting\")\n\t\t}),\n\t\tasync execute(_id, params, signal) {\n\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\tconst { command, description, background } = params;\n\t\t\tconst { jobId } = await runtime.startExec(command, {\n\t\t\t\tdescription,\n\t\t\t\t...signal ? { signal } : {}\n\t\t\t});\n\t\t\tif (background) {\n\t\t\t\tconst snapshot = await runtime.waitExec(jobId, {\n\t\t\t\t\twaitMs: 0,\n\t\t\t\t\t...signal ? { signal } : {}\n\t\t\t\t});\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: formatExecJobSnapshot(snapshot)\n\t\t\t\t\t}],\n\t\t\t\t\tdetails: snapshot\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst snapshot = await runtime.waitExec(jobId, {\n\t\t\t\twaitMs: resolveSoftWaitMs(DEFAULT_EXEC_SOFT_WAIT_MS),\n\t\t\t\t...signal ? { signal } : {}\n\t\t\t});\n\t\t\tconst images = options.drainPendingBrowserImages?.() ?? [];\n\t\t\treturn {\n\t\t\t\tcontent: [{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: formatExecJobSnapshot(snapshot)\n\t\t\t\t}, ...images.map((image) => ({\n\t\t\t\t\ttype: \"image\",\n\t\t\t\t\t...image\n\t\t\t\t}))],\n\t\t\t\tdetails: snapshot\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 = z.object({\n\toldText: z.string().describe(\"Exact text to replace. Must be unique in the file and must not overlap other edits in this call.\"),\n\tnewText: z.string().describe(\"Replacement text\")\n});\nconst editSchema = z.object({\n\tpath: z.string().describe(\"Path under /workspace (e.g. session/out.txt or agent/data.json)\"),\n\tedits: z.array(replaceEditSchema).describe(\"Replacements applied against the original file (not chained). Each oldText must be unique and non-overlapping.\")\n});\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 = z.object({\n\tpath: z.string().describe(\"Path under /workspace (e.g. session/out.txt or agent/data.json)\"),\n\toffset: z.number().describe(\"Line number to start reading from (1-indexed)\").optional(),\n\tlimit: z.number().describe(\"Maximum number of lines to read\").optional()\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 = z.object({\n\tpath: z.string().describe(\"Path under /workspace (e.g. session/out.txt or agent/data.json)\"),\n\tcontent: z.string().describe(\"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, {\n\t\t\tcodemode,\n\t\t\t...options.drainPendingBrowserImages ? { drainPendingBrowserImages: options.drainPendingBrowserImages } : {}\n\t\t}),\n\t\tcreateBashJobTool(runtime)\n\t];\n}\n//#endregion\n//#region src/with-exec-timeout.ts\nfunction timedOutResult(timeoutMs) {\n\treturn {\n\t\tstdout: \"\",\n\t\tstderr: `Command timed out after ${timeoutMs}ms`,\n\t\texitCode: 124\n\t};\n}\n/**\n* Race `run` against `timeoutMs`, aborting via AbortSignal so cooperative\n* executors (just-bash) stop at the next statement boundary.\n*/\nasync function withExecTimeout(run, timeoutMs, externalSignal) {\n\tif (externalSignal?.aborted) return timedOutResult(timeoutMs);\n\tconst controller = new AbortController();\n\tconst onExternalAbort = () => controller.abort();\n\texternalSignal?.addEventListener(\"abort\", onExternalAbort, { once: true });\n\tlet timer;\n\ttry {\n\t\treturn await Promise.race([run(controller.signal).then((result) => controller.signal.aborted ? timedOutResult(timeoutMs) : result), new Promise((resolve) => {\n\t\t\ttimer = setTimeout(() => {\n\t\t\t\tcontroller.abort();\n\t\t\t\tresolve(timedOutResult(timeoutMs));\n\t\t\t}, timeoutMs);\n\t\t})]);\n\t} finally {\n\t\tif (timer !== void 0) clearTimeout(timer);\n\t\texternalSignal?.removeEventListener(\"abort\", onExternalAbort);\n\t}\n}\n//#endregion\nexport { execResultFromSnapshot as _, createBashTool as a, AGENT_MOUNT as c, createInMemoryExecJobs as d, DEFAULT_EXEC_JOB_DELTA_BYTES as f, execJobLogPath as g, MAX_EXEC_SOFT_WAIT_MS as h, bashDescriptionSchema as i, SESSION_MOUNT as l, EXEC_JOB_LOG_DIR as m, withExecTimeout as n, createBashJobTool as o, DEFAULT_EXEC_SOFT_WAIT_MS as p, createCodingTools as r, resolveSandboxPath as s, timedOutResult as t, WORKSPACE_MOUNT as u, resolveSoftWaitMs as v, sliceOutputDelta as y };\n\n//# sourceMappingURL=with-exec-timeout-D45q6sQP.mjs.map","import { a as defaultCommandTimeoutMs, c as resolveExecTimeoutMs, d as resolveAgentRoot, f as resolveSandboxRoot, i as SandboxSizeSchema, l as resolveSandboxResources, m as writeWorkspaceFileIfAbsent, n as DEFAULT_SANDBOX_SIZE, o as defaultCommandTimeoutSeconds, p as resolveSessionRoot, r as MAX_EXEC_TIMEOUT_MS, s as normalizeSandboxSize, t as DEFAULT_EXEC_TIMEOUT_MS, u as ensureWorkspaceDir } from \"./sizes-CeGfTo5B.mjs\";\nimport { _ as execResultFromSnapshot, a as createBashTool, c as AGENT_MOUNT, d as createInMemoryExecJobs, f as DEFAULT_EXEC_JOB_DELTA_BYTES, g as execJobLogPath, h as MAX_EXEC_SOFT_WAIT_MS, i as bashDescriptionSchema, l as SESSION_MOUNT, m as EXEC_JOB_LOG_DIR, n as withExecTimeout, o as createBashJobTool, p as DEFAULT_EXEC_SOFT_WAIT_MS, r as createCodingTools, s as resolveSandboxPath, t as timedOutResult, u as WORKSPACE_MOUNT, v as resolveSoftWaitMs, y as sliceOutputDelta } from \"./with-exec-timeout-D45q6sQP.mjs\";\nimport { E as validateSandboxEnvOutput, S as SandboxSetupSchema, T as resolveSandboxGitUser, a as defineSandbox, c as DEFAULT_GIT_USER_NAME, f as SandboxDefinitionInputSchema, i as flattenSandboxFiles, n as resolveAppRootFromModule, o as DEFAULT_GIT_CLONE_PATH, p as SandboxDefinitionSchema, r as materializeSandbox, s as DEFAULT_GIT_USER_EMAIL, t as resolveAppRoot, u as GIT_TOKEN_ENV_KEYS, w as parseSandboxDefinitionInput } from \"./files-Ds9QSoth.mjs\";\nimport { a as packAssetDirs, i as runWithAppRoot, n as resolveSandboxDefinition, o as packDirFromDisk, r as getBoundAppRoot, t as loadAssetManifest } from \"./resolve-sandbox-definition-Bgbd2rfm.mjs\";\nimport { a as DEPLOYED_FILES_RESERVED_PREFIX, c as forceWriteDesiredDeployedFiles, d as parseDeployedFilesManifest, i as DEPLOYED_FILES_MANIFEST_VERSION, l as hashDeployedFileContent, n as resolveDeployedFilesControlDir, o as buildDesiredDeployedFiles, r as resolveDeployedFilesManifestPath, s as diffDeployedFiles, t as reconcileDeployedFilesHost, u as normalizeDeployedFilePath } from \"./reconcile-deployed-files-host-D_FtT3kO.mjs\";\nimport { t as prepareHostDeployedFiles } from \"./prepare-host-deployed-files-DqNwWxEJ.mjs\";\nimport { t as defineSkill } from \"./define-skill-C3w07coI.mjs\";\nimport { tmpdir } from \"node:os\";\nimport { join, posix, resolve } from \"node:path\";\nimport { mkdir } from \"node:fs/promises\";\nimport { browserProcessEnv, createAgentBrowserCommand, drainPendingToolImages } from \"@keystrokehq/browser\";\nimport { z } from \"zod\";\nimport { randomUUID } from \"node:crypto\";\nimport { defineTool, defineTool as defineTool$1 } from \"@keystrokehq/shared/action-runtime\";\nimport { Bash, InMemoryFs, MountableFs, ReadWriteFs } from \"just-bash\";\n//#region src/providers/just-bash/filesystem.ts\nfunction buildFilesystem(options) {\n\treturn new MountableFs({\n\t\tbase: new InMemoryFs(),\n\t\tmounts: [{\n\t\t\tmountPoint: AGENT_MOUNT,\n\t\t\tfilesystem: new ReadWriteFs({ root: options.agentRoot })\n\t\t}, {\n\t\t\tmountPoint: SESSION_MOUNT,\n\t\t\tfilesystem: new ReadWriteFs({ root: options.sessionRoot })\n\t\t}]\n\t});\n}\nasync function createBashEnv(options) {\n\tawait ensureWorkspaceDir(options.agentRoot);\n\tawait ensureWorkspaceDir(options.sessionRoot);\n\tconst customCommands = options.browser ? [createAgentBrowserCommand(options.browser)] : void 0;\n\treturn new Bash({\n\t\tfs: buildFilesystem(options),\n\t\tcwd: WORKSPACE_MOUNT,\n\t\tjavascript: options.invokeTool ? { invokeTool: options.invokeTool } : true,\n\t\t...customCommands ? { customCommands } : {}\n\t});\n}\n//#endregion\n//#region src/providers/just-bash/index.ts\nfunction mergeBrowserExecEnv(options, execEnv) {\n\tif (!options.browser) return execEnv;\n\tconst browserEnv = browserProcessEnv(options.browser);\n\tconst stringEnv = {};\n\tfor (const [key, value] of Object.entries(browserEnv)) if (typeof value === \"string\") stringEnv[key] = value;\n\treturn {\n\t\t...stringEnv,\n\t\t...options.env ?? {},\n\t\t...execEnv ?? {}\n\t};\n}\nfunction hookContext(options) {\n\treturn {\n\t\tagentId: options.agentId,\n\t\tsessionId: options.sessionId,\n\t\tagentRoot: options.agentRoot,\n\t\tsessionRoot: options.sessionRoot\n\t};\n}\nfunction createJustBashProvider() {\n\treturn { async create(options) {\n\t\tconst { prepareHostDeployedFiles } = await import(\"./prepare-host-deployed-files-DqNwWxEJ.mjs\").then((n) => n.n);\n\t\tawait prepareHostDeployedFiles(options.agentId, options.agentRoot, options.deployedFiles);\n\t\tconst bash = await createBashEnv(options);\n\t\tconst hooks = options.hooks;\n\t\tconst ctx = hookContext(options);\n\t\tconst jobs = createInMemoryExecJobs({\n\t\t\tbeforeStart: async (script) => {\n\t\t\t\tawait hooks?.beforeExec?.({\n\t\t\t\t\t...ctx,\n\t\t\t\t\tscript\n\t\t\t\t});\n\t\t\t},\n\t\t\tafterTerminal: async (script, result) => {\n\t\t\t\tawait hooks?.afterExec?.({\n\t\t\t\t\t...ctx,\n\t\t\t\t\tscript,\n\t\t\t\t\tresult\n\t\t\t\t});\n\t\t\t},\n\t\t\twriteLog: async (path, content) => {\n\t\t\t\tawait bash.fs.mkdir(posix.dirname(path), { recursive: true });\n\t\t\t\tawait bash.fs.writeFile(path, content);\n\t\t\t},\n\t\t\trun: async (script, execOptions, signal) => {\n\t\t\t\tconst result = await bash.exec(script, {\n\t\t\t\t\tcwd: execOptions?.cwd ?? \"/workspace\",\n\t\t\t\t\tenv: mergeBrowserExecEnv(options, execOptions?.env),\n\t\t\t\t\tstdin: execOptions?.stdin,\n\t\t\t\t\tsignal\n\t\t\t\t});\n\t\t\t\treturn {\n\t\t\t\t\tstdout: result.stdout,\n\t\t\t\t\tstderr: result.stderr,\n\t\t\t\t\texitCode: result.exitCode\n\t\t\t\t};\n\t\t\t}\n\t\t});\n\t\tconst runtime = {\n\t\t\tagentId: options.agentId,\n\t\t\tsessionId: options.sessionId,\n\t\t\tagentRoot: options.agentRoot,\n\t\t\tsessionRoot: options.sessionRoot,\n\t\t\tasync exec(script, execOptions) {\n\t\t\t\tawait hooks?.beforeExec?.({\n\t\t\t\t\t...ctx,\n\t\t\t\t\tscript\n\t\t\t\t});\n\t\t\t\tconst execResult = await withExecTimeout(async (signal) => {\n\t\t\t\t\tconst result = await bash.exec(script, {\n\t\t\t\t\t\tcwd: execOptions?.cwd ?? \"/workspace\",\n\t\t\t\t\t\tenv: mergeBrowserExecEnv(options, execOptions?.env),\n\t\t\t\t\t\tstdin: execOptions?.stdin,\n\t\t\t\t\t\tsignal\n\t\t\t\t\t});\n\t\t\t\t\treturn {\n\t\t\t\t\t\tstdout: result.stdout,\n\t\t\t\t\t\tstderr: result.stderr,\n\t\t\t\t\t\texitCode: result.exitCode\n\t\t\t\t\t};\n\t\t\t\t}, resolveExecTimeoutMs(execOptions?.timeoutMs, options.size), execOptions?.signal);\n\t\t\t\tawait hooks?.afterExec?.({\n\t\t\t\t\t...ctx,\n\t\t\t\t\tscript,\n\t\t\t\t\tresult: execResult\n\t\t\t\t});\n\t\t\t\treturn execResult;\n\t\t\t},\n\t\t\tstartExec(script, startOptions) {\n\t\t\t\treturn jobs.startExec(script, startOptions);\n\t\t\t},\n\t\t\twaitExec(jobId, waitOptions) {\n\t\t\t\treturn jobs.waitExec(jobId, waitOptions);\n\t\t\t},\n\t\t\tcancelExec(jobId) {\n\t\t\t\treturn jobs.cancelExec(jobId);\n\t\t\t},\n\t\t\tlistExec() {\n\t\t\t\treturn jobs.listExec();\n\t\t\t},\n\t\t\tasync readFile(path, pathOptions) {\n\t\t\t\treturn bash.fs.readFile(resolveSandboxPath(path, pathOptions));\n\t\t\t},\n\t\t\tasync readBytes(path, pathOptions) {\n\t\t\t\treturn bash.fs.readFileBuffer(resolveSandboxPath(path, pathOptions));\n\t\t\t},\n\t\t\tasync stat(path, pathOptions) {\n\t\t\t\tconst result = await bash.fs.lstat(resolveSandboxPath(path, pathOptions));\n\t\t\t\treturn {\n\t\t\t\t\ttype: result.isFile ? \"file\" : result.isDirectory ? \"directory\" : result.isSymbolicLink ? \"symlink\" : \"other\",\n\t\t\t\t\tsize: result.size,\n\t\t\t\t\tmode: result.mode,\n\t\t\t\t\tmodifiedAt: result.mtime.toISOString()\n\t\t\t\t};\n\t\t\t},\n\t\t\tasync writeFile(path, content) {\n\t\t\t\tawait bash.fs.mkdir(posix.dirname(path), { recursive: true });\n\t\t\t\tawait bash.fs.writeFile(path, content);\n\t\t\t},\n\t\t\tasync dispose() {\n\t\t\t\tawait jobs.disposeJobs();\n\t\t\t\tawait hooks?.onDispose?.(ctx);\n\t\t\t}\n\t\t};\n\t\treturn {\n\t\t\truntime,\n\t\t\ttools: createCodingTools(runtime, {\n\t\t\t\t...options.size ? { size: options.size } : {},\n\t\t\t\t...options.browser ? { drainPendingBrowserImages: () => drainPendingToolImages(options.browser) } : {}\n\t\t\t})\n\t\t};\n\t} };\n}\n//#endregion\n//#region src/runtime-config.ts\n/** Env var for sandbox mode override (`in-process` | `vm`). */\nconst SANDBOX_MODE_ENV = \"KEYSTROKE_SANDBOX_MODE\";\nfunction resolveSandboxMode(options, env = process.env) {\n\tconst fromEnv = env[SANDBOX_MODE_ENV]?.trim();\n\tif (options.mode) return options.mode;\n\tif (fromEnv === \"vm\" || fromEnv === \"in-process\") return fromEnv;\n\treturn \"in-process\";\n}\n/** Default provider from mode (just-bash in-process or microsandbox VM fallback). */\nasync function resolveDefaultRuntimeProvider(options = {}, env = process.env) {\n\tif (resolveSandboxMode(options, env) === \"in-process\") return options.inProcessProvider ?? createJustBashProvider();\n\tif (options.vmProvider) return options.vmProvider;\n\treturn loadMicrosandboxFallback();\n}\nasync function loadMicrosandboxFallback() {\n\tconst mod = await import(\"./microsandbox-BGjh4Vaz.mjs\").then((n) => n.t);\n\tif (!await mod.isMicrosandboxAvailable()) throw new Error(\"no vm runtime provider available\");\n\treturn mod.createMicrosandboxProvider();\n}\n//#endregion\n//#region src/create-sandbox.ts\nfunction defaultWorkspacesRoot() {\n\treturn join(tmpdir(), \"keystroke-workspaces\");\n}\n/** Spin up workspace + coding tools (read, write, edit, bash). */\nasync function createSandbox(options) {\n\tconst workspacesRoot = options.workspacesRoot ?? defaultWorkspacesRoot();\n\tconst agentRoot = options.agentRoot ?? resolveAgentRoot(workspacesRoot, options.agentId);\n\tconst sessionRoot = options.sessionRoot ?? resolveSessionRoot(workspacesRoot, options.sessionId);\n\treturn (await resolveDefaultRuntimeProvider({\n\t\tmode: options.mode,\n\t\tinProcessProvider: options.provider,\n\t\tvmProvider: options.vmProvider\n\t})).create({\n\t\tagentId: options.agentId,\n\t\tsessionId: options.sessionId,\n\t\tagentRoot,\n\t\tsessionRoot,\n\t\thooks: options.hooks,\n\t\tinvokeTool: options.invokeTool,\n\t\t...options.env ? { env: options.env } : {},\n\t\t...options.git ? { git: options.git } : {},\n\t\t...options.setup ? { setup: options.setup } : {},\n\t\t...options.size ? { size: options.size } : {},\n\t\t...options.onProvisioning ? { onProvisioning: options.onProvisioning } : {},\n\t\t...options.deployedFiles ? { deployedFiles: options.deployedFiles } : {},\n\t\t...options.browser ? { browser: options.browser } : {}\n\t});\n}\n//#endregion\n//#region src/provisioning.ts\n/** Phases reported while a VM sandbox is provisioned on the worker. */\nconst SANDBOX_PROVISIONING_PHASES = [\"starting_sandbox\", \"ready\"];\nconst SANDBOX_PROVISIONING_LABELS = {\n\t/** Covers create + git bootstrap + setup — platform work is one blocking create call. */\n\tstarting_sandbox: \"Setting up sandbox…\",\n\tready: \"\"\n};\n/** Best-effort report; never throws into the create path. */\nasync function reportSandboxProvisioning(report, phase) {\n\tif (!report) return;\n\ttry {\n\t\tawait report(phase);\n\t} catch {}\n}\nfunction isSandboxProvisioningPhase(value) {\n\treturn typeof value === \"string\" && SANDBOX_PROVISIONING_PHASES.includes(value);\n}\n//#endregion\n//#region src/tools/git-clone-path.ts\n/**\n* Resolve a built-in git clone destination under `/workspace/session`.\n* Relative paths resolve beneath the session mount. Absolute paths must stay under it.\n*/\nfunction resolveGitClonePath(path) {\n\tconst raw = (path ?? \"/workspace/session/repo\").trim();\n\tif (!raw) throw new Error(\"git clone path must be non-empty\");\n\tif (raw.includes(\"\\0\") || raw.includes(\"\\n\") || raw.includes(\"\\r\")) throw new Error(`Invalid git clone path: ${path}`);\n\tconst normalized = raw.replace(/\\\\/g, \"/\");\n\tlet resolved;\n\tif (normalized.startsWith(\"/\")) resolved = posix.normalize(normalized);\n\telse resolved = posix.normalize(posix.join(SESSION_MOUNT, normalized.replace(/^\\.\\//, \"\")));\n\tif (resolved === SESSION_MOUNT || resolved === `${SESSION_MOUNT}/`) throw new Error(`git clone path must be a child of ${SESSION_MOUNT}`);\n\tif (resolved === \"/workspace\" || resolved === `/workspace/`) throw new Error(`git clone path must be under ${SESSION_MOUNT}`);\n\tif (!resolved.startsWith(`${SESSION_MOUNT}/`)) throw new Error(`git clone path must be under ${SESSION_MOUNT}: ${path}`);\n\treturn resolved;\n}\n/** Canonical HTTPS URL for a GitHub `owner/repo` shorthand. */\nfunction githubHttpsUrl(repository) {\n\treturn `https://github.com/${repository}.git`;\n}\n/** Normalize GitHub remotes for origin comparison. */\nfunction normalizeGithubOrigin(origin) {\n\tconst trimmed = origin.trim();\n\tif (!trimmed) throw new Error(\"git origin is empty\");\n\tif (trimmed.includes(\"@\") && trimmed.includes(\"://\") && /\\/\\/[^/]*:/.test(trimmed)) throw new Error(\"git origin must not embed credentials\");\n\tlet value = trimmed;\n\tconst sshMatch = /^git@github\\.com:(.+)$/i.exec(value);\n\tif (sshMatch?.[1]) value = `https://github.com/${sshMatch[1]}`;\n\tvalue = value.replace(/^ssh:\\/\\/git@github\\.com\\//i, \"https://github.com/\");\n\tvalue = value.replace(/\\.git$/i, \"\");\n\tvalue = value.replace(/\\/+$/, \"\");\n\tconst httpsMatch = /^https:\\/\\/github\\.com\\/([^/]+\\/[^/]+)$/i.exec(value);\n\tif (!httpsMatch?.[1]) throw new Error(`unsupported git origin: ${origin}`);\n\treturn `https://github.com/${httpsMatch[1].toLowerCase()}`;\n}\n/** Compare configured repository shorthand against an observed remote URL. */\nfunction githubOriginsMatch(repository, origin) {\n\treturn normalizeGithubOrigin(githubHttpsUrl(repository)) === normalizeGithubOrigin(origin);\n}\n//#endregion\n//#region src/tools/assert-sandbox-exec-ok.ts\n/** Redact common credential patterns before surfacing exec failure output. */\nfunction sanitizeSandboxExecDetail(detail) {\n\treturn detail.replace(/x-access-token:[^\\s@/]+/gi, \"x-access-token:***\").replace(/gh[pousr]_[A-Za-z0-9_]+/g, \"***\");\n}\n/** Throw when a sandbox exec exits non-zero, with sanitized stdout/stderr in the message. */\nfunction assertSandboxExecOk(result, label) {\n\tif (result.exitCode === 0) return;\n\tconst sanitized = sanitizeSandboxExecDetail([result.stderr, result.stdout].filter(Boolean).join(\"\\n\").trim());\n\tthrow new Error(`${label} failed (exit ${result.exitCode})${sanitized ? `: ${sanitized}` : \"\"}`);\n}\n//#endregion\n//#region src/tools/git-bootstrap.ts\n/** Ephemeral VM-local path — outside `/workspace` mounts (not object/session storage). */\nconst CREDENTIAL_HELPER_DIR = \"/tmp/keystroke\";\nconst CREDENTIAL_HELPER_PATH = `${CREDENTIAL_HELPER_DIR}/git-credential-helper`;\n/** Shell script that reads GH_TOKEN/GITHUB_TOKEN from the process env — never embeds secrets. */\nfunction gitCredentialHelperScript() {\n\treturn `#!/bin/sh\n# Keystroke git credential helper — reads tokens from the environment only.\ncase \"$1\" in\n  get)\n    token=\"\\${GH_TOKEN:-\\${GITHUB_TOKEN:-}}\"\n    if [ -n \"$token\" ]; then\n      printf 'username=x-access-token\\\\npassword=%s\\\\n' \"$token\"\n    fi\n    ;;\nesac\n`;\n}\nfunction shellSingleQuote(value) {\n\treturn `'${value.replace(/'/g, `'\\\\''`)}'`;\n}\n/**\n* Write the no-secret credential helper under `/tmp/keystroke` (ephemeral local disk).\n* Must run before `git clone` so the helper can be passed via `-c credential.helper`.\n*/\nasync function ensureGitCredentialHelper(options) {\n\tconst helperBody = gitCredentialHelperScript();\n\tconst setupHelper = [\n\t\t`mkdir -p ${shellSingleQuote(CREDENTIAL_HELPER_DIR)}`,\n\t\t`cat > ${shellSingleQuote(CREDENTIAL_HELPER_PATH)} <<'KEYSTROKE_EOF'`,\n\t\thelperBody.trimEnd(),\n\t\t\"KEYSTROKE_EOF\",\n\t\t`chmod 755 ${shellSingleQuote(CREDENTIAL_HELPER_PATH)}`\n\t].join(\"\\n\");\n\tassertSandboxExecOk(await options.exec(setupHelper, { env: options.env }), \"Git credential helper setup\");\n\tconst helperContents = await options.exec(`cat ${shellSingleQuote(CREDENTIAL_HELPER_PATH)}`, { env: options.env });\n\tassertSandboxExecOk(helperContents, \"Git credential helper read\");\n\tif (/GH_TOKEN=|GITHUB_TOKEN=|x-access-token:[^\\s]+|gh[pousr]_/i.test(helperContents.stdout)) throw new Error(\"Git credential helper must not contain secrets\");\n\treturn CREDENTIAL_HELPER_PATH;\n}\n/**\n* Ensure the no-secret credential helper exists and repo-local git identity/helper\n* are configured. Idempotent.\n*/\nasync function configureClonedRepo(options) {\n\tconst helperPath = await ensureGitCredentialHelper({\n\t\texec: options.exec,\n\t\tenv: options.env\n\t});\n\tconst configure = [\n\t\t`git -C ${shellSingleQuote(options.clonePath)} config --local credential.helper ${shellSingleQuote(helperPath)}`,\n\t\t`git -C ${shellSingleQuote(options.clonePath)} config --local user.name ${shellSingleQuote(options.user.name)}`,\n\t\t`git -C ${shellSingleQuote(options.clonePath)} config --local user.email ${shellSingleQuote(options.user.email)}`\n\t].join(\"\\n\");\n\tassertSandboxExecOk(await options.exec(configure, { env: options.env }), \"Git repository configure\");\n}\nasync function pathExists(exec, path, env) {\n\treturn (await exec(`test -e ${shellSingleQuote(path)}`, { env })).exitCode === 0;\n}\nasync function readRemoteOrigin(exec, clonePath, env) {\n\tconst result = await exec(`git -C ${shellSingleQuote(clonePath)} remote get-url origin`, { env });\n\tassertSandboxExecOk(result, \"Git remote origin\");\n\treturn result.stdout.trim();\n}\n/**\n* Build the shell script that materializes a GitHub clone.\n* - `commit` → init + fetch by SHA (GitHub supports this; `clone --branch` does not)\n* - otherwise → `git clone` with optional `--branch` / shallow depth\n*/\nfunction buildGitCloneScript(options) {\n\tconst shallow = options.shallow !== false;\n\tconst quotedHelper = shellSingleQuote(options.helperPath);\n\tconst quotedUrl = shellSingleQuote(options.url);\n\tconst quotedPath = shellSingleQuote(options.clonePath);\n\tconst gitAuth = `GIT_TERMINAL_PROMPT=0 git -c credential.helper=${quotedHelper}`;\n\tconst mkdir = `mkdir -p $(dirname ${quotedPath})`;\n\tif (options.commit) {\n\t\tconst quotedCommit = shellSingleQuote(options.commit);\n\t\tconst depthArgs = shallow ? \"--depth 1 \" : \"\";\n\t\treturn [\n\t\t\tmkdir,\n\t\t\t`git init ${quotedPath}`,\n\t\t\t`git -C ${quotedPath} remote add origin ${quotedUrl}`,\n\t\t\t`${gitAuth} -C ${quotedPath} fetch ${depthArgs}origin ${quotedCommit}`,\n\t\t\t`git -C ${quotedPath} checkout --detach ${quotedCommit}`\n\t\t].join(\"\\n\");\n\t}\n\tconst branchArgs = options.branch ? `--branch ${shellSingleQuote(options.branch)} ` : \"\";\n\treturn [mkdir, `${gitAuth} clone ${shallow ? \"--depth 1 --no-tags \" : \"\"}${branchArgs}${quotedUrl} ${quotedPath}`].join(\"\\n\");\n}\n/**\n* Bootstrap (or verify) a single GitHub clone for a sandbox VM session.\n* - created / missing path → clone\n* - existing / restarted with path → verify origin + reconfigure helper/identity\n*/\nasync function bootstrapSandboxGit(options) {\n\tconst clonePath = resolveGitClonePath(options.git.clone.path);\n\tconst user = resolveSandboxGitUser(options.git.user);\n\tconst url = githubHttpsUrl(options.git.clone.repository);\n\tif (!(options.env.GH_TOKEN ?? options.env.GITHUB_TOKEN)) throw new Error(\"Git bootstrap requires GH_TOKEN or GITHUB_TOKEN in sandbox env\");\n\tconst exists = await pathExists(options.exec, clonePath, options.env);\n\tif (options.lifecycle === \"created\" || !exists) {\n\t\tif (exists) assertSandboxExecOk(await options.exec(`rm -rf ${shellSingleQuote(clonePath)}`, { env: options.env }), \"Git clone path cleanup\");\n\t\tconst cloneScript = buildGitCloneScript({\n\t\t\thelperPath: await ensureGitCredentialHelper({\n\t\t\t\texec: options.exec,\n\t\t\t\tenv: options.env\n\t\t\t}),\n\t\t\turl,\n\t\t\tclonePath,\n\t\t\tbranch: options.git.clone.branch,\n\t\t\tcommit: options.git.clone.commit,\n\t\t\tshallow: options.git.clone.shallow\n\t\t});\n\t\tassertSandboxExecOk(await options.exec(cloneScript, { env: options.env }), \"Git clone\");\n\t} else {\n\t\tconst origin = await readRemoteOrigin(options.exec, clonePath, options.env);\n\t\tif (!githubOriginsMatch(options.git.clone.repository, origin)) throw new Error(`Git clone path ${clonePath} origin does not match configured repository ${options.git.clone.repository}`);\n\t}\n\tawait configureClonedRepo({\n\t\texec: options.exec,\n\t\tclonePath,\n\t\tuser,\n\t\tenv: options.env\n\t});\n\treturn { clonePath };\n}\n//#endregion\n//#region src/tools/run-sandbox-setup.ts\n/**\n* Run author `setup` commands once when a session sandbox is first created.\n* Skips remounts / later prompts (`existing` / `restarted`). Fail-fast on non-zero exit.\n* Each command gets the max exec timeout (installs like Playwright browsers can be slow).\n*/\nasync function runSandboxSetup(options) {\n\tif (options.lifecycle !== \"created\" || !options.setup?.length) return;\n\tfor (const [index, command] of options.setup.entries()) {\n\t\tconst label = `Sandbox setup[${index}]`;\n\t\tassertSandboxExecOk(await options.exec(command, {\n\t\t\ttimeoutMs: MAX_EXEC_TIMEOUT_MS,\n\t\t\t...options.env ? { env: options.env } : {}\n\t\t}), label);\n\t}\n}\n//#endregion\n//#region src/tools/merge-sandbox-env.ts\n/** Merge per-exec env under sandbox session env (sandbox wins). */\nfunction mergeSandboxExecEnv(sandboxEnv, execEnv) {\n\tif (!sandboxEnv && !execEnv) return;\n\treturn {\n\t\t...execEnv,\n\t\t...sandboxEnv\n\t};\n}\n/** Zod schema for {@link SandboxGitBootstrapConfig} — shared by proxy routes and providers. */\nconst SandboxGitBootstrapSchema = z.object({\n\tclone: z.object({\n\t\trepository: z.string().trim().min(1),\n\t\tcredential: z.string().trim().min(1),\n\t\tbranch: z.string().trim().min(1).optional(),\n\t\tcommit: z.string().trim().min(1).optional(),\n\t\tshallow: z.boolean().optional(),\n\t\tpath: z.string().trim().min(1).optional()\n\t}),\n\tuser: z.object({\n\t\tname: z.string().trim().min(1).optional(),\n\t\temail: z.string().trim().min(1).optional()\n\t}).optional()\n});\nfunction toSandboxGitBootstrapConfig(git) {\n\tif (!git) return;\n\treturn {\n\t\tclone: {\n\t\t\trepository: git.clone.repository,\n\t\t\tcredential: git.clone.credential,\n\t\t\t...git.clone.branch ? { branch: git.clone.branch } : {},\n\t\t\t...git.clone.commit ? { commit: git.clone.commit } : {},\n\t\t\t...git.clone.shallow === false ? { shallow: false } : {},\n\t\t\t...git.clone.path ? { path: git.clone.path } : {}\n\t\t},\n\t\t...git.user ? { user: { ...git.user } } : {}\n\t};\n}\n//#endregion\n//#region src/skills/types.ts\nconst AGENT_SKILLS_DIR = \"skills\";\n//#endregion\n//#region src/skills/create-skill-view-tool.ts\nconst SKILL_MD = \"SKILL.md\";\nconst MAX_LISTED_RESOURCES = 40;\nfunction skillGuestDir(slug) {\n\treturn `${AGENT_MOUNT}/${AGENT_SKILLS_DIR}/${slug}`;\n}\nfunction skillGuestPath(slug, relativePath) {\n\treturn `${skillGuestDir(slug)}/${relativePath}`;\n}\nfunction isSafeRelativePath(filePath) {\n\tif (!filePath || filePath.startsWith(\"/\") || filePath.includes(\"\\\\\")) return false;\n\treturn filePath.split(\"/\").every((segment) => segment.length > 0 && segment !== \".\" && segment !== \"..\");\n}\nfunction groupResourcePaths(paths) {\n\tconst groups = {};\n\tfor (const path of paths) {\n\t\tconst slash = path.indexOf(\"/\");\n\t\tconst group = slash === -1 ? \".\" : path.slice(0, slash);\n\t\tconst list = groups[group] ?? [];\n\t\tlist.push(path);\n\t\tgroups[group] = list;\n\t}\n\treturn groups;\n}\n/** Load an attached skill's SKILL.md or a packed resource via Sandbox.readFile. */\nfunction createSkillViewTool(options) {\n\tconst { runtime, skills } = options;\n\tif (skills.length === 0) throw new Error(\"createSkillViewTool requires at least one attached skill\");\n\tconst bySlug = new Map(skills.map((skill) => [skill.slug, skill]));\n\tconst names = skills.map((skill) => skill.slug);\n\treturn defineTool$1({\n\t\tname: \"skill_view\",\n\t\tlabel: \"skill_view\",\n\t\tdescription: \"Load an attached skill. Omit file_path to read SKILL.md. Pass file_path only for a packed file listed in the skill response.\",\n\t\tparameters: z.object({\n\t\t\tname: z.enum(names).describe(\"Attached skill name from the available_skills catalog\"),\n\t\t\tfile_path: z.string().optional().describe(\"Optional packed file path relative to the skill root (omit for SKILL.md)\")\n\t\t}),\n\t\tasync execute(_id, params, signal) {\n\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\tconst skill = bySlug.get(params.name);\n\t\t\tif (!skill) throw new Error(`Unknown skill \"${params.name}\"`);\n\t\t\tconst packedPaths = skill.files.map((file) => file.path);\n\t\t\tconst relativePath = params.file_path ?? SKILL_MD;\n\t\t\tif (params.file_path !== void 0) {\n\t\t\t\tif (!isSafeRelativePath(params.file_path)) throw new Error(`Invalid file_path \"${params.file_path}\" — must be a relative path inside the skill`);\n\t\t\t\tif (!packedPaths.includes(params.file_path)) throw new Error(`Unknown file_path \"${params.file_path}\" for skill \"${params.name}\" — use a packed path from the skill listing`);\n\t\t\t} else if (!packedPaths.includes(SKILL_MD)) throw new Error(`Skill \"${params.name}\" is missing ${SKILL_MD}`);\n\t\t\tconst guestPath = skillGuestPath(params.name, relativePath);\n\t\t\tconst content = await runtime.readFile(guestPath);\n\t\t\tconst skillDir = skillGuestDir(params.name);\n\t\t\tconst resources = groupResourcePaths(packedPaths.filter((path) => path !== relativePath).slice(0, MAX_LISTED_RESOURCES));\n\t\t\tconst truncated = packedPaths.filter((path) => path !== relativePath).length > MAX_LISTED_RESOURCES;\n\t\t\tconst listingLines = Object.entries(resources).flatMap(([group, paths]) => [`${group}/`, ...paths.map((path) => `  - ${path}`)]);\n\t\t\tif (truncated) listingLines.push(`… truncated to ${MAX_LISTED_RESOURCES} resources`);\n\t\t\treturn {\n\t\t\t\tcontent: [{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: [\n\t\t\t\t\t\t`# Skill: ${params.name}`,\n\t\t\t\t\t\t`Directory: ${skillDir}`,\n\t\t\t\t\t\t`Loaded: ${relativePath}`,\n\t\t\t\t\t\t\"\",\n\t\t\t\t\t\tcontent,\n\t\t\t\t\t\t\"\",\n\t\t\t\t\t\t\"## Other packed files\",\n\t\t\t\t\t\tlistingLines.length > 0 ? listingLines.join(\"\\n\") : \"(none)\",\n\t\t\t\t\t\t\"\",\n\t\t\t\t\t\t\"Load another packed file with skill_view({ name, file_path }).\"\n\t\t\t\t\t].join(\"\\n\")\n\t\t\t\t}],\n\t\t\t\tdetails: {\n\t\t\t\t\tname: params.name,\n\t\t\t\t\tskillDir,\n\t\t\t\t\tloadedPath: relativePath,\n\t\t\t\t\tguestPath,\n\t\t\t\t\tresources,\n\t\t\t\t\ttruncated\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t});\n}\n//#endregion\n//#region src/skills/materialize-skills.ts\n/** Write skill files to `{workspaceRoot}/skills/{slug}/`. */\nasync function materializeSkills(options) {\n\tfor (const skill of options.skills) for (const entry of skill.files) await writeWorkspaceFileIfAbsent(resolve(options.workspaceRoot, AGENT_SKILLS_DIR, skill.slug, entry.path), entry.file);\n}\n//#endregion\n//#region src/workspace-system-prompt.ts\n/** System-prompt note describing the dual workspace layout. */\nfunction sandboxSystemPromptInjection(options = {}) {\n\tconst deployedFilePaths = [...options.deployedFilePaths ?? []].sort();\n\tconst hasUserFiles = options.hasUserFiles === true || deployedFilePaths.length > 0;\n\tconst lines = [\n\t\t`You start in ${WORKSPACE_MOUNT}. Use ${SESSION_MOUNT}/ for session work and debugging — it persists for the current session only. Use ${AGENT_MOUNT}/ for files that must persist across sessions. If you're not sure ask the user where to put new files.`,\n\t\t\"read, write, and edit default unprefixed paths to /workspace/session. In bash, prefix session/ or agent/ for persisted mounts.\",\n\t\t`Write to ${AGENT_MOUNT}/ only when you need cross-session persistence; prefer ${SESSION_MOUNT}/ for temporary work.`,\n\t\t`Oversized tool output may be saved under ${SESSION_MOUNT}/tool-output/. Use the format and shape metadata in its handle, then inspect its format and shape before querying. For JSON, start with jq type/keys; for text, use tail/grep or read with offset/limit. Do not suppress inspection errors; treat empty output as an unknown shape. Do not re-call the original tool just to get the full payload.`\n\t];\n\tif (hasUserFiles || options.hasSkills) {\n\t\tconst parts = [];\n\t\tif (hasUserFiles) parts.push(\"user-supplied files\");\n\t\tif (options.hasSkills) parts.push(\"skills\");\n\t\tlines.push(`This agent has ${parts.join(\" and \")} under ${AGENT_MOUNT}/ (including ${AGENT_MOUNT}/skills/ when skills are attached).`);\n\t\tif (deployedFilePaths.length > 0) lines.push(`Deployed project files (overwritten or deleted on a later deploy):`, ...deployedFilePaths.map((path) => `- ${AGENT_MOUNT}/${path}`), `Other files you write under ${AGENT_MOUNT}/ persist for this agent across sessions and deploys. Prefer ${SESSION_MOUNT}/ for temporary work.`);\n\t\telse if (hasUserFiles) lines.push(`Deployed project files under ${AGENT_MOUNT}/ are managed by the project: a later deploy may overwrite or delete those paths. Prefer ${SESSION_MOUNT}/ for work you want to keep only for this session, or write agent-owned files under ${AGENT_MOUNT}/ outside the deployed set.`);\n\t}\n\tif (options.gitClonePath) lines.push(`A GitHub repository is available at ${options.gitClonePath}. Prefer working in that directory for repository changes.`);\n\tif (options.hasGithubAuth) lines.push(\"GitHub authentication is available via GH_TOKEN/GITHUB_TOKEN for `git` (and `gh` if installed in the image). Do not print credential environment variables.\");\n\treturn lines.join(\"\\n\");\n}\n//#endregion\n//#region src/providers/just-bash/create-invoke-tool-bridge.ts\nfunction serializeToolResult(result) {\n\tconst textBlocks = result.content.filter((block) => block.type === \"text\");\n\tconst text = textBlocks.map((block) => block.text).join(\"\");\n\tif (textBlocks.length === 1) try {\n\t\treturn JSON.stringify(JSON.parse(text));\n\t} catch {}\n\treturn JSON.stringify(result);\n}\n/** Normalize tool paths for tolerant lookup (hyphen, underscore, camelCase). */\nfunction normalizeToolPath(path) {\n\treturn path.toLowerCase().replace(/[-_]/g, \"\");\n}\nfunction buildToolIndex(tools) {\n\tconst byExact = new Map(tools.map((tool) => [tool.name, tool]));\n\tconst byNormalized = /* @__PURE__ */ new Map();\n\tfor (const tool of tools) {\n\t\tconst key = normalizeToolPath(tool.name);\n\t\tconst group = byNormalized.get(key) ?? [];\n\t\tgroup.push(tool);\n\t\tbyNormalized.set(key, group);\n\t}\n\treturn {\n\t\tbyExact,\n\t\tbyNormalized\n\t};\n}\nfunction resolveTool(index, path) {\n\tconst exact = index.byExact.get(path);\n\tif (exact) return exact;\n\tconst matches = index.byNormalized.get(normalizeToolPath(path));\n\tif (matches?.length === 1) return matches[0];\n}\nfunction unknownToolError(path, tools) {\n\tconst names = [...tools.map((tool) => tool.name)].sort();\n\tconst example = pickToolExample(path, names);\n\tconst available = names.length > 0 ? names.join(\", \") : \"(none — you can only call tools you currently have)\";\n\treturn /* @__PURE__ */ new Error(`Unknown tool \"${path}\". Available tools: ${available}. Call tools by exact name with bracket notation, e.g. tools[\"${example}\"](args).`);\n}\nfunction pickToolExample(path, names) {\n\tif (names.length === 0) return \"tool-name\";\n\tconst normalized = normalizeToolPath(path);\n\treturn names.map((name) => {\n\t\tconst nameNorm = normalizeToolPath(name);\n\t\tlet score = 0;\n\t\tif (nameNorm.includes(normalized) || normalized.includes(nameNorm)) score += 100;\n\t\tfor (let i = 0; i < Math.min(nameNorm.length, normalized.length); i++) if (nameNorm[i] === normalized[i]) score += 1;\n\t\treturn {\n\t\t\tname,\n\t\t\tscore\n\t\t};\n\t}).sort((left, right) => right.score - left.score || left.name.localeCompare(right.name))[0]?.name ?? names[0];\n}\nconst POLL_SCRIPT_TOOL_CALL = /tools(?:\\[\\s*[\"']([^\"']+)[\"']\\s*\\]|\\.\\s*([a-zA-Z_][\\w]*))\\s*\\(/g;\n/** Static poll-script check for tool references agents cannot call. */\nfunction findUnknownPollScriptToolCalls(code, tools) {\n\tconst index = buildToolIndex(tools);\n\tfor (const match of code.matchAll(POLL_SCRIPT_TOOL_CALL)) {\n\t\tconst path = match[1] ?? match[2];\n\t\tif (!path || resolveTool(index, path)) continue;\n\t\tthrow unknownToolError(path, tools);\n\t}\n}\n/** Empty collections so dry-run scripts can guard on `.messages.length` safely. */\nconst STUB_TOOL_RESPONSE_JSON = JSON.stringify({\n\tmessages: [],\n\tresults: [],\n\titems: [],\n\tdata: {\n\t\tmessages: [],\n\t\titems: [],\n\t\tresults: []\n\t}\n});\nfunction resolveToolOrThrow(index, path, tools) {\n\tconst tool = resolveTool(index, path);\n\tif (!tool) throw unknownToolError(path, tools);\n\treturn tool;\n}\n/** Bridge host {@link AgentTool}s into just-bash js-exec via `tools[\"name\"](args)`. */\nfunction createInvokeToolBridge(tools) {\n\tconst index = buildToolIndex(tools);\n\treturn async (path, argsJson) => {\n\t\tconst tool = resolveToolOrThrow(index, path, tools);\n\t\tconst args = argsJson ? JSON.parse(argsJson) : {};\n\t\treturn serializeToolResult(await tool.execute(randomUUID(), args));\n\t};\n}\n/** Dry-run bridge: validates tool names resolve but stubs responses without calling tools. */\nfunction createStubInvokeToolBridge(tools) {\n\tconst index = buildToolIndex(tools);\n\treturn async (path) => {\n\t\tresolveToolOrThrow(index, path, tools);\n\t\treturn STUB_TOOL_RESPONSE_JSON;\n\t};\n}\n//#endregion\n//#region src/ensure-sandbox-dirs.ts\n/** Ensure the workspaces root directory exists. Session dirs are created on demand. */\nasync function ensureSandboxDirs(workspacesRoot) {\n\tawait mkdir(workspacesRoot, { recursive: true });\n}\n//#endregion\n//#region src/project-scope-registry.ts\n/**\n* Read-only bridge to the bound project scope registered by the runtime via\n* `@keystrokehq/action`. Duplicated here so `@keystrokehq/sandbox` stays\n* publishable without depending on private `@keystrokehq/action`. Uses the same\n* `Symbol.for` slot as action/keystroke so registration is shared process-wide.\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}\n/** @internal Test hook — runtime registers via `@keystrokehq/action`. */\nfunction registerProjectScopeGetter(fn) {\n\tregistry().getter = fn;\n}\nfunction getRegisteredProjectScopeId() {\n\treturn registry().getter?.();\n}\n//#endregion\nexport { AGENT_MOUNT, AGENT_SKILLS_DIR, DEFAULT_EXEC_JOB_DELTA_BYTES, DEFAULT_EXEC_SOFT_WAIT_MS, DEFAULT_EXEC_TIMEOUT_MS, DEFAULT_GIT_CLONE_PATH, DEFAULT_GIT_USER_EMAIL, DEFAULT_GIT_USER_NAME, DEFAULT_SANDBOX_SIZE, DEPLOYED_FILES_MANIFEST_VERSION, DEPLOYED_FILES_RESERVED_PREFIX, EXEC_JOB_LOG_DIR, GIT_TOKEN_ENV_KEYS, MAX_EXEC_SOFT_WAIT_MS, MAX_EXEC_TIMEOUT_MS, SANDBOX_MODE_ENV, SANDBOX_PROVISIONING_LABELS, SANDBOX_PROVISIONING_PHASES, SESSION_MOUNT, STUB_TOOL_RESPONSE_JSON, SandboxDefinitionInputSchema, SandboxDefinitionSchema, SandboxGitBootstrapSchema, SandboxSetupSchema, SandboxSizeSchema, WORKSPACE_MOUNT, bashDescriptionSchema, bootstrapSandboxGit, buildDesiredDeployedFiles, buildGitCloneScript, configureClonedRepo, createBashJobTool, createBashTool, createCodingTools, createInMemoryExecJobs, createInvokeToolBridge, createJustBashProvider, createSandbox, createSkillViewTool, createStubInvokeToolBridge, defaultCommandTimeoutMs, defaultCommandTimeoutSeconds, defaultWorkspacesRoot, defineSandbox, defineSkill, defineTool, diffDeployedFiles, ensureSandboxDirs, ensureWorkspaceDir, execJobLogPath, execResultFromSnapshot, findUnknownPollScriptToolCalls, flattenSandboxFiles, forceWriteDesiredDeployedFiles, getBoundAppRoot, getRegisteredProjectScopeId, gitCredentialHelperScript, githubHttpsUrl, githubOriginsMatch, hashDeployedFileContent, isSandboxProvisioningPhase, loadAssetManifest, materializeSandbox, materializeSkills, mergeSandboxExecEnv, normalizeDeployedFilePath, normalizeGithubOrigin, normalizeSandboxSize, packAssetDirs, packDirFromDisk, parseDeployedFilesManifest, parseSandboxDefinitionInput, prepareHostDeployedFiles, reconcileDeployedFilesHost, registerProjectScopeGetter, reportSandboxProvisioning, resolveAgentRoot, resolveAppRoot, resolveAppRootFromModule, resolveDefaultRuntimeProvider, resolveDeployedFilesControlDir, resolveDeployedFilesManifestPath, resolveExecTimeoutMs, resolveGitClonePath, resolveSandboxDefinition, resolveSandboxGitUser, resolveSandboxMode, resolveSandboxPath, resolveSandboxResources, resolveSandboxRoot, resolveSessionRoot, resolveSoftWaitMs, runSandboxSetup, runWithAppRoot, sandboxSystemPromptInjection, sliceOutputDelta, timedOutResult, toSandboxGitBootstrapConfig, validateSandboxEnvOutput, withExecTimeout };\n\n//# sourceMappingURL=index.mjs.map","import { z } from \"zod\";\nimport { credential, credentialInputSchema, defineCredential, isCredentialInput, normalizeCredentialList, requiredDisplayTextSchema, toCredentialRequirement } from \"@keystrokehq/shared/action-runtime\";\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: requiredDisplayTextSchema,\n\tdescription: requiredDisplayTextSchema,\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 = Symbol.for(\"keystroke.workflowRunGetter\");\nfunction registry() {\n\tconst globalScope = globalThis;\n\tif (!globalScope[REGISTRY_KEY]) globalScope[REGISTRY_KEY] = {};\n\treturn globalScope[REGISTRY_KEY];\n}\nfunction registerWorkflowRunGetter(fn) {\n\tregistry().getter = fn;\n}\nfunction getWorkflowRunHandle() {\n\treturn registry().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\tcallSiteId: state.callSiteId,\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\t__site(callSiteId) {\n\t\t\treturn createStepInvocation({\n\t\t\t\t...state,\n\t\t\t\tcallSiteId\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, context) {\n\t\t\tif (credentials !== void 0) return execute(input, credentials, context);\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, context) => runWithinActionExecution(result.data.slug, () => def.run(input, credentials, {\n\t\t...context,\n\t\tsignal: context?.signal ?? getRunSignal()\n\t}));\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\nexport { defineCredential as _, registerWorkflowRunGetter as a, toCredentialRequirement as b, isWithinActionExecution as c, ACTION as d, actionCoreSchema as f, credentialInputSchema as g, credential as h, getWorkflowRunHandle as i, runOutsideActionExecution as l, isAction as m, createStepInvocation as n, getRunSignal as o, getActionCredentialRequirements as p, isStepInvocation as r, runWithRunSignal as s, defineAction as t, runWithinActionExecution as u, isCredentialInput as v, normalizeCredentialList as y };\n\n//# sourceMappingURL=define-action-CrYCWt9v.mjs.map","import { credential, defineAction } from \"@keystrokehq/action\";\nimport \"@keystrokehq/shared\";\nimport { z } from \"zod\";\n//#region src/define-app.ts\n/** Brand for {@link isApp} / agent `tools[]` expansion. */\nconst APP = Symbol.for(\"keystroke.app\");\nfunction appCredentialFor(slug, input) {\n\tif (input.auth === \"api_key\") return credential.static(slug, input.credential);\n\tif (input.auth === \"oauth\") return input.tokenField !== void 0 ? credential.oauth(slug, { tokenField: input.tokenField }) : credential.oauth(slug);\n\tif (input.credential !== void 0) return credential.keystroke(slug, z.object(input.credential));\n\treturn credential.keystroke(slug);\n}\n/** True when `value` is a {@link defineApp} result. */\nfunction isApp(value) {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tif (!(APP in value) || value[APP] !== true) return false;\n\tconst record = value;\n\treturn typeof record.slug === \"string\" && typeof record.action === \"function\";\n}\nfunction defineApp(input) {\n\tconst slug = input.slug.trim();\n\tif (!slug) throw new Error(\"defineApp requires a non-empty slug\");\n\tconst auth = input.auth ?? \"keystroke\";\n\tconst appCredential = appCredentialFor(slug, input);\n\tconst registered = [];\n\tfunction action(def) {\n\t\tconst created = defineAction({\n\t\t\tslug: def.slug,\n\t\t\tname: def.name,\n\t\t\tdescription: def.description,\n\t\t\tinput: def.input,\n\t\t\toutput: def.output,\n\t\t\tcredentials: [appCredential],\n\t\t\trun: def.run\n\t\t});\n\t\tconst mcpToolName = def.mcpToolName?.trim() || def.slug.trim();\n\t\tif (def.mcpToolName?.trim()) Object.defineProperty(created, \"mcpToolName\", {\n\t\t\tvalue: mcpToolName,\n\t\t\tenumerable: true,\n\t\t\twritable: false\n\t\t});\n\t\tregistered.push({\n\t\t\taction: created,\n\t\t\tmcpToolName\n\t\t});\n\t\treturn created;\n\t}\n\treturn {\n\t\t[APP]: true,\n\t\tslug,\n\t\tauth,\n\t\t...input.source ? { source: input.source } : {},\n\t\t...input.url?.trim() ? { url: input.url.trim() } : {},\n\t\tcredential: appCredential,\n\t\tactions: registered,\n\t\taction\n\t};\n}\n//#endregion\nexport { APP, defineApp, isApp };\n\n//# sourceMappingURL=index.mjs.map","import { z } from \"zod\";\n//#region src/define/agent-model-id.ts\nconst AGENT_MODEL_ID_PATTERN = /^[a-z0-9-]+\\/.+/;\nconst AgentModelIdSchema = z.custom((value) => typeof value === \"string\" && AGENT_MODEL_ID_PATTERN.test(value), \"model must be vendor/model-id\");\nfunction splitAgentModelId(modelId) {\n\tconst slash = modelId.indexOf(\"/\");\n\treturn {\n\t\tvendor: modelId.slice(0, slash),\n\t\tdirectId: modelId.slice(slash + 1)\n\t};\n}\n//#endregion\nexport { splitAgentModelId as n, AgentModelIdSchema as t };\n\n//# sourceMappingURL=agent-model-id-D8Vimsri.mjs.map","import { t as AgentModelIdSchema } from \"./agent-model-id-D8Vimsri.mjs\";\nimport { DEFAULT_CLOUD_PLATFORM_ORIGIN, PublicModelsResponseSchema } from \"@keystrokehq/shared/agent-runtime\";\n//#endregion\n//#region src/ai/validate-agent-model-ids.ts\nconst STATIC_MODEL_IDS = new Set([\n\t\"alibaba/qwen-3-14b\",\n\t\"alibaba/qwen-3-235b\",\n\t\"alibaba/qwen-3-30b\",\n\t\"alibaba/qwen-3-32b\",\n\t\"alibaba/qwen-3.6-max-preview\",\n\t\"alibaba/qwen3-235b-a22b-thinking\",\n\t\"alibaba/qwen3-coder\",\n\t\"alibaba/qwen3-coder-30b-a3b\",\n\t\"alibaba/qwen3-coder-next\",\n\t\"alibaba/qwen3-coder-plus\",\n\t\"alibaba/qwen3-embedding-0.6b\",\n\t\"alibaba/qwen3-embedding-4b\",\n\t\"alibaba/qwen3-embedding-8b\",\n\t\"alibaba/qwen3-max\",\n\t\"alibaba/qwen3-max-preview\",\n\t\"alibaba/qwen3-max-thinking\",\n\t\"alibaba/qwen3-next-80b-a3b-instruct\",\n\t\"alibaba/qwen3-next-80b-a3b-thinking\",\n\t\"alibaba/qwen3-vl-235b-a22b-instruct\",\n\t\"alibaba/qwen3-vl-instruct\",\n\t\"alibaba/qwen3-vl-thinking\",\n\t\"alibaba/qwen3.5-flash\",\n\t\"alibaba/qwen3.5-plus\",\n\t\"alibaba/qwen3.6-27b\",\n\t\"alibaba/qwen3.6-plus\",\n\t\"alibaba/qwen3.7-flash\",\n\t\"alibaba/qwen3.7-max\",\n\t\"alibaba/qwen3.7-plus\",\n\t\"alibaba/wan-v2.5-t2v-preview\",\n\t\"alibaba/wan-v2.6-i2v\",\n\t\"alibaba/wan-v2.6-i2v-flash\",\n\t\"alibaba/wan-v2.6-r2v\",\n\t\"alibaba/wan-v2.6-r2v-flash\",\n\t\"alibaba/wan-v2.6-t2v\",\n\t\"alibaba/wan-v2.7-r2v\",\n\t\"alibaba/wan-v2.7-t2v\",\n\t\"amazon/nova-2-lite\",\n\t\"amazon/nova-lite\",\n\t\"amazon/nova-micro\",\n\t\"amazon/nova-pro\",\n\t\"amazon/titan-embed-text-v2\",\n\t\"anthropic/claude-3-haiku\",\n\t\"anthropic/claude-fable-5\",\n\t\"anthropic/claude-haiku-4.5\",\n\t\"anthropic/claude-opus-4\",\n\t\"anthropic/claude-opus-4.1\",\n\t\"anthropic/claude-opus-4.5\",\n\t\"anthropic/claude-opus-4.6\",\n\t\"anthropic/claude-opus-4.7\",\n\t\"anthropic/claude-opus-4.8\",\n\t\"anthropic/claude-opus-4.8-fast\",\n\t\"anthropic/claude-opus-5\",\n\t\"anthropic/claude-opus-5-fast\",\n\t\"anthropic/claude-sonnet-4\",\n\t\"anthropic/claude-sonnet-4.5\",\n\t\"anthropic/claude-sonnet-4.6\",\n\t\"anthropic/claude-sonnet-5\",\n\t\"arcee-ai/trinity-large-thinking\",\n\t\"arcee-ai/trinity-mini\",\n\t\"bfl/flux-2-flex\",\n\t\"bfl/flux-2-klein-4b\",\n\t\"bfl/flux-2-klein-9b\",\n\t\"bfl/flux-2-max\",\n\t\"bfl/flux-2-pro\",\n\t\"bfl/flux-kontext-max\",\n\t\"bfl/flux-kontext-pro\",\n\t\"bfl/flux-pro-1.0-fill\",\n\t\"bfl/flux-pro-1.1\",\n\t\"bfl/flux-pro-1.1-ultra\",\n\t\"bytedance/seed-1.6\",\n\t\"bytedance/seed-1.8\",\n\t\"bytedance/seedance-2.0\",\n\t\"bytedance/seedance-2.0-fast\",\n\t\"bytedance/seedance-v1.0-pro\",\n\t\"bytedance/seedance-v1.0-pro-fast\",\n\t\"bytedance/seedance-v1.5-pro\",\n\t\"bytedance/seedream-4.0\",\n\t\"bytedance/seedream-4.5\",\n\t\"bytedance/seedream-5.0-lite\",\n\t\"bytedance/seedream-5.0-pro\",\n\t\"cohere/command-a\",\n\t\"cohere/embed-v4.0\",\n\t\"cohere/rerank-v3.5\",\n\t\"cohere/rerank-v4-fast\",\n\t\"cohere/rerank-v4-pro\",\n\t\"deepseek/deepseek-r1\",\n\t\"deepseek/deepseek-v3\",\n\t\"deepseek/deepseek-v3.1\",\n\t\"deepseek/deepseek-v3.1-terminus\",\n\t\"deepseek/deepseek-v3.2\",\n\t\"deepseek/deepseek-v3.2-thinking\",\n\t\"deepseek/deepseek-v4-flash\",\n\t\"deepseek/deepseek-v4-pro\",\n\t\"google/gemini-2.5-flash\",\n\t\"google/gemini-2.5-flash-image\",\n\t\"google/gemini-2.5-flash-lite\",\n\t\"google/gemini-2.5-pro\",\n\t\"google/gemini-3-flash\",\n\t\"google/gemini-3-pro-image\",\n\t\"google/gemini-3.1-flash-image\",\n\t\"google/gemini-3.1-flash-image-preview\",\n\t\"google/gemini-3.1-flash-lite\",\n\t\"google/gemini-3.1-flash-lite-image\",\n\t\"google/gemini-3.1-pro-preview\",\n\t\"google/gemini-3.5-flash\",\n\t\"google/gemini-3.5-flash-lite\",\n\t\"google/gemini-3.6-flash\",\n\t\"google/gemini-embedding-001\",\n\t\"google/gemini-embedding-2\",\n\t\"google/gemini-omni-flash-preview\",\n\t\"google/gemma-4-26b-a4b-it\",\n\t\"google/gemma-4-31b-it\",\n\t\"google/imagen-4.0-fast-generate-001\",\n\t\"google/imagen-4.0-generate-001\",\n\t\"google/imagen-4.0-ultra-generate-001\",\n\t\"google/text-embedding-005\",\n\t\"google/text-multilingual-embedding-002\",\n\t\"google/veo-3.0-fast-generate-001\",\n\t\"google/veo-3.0-generate-001\",\n\t\"google/veo-3.1-fast-generate-001\",\n\t\"google/veo-3.1-generate-001\",\n\t\"inception/mercury-2\",\n\t\"inception/mercury-coder-small\",\n\t\"inclusionai/ling-3.0-flash-free\",\n\t\"interfaze/interfaze-beta\",\n\t\"klingai/kling-v2.5-turbo-i2v\",\n\t\"klingai/kling-v2.5-turbo-t2v\",\n\t\"klingai/kling-v2.6-i2v\",\n\t\"klingai/kling-v2.6-motion-control\",\n\t\"klingai/kling-v2.6-t2v\",\n\t\"klingai/kling-v3.0-i2v\",\n\t\"klingai/kling-v3.0-motion-control\",\n\t\"klingai/kling-v3.0-t2v\",\n\t\"kwaipilot/kat-coder-air-v2.5\",\n\t\"kwaipilot/kat-coder-pro-v1\",\n\t\"kwaipilot/kat-coder-pro-v2\",\n\t\"kwaipilot/kat-coder-pro-v2.5\",\n\t\"meta/llama-3.1-70b\",\n\t\"meta/llama-3.1-8b\",\n\t\"meta/llama-3.3-70b\",\n\t\"meta/llama-4-maverick\",\n\t\"meta/llama-4-scout\",\n\t\"meta/muse-spark-1.1\",\n\t\"minimax/minimax-m2\",\n\t\"minimax/minimax-m2.1\",\n\t\"minimax/minimax-m2.1-lightning\",\n\t\"minimax/minimax-m2.5\",\n\t\"minimax/minimax-m2.5-highspeed\",\n\t\"minimax/minimax-m2.7\",\n\t\"minimax/minimax-m2.7-highspeed\",\n\t\"minimax/minimax-m3\",\n\t\"mistral/codestral\",\n\t\"mistral/codestral-embed\",\n\t\"mistral/devstral-2\",\n\t\"mistral/devstral-small-2\",\n\t\"mistral/magistral-medium\",\n\t\"mistral/magistral-small\",\n\t\"mistral/ministral-14b\",\n\t\"mistral/ministral-3b\",\n\t\"mistral/ministral-8b\",\n\t\"mistral/mistral-embed\",\n\t\"mistral/mistral-large-3\",\n\t\"mistral/mistral-medium\",\n\t\"mistral/mistral-medium-3.5\",\n\t\"mistral/mistral-nemo\",\n\t\"mistral/mistral-small\",\n\t\"mistral/pixtral-12b\",\n\t\"moonshotai/kimi-k2\",\n\t\"moonshotai/kimi-k2-thinking\",\n\t\"moonshotai/kimi-k2.5\",\n\t\"moonshotai/kimi-k2.6\",\n\t\"moonshotai/kimi-k2.7-code\",\n\t\"moonshotai/kimi-k2.7-code-highspeed\",\n\t\"moonshotai/kimi-k3\",\n\t\"moonshotai/kimi-k3-fast\",\n\t\"morph/morph-v3-fast\",\n\t\"morph/morph-v3-large\",\n\t\"nvidia/nemotron-3-nano-30b-a3b\",\n\t\"nvidia/nemotron-3-super-120b-a12b\",\n\t\"nvidia/nemotron-3-ultra-550b-a55b\",\n\t\"nvidia/nemotron-nano-12b-v2-vl\",\n\t\"nvidia/nemotron-nano-9b-v2\",\n\t\"openai/gpt-3.5-turbo\",\n\t\"openai/gpt-4-turbo\",\n\t\"openai/gpt-4.1\",\n\t\"openai/gpt-4.1-mini\",\n\t\"openai/gpt-4.1-nano\",\n\t\"openai/gpt-4o\",\n\t\"openai/gpt-4o-mini\",\n\t\"openai/gpt-4o-mini-search-preview\",\n\t\"openai/gpt-4o-mini-transcribe\",\n\t\"openai/gpt-4o-transcribe\",\n\t\"openai/gpt-5\",\n\t\"openai/gpt-5-codex\",\n\t\"openai/gpt-5-mini\",\n\t\"openai/gpt-5-nano\",\n\t\"openai/gpt-5-pro\",\n\t\"openai/gpt-5.1-codex\",\n\t\"openai/gpt-5.1-codex-max\",\n\t\"openai/gpt-5.1-codex-mini\",\n\t\"openai/gpt-5.1-instant\",\n\t\"openai/gpt-5.1-thinking\",\n\t\"openai/gpt-5.2\",\n\t\"openai/gpt-5.2-codex\",\n\t\"openai/gpt-5.2-pro\",\n\t\"openai/gpt-5.3-chat\",\n\t\"openai/gpt-5.3-codex\",\n\t\"openai/gpt-5.4\",\n\t\"openai/gpt-5.4-mini\",\n\t\"openai/gpt-5.4-nano\",\n\t\"openai/gpt-5.4-pro\",\n\t\"openai/gpt-5.5\",\n\t\"openai/gpt-5.5-pro\",\n\t\"openai/gpt-5.6-luna\",\n\t\"openai/gpt-5.6-sol\",\n\t\"openai/gpt-5.6-terra\",\n\t\"openai/gpt-image-1\",\n\t\"openai/gpt-image-1-mini\",\n\t\"openai/gpt-image-1.5\",\n\t\"openai/gpt-image-2\",\n\t\"openai/gpt-oss-120b\",\n\t\"openai/gpt-oss-20b\",\n\t\"openai/gpt-oss-safeguard-20b\",\n\t\"openai/gpt-realtime-1.5\",\n\t\"openai/gpt-realtime-2\",\n\t\"openai/gpt-realtime-2.1\",\n\t\"openai/gpt-realtime-mini\",\n\t\"openai/gpt-realtime-whisper\",\n\t\"openai/o1\",\n\t\"openai/o3\",\n\t\"openai/o3-deep-research\",\n\t\"openai/o3-mini\",\n\t\"openai/o3-pro\",\n\t\"openai/o4-mini\",\n\t\"openai/text-embedding-3-large\",\n\t\"openai/text-embedding-3-small\",\n\t\"openai/text-embedding-ada-002\",\n\t\"openai/tts-1\",\n\t\"openai/tts-1-hd\",\n\t\"openai/whisper-1\",\n\t\"perplexity/sonar\",\n\t\"perplexity/sonar-pro\",\n\t\"perplexity/sonar-reasoning-pro\",\n\t\"poolside/laguna-s-2.1\",\n\t\"poolside/laguna-s-2.1-free\",\n\t\"prodia/flux-fast-schnell\",\n\t\"quiverai/arrow-1.1\",\n\t\"recraft/recraft-v2\",\n\t\"recraft/recraft-v3\",\n\t\"recraft/recraft-v4\",\n\t\"recraft/recraft-v4-pro\",\n\t\"recraft/recraft-v4.1\",\n\t\"recraft/recraft-v4.1-pro\",\n\t\"recraft/recraft-v4.1-utility\",\n\t\"recraft/recraft-v4.1-utility-pro\",\n\t\"sakana/fugu-ultra\",\n\t\"stepfun/step-3.5-flash\",\n\t\"stepfun/step-3.7-flash\",\n\t\"tencent/hy3\",\n\t\"thinkingmachines/inkling\",\n\t\"voyage/rerank-2.5\",\n\t\"voyage/rerank-2.5-lite\",\n\t\"voyage/voyage-3-large\",\n\t\"voyage/voyage-3.5\",\n\t\"voyage/voyage-3.5-lite\",\n\t\"voyage/voyage-4\",\n\t\"voyage/voyage-4-large\",\n\t\"voyage/voyage-4-lite\",\n\t\"voyage/voyage-code-2\",\n\t\"voyage/voyage-code-3\",\n\t\"voyage/voyage-finance-2\",\n\t\"voyage/voyage-law-2\",\n\t\"xai/grok-4.1-fast-non-reasoning\",\n\t\"xai/grok-4.1-fast-reasoning\",\n\t\"xai/grok-4.20-multi-agent\",\n\t\"xai/grok-4.20-multi-agent-beta\",\n\t\"xai/grok-4.20-non-reasoning\",\n\t\"xai/grok-4.20-non-reasoning-beta\",\n\t\"xai/grok-4.20-reasoning\",\n\t\"xai/grok-4.20-reasoning-beta\",\n\t\"xai/grok-4.3\",\n\t\"xai/grok-4.5\",\n\t\"xai/grok-build-0.1\",\n\t\"xai/grok-imagine-image\",\n\t\"xai/grok-imagine-video\",\n\t\"xai/grok-imagine-video-1.5\",\n\t\"xai/grok-imagine-video-1.5-preview\",\n\t\"xai/grok-stt\",\n\t\"xai/grok-tts\",\n\t\"xai/grok-voice-think-fast-1.0\",\n\t\"xiaomi/mimo-v2.5\",\n\t\"xiaomi/mimo-v2.5-pro\",\n\t\"zai/glm-4.5\",\n\t\"zai/glm-4.5-air\",\n\t\"zai/glm-4.5v\",\n\t\"zai/glm-4.6\",\n\t\"zai/glm-4.6v\",\n\t\"zai/glm-4.6v-flash\",\n\t\"zai/glm-4.7\",\n\t\"zai/glm-4.7-flash\",\n\t\"zai/glm-4.7-flashx\",\n\t\"zai/glm-5\",\n\t\"zai/glm-5-turbo\",\n\t\"zai/glm-5.1\",\n\t\"zai/glm-5.2\",\n\t\"zai/glm-5.2-fast\",\n\t\"zai/glm-5v-turbo\"\n]);\nlet cachedModelIds;\nlet pendingModelIds;\n/** Clears cached public model list (for tests). */\nfunction clearPublicModelCatalogCache() {\n\tcachedModelIds = void 0;\n\tpendingModelIds = void 0;\n}\nfunction resolvePlatformOriginForModelCatalog() {\n\tconst fromKeystroke = process.env.KEYSTROKE_PLATFORM_URL?.trim();\n\tif (fromKeystroke) return fromKeystroke.replace(/\\/+$/, \"\");\n\tconst fromPlatform = process.env.PLATFORM_URL?.trim();\n\tif (fromPlatform) return fromPlatform.replace(/\\/+$/, \"\");\n\treturn DEFAULT_CLOUD_PLATFORM_ORIGIN;\n}\nasync function fetchPublicModelIds() {\n\tif (cachedModelIds) return cachedModelIds;\n\tif (pendingModelIds) return pendingModelIds;\n\tconst platformOrigin = resolvePlatformOriginForModelCatalog();\n\tpendingModelIds = (async () => {\n\t\ttry {\n\t\t\tconst response = await fetch(`${platformOrigin}/api/public/models`, { headers: { accept: \"application/json\" } });\n\t\t\tif (!response.ok) throw new Error(`Failed to fetch public model catalog (${response.status})`);\n\t\t\tconst parsed = PublicModelsResponseSchema.safeParse(await response.json());\n\t\t\tif (!parsed.success || parsed.data.models.length === 0) throw new Error(\"Public model catalog response had no models\");\n\t\t\tcachedModelIds = new Set(parsed.data.models);\n\t\t\treturn cachedModelIds;\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tconsole.warn(`Skipping agent model validation: ${message}`);\n\t\t\treturn;\n\t\t} finally {\n\t\t\tpendingModelIds = void 0;\n\t\t}\n\t})();\n\treturn pendingModelIds;\n}\n/**\n* Fail when any model id is unknown. Checks the committed catalog first (fast,\n* offline) and only fetches the live catalog to confirm misses — so newly added\n* gateway models still validate without a per-build network round-trip.\n*/\nasync function validateAgentModelIds(modelIds) {\n\tconst missingFromStatic = [...new Set(modelIds)].filter((id) => !STATIC_MODEL_IDS.has(id));\n\tif (missingFromStatic.length === 0) return;\n\tconst live = await fetchPublicModelIds();\n\tif (!live) return;\n\tconst unknown = missingFromStatic.filter((id) => !live.has(id));\n\tif (unknown.length === 0) return;\n\tthrow Object.assign(/* @__PURE__ */ new Error(unknown.length === 1 ? `Unknown gateway model: ${unknown[0]}` : `Unknown gateway models: ${unknown.join(\", \")}`), { status: 400 });\n}\n/** Collect agent model ids from a stored route manifest (deploy validation). */\nfunction agentModelIdsFromStoredManifest(manifest) {\n\tconst ids = [];\n\tfor (const entry of manifest.entries) {\n\t\tif (entry.kind !== \"agent\") continue;\n\t\tconst parsed = AgentModelIdSchema.safeParse(entry.model);\n\t\tif (parsed.success) ids.push(parsed.data);\n\t\tif (\"compactionModel\" in entry && typeof entry.compactionModel === \"string\") {\n\t\t\tconst compaction = AgentModelIdSchema.safeParse(entry.compactionModel);\n\t\t\tif (compaction.success) ids.push(compaction.data);\n\t\t}\n\t}\n\treturn ids;\n}\n//#endregion\nexport { clearPublicModelCatalogCache as n, validateAgentModelIds as r, agentModelIdsFromStoredManifest as t };\n\n//# sourceMappingURL=validate-agent-model-ids-D2ODPNKe.mjs.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CronField = void 0;\n/**\n * Represents a field within a cron expression.\n * This is a base class and should not be instantiated directly.\n * @class CronField\n */\nclass CronField {\n    #hasLastChar = false;\n    #hasQuestionMarkChar = false;\n    #wildcard = false;\n    #values = [];\n    options = { rawValue: '' };\n    /**\n     * Returns the minimum value allowed for this field.\n     */\n    /* istanbul ignore next */ static get min() {\n        /* istanbul ignore next */\n        throw new Error('min must be overridden');\n    }\n    /**\n     * Returns the maximum value allowed for this field.\n     */\n    /* istanbul ignore next */ static get max() {\n        /* istanbul ignore next */\n        throw new Error('max must be overridden');\n    }\n    /**\n     * Returns the allowed characters for this field.\n     */\n    /* istanbul ignore next */ static get chars() {\n        /* istanbul ignore next - this is overridden */\n        return Object.freeze([]);\n    }\n    /**\n     * Returns the regular expression used to validate this field.\n     */\n    static get validChars() {\n        return /^[?,*\\dH/-]+$|^.*H\\(\\d+-\\d+\\)\\/\\d+.*$|^.*H\\(\\d+-\\d+\\).*$|^.*H\\/\\d+.*$/;\n    }\n    /**\n     * Returns the constraints for this field.\n     */\n    static get constraints() {\n        return { min: this.min, max: this.max, chars: this.chars, validChars: this.validChars };\n    }\n    /**\n     * CronField constructor. Initializes the field with the provided values.\n     * @param {number[] | string[]} values - Values for this field\n     * @param {CronFieldOptions} [options] - Options provided by the parser\n     * @throws {TypeError} if the constructor is called directly\n     * @throws {Error} if validation fails\n     */\n    constructor(values, options = { rawValue: '' }) {\n        if (!Array.isArray(values)) {\n            throw new Error(`${this.constructor.name} Validation error, values is not an array`);\n        }\n        if (!(values.length > 0)) {\n            throw new Error(`${this.constructor.name} Validation error, values contains no values`);\n        }\n        /* istanbul ignore next */\n        this.options = {\n            ...options,\n            rawValue: options.rawValue ?? '',\n        };\n        this.#values = values.sort(CronField.sorter);\n        this.#wildcard = this.options.wildcard !== undefined ? this.options.wildcard : this.#isWildcardValue();\n        this.#hasLastChar = this.options.rawValue.includes('L') || values.includes('L');\n        this.#hasQuestionMarkChar = this.options.rawValue.includes('?') || values.includes('?');\n    }\n    /**\n     * Returns the minimum value allowed for this field.\n     * @returns {number}\n     */\n    get min() {\n        // return the static value from the child class\n        return this.constructor.min;\n    }\n    /**\n     * Returns the maximum value allowed for this field.\n     * @returns {number}\n     */\n    get max() {\n        // return the static value from the child class\n        return this.constructor.max;\n    }\n    /**\n     * Returns an array of allowed special characters for this field.\n     * @returns {string[]}\n     */\n    get chars() {\n        // return the frozen static value from the child class\n        return this.constructor.chars;\n    }\n    /**\n     * Indicates whether this field has a \"last\" character.\n     * @returns {boolean}\n     */\n    get hasLastChar() {\n        return this.#hasLastChar;\n    }\n    /**\n     * Indicates whether this field has a \"question mark\" character.\n     * @returns {boolean}\n     */\n    get hasQuestionMarkChar() {\n        return this.#hasQuestionMarkChar;\n    }\n    /**\n     * Indicates whether this field is a wildcard.\n     * @returns {boolean}\n     */\n    get isWildcard() {\n        return this.#wildcard;\n    }\n    /**\n     * Returns an array of allowed values for this field.\n     * @returns {CronFieldType}\n     */\n    get values() {\n        return this.#values;\n    }\n    /**\n     * Helper function to sort values in ascending order.\n     * @param {number | string} a - First value to compare\n     * @param {number | string} b - Second value to compare\n     * @returns {number} - A negative, zero, or positive value, depending on the sort order\n     */\n    static sorter(a, b) {\n        const aIsNumber = typeof a === 'number';\n        const bIsNumber = typeof b === 'number';\n        if (aIsNumber && bIsNumber)\n            return a - b;\n        if (!aIsNumber && !bIsNumber)\n            return a.localeCompare(b);\n        return aIsNumber ? /* istanbul ignore next - A will always be a number until L-2 is supported */ -1 : 1;\n    }\n    /**\n     * Find the next (or previous when `reverse` is true) numeric value in a sorted list.\n     * Returns null if there's no value strictly after/before the current one.\n     *\n     * @param values - Sorted numeric values\n     * @param currentValue - Current value to compare against\n     * @param reverse - When true, search in reverse for previous smaller value\n     */\n    static findNearestValueInList(values, currentValue, reverse = false) {\n        if (reverse) {\n            for (let i = values.length - 1; i >= 0; i--) {\n                if (values[i] < currentValue)\n                    return values[i];\n            }\n            return null;\n        }\n        for (let i = 0; i < values.length; i++) {\n            if (values[i] > currentValue)\n                return values[i];\n        }\n        return null;\n    }\n    /**\n     * Instance helper that operates on this field's numeric `values`.\n     *\n     * @param currentValue - Current value to compare against\n     * @param reverse - When true, search in reverse for previous smaller value\n     */\n    findNearestValue(currentValue, reverse = false) {\n        return this.constructor.findNearestValueInList(this.values, currentValue, reverse);\n    }\n    /**\n     * Serializes the field to an object.\n     * @returns {SerializedCronField}\n     */\n    serialize() {\n        return {\n            wildcard: this.#wildcard,\n            values: this.#values,\n        };\n    }\n    /**\n     * Validates the field values against the allowed range and special characters.\n     * @throws {Error} if validation fails\n     */\n    validate() {\n        let badValue;\n        const charsString = this.chars.length > 0 ? ` or chars ${this.chars.join('')}` : '';\n        const charTest = (value) => (char) => new RegExp(`^\\\\d{0,2}${char}$`).test(value);\n        const rangeTest = (value) => {\n            badValue = value;\n            return typeof value === 'number' ? value >= this.min && value <= this.max : this.chars.some(charTest(value));\n        };\n        const isValidRange = this.#values.every(rangeTest);\n        if (!isValidRange) {\n            throw new Error(`${this.constructor.name} Validation error, got value ${badValue} expected range ${this.min}-${this.max}${charsString}`);\n        }\n        // check for duplicate value in this.#values array\n        const duplicate = this.#values.find((value, index) => this.#values.indexOf(value) !== index);\n        if (duplicate) {\n            throw new Error(`${this.constructor.name} Validation error, duplicate values found: ${duplicate}`);\n        }\n    }\n    /**\n     * Determines if the field is a wildcard based on the values.\n     * When options.rawValue is not empty, it checks if the raw value is a wildcard, otherwise it checks if all values in the range are included.\n     * @returns {boolean}\n     */\n    #isWildcardValue() {\n        if (this.options.rawValue.length > 0) {\n            return ['*', '?'].includes(this.options.rawValue);\n        }\n        return Array.from({ length: this.max - this.min + 1 }, (_, i) => i + this.min).every((value) => this.#values.includes(value));\n    }\n}\nexports.CronField = CronField;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CronDayOfMonth = void 0;\nconst CronField_1 = require(\"./CronField\");\nconst MIN_DAY = 1;\nconst MAX_DAY = 31;\nconst DAY_CHARS = Object.freeze(['L']);\n/**\n * Represents the \"day of the month\" field within a cron expression.\n * @class CronDayOfMonth\n * @extends CronField\n */\nclass CronDayOfMonth extends CronField_1.CronField {\n    static get min() {\n        return MIN_DAY;\n    }\n    static get max() {\n        return MAX_DAY;\n    }\n    static get chars() {\n        return DAY_CHARS;\n    }\n    static get validChars() {\n        return /^[?,*\\dLH/-]+$|^.*H\\(\\d+-\\d+\\)\\/\\d+.*$|^.*H\\(\\d+-\\d+\\).*$|^.*H\\/\\d+.*$/;\n    }\n    /**\n     * CronDayOfMonth constructor. Initializes the \"day of the month\" field with the provided values.\n     * @param {DayOfMonthRange[]} values - Values for the \"day of the month\" field\n     * @param {CronFieldOptions} [options] - Options provided by the parser\n     * @throws {Error} if validation fails\n     */\n    constructor(values, options) {\n        super(values, options);\n        this.validate();\n    }\n    /**\n     * Returns an array of allowed values for the \"day of the month\" field.\n     * @returns {DayOfMonthRange[]}\n     */\n    get values() {\n        return super.values;\n    }\n}\nexports.CronDayOfMonth = CronDayOfMonth;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CronDayOfWeek = void 0;\nconst CronField_1 = require(\"./CronField\");\nconst MIN_DAY = 0;\nconst MAX_DAY = 7;\nconst DAY_CHARS = Object.freeze(['L']);\n/**\n * Represents the \"day of the week\" field within a cron expression.\n * @class CronDayOfTheWeek\n * @extends CronField\n */\nclass CronDayOfWeek extends CronField_1.CronField {\n    static get min() {\n        return MIN_DAY;\n    }\n    static get max() {\n        return MAX_DAY;\n    }\n    static get chars() {\n        return DAY_CHARS;\n    }\n    static get validChars() {\n        return /^[?,*\\dLH#/-]+$|^.*H\\(\\d+-\\d+\\)\\/\\d+.*$|^.*H\\(\\d+-\\d+\\).*$|^.*H\\/\\d+.*$/;\n    }\n    /**\n     * CronDayOfTheWeek constructor. Initializes the \"day of the week\" field with the provided values.\n     * @param {DayOfWeekRange[]} values - Values for the \"day of the week\" field\n     * @param {CronFieldOptions} [options] - Options provided by the parser\n     */\n    constructor(values, options) {\n        super(values, options);\n        this.validate();\n    }\n    /**\n     * Returns an array of allowed values for the \"day of the week\" field.\n     * @returns {DayOfWeekRange[]}\n     */\n    get values() {\n        return super.values;\n    }\n    /**\n     * Returns the nth day of the week if specified in the cron expression.\n     * This is used for the '#' character in the cron expression.\n     * @returns {number} The nth day of the week (1-5) or 0 if not specified.\n     */\n    get nthDay() {\n        return this.options.nthDayOfWeek ?? 0;\n    }\n}\nexports.CronDayOfWeek = CronDayOfWeek;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CronHour = void 0;\nconst CronField_1 = require(\"./CronField\");\nconst MIN_HOUR = 0;\nconst MAX_HOUR = 23;\nconst HOUR_CHARS = Object.freeze([]);\n/**\n * Represents the \"hour\" field within a cron expression.\n * @class CronHour\n * @extends CronField\n */\nclass CronHour extends CronField_1.CronField {\n    static get min() {\n        return MIN_HOUR;\n    }\n    static get max() {\n        return MAX_HOUR;\n    }\n    static get chars() {\n        return HOUR_CHARS;\n    }\n    /**\n     * CronHour constructor. Initializes the \"hour\" field with the provided values.\n     * @param {HourRange[]} values - Values for the \"hour\" field\n     * @param {CronFieldOptions} [options] - Options provided by the parser\n     */\n    constructor(values, options) {\n        super(values, options);\n        this.validate();\n    }\n    /**\n     * Returns an array of allowed values for the \"hour\" field.\n     * @returns {HourRange[]}\n     */\n    get values() {\n        return super.values;\n    }\n}\nexports.CronHour = CronHour;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CronMinute = void 0;\nconst CronField_1 = require(\"./CronField\");\nconst MIN_MINUTE = 0;\nconst MAX_MINUTE = 59;\nconst MINUTE_CHARS = Object.freeze([]);\n/**\n * Represents the \"second\" field within a cron expression.\n * @class CronSecond\n * @extends CronField\n */\nclass CronMinute extends CronField_1.CronField {\n    static get min() {\n        return MIN_MINUTE;\n    }\n    static get max() {\n        return MAX_MINUTE;\n    }\n    static get chars() {\n        return MINUTE_CHARS;\n    }\n    /**\n     * CronSecond constructor. Initializes the \"second\" field with the provided values.\n     * @param {SixtyRange[]} values - Values for the \"second\" field\n     * @param {CronFieldOptions} [options] - Options provided by the parser\n     */\n    constructor(values, options) {\n        super(values, options);\n        this.validate();\n    }\n    /**\n     * Returns an array of allowed values for the \"second\" field.\n     * @returns {SixtyRange[]}\n     */\n    get values() {\n        return super.values;\n    }\n}\nexports.CronMinute = CronMinute;\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\n// these aren't really private, but nor are they really useful to document\n\n/**\n * @private\n */\nclass LuxonError extends Error {}\n\n/**\n * @private\n */\nclass InvalidDateTimeError extends LuxonError {\n  constructor(reason) {\n    super(`Invalid DateTime: ${reason.toMessage()}`);\n  }\n}\n\n/**\n * @private\n */\nclass InvalidIntervalError extends LuxonError {\n  constructor(reason) {\n    super(`Invalid Interval: ${reason.toMessage()}`);\n  }\n}\n\n/**\n * @private\n */\nclass InvalidDurationError extends LuxonError {\n  constructor(reason) {\n    super(`Invalid Duration: ${reason.toMessage()}`);\n  }\n}\n\n/**\n * @private\n */\nclass ConflictingSpecificationError extends LuxonError {}\n\n/**\n * @private\n */\nclass InvalidUnitError extends LuxonError {\n  constructor(unit) {\n    super(`Invalid unit ${unit}`);\n  }\n}\n\n/**\n * @private\n */\nclass InvalidArgumentError extends LuxonError {}\n\n/**\n * @private\n */\nclass ZoneIsAbstractError extends LuxonError {\n  constructor() {\n    super(\"Zone is an abstract class\");\n  }\n}\n\n/**\n * @private\n */\n\nconst n = \"numeric\",\n  s = \"short\",\n  l = \"long\";\nconst DATE_SHORT = {\n  year: n,\n  month: n,\n  day: n\n};\nconst DATE_MED = {\n  year: n,\n  month: s,\n  day: n\n};\nconst DATE_MED_WITH_WEEKDAY = {\n  year: n,\n  month: s,\n  day: n,\n  weekday: s\n};\nconst DATE_FULL = {\n  year: n,\n  month: l,\n  day: n\n};\nconst DATE_HUGE = {\n  year: n,\n  month: l,\n  day: n,\n  weekday: l\n};\nconst TIME_SIMPLE = {\n  hour: n,\n  minute: n\n};\nconst TIME_WITH_SECONDS = {\n  hour: n,\n  minute: n,\n  second: n\n};\nconst TIME_WITH_SHORT_OFFSET = {\n  hour: n,\n  minute: n,\n  second: n,\n  timeZoneName: s\n};\nconst TIME_WITH_LONG_OFFSET = {\n  hour: n,\n  minute: n,\n  second: n,\n  timeZoneName: l\n};\nconst TIME_24_SIMPLE = {\n  hour: n,\n  minute: n,\n  hourCycle: \"h23\"\n};\nconst TIME_24_WITH_SECONDS = {\n  hour: n,\n  minute: n,\n  second: n,\n  hourCycle: \"h23\"\n};\nconst TIME_24_WITH_SHORT_OFFSET = {\n  hour: n,\n  minute: n,\n  second: n,\n  hourCycle: \"h23\",\n  timeZoneName: s\n};\nconst TIME_24_WITH_LONG_OFFSET = {\n  hour: n,\n  minute: n,\n  second: n,\n  hourCycle: \"h23\",\n  timeZoneName: l\n};\nconst DATETIME_SHORT = {\n  year: n,\n  month: n,\n  day: n,\n  hour: n,\n  minute: n\n};\nconst DATETIME_SHORT_WITH_SECONDS = {\n  year: n,\n  month: n,\n  day: n,\n  hour: n,\n  minute: n,\n  second: n\n};\nconst DATETIME_MED = {\n  year: n,\n  month: s,\n  day: n,\n  hour: n,\n  minute: n\n};\nconst DATETIME_MED_WITH_SECONDS = {\n  year: n,\n  month: s,\n  day: n,\n  hour: n,\n  minute: n,\n  second: n\n};\nconst DATETIME_MED_WITH_WEEKDAY = {\n  year: n,\n  month: s,\n  day: n,\n  weekday: s,\n  hour: n,\n  minute: n\n};\nconst DATETIME_FULL = {\n  year: n,\n  month: l,\n  day: n,\n  hour: n,\n  minute: n,\n  timeZoneName: s\n};\nconst DATETIME_FULL_WITH_SECONDS = {\n  year: n,\n  month: l,\n  day: n,\n  hour: n,\n  minute: n,\n  second: n,\n  timeZoneName: s\n};\nconst DATETIME_HUGE = {\n  year: n,\n  month: l,\n  day: n,\n  weekday: l,\n  hour: n,\n  minute: n,\n  timeZoneName: l\n};\nconst DATETIME_HUGE_WITH_SECONDS = {\n  year: n,\n  month: l,\n  day: n,\n  weekday: l,\n  hour: n,\n  minute: n,\n  second: n,\n  timeZoneName: l\n};\n\n/**\n * @interface\n */\nclass Zone {\n  /**\n   * The type of zone\n   * @abstract\n   * @type {string}\n   */\n  get type() {\n    throw new ZoneIsAbstractError();\n  }\n\n  /**\n   * The name of this zone.\n   * @abstract\n   * @type {string}\n   */\n  get name() {\n    throw new ZoneIsAbstractError();\n  }\n\n  /**\n   * The IANA name of this zone.\n   * Defaults to `name` if not overwritten by a subclass.\n   * @abstract\n   * @type {string}\n   */\n  get ianaName() {\n    return this.name;\n  }\n\n  /**\n   * Returns whether the offset is known to be fixed for the whole year.\n   * @abstract\n   * @type {boolean}\n   */\n  get isUniversal() {\n    throw new ZoneIsAbstractError();\n  }\n\n  /**\n   * Returns the offset's common name (such as EST) at the specified timestamp\n   * @abstract\n   * @param {number} ts - Epoch milliseconds for which to get the name\n   * @param {Object} opts - Options to affect the format\n   * @param {string} opts.format - What style of offset to return. Accepts 'long' or 'short'.\n   * @param {string} opts.locale - What locale to return the offset name in.\n   * @return {string}\n   */\n  offsetName(ts, opts) {\n    throw new ZoneIsAbstractError();\n  }\n\n  /**\n   * Returns the offset's value as a string\n   * @abstract\n   * @param {number} ts - Epoch milliseconds for which to get the offset\n   * @param {string} format - What style of offset to return.\n   *                          Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively\n   * @return {string}\n   */\n  formatOffset(ts, format) {\n    throw new ZoneIsAbstractError();\n  }\n\n  /**\n   * Return the offset in minutes for this zone at the specified timestamp.\n   * @abstract\n   * @param {number} ts - Epoch milliseconds for which to compute the offset\n   * @return {number}\n   */\n  offset(ts) {\n    throw new ZoneIsAbstractError();\n  }\n\n  /**\n   * Return whether this Zone is equal to another zone\n   * @abstract\n   * @param {Zone} otherZone - the zone to compare\n   * @return {boolean}\n   */\n  equals(otherZone) {\n    throw new ZoneIsAbstractError();\n  }\n\n  /**\n   * Return whether this Zone is valid.\n   * @abstract\n   * @type {boolean}\n   */\n  get isValid() {\n    throw new ZoneIsAbstractError();\n  }\n}\n\nlet singleton$1 = null;\n\n/**\n * Represents the local zone for this JavaScript environment.\n * @implements {Zone}\n */\nclass SystemZone extends Zone {\n  /**\n   * Get a singleton instance of the local zone\n   * @return {SystemZone}\n   */\n  static get instance() {\n    if (singleton$1 === null) {\n      singleton$1 = new SystemZone();\n    }\n    return singleton$1;\n  }\n\n  /** @override **/\n  get type() {\n    return \"system\";\n  }\n\n  /** @override **/\n  get name() {\n    return new Intl.DateTimeFormat().resolvedOptions().timeZone;\n  }\n\n  /** @override **/\n  get isUniversal() {\n    return false;\n  }\n\n  /** @override **/\n  offsetName(ts, {\n    format,\n    locale\n  }) {\n    return parseZoneInfo(ts, format, locale);\n  }\n\n  /** @override **/\n  formatOffset(ts, format) {\n    return formatOffset(this.offset(ts), format);\n  }\n\n  /** @override **/\n  offset(ts) {\n    return -new Date(ts).getTimezoneOffset();\n  }\n\n  /** @override **/\n  equals(otherZone) {\n    return otherZone.type === \"system\";\n  }\n\n  /** @override **/\n  get isValid() {\n    return true;\n  }\n}\n\nconst dtfCache = new Map();\nfunction makeDTF(zoneName) {\n  let dtf = dtfCache.get(zoneName);\n  if (dtf === undefined) {\n    dtf = new Intl.DateTimeFormat(\"en-US\", {\n      hour12: false,\n      timeZone: zoneName,\n      year: \"numeric\",\n      month: \"2-digit\",\n      day: \"2-digit\",\n      hour: \"2-digit\",\n      minute: \"2-digit\",\n      second: \"2-digit\",\n      era: \"short\"\n    });\n    dtfCache.set(zoneName, dtf);\n  }\n  return dtf;\n}\nconst typeToPos = {\n  year: 0,\n  month: 1,\n  day: 2,\n  era: 3,\n  hour: 4,\n  minute: 5,\n  second: 6\n};\nfunction hackyOffset(dtf, date) {\n  const formatted = dtf.format(date).replace(/\\u200E/g, \"\"),\n    parsed = /(\\d+)\\/(\\d+)\\/(\\d+) (AD|BC),? (\\d+):(\\d+):(\\d+)/.exec(formatted),\n    [, fMonth, fDay, fYear, fadOrBc, fHour, fMinute, fSecond] = parsed;\n  return [fYear, fMonth, fDay, fadOrBc, fHour, fMinute, fSecond];\n}\nfunction partsOffset(dtf, date) {\n  const formatted = dtf.formatToParts(date);\n  const filled = [];\n  for (let i = 0; i < formatted.length; i++) {\n    const {\n      type,\n      value\n    } = formatted[i];\n    const pos = typeToPos[type];\n    if (type === \"era\") {\n      filled[pos] = value;\n    } else if (!isUndefined(pos)) {\n      filled[pos] = parseInt(value, 10);\n    }\n  }\n  return filled;\n}\nconst ianaZoneCache = new Map();\n/**\n * A zone identified by an IANA identifier, like America/New_York\n * @implements {Zone}\n */\nclass IANAZone extends Zone {\n  /**\n   * @param {string} name - Zone name\n   * @return {IANAZone}\n   */\n  static create(name) {\n    let zone = ianaZoneCache.get(name);\n    if (zone === undefined) {\n      ianaZoneCache.set(name, zone = new IANAZone(name));\n    }\n    return zone;\n  }\n\n  /**\n   * Reset local caches. Should only be necessary in testing scenarios.\n   * @return {void}\n   */\n  static resetCache() {\n    ianaZoneCache.clear();\n    dtfCache.clear();\n  }\n\n  /**\n   * Returns whether the provided string is a valid specifier. This only checks the string's format, not that the specifier identifies a known zone; see isValidZone for that.\n   * @param {string} s - The string to check validity on\n   * @example IANAZone.isValidSpecifier(\"America/New_York\") //=> true\n   * @example IANAZone.isValidSpecifier(\"Sport~~blorp\") //=> false\n   * @deprecated For backward compatibility, this forwards to isValidZone, better use `isValidZone()` directly instead.\n   * @return {boolean}\n   */\n  static isValidSpecifier(s) {\n    return this.isValidZone(s);\n  }\n\n  /**\n   * Returns whether the provided string identifies a real zone\n   * @param {string} zone - The string to check\n   * @example IANAZone.isValidZone(\"America/New_York\") //=> true\n   * @example IANAZone.isValidZone(\"Fantasia/Castle\") //=> false\n   * @example IANAZone.isValidZone(\"Sport~~blorp\") //=> false\n   * @return {boolean}\n   */\n  static isValidZone(zone) {\n    if (!zone) {\n      return false;\n    }\n    try {\n      new Intl.DateTimeFormat(\"en-US\", {\n        timeZone: zone\n      }).format();\n      return true;\n    } catch (e) {\n      return false;\n    }\n  }\n  constructor(name) {\n    super();\n    /** @private **/\n    this.zoneName = name;\n    /** @private **/\n    this.valid = IANAZone.isValidZone(name);\n  }\n\n  /**\n   * The type of zone. `iana` for all instances of `IANAZone`.\n   * @override\n   * @type {string}\n   */\n  get type() {\n    return \"iana\";\n  }\n\n  /**\n   * The name of this zone (i.e. the IANA zone name).\n   * @override\n   * @type {string}\n   */\n  get name() {\n    return this.zoneName;\n  }\n\n  /**\n   * Returns whether the offset is known to be fixed for the whole year:\n   * Always returns false for all IANA zones.\n   * @override\n   * @type {boolean}\n   */\n  get isUniversal() {\n    return false;\n  }\n\n  /**\n   * Returns the offset's common name (such as EST) at the specified timestamp\n   * @override\n   * @param {number} ts - Epoch milliseconds for which to get the name\n   * @param {Object} opts - Options to affect the format\n   * @param {string} opts.format - What style of offset to return. Accepts 'long' or 'short'.\n   * @param {string} opts.locale - What locale to return the offset name in.\n   * @return {string}\n   */\n  offsetName(ts, {\n    format,\n    locale\n  }) {\n    return parseZoneInfo(ts, format, locale, this.name);\n  }\n\n  /**\n   * Returns the offset's value as a string\n   * @override\n   * @param {number} ts - Epoch milliseconds for which to get the offset\n   * @param {string} format - What style of offset to return.\n   *                          Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively\n   * @return {string}\n   */\n  formatOffset(ts, format) {\n    return formatOffset(this.offset(ts), format);\n  }\n\n  /**\n   * Return the offset in minutes for this zone at the specified timestamp.\n   * @override\n   * @param {number} ts - Epoch milliseconds for which to compute the offset\n   * @return {number}\n   */\n  offset(ts) {\n    if (!this.valid) return NaN;\n    const date = new Date(ts);\n    if (isNaN(date)) return NaN;\n    const dtf = makeDTF(this.name);\n    let [year, month, day, adOrBc, hour, minute, second] = dtf.formatToParts ? partsOffset(dtf, date) : hackyOffset(dtf, date);\n    if (adOrBc === \"BC\") {\n      year = -Math.abs(year) + 1;\n    }\n\n    // because we're using hour12 and https://bugs.chromium.org/p/chromium/issues/detail?id=1025564&can=2&q=%2224%3A00%22%20datetimeformat\n    const adjustedHour = hour === 24 ? 0 : hour;\n    const asUTC = objToLocalTS({\n      year,\n      month,\n      day,\n      hour: adjustedHour,\n      minute,\n      second,\n      millisecond: 0\n    });\n    let asTS = +date;\n    const over = asTS % 1000;\n    asTS -= over >= 0 ? over : 1000 + over;\n    return (asUTC - asTS) / (60 * 1000);\n  }\n\n  /**\n   * Return whether this Zone is equal to another zone\n   * @override\n   * @param {Zone} otherZone - the zone to compare\n   * @return {boolean}\n   */\n  equals(otherZone) {\n    return otherZone.type === \"iana\" && otherZone.name === this.name;\n  }\n\n  /**\n   * Return whether this Zone is valid.\n   * @override\n   * @type {boolean}\n   */\n  get isValid() {\n    return this.valid;\n  }\n}\n\n// todo - remap caching\n\nlet intlLFCache = {};\nfunction getCachedLF(locString, opts = {}) {\n  const key = JSON.stringify([locString, opts]);\n  let dtf = intlLFCache[key];\n  if (!dtf) {\n    dtf = new Intl.ListFormat(locString, opts);\n    intlLFCache[key] = dtf;\n  }\n  return dtf;\n}\nconst intlDTCache = new Map();\nfunction getCachedDTF(locString, opts = {}) {\n  const key = JSON.stringify([locString, opts]);\n  let dtf = intlDTCache.get(key);\n  if (dtf === undefined) {\n    dtf = new Intl.DateTimeFormat(locString, opts);\n    intlDTCache.set(key, dtf);\n  }\n  return dtf;\n}\nconst intlNumCache = new Map();\nfunction getCachedINF(locString, opts = {}) {\n  const key = JSON.stringify([locString, opts]);\n  let inf = intlNumCache.get(key);\n  if (inf === undefined) {\n    inf = new Intl.NumberFormat(locString, opts);\n    intlNumCache.set(key, inf);\n  }\n  return inf;\n}\nconst intlRelCache = new Map();\nfunction getCachedRTF(locString, opts = {}) {\n  const {\n    base,\n    ...cacheKeyOpts\n  } = opts; // exclude `base` from the options\n  const key = JSON.stringify([locString, cacheKeyOpts]);\n  let inf = intlRelCache.get(key);\n  if (inf === undefined) {\n    inf = new Intl.RelativeTimeFormat(locString, opts);\n    intlRelCache.set(key, inf);\n  }\n  return inf;\n}\nlet sysLocaleCache = null;\nfunction systemLocale() {\n  if (sysLocaleCache) {\n    return sysLocaleCache;\n  } else {\n    sysLocaleCache = new Intl.DateTimeFormat().resolvedOptions().locale;\n    return sysLocaleCache;\n  }\n}\nconst intlResolvedOptionsCache = new Map();\nfunction getCachedIntResolvedOptions(locString) {\n  let opts = intlResolvedOptionsCache.get(locString);\n  if (opts === undefined) {\n    opts = new Intl.DateTimeFormat(locString).resolvedOptions();\n    intlResolvedOptionsCache.set(locString, opts);\n  }\n  return opts;\n}\nconst weekInfoCache = new Map();\nfunction getCachedWeekInfo(locString) {\n  let data = weekInfoCache.get(locString);\n  if (!data) {\n    const locale = new Intl.Locale(locString);\n    // browsers currently implement this as a property, but spec says it should be a getter function\n    data = \"getWeekInfo\" in locale ? locale.getWeekInfo() : locale.weekInfo;\n    // minimalDays was removed from WeekInfo: https://github.com/tc39/proposal-intl-locale-info/issues/86\n    if (!(\"minimalDays\" in data)) {\n      data = {\n        ...fallbackWeekSettings,\n        ...data\n      };\n    }\n    weekInfoCache.set(locString, data);\n  }\n  return data;\n}\nfunction parseLocaleString(localeStr) {\n  // I really want to avoid writing a BCP 47 parser\n  // see, e.g. https://github.com/wooorm/bcp-47\n  // Instead, we'll do this:\n\n  // a) if the string has no -u extensions, just leave it alone\n  // b) if it does, use Intl to resolve everything\n  // c) if Intl fails, try again without the -u\n\n  // private subtags and unicode subtags have ordering requirements,\n  // and we're not properly parsing this, so just strip out the\n  // private ones if they exist.\n  const xIndex = localeStr.indexOf(\"-x-\");\n  if (xIndex !== -1) {\n    localeStr = localeStr.substring(0, xIndex);\n  }\n  const uIndex = localeStr.indexOf(\"-u-\");\n  if (uIndex === -1) {\n    return [localeStr];\n  } else {\n    let options;\n    let selectedStr;\n    try {\n      options = getCachedDTF(localeStr).resolvedOptions();\n      selectedStr = localeStr;\n    } catch (e) {\n      const smaller = localeStr.substring(0, uIndex);\n      options = getCachedDTF(smaller).resolvedOptions();\n      selectedStr = smaller;\n    }\n    const {\n      numberingSystem,\n      calendar\n    } = options;\n    return [selectedStr, numberingSystem, calendar];\n  }\n}\nfunction intlConfigString(localeStr, numberingSystem, outputCalendar) {\n  if (outputCalendar || numberingSystem) {\n    if (!localeStr.includes(\"-u-\")) {\n      localeStr += \"-u\";\n    }\n    if (outputCalendar) {\n      localeStr += `-ca-${outputCalendar}`;\n    }\n    if (numberingSystem) {\n      localeStr += `-nu-${numberingSystem}`;\n    }\n    return localeStr;\n  } else {\n    return localeStr;\n  }\n}\nfunction mapMonths(f) {\n  const ms = [];\n  for (let i = 1; i <= 12; i++) {\n    const dt = DateTime.utc(2009, i, 1);\n    ms.push(f(dt));\n  }\n  return ms;\n}\nfunction mapWeekdays(f) {\n  const ms = [];\n  for (let i = 1; i <= 7; i++) {\n    const dt = DateTime.utc(2016, 11, 13 + i);\n    ms.push(f(dt));\n  }\n  return ms;\n}\nfunction listStuff(loc, length, englishFn, intlFn) {\n  const mode = loc.listingMode();\n  if (mode === \"error\") {\n    return null;\n  } else if (mode === \"en\") {\n    return englishFn(length);\n  } else {\n    return intlFn(length);\n  }\n}\nfunction supportsFastNumbers(loc) {\n  if (loc.numberingSystem && loc.numberingSystem !== \"latn\") {\n    return false;\n  } else {\n    return loc.numberingSystem === \"latn\" || !loc.locale || loc.locale.startsWith(\"en\") || getCachedIntResolvedOptions(loc.locale).numberingSystem === \"latn\";\n  }\n}\n\n/**\n * @private\n */\n\nclass PolyNumberFormatter {\n  constructor(intl, forceSimple, opts) {\n    this.padTo = opts.padTo || 0;\n    this.floor = opts.floor || false;\n    const {\n      padTo,\n      floor,\n      ...otherOpts\n    } = opts;\n    if (!forceSimple || Object.keys(otherOpts).length > 0) {\n      const intlOpts = {\n        useGrouping: false,\n        ...opts\n      };\n      if (opts.padTo > 0) intlOpts.minimumIntegerDigits = opts.padTo;\n      this.inf = getCachedINF(intl, intlOpts);\n    }\n  }\n  format(i) {\n    if (this.inf) {\n      const fixed = this.floor ? Math.floor(i) : i;\n      return this.inf.format(fixed);\n    } else {\n      // to match the browser's numberformatter defaults\n      const fixed = this.floor ? Math.floor(i) : roundTo(i, 3);\n      return padStart(fixed, this.padTo);\n    }\n  }\n}\n\n/**\n * @private\n */\n\nclass PolyDateFormatter {\n  constructor(dt, intl, opts) {\n    this.opts = opts;\n    this.originalZone = undefined;\n    let z = undefined;\n    if (this.opts.timeZone) {\n      // Don't apply any workarounds if a timeZone is explicitly provided in opts\n      this.dt = dt;\n    } else if (dt.zone.type === \"fixed\") {\n      // UTC-8 or Etc/UTC-8 are not part of tzdata, only Etc/GMT+8 and the like.\n      // That is why fixed-offset TZ is set to that unless it is:\n      // 1. Representing offset 0 when UTC is used to maintain previous behavior and does not become GMT.\n      // 2. Unsupported by the browser:\n      //    - some do not support Etc/\n      //    - < Etc/GMT-14, > Etc/GMT+12, and 30-minute or 45-minute offsets are not part of tzdata\n      const gmtOffset = -1 * (dt.offset / 60);\n      const offsetZ = gmtOffset >= 0 ? `Etc/GMT+${gmtOffset}` : `Etc/GMT${gmtOffset}`;\n      if (dt.offset !== 0 && IANAZone.create(offsetZ).valid) {\n        z = offsetZ;\n        this.dt = dt;\n      } else {\n        // Not all fixed-offset zones like Etc/+4:30 are present in tzdata so\n        // we manually apply the offset and substitute the zone as needed.\n        z = \"UTC\";\n        this.dt = dt.offset === 0 ? dt : dt.setZone(\"UTC\").plus({\n          minutes: dt.offset\n        });\n        this.originalZone = dt.zone;\n      }\n    } else if (dt.zone.type === \"system\") {\n      this.dt = dt;\n    } else if (dt.zone.type === \"iana\") {\n      this.dt = dt;\n      z = dt.zone.name;\n    } else {\n      // Custom zones can have any offset / offsetName so we just manually\n      // apply the offset and substitute the zone as needed.\n      z = \"UTC\";\n      this.dt = dt.setZone(\"UTC\").plus({\n        minutes: dt.offset\n      });\n      this.originalZone = dt.zone;\n    }\n    const intlOpts = {\n      ...this.opts\n    };\n    intlOpts.timeZone = intlOpts.timeZone || z;\n    this.dtf = getCachedDTF(intl, intlOpts);\n  }\n  format() {\n    if (this.originalZone) {\n      // If we have to substitute in the actual zone name, we have to use\n      // formatToParts so that the timezone can be replaced.\n      return this.formatToParts().map(({\n        value\n      }) => value).join(\"\");\n    }\n    return this.dtf.format(this.dt.toJSDate());\n  }\n  formatToParts() {\n    const parts = this.dtf.formatToParts(this.dt.toJSDate());\n    if (this.originalZone) {\n      return parts.map(part => {\n        if (part.type === \"timeZoneName\") {\n          const offsetName = this.originalZone.offsetName(this.dt.ts, {\n            locale: this.dt.locale,\n            format: this.opts.timeZoneName\n          });\n          return {\n            ...part,\n            value: offsetName\n          };\n        } else {\n          return part;\n        }\n      });\n    }\n    return parts;\n  }\n  resolvedOptions() {\n    return this.dtf.resolvedOptions();\n  }\n}\n\n/**\n * @private\n */\nclass PolyRelFormatter {\n  constructor(intl, isEnglish, opts) {\n    this.opts = {\n      style: \"long\",\n      ...opts\n    };\n    if (!isEnglish && hasRelative()) {\n      this.rtf = getCachedRTF(intl, opts);\n    }\n  }\n  format(count, unit) {\n    if (this.rtf) {\n      return this.rtf.format(count, unit);\n    } else {\n      return formatRelativeTime(unit, count, this.opts.numeric, this.opts.style !== \"long\");\n    }\n  }\n  formatToParts(count, unit) {\n    if (this.rtf) {\n      return this.rtf.formatToParts(count, unit);\n    } else {\n      return [];\n    }\n  }\n}\nconst fallbackWeekSettings = {\n  firstDay: 1,\n  minimalDays: 4,\n  weekend: [6, 7]\n};\n\n/**\n * @private\n */\nclass Locale {\n  static fromOpts(opts) {\n    return Locale.create(opts.locale, opts.numberingSystem, opts.outputCalendar, opts.weekSettings, opts.defaultToEN);\n  }\n  static create(locale, numberingSystem, outputCalendar, weekSettings, defaultToEN = false) {\n    const specifiedLocale = locale || Settings.defaultLocale;\n    // the system locale is useful for human-readable strings but annoying for parsing/formatting known formats\n    const localeR = specifiedLocale || (defaultToEN ? \"en-US\" : systemLocale());\n    const numberingSystemR = numberingSystem || Settings.defaultNumberingSystem;\n    const outputCalendarR = outputCalendar || Settings.defaultOutputCalendar;\n    const weekSettingsR = validateWeekSettings(weekSettings) || Settings.defaultWeekSettings;\n    return new Locale(localeR, numberingSystemR, outputCalendarR, weekSettingsR, specifiedLocale);\n  }\n  static resetCache() {\n    sysLocaleCache = null;\n    intlDTCache.clear();\n    intlNumCache.clear();\n    intlRelCache.clear();\n    intlResolvedOptionsCache.clear();\n    weekInfoCache.clear();\n  }\n  static fromObject({\n    locale,\n    numberingSystem,\n    outputCalendar,\n    weekSettings\n  } = {}) {\n    return Locale.create(locale, numberingSystem, outputCalendar, weekSettings);\n  }\n  constructor(locale, numbering, outputCalendar, weekSettings, specifiedLocale) {\n    const [parsedLocale, parsedNumberingSystem, parsedOutputCalendar] = parseLocaleString(locale);\n    this.locale = parsedLocale;\n    this.numberingSystem = numbering || parsedNumberingSystem || null;\n    this.outputCalendar = outputCalendar || parsedOutputCalendar || null;\n    this.weekSettings = weekSettings;\n    this.intl = intlConfigString(this.locale, this.numberingSystem, this.outputCalendar);\n    this.weekdaysCache = {\n      format: {},\n      standalone: {}\n    };\n    this.monthsCache = {\n      format: {},\n      standalone: {}\n    };\n    this.meridiemCache = null;\n    this.eraCache = {};\n    this.specifiedLocale = specifiedLocale;\n    this.fastNumbersCached = null;\n  }\n  get fastNumbers() {\n    if (this.fastNumbersCached == null) {\n      this.fastNumbersCached = supportsFastNumbers(this);\n    }\n    return this.fastNumbersCached;\n  }\n  listingMode() {\n    const isActuallyEn = this.isEnglish();\n    const hasNoWeirdness = (this.numberingSystem === null || this.numberingSystem === \"latn\") && (this.outputCalendar === null || this.outputCalendar === \"gregory\");\n    return isActuallyEn && hasNoWeirdness ? \"en\" : \"intl\";\n  }\n  clone(alts) {\n    if (!alts || Object.getOwnPropertyNames(alts).length === 0) {\n      return this;\n    } else {\n      return Locale.create(alts.locale || this.specifiedLocale, alts.numberingSystem || this.numberingSystem, alts.outputCalendar || this.outputCalendar, validateWeekSettings(alts.weekSettings) || this.weekSettings, alts.defaultToEN || false);\n    }\n  }\n  redefaultToEN(alts = {}) {\n    return this.clone({\n      ...alts,\n      defaultToEN: true\n    });\n  }\n  redefaultToSystem(alts = {}) {\n    return this.clone({\n      ...alts,\n      defaultToEN: false\n    });\n  }\n  months(length, format = false) {\n    return listStuff(this, length, months, () => {\n      // Workaround for \"ja\" locale: formatToParts does not label all parts of the month\n      // as \"month\" and for this locale there is no difference between \"format\" and \"non-format\".\n      // As such, just use format() instead of formatToParts() and take the whole string\n      const monthSpecialCase = this.intl === \"ja\" || this.intl.startsWith(\"ja-\");\n      format &= !monthSpecialCase;\n      const intl = format ? {\n          month: length,\n          day: \"numeric\"\n        } : {\n          month: length\n        },\n        formatStr = format ? \"format\" : \"standalone\";\n      if (!this.monthsCache[formatStr][length]) {\n        const mapper = !monthSpecialCase ? dt => this.extract(dt, intl, \"month\") : dt => this.dtFormatter(dt, intl).format();\n        this.monthsCache[formatStr][length] = mapMonths(mapper);\n      }\n      return this.monthsCache[formatStr][length];\n    });\n  }\n  weekdays(length, format = false) {\n    return listStuff(this, length, weekdays, () => {\n      const intl = format ? {\n          weekday: length,\n          year: \"numeric\",\n          month: \"long\",\n          day: \"numeric\"\n        } : {\n          weekday: length\n        },\n        formatStr = format ? \"format\" : \"standalone\";\n      if (!this.weekdaysCache[formatStr][length]) {\n        this.weekdaysCache[formatStr][length] = mapWeekdays(dt => this.extract(dt, intl, \"weekday\"));\n      }\n      return this.weekdaysCache[formatStr][length];\n    });\n  }\n  meridiems() {\n    return listStuff(this, undefined, () => meridiems, () => {\n      // In theory there could be aribitrary day periods. We're gonna assume there are exactly two\n      // for AM and PM. This is probably wrong, but it's makes parsing way easier.\n      if (!this.meridiemCache) {\n        const intl = {\n          hour: \"numeric\",\n          hourCycle: \"h12\"\n        };\n        this.meridiemCache = [DateTime.utc(2016, 11, 13, 9), DateTime.utc(2016, 11, 13, 19)].map(dt => this.extract(dt, intl, \"dayperiod\"));\n      }\n      return this.meridiemCache;\n    });\n  }\n  eras(length) {\n    return listStuff(this, length, eras, () => {\n      const intl = {\n        era: length\n      };\n\n      // This is problematic. Different calendars are going to define eras totally differently. What I need is the minimum set of dates\n      // to definitely enumerate them.\n      if (!this.eraCache[length]) {\n        this.eraCache[length] = [DateTime.utc(-40, 1, 1), DateTime.utc(2017, 1, 1)].map(dt => this.extract(dt, intl, \"era\"));\n      }\n      return this.eraCache[length];\n    });\n  }\n  extract(dt, intlOpts, field) {\n    const df = this.dtFormatter(dt, intlOpts),\n      results = df.formatToParts(),\n      matching = results.find(m => m.type.toLowerCase() === field);\n    return matching ? matching.value : null;\n  }\n  numberFormatter(opts = {}) {\n    // this forcesimple option is never used (the only caller short-circuits on it, but it seems safer to leave)\n    // (in contrast, the rest of the condition is used heavily)\n    return new PolyNumberFormatter(this.intl, opts.forceSimple || this.fastNumbers, opts);\n  }\n  dtFormatter(dt, intlOpts = {}) {\n    return new PolyDateFormatter(dt, this.intl, intlOpts);\n  }\n  relFormatter(opts = {}) {\n    return new PolyRelFormatter(this.intl, this.isEnglish(), opts);\n  }\n  listFormatter(opts = {}) {\n    return getCachedLF(this.intl, opts);\n  }\n  isEnglish() {\n    return this.locale === \"en\" || this.locale.toLowerCase() === \"en-us\" || getCachedIntResolvedOptions(this.intl).locale.startsWith(\"en-us\");\n  }\n  getWeekSettings() {\n    if (this.weekSettings) {\n      return this.weekSettings;\n    } else if (!hasLocaleWeekInfo()) {\n      return fallbackWeekSettings;\n    } else {\n      return getCachedWeekInfo(this.locale);\n    }\n  }\n  getStartOfWeek() {\n    return this.getWeekSettings().firstDay;\n  }\n  getMinDaysInFirstWeek() {\n    return this.getWeekSettings().minimalDays;\n  }\n  getWeekendDays() {\n    return this.getWeekSettings().weekend;\n  }\n  equals(other) {\n    return this.locale === other.locale && this.numberingSystem === other.numberingSystem && this.outputCalendar === other.outputCalendar;\n  }\n  toString() {\n    return `Locale(${this.locale}, ${this.numberingSystem}, ${this.outputCalendar})`;\n  }\n}\n\nlet singleton = null;\n\n/**\n * A zone with a fixed offset (meaning no DST)\n * @implements {Zone}\n */\nclass FixedOffsetZone extends Zone {\n  /**\n   * Get a singleton instance of UTC\n   * @return {FixedOffsetZone}\n   */\n  static get utcInstance() {\n    if (singleton === null) {\n      singleton = new FixedOffsetZone(0);\n    }\n    return singleton;\n  }\n\n  /**\n   * Get an instance with a specified offset\n   * @param {number} offset - The offset in minutes\n   * @return {FixedOffsetZone}\n   */\n  static instance(offset) {\n    return offset === 0 ? FixedOffsetZone.utcInstance : new FixedOffsetZone(offset);\n  }\n\n  /**\n   * Get an instance of FixedOffsetZone from a UTC offset string, like \"UTC+6\"\n   * @param {string} s - The offset string to parse\n   * @example FixedOffsetZone.parseSpecifier(\"UTC+6\")\n   * @example FixedOffsetZone.parseSpecifier(\"UTC+06\")\n   * @example FixedOffsetZone.parseSpecifier(\"UTC-6:00\")\n   * @return {FixedOffsetZone}\n   */\n  static parseSpecifier(s) {\n    if (s) {\n      const r = s.match(/^utc(?:([+-]\\d{1,2})(?::(\\d{2}))?)?$/i);\n      if (r) {\n        return new FixedOffsetZone(signedOffset(r[1], r[2]));\n      }\n    }\n    return null;\n  }\n  constructor(offset) {\n    super();\n    /** @private **/\n    this.fixed = offset;\n  }\n\n  /**\n   * The type of zone. `fixed` for all instances of `FixedOffsetZone`.\n   * @override\n   * @type {string}\n   */\n  get type() {\n    return \"fixed\";\n  }\n\n  /**\n   * The name of this zone.\n   * All fixed zones' names always start with \"UTC\" (plus optional offset)\n   * @override\n   * @type {string}\n   */\n  get name() {\n    return this.fixed === 0 ? \"UTC\" : `UTC${formatOffset(this.fixed, \"narrow\")}`;\n  }\n\n  /**\n   * The IANA name of this zone, i.e. `Etc/UTC` or `Etc/GMT+/-nn`\n   *\n   * @override\n   * @type {string}\n   */\n  get ianaName() {\n    if (this.fixed === 0) {\n      return \"Etc/UTC\";\n    } else {\n      return `Etc/GMT${formatOffset(-this.fixed, \"narrow\")}`;\n    }\n  }\n\n  /**\n   * Returns the offset's common name at the specified timestamp.\n   *\n   * For fixed offset zones this equals to the zone name.\n   * @override\n   */\n  offsetName() {\n    return this.name;\n  }\n\n  /**\n   * Returns the offset's value as a string\n   * @override\n   * @param {number} ts - Epoch milliseconds for which to get the offset\n   * @param {string} format - What style of offset to return.\n   *                          Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively\n   * @return {string}\n   */\n  formatOffset(ts, format) {\n    return formatOffset(this.fixed, format);\n  }\n\n  /**\n   * Returns whether the offset is known to be fixed for the whole year:\n   * Always returns true for all fixed offset zones.\n   * @override\n   * @type {boolean}\n   */\n  get isUniversal() {\n    return true;\n  }\n\n  /**\n   * Return the offset in minutes for this zone at the specified timestamp.\n   *\n   * For fixed offset zones, this is constant and does not depend on a timestamp.\n   * @override\n   * @return {number}\n   */\n  offset() {\n    return this.fixed;\n  }\n\n  /**\n   * Return whether this Zone is equal to another zone (i.e. also fixed and same offset)\n   * @override\n   * @param {Zone} otherZone - the zone to compare\n   * @return {boolean}\n   */\n  equals(otherZone) {\n    return otherZone.type === \"fixed\" && otherZone.fixed === this.fixed;\n  }\n\n  /**\n   * Return whether this Zone is valid:\n   * All fixed offset zones are valid.\n   * @override\n   * @type {boolean}\n   */\n  get isValid() {\n    return true;\n  }\n}\n\n/**\n * A zone that failed to parse. You should never need to instantiate this.\n * @implements {Zone}\n */\nclass InvalidZone extends Zone {\n  constructor(zoneName) {\n    super();\n    /**  @private */\n    this.zoneName = zoneName;\n  }\n\n  /** @override **/\n  get type() {\n    return \"invalid\";\n  }\n\n  /** @override **/\n  get name() {\n    return this.zoneName;\n  }\n\n  /** @override **/\n  get isUniversal() {\n    return false;\n  }\n\n  /** @override **/\n  offsetName() {\n    return null;\n  }\n\n  /** @override **/\n  formatOffset() {\n    return \"\";\n  }\n\n  /** @override **/\n  offset() {\n    return NaN;\n  }\n\n  /** @override **/\n  equals() {\n    return false;\n  }\n\n  /** @override **/\n  get isValid() {\n    return false;\n  }\n}\n\n/**\n * @private\n */\nfunction normalizeZone(input, defaultZone) {\n  if (isUndefined(input) || input === null) {\n    return defaultZone;\n  } else if (input instanceof Zone) {\n    return input;\n  } else if (isString(input)) {\n    const lowered = input.toLowerCase();\n    if (lowered === \"default\") return defaultZone;else if (lowered === \"local\" || lowered === \"system\") return SystemZone.instance;else if (lowered === \"utc\" || lowered === \"gmt\") return FixedOffsetZone.utcInstance;else return FixedOffsetZone.parseSpecifier(lowered) || IANAZone.create(input);\n  } else if (isNumber(input)) {\n    return FixedOffsetZone.instance(input);\n  } else if (typeof input === \"object\" && \"offset\" in input && typeof input.offset === \"function\") {\n    // This is dumb, but the instanceof check above doesn't seem to really work\n    // so we're duck checking it\n    return input;\n  } else {\n    return new InvalidZone(input);\n  }\n}\n\nconst numberingSystems = {\n  arab: \"[\\u0660-\\u0669]\",\n  arabext: \"[\\u06F0-\\u06F9]\",\n  bali: \"[\\u1B50-\\u1B59]\",\n  beng: \"[\\u09E6-\\u09EF]\",\n  deva: \"[\\u0966-\\u096F]\",\n  fullwide: \"[\\uFF10-\\uFF19]\",\n  gujr: \"[\\u0AE6-\\u0AEF]\",\n  hanidec: \"[〇|一|二|三|四|五|六|七|八|九]\",\n  khmr: \"[\\u17E0-\\u17E9]\",\n  knda: \"[\\u0CE6-\\u0CEF]\",\n  laoo: \"[\\u0ED0-\\u0ED9]\",\n  limb: \"[\\u1946-\\u194F]\",\n  mlym: \"[\\u0D66-\\u0D6F]\",\n  mong: \"[\\u1810-\\u1819]\",\n  mymr: \"[\\u1040-\\u1049]\",\n  orya: \"[\\u0B66-\\u0B6F]\",\n  tamldec: \"[\\u0BE6-\\u0BEF]\",\n  telu: \"[\\u0C66-\\u0C6F]\",\n  thai: \"[\\u0E50-\\u0E59]\",\n  tibt: \"[\\u0F20-\\u0F29]\",\n  latn: \"\\\\d\"\n};\nconst numberingSystemsUTF16 = {\n  arab: [1632, 1641],\n  arabext: [1776, 1785],\n  bali: [6992, 7001],\n  beng: [2534, 2543],\n  deva: [2406, 2415],\n  fullwide: [65296, 65303],\n  gujr: [2790, 2799],\n  khmr: [6112, 6121],\n  knda: [3302, 3311],\n  laoo: [3792, 3801],\n  limb: [6470, 6479],\n  mlym: [3430, 3439],\n  mong: [6160, 6169],\n  mymr: [4160, 4169],\n  orya: [2918, 2927],\n  tamldec: [3046, 3055],\n  telu: [3174, 3183],\n  thai: [3664, 3673],\n  tibt: [3872, 3881]\n};\nconst hanidecChars = numberingSystems.hanidec.replace(/[\\[|\\]]/g, \"\").split(\"\");\nfunction parseDigits(str) {\n  let value = parseInt(str, 10);\n  if (isNaN(value)) {\n    value = \"\";\n    for (let i = 0; i < str.length; i++) {\n      const code = str.charCodeAt(i);\n      if (str[i].search(numberingSystems.hanidec) !== -1) {\n        value += hanidecChars.indexOf(str[i]);\n      } else {\n        for (const key in numberingSystemsUTF16) {\n          const [min, max] = numberingSystemsUTF16[key];\n          if (code >= min && code <= max) {\n            value += code - min;\n          }\n        }\n      }\n    }\n    return parseInt(value, 10);\n  } else {\n    return value;\n  }\n}\n\n// cache of {numberingSystem: {append: regex}}\nconst digitRegexCache = new Map();\nfunction resetDigitRegexCache() {\n  digitRegexCache.clear();\n}\nfunction digitRegex({\n  numberingSystem\n}, append = \"\") {\n  const ns = numberingSystem || \"latn\";\n  let appendCache = digitRegexCache.get(ns);\n  if (appendCache === undefined) {\n    appendCache = new Map();\n    digitRegexCache.set(ns, appendCache);\n  }\n  let regex = appendCache.get(append);\n  if (regex === undefined) {\n    regex = new RegExp(`${numberingSystems[ns]}${append}`);\n    appendCache.set(append, regex);\n  }\n  return regex;\n}\n\nlet now = () => Date.now(),\n  defaultZone = \"system\",\n  defaultLocale = null,\n  defaultNumberingSystem = null,\n  defaultOutputCalendar = null,\n  twoDigitCutoffYear = 60,\n  throwOnInvalid,\n  defaultWeekSettings = null;\n\n/**\n * Settings contains static getters and setters that control Luxon's overall behavior. Luxon is a simple library with few options, but the ones it does have live here.\n */\nclass Settings {\n  /**\n   * Get the callback for returning the current timestamp.\n   * @type {function}\n   */\n  static get now() {\n    return now;\n  }\n\n  /**\n   * Set the callback for returning the current timestamp.\n   * The function should return a number, which will be interpreted as an Epoch millisecond count\n   * @type {function}\n   * @example Settings.now = () => Date.now() + 3000 // pretend it is 3 seconds in the future\n   * @example Settings.now = () => 0 // always pretend it's Jan 1, 1970 at midnight in UTC time\n   */\n  static set now(n) {\n    now = n;\n  }\n\n  /**\n   * Set the default time zone to create DateTimes in. Does not affect existing instances.\n   * Use the value \"system\" to reset this value to the system's time zone.\n   * @type {string}\n   */\n  static set defaultZone(zone) {\n    defaultZone = zone;\n  }\n\n  /**\n   * Get the default time zone object currently used to create DateTimes. Does not affect existing instances.\n   * The default value is the system's time zone (the one set on the machine that runs this code).\n   * @type {Zone}\n   */\n  static get defaultZone() {\n    return normalizeZone(defaultZone, SystemZone.instance);\n  }\n\n  /**\n   * Get the default locale to create DateTimes with. Does not affect existing instances.\n   * @type {string}\n   */\n  static get defaultLocale() {\n    return defaultLocale;\n  }\n\n  /**\n   * Set the default locale to create DateTimes with. Does not affect existing instances.\n   * @type {string}\n   */\n  static set defaultLocale(locale) {\n    defaultLocale = locale;\n  }\n\n  /**\n   * Get the default numbering system to create DateTimes with. Does not affect existing instances.\n   * @type {string}\n   */\n  static get defaultNumberingSystem() {\n    return defaultNumberingSystem;\n  }\n\n  /**\n   * Set the default numbering system to create DateTimes with. Does not affect existing instances.\n   * @type {string}\n   */\n  static set defaultNumberingSystem(numberingSystem) {\n    defaultNumberingSystem = numberingSystem;\n  }\n\n  /**\n   * Get the default output calendar to create DateTimes with. Does not affect existing instances.\n   * @type {string}\n   */\n  static get defaultOutputCalendar() {\n    return defaultOutputCalendar;\n  }\n\n  /**\n   * Set the default output calendar to create DateTimes with. Does not affect existing instances.\n   * @type {string}\n   */\n  static set defaultOutputCalendar(outputCalendar) {\n    defaultOutputCalendar = outputCalendar;\n  }\n\n  /**\n   * @typedef {Object} WeekSettings\n   * @property {number} firstDay\n   * @property {number} minimalDays\n   * @property {number[]} weekend\n   */\n\n  /**\n   * @return {WeekSettings|null}\n   */\n  static get defaultWeekSettings() {\n    return defaultWeekSettings;\n  }\n\n  /**\n   * Allows overriding the default locale week settings, i.e. the start of the week, the weekend and\n   * how many days are required in the first week of a year.\n   * Does not affect existing instances.\n   *\n   * @param {WeekSettings|null} weekSettings\n   */\n  static set defaultWeekSettings(weekSettings) {\n    defaultWeekSettings = validateWeekSettings(weekSettings);\n  }\n\n  /**\n   * Get the cutoff year for whether a 2-digit year string is interpreted in the current or previous century. Numbers higher than the cutoff will be considered to mean 19xx and numbers lower or equal to the cutoff will be considered 20xx.\n   * @type {number}\n   */\n  static get twoDigitCutoffYear() {\n    return twoDigitCutoffYear;\n  }\n\n  /**\n   * Set the cutoff year for whether a 2-digit year string is interpreted in the current or previous century. Numbers higher than the cutoff will be considered to mean 19xx and numbers lower or equal to the cutoff will be considered 20xx.\n   * @type {number}\n   * @example Settings.twoDigitCutoffYear = 0 // all 'yy' are interpreted as 20th century\n   * @example Settings.twoDigitCutoffYear = 99 // all 'yy' are interpreted as 21st century\n   * @example Settings.twoDigitCutoffYear = 50 // '49' -> 2049; '50' -> 1950\n   * @example Settings.twoDigitCutoffYear = 1950 // interpreted as 50\n   * @example Settings.twoDigitCutoffYear = 2050 // ALSO interpreted as 50\n   */\n  static set twoDigitCutoffYear(cutoffYear) {\n    twoDigitCutoffYear = cutoffYear % 100;\n  }\n\n  /**\n   * Get whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals\n   * @type {boolean}\n   */\n  static get throwOnInvalid() {\n    return throwOnInvalid;\n  }\n\n  /**\n   * Set whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals\n   * @type {boolean}\n   */\n  static set throwOnInvalid(t) {\n    throwOnInvalid = t;\n  }\n\n  /**\n   * Reset Luxon's global caches. Should only be necessary in testing scenarios.\n   * @return {void}\n   */\n  static resetCaches() {\n    Locale.resetCache();\n    IANAZone.resetCache();\n    DateTime.resetCache();\n    resetDigitRegexCache();\n  }\n}\n\nclass Invalid {\n  constructor(reason, explanation) {\n    this.reason = reason;\n    this.explanation = explanation;\n  }\n  toMessage() {\n    if (this.explanation) {\n      return `${this.reason}: ${this.explanation}`;\n    } else {\n      return this.reason;\n    }\n  }\n}\n\nconst nonLeapLadder = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334],\n  leapLadder = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335];\nfunction unitOutOfRange(unit, value) {\n  return new Invalid(\"unit out of range\", `you specified ${value} (of type ${typeof value}) as a ${unit}, which is invalid`);\n}\nfunction dayOfWeek(year, month, day) {\n  const d = new Date(Date.UTC(year, month - 1, day));\n  if (year < 100 && year >= 0) {\n    d.setUTCFullYear(d.getUTCFullYear() - 1900);\n  }\n  const js = d.getUTCDay();\n  return js === 0 ? 7 : js;\n}\nfunction computeOrdinal(year, month, day) {\n  return day + (isLeapYear(year) ? leapLadder : nonLeapLadder)[month - 1];\n}\nfunction uncomputeOrdinal(year, ordinal) {\n  const table = isLeapYear(year) ? leapLadder : nonLeapLadder,\n    month0 = table.findIndex(i => i < ordinal),\n    day = ordinal - table[month0];\n  return {\n    month: month0 + 1,\n    day\n  };\n}\nfunction isoWeekdayToLocal(isoWeekday, startOfWeek) {\n  return (isoWeekday - startOfWeek + 7) % 7 + 1;\n}\n\n/**\n * @private\n */\n\nfunction gregorianToWeek(gregObj, minDaysInFirstWeek = 4, startOfWeek = 1) {\n  const {\n      year,\n      month,\n      day\n    } = gregObj,\n    ordinal = computeOrdinal(year, month, day),\n    weekday = isoWeekdayToLocal(dayOfWeek(year, month, day), startOfWeek);\n  let weekNumber = Math.floor((ordinal - weekday + 14 - minDaysInFirstWeek) / 7),\n    weekYear;\n  if (weekNumber < 1) {\n    weekYear = year - 1;\n    weekNumber = weeksInWeekYear(weekYear, minDaysInFirstWeek, startOfWeek);\n  } else if (weekNumber > weeksInWeekYear(year, minDaysInFirstWeek, startOfWeek)) {\n    weekYear = year + 1;\n    weekNumber = 1;\n  } else {\n    weekYear = year;\n  }\n  return {\n    weekYear,\n    weekNumber,\n    weekday,\n    ...timeObject(gregObj)\n  };\n}\nfunction weekToGregorian(weekData, minDaysInFirstWeek = 4, startOfWeek = 1) {\n  const {\n      weekYear,\n      weekNumber,\n      weekday\n    } = weekData,\n    weekdayOfJan4 = isoWeekdayToLocal(dayOfWeek(weekYear, 1, minDaysInFirstWeek), startOfWeek),\n    yearInDays = daysInYear(weekYear);\n  let ordinal = weekNumber * 7 + weekday - weekdayOfJan4 - 7 + minDaysInFirstWeek,\n    year;\n  if (ordinal < 1) {\n    year = weekYear - 1;\n    ordinal += daysInYear(year);\n  } else if (ordinal > yearInDays) {\n    year = weekYear + 1;\n    ordinal -= daysInYear(weekYear);\n  } else {\n    year = weekYear;\n  }\n  const {\n    month,\n    day\n  } = uncomputeOrdinal(year, ordinal);\n  return {\n    year,\n    month,\n    day,\n    ...timeObject(weekData)\n  };\n}\nfunction gregorianToOrdinal(gregData) {\n  const {\n    year,\n    month,\n    day\n  } = gregData;\n  const ordinal = computeOrdinal(year, month, day);\n  return {\n    year,\n    ordinal,\n    ...timeObject(gregData)\n  };\n}\nfunction ordinalToGregorian(ordinalData) {\n  const {\n    year,\n    ordinal\n  } = ordinalData;\n  const {\n    month,\n    day\n  } = uncomputeOrdinal(year, ordinal);\n  return {\n    year,\n    month,\n    day,\n    ...timeObject(ordinalData)\n  };\n}\n\n/**\n * Check if local week units like localWeekday are used in obj.\n * If so, validates that they are not mixed with ISO week units and then copies them to the normal week unit properties.\n * Modifies obj in-place!\n * @param obj the object values\n */\nfunction usesLocalWeekValues(obj, loc) {\n  const hasLocaleWeekData = !isUndefined(obj.localWeekday) || !isUndefined(obj.localWeekNumber) || !isUndefined(obj.localWeekYear);\n  if (hasLocaleWeekData) {\n    const hasIsoWeekData = !isUndefined(obj.weekday) || !isUndefined(obj.weekNumber) || !isUndefined(obj.weekYear);\n    if (hasIsoWeekData) {\n      throw new ConflictingSpecificationError(\"Cannot mix locale-based week fields with ISO-based week fields\");\n    }\n    if (!isUndefined(obj.localWeekday)) obj.weekday = obj.localWeekday;\n    if (!isUndefined(obj.localWeekNumber)) obj.weekNumber = obj.localWeekNumber;\n    if (!isUndefined(obj.localWeekYear)) obj.weekYear = obj.localWeekYear;\n    delete obj.localWeekday;\n    delete obj.localWeekNumber;\n    delete obj.localWeekYear;\n    return {\n      minDaysInFirstWeek: loc.getMinDaysInFirstWeek(),\n      startOfWeek: loc.getStartOfWeek()\n    };\n  } else {\n    return {\n      minDaysInFirstWeek: 4,\n      startOfWeek: 1\n    };\n  }\n}\nfunction hasInvalidWeekData(obj, minDaysInFirstWeek = 4, startOfWeek = 1) {\n  const validYear = isInteger(obj.weekYear),\n    validWeek = integerBetween(obj.weekNumber, 1, weeksInWeekYear(obj.weekYear, minDaysInFirstWeek, startOfWeek)),\n    validWeekday = integerBetween(obj.weekday, 1, 7);\n  if (!validYear) {\n    return unitOutOfRange(\"weekYear\", obj.weekYear);\n  } else if (!validWeek) {\n    return unitOutOfRange(\"week\", obj.weekNumber);\n  } else if (!validWeekday) {\n    return unitOutOfRange(\"weekday\", obj.weekday);\n  } else return false;\n}\nfunction hasInvalidOrdinalData(obj) {\n  const validYear = isInteger(obj.year),\n    validOrdinal = integerBetween(obj.ordinal, 1, daysInYear(obj.year));\n  if (!validYear) {\n    return unitOutOfRange(\"year\", obj.year);\n  } else if (!validOrdinal) {\n    return unitOutOfRange(\"ordinal\", obj.ordinal);\n  } else return false;\n}\nfunction hasInvalidGregorianData(obj) {\n  const validYear = isInteger(obj.year),\n    validMonth = integerBetween(obj.month, 1, 12),\n    validDay = integerBetween(obj.day, 1, daysInMonth(obj.year, obj.month));\n  if (!validYear) {\n    return unitOutOfRange(\"year\", obj.year);\n  } else if (!validMonth) {\n    return unitOutOfRange(\"month\", obj.month);\n  } else if (!validDay) {\n    return unitOutOfRange(\"day\", obj.day);\n  } else return false;\n}\nfunction hasInvalidTimeData(obj) {\n  const {\n    hour,\n    minute,\n    second,\n    millisecond\n  } = obj;\n  const validHour = integerBetween(hour, 0, 23) || hour === 24 && minute === 0 && second === 0 && millisecond === 0,\n    validMinute = integerBetween(minute, 0, 59),\n    validSecond = integerBetween(second, 0, 59),\n    validMillisecond = integerBetween(millisecond, 0, 999);\n  if (!validHour) {\n    return unitOutOfRange(\"hour\", hour);\n  } else if (!validMinute) {\n    return unitOutOfRange(\"minute\", minute);\n  } else if (!validSecond) {\n    return unitOutOfRange(\"second\", second);\n  } else if (!validMillisecond) {\n    return unitOutOfRange(\"millisecond\", millisecond);\n  } else return false;\n}\n\n/*\n  This is just a junk drawer, containing anything used across multiple classes.\n  Because Luxon is small(ish), this should stay small and we won't worry about splitting\n  it up into, say, parsingUtil.js and basicUtil.js and so on. But they are divided up by feature area.\n*/\n\n/**\n * @private\n */\n\n// TYPES\n\nfunction isUndefined(o) {\n  return typeof o === \"undefined\";\n}\nfunction isNumber(o) {\n  return typeof o === \"number\";\n}\nfunction isInteger(o) {\n  return typeof o === \"number\" && o % 1 === 0;\n}\nfunction isString(o) {\n  return typeof o === \"string\";\n}\nfunction isDate(o) {\n  return Object.prototype.toString.call(o) === \"[object Date]\";\n}\n\n// CAPABILITIES\n\nfunction hasRelative() {\n  try {\n    return typeof Intl !== \"undefined\" && !!Intl.RelativeTimeFormat;\n  } catch (e) {\n    return false;\n  }\n}\nfunction hasLocaleWeekInfo() {\n  try {\n    return typeof Intl !== \"undefined\" && !!Intl.Locale && (\"weekInfo\" in Intl.Locale.prototype || \"getWeekInfo\" in Intl.Locale.prototype);\n  } catch (e) {\n    return false;\n  }\n}\n\n// OBJECTS AND ARRAYS\n\nfunction maybeArray(thing) {\n  return Array.isArray(thing) ? thing : [thing];\n}\nfunction bestBy(arr, by, compare) {\n  if (arr.length === 0) {\n    return undefined;\n  }\n  return arr.reduce((best, next) => {\n    const pair = [by(next), next];\n    if (!best) {\n      return pair;\n    } else if (compare(best[0], pair[0]) === best[0]) {\n      return best;\n    } else {\n      return pair;\n    }\n  }, null)[1];\n}\nfunction pick(obj, keys) {\n  return keys.reduce((a, k) => {\n    a[k] = obj[k];\n    return a;\n  }, {});\n}\nfunction hasOwnProperty(obj, prop) {\n  return Object.prototype.hasOwnProperty.call(obj, prop);\n}\nfunction validateWeekSettings(settings) {\n  if (settings == null) {\n    return null;\n  } else if (typeof settings !== \"object\") {\n    throw new InvalidArgumentError(\"Week settings must be an object\");\n  } else {\n    if (!integerBetween(settings.firstDay, 1, 7) || !integerBetween(settings.minimalDays, 1, 7) || !Array.isArray(settings.weekend) || settings.weekend.some(v => !integerBetween(v, 1, 7))) {\n      throw new InvalidArgumentError(\"Invalid week settings\");\n    }\n    return {\n      firstDay: settings.firstDay,\n      minimalDays: settings.minimalDays,\n      weekend: Array.from(settings.weekend)\n    };\n  }\n}\n\n// NUMBERS AND STRINGS\n\nfunction integerBetween(thing, bottom, top) {\n  return isInteger(thing) && thing >= bottom && thing <= top;\n}\n\n// x % n but takes the sign of n instead of x\nfunction floorMod(x, n) {\n  return x - n * Math.floor(x / n);\n}\nfunction padStart(input, n = 2) {\n  const isNeg = input < 0;\n  let padded;\n  if (isNeg) {\n    padded = \"-\" + (\"\" + -input).padStart(n, \"0\");\n  } else {\n    padded = (\"\" + input).padStart(n, \"0\");\n  }\n  return padded;\n}\nfunction parseInteger(string) {\n  if (isUndefined(string) || string === null || string === \"\") {\n    return undefined;\n  } else {\n    return parseInt(string, 10);\n  }\n}\nfunction parseFloating(string) {\n  if (isUndefined(string) || string === null || string === \"\") {\n    return undefined;\n  } else {\n    return parseFloat(string);\n  }\n}\nfunction parseMillis(fraction) {\n  // Return undefined (instead of 0) in these cases, where fraction is not set\n  if (isUndefined(fraction) || fraction === null || fraction === \"\") {\n    return undefined;\n  } else {\n    const f = parseFloat(\"0.\" + fraction) * 1000;\n    return Math.floor(f);\n  }\n}\nfunction roundTo(number, digits, rounding = \"round\") {\n  const factor = 10 ** digits;\n  switch (rounding) {\n    case \"expand\":\n      return number > 0 ? Math.ceil(number * factor) / factor : Math.floor(number * factor) / factor;\n    case \"trunc\":\n      return Math.trunc(number * factor) / factor;\n    case \"round\":\n      return Math.round(number * factor) / factor;\n    case \"floor\":\n      return Math.floor(number * factor) / factor;\n    case \"ceil\":\n      return Math.ceil(number * factor) / factor;\n    default:\n      throw new RangeError(`Value rounding ${rounding} is out of range`);\n  }\n}\n\n// DATE BASICS\n\nfunction isLeapYear(year) {\n  return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n}\nfunction daysInYear(year) {\n  return isLeapYear(year) ? 366 : 365;\n}\nfunction daysInMonth(year, month) {\n  const modMonth = floorMod(month - 1, 12) + 1,\n    modYear = year + (month - modMonth) / 12;\n  if (modMonth === 2) {\n    return isLeapYear(modYear) ? 29 : 28;\n  } else {\n    return [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][modMonth - 1];\n  }\n}\n\n// convert a calendar object to a local timestamp (epoch, but with the offset baked in)\nfunction objToLocalTS(obj) {\n  let d = Date.UTC(obj.year, obj.month - 1, obj.day, obj.hour, obj.minute, obj.second, obj.millisecond);\n\n  // for legacy reasons, years between 0 and 99 are interpreted as 19XX; revert that\n  if (obj.year < 100 && obj.year >= 0) {\n    d = new Date(d);\n    // set the month and day again, this is necessary because year 2000 is a leap year, but year 100 is not\n    // so if obj.year is in 99, but obj.day makes it roll over into year 100,\n    // the calculations done by Date.UTC are using year 2000 - which is incorrect\n    d.setUTCFullYear(obj.year, obj.month - 1, obj.day);\n  }\n  return +d;\n}\n\n// adapted from moment.js: https://github.com/moment/moment/blob/000ac1800e620f770f4eb31b5ae908f6167b0ab2/src/lib/units/week-calendar-utils.js\nfunction firstWeekOffset(year, minDaysInFirstWeek, startOfWeek) {\n  const fwdlw = isoWeekdayToLocal(dayOfWeek(year, 1, minDaysInFirstWeek), startOfWeek);\n  return -fwdlw + minDaysInFirstWeek - 1;\n}\nfunction weeksInWeekYear(weekYear, minDaysInFirstWeek = 4, startOfWeek = 1) {\n  const weekOffset = firstWeekOffset(weekYear, minDaysInFirstWeek, startOfWeek);\n  const weekOffsetNext = firstWeekOffset(weekYear + 1, minDaysInFirstWeek, startOfWeek);\n  return (daysInYear(weekYear) - weekOffset + weekOffsetNext) / 7;\n}\nfunction untruncateYear(year) {\n  if (year > 99) {\n    return year;\n  } else return year > Settings.twoDigitCutoffYear ? 1900 + year : 2000 + year;\n}\n\n// PARSING\n\nfunction parseZoneInfo(ts, offsetFormat, locale, timeZone = null) {\n  const date = new Date(ts),\n    intlOpts = {\n      hourCycle: \"h23\",\n      year: \"numeric\",\n      month: \"2-digit\",\n      day: \"2-digit\",\n      hour: \"2-digit\",\n      minute: \"2-digit\"\n    };\n  if (timeZone) {\n    intlOpts.timeZone = timeZone;\n  }\n  const modified = {\n    timeZoneName: offsetFormat,\n    ...intlOpts\n  };\n  const parsed = new Intl.DateTimeFormat(locale, modified).formatToParts(date).find(m => m.type.toLowerCase() === \"timezonename\");\n  return parsed ? parsed.value : null;\n}\n\n// signedOffset('-5', '30') -> -330\nfunction signedOffset(offHourStr, offMinuteStr) {\n  let offHour = parseInt(offHourStr, 10);\n\n  // don't || this because we want to preserve -0\n  if (Number.isNaN(offHour)) {\n    offHour = 0;\n  }\n  const offMin = parseInt(offMinuteStr, 10) || 0,\n    offMinSigned = offHour < 0 || Object.is(offHour, -0) ? -offMin : offMin;\n  return offHour * 60 + offMinSigned;\n}\n\n// COERCION\n\nfunction asNumber(value) {\n  const numericValue = Number(value);\n  if (typeof value === \"boolean\" || value === \"\" || !Number.isFinite(numericValue)) throw new InvalidArgumentError(`Invalid unit value ${value}`);\n  return numericValue;\n}\nfunction normalizeObject(obj, normalizer) {\n  const normalized = {};\n  for (const u in obj) {\n    if (hasOwnProperty(obj, u)) {\n      const v = obj[u];\n      if (v === undefined || v === null) continue;\n      normalized[normalizer(u)] = asNumber(v);\n    }\n  }\n  return normalized;\n}\n\n/**\n * Returns the offset's value as a string\n * @param {number} ts - Epoch milliseconds for which to get the offset\n * @param {string} format - What style of offset to return.\n *                          Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively\n * @return {string}\n */\nfunction formatOffset(offset, format) {\n  const hours = Math.trunc(Math.abs(offset / 60)),\n    minutes = Math.trunc(Math.abs(offset % 60)),\n    sign = offset >= 0 ? \"+\" : \"-\";\n  switch (format) {\n    case \"short\":\n      return `${sign}${padStart(hours, 2)}:${padStart(minutes, 2)}`;\n    case \"narrow\":\n      return `${sign}${hours}${minutes > 0 ? `:${minutes}` : \"\"}`;\n    case \"techie\":\n      return `${sign}${padStart(hours, 2)}${padStart(minutes, 2)}`;\n    default:\n      throw new RangeError(`Value format ${format} is out of range for property format`);\n  }\n}\nfunction timeObject(obj) {\n  return pick(obj, [\"hour\", \"minute\", \"second\", \"millisecond\"]);\n}\n\n/**\n * @private\n */\n\nconst monthsLong = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"];\nconst monthsShort = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"];\nconst monthsNarrow = [\"J\", \"F\", \"M\", \"A\", \"M\", \"J\", \"J\", \"A\", \"S\", \"O\", \"N\", \"D\"];\nfunction months(length) {\n  switch (length) {\n    case \"narrow\":\n      return [...monthsNarrow];\n    case \"short\":\n      return [...monthsShort];\n    case \"long\":\n      return [...monthsLong];\n    case \"numeric\":\n      return [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"11\", \"12\"];\n    case \"2-digit\":\n      return [\"01\", \"02\", \"03\", \"04\", \"05\", \"06\", \"07\", \"08\", \"09\", \"10\", \"11\", \"12\"];\n    default:\n      return null;\n  }\n}\nconst weekdaysLong = [\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\"];\nconst weekdaysShort = [\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\"];\nconst weekdaysNarrow = [\"M\", \"T\", \"W\", \"T\", \"F\", \"S\", \"S\"];\nfunction weekdays(length) {\n  switch (length) {\n    case \"narrow\":\n      return [...weekdaysNarrow];\n    case \"short\":\n      return [...weekdaysShort];\n    case \"long\":\n      return [...weekdaysLong];\n    case \"numeric\":\n      return [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\"];\n    default:\n      return null;\n  }\n}\nconst meridiems = [\"AM\", \"PM\"];\nconst erasLong = [\"Before Christ\", \"Anno Domini\"];\nconst erasShort = [\"BC\", \"AD\"];\nconst erasNarrow = [\"B\", \"A\"];\nfunction eras(length) {\n  switch (length) {\n    case \"narrow\":\n      return [...erasNarrow];\n    case \"short\":\n      return [...erasShort];\n    case \"long\":\n      return [...erasLong];\n    default:\n      return null;\n  }\n}\nfunction meridiemForDateTime(dt) {\n  return meridiems[dt.hour < 12 ? 0 : 1];\n}\nfunction weekdayForDateTime(dt, length) {\n  return weekdays(length)[dt.weekday - 1];\n}\nfunction monthForDateTime(dt, length) {\n  return months(length)[dt.month - 1];\n}\nfunction eraForDateTime(dt, length) {\n  return eras(length)[dt.year < 0 ? 0 : 1];\n}\nfunction formatRelativeTime(unit, count, numeric = \"always\", narrow = false) {\n  const units = {\n    years: [\"year\", \"yr.\"],\n    quarters: [\"quarter\", \"qtr.\"],\n    months: [\"month\", \"mo.\"],\n    weeks: [\"week\", \"wk.\"],\n    days: [\"day\", \"day\", \"days\"],\n    hours: [\"hour\", \"hr.\"],\n    minutes: [\"minute\", \"min.\"],\n    seconds: [\"second\", \"sec.\"]\n  };\n  const lastable = [\"hours\", \"minutes\", \"seconds\"].indexOf(unit) === -1;\n  if (numeric === \"auto\" && lastable) {\n    const isDay = unit === \"days\";\n    switch (count) {\n      case 1:\n        return isDay ? \"tomorrow\" : `next ${units[unit][0]}`;\n      case -1:\n        return isDay ? \"yesterday\" : `last ${units[unit][0]}`;\n      case 0:\n        return isDay ? \"today\" : `this ${units[unit][0]}`;\n    }\n  }\n\n  const isInPast = Object.is(count, -0) || count < 0,\n    fmtValue = Math.abs(count),\n    singular = fmtValue === 1,\n    lilUnits = units[unit],\n    fmtUnit = narrow ? singular ? lilUnits[1] : lilUnits[2] || lilUnits[1] : singular ? units[unit][0] : unit;\n  return isInPast ? `${fmtValue} ${fmtUnit} ago` : `in ${fmtValue} ${fmtUnit}`;\n}\n\nfunction stringifyTokens(splits, tokenToString) {\n  let s = \"\";\n  for (const token of splits) {\n    if (token.literal) {\n      s += token.val;\n    } else {\n      s += tokenToString(token.val);\n    }\n  }\n  return s;\n}\nconst macroTokenToFormatOpts = {\n  D: DATE_SHORT,\n  DD: DATE_MED,\n  DDD: DATE_FULL,\n  DDDD: DATE_HUGE,\n  t: TIME_SIMPLE,\n  tt: TIME_WITH_SECONDS,\n  ttt: TIME_WITH_SHORT_OFFSET,\n  tttt: TIME_WITH_LONG_OFFSET,\n  T: TIME_24_SIMPLE,\n  TT: TIME_24_WITH_SECONDS,\n  TTT: TIME_24_WITH_SHORT_OFFSET,\n  TTTT: TIME_24_WITH_LONG_OFFSET,\n  f: DATETIME_SHORT,\n  ff: DATETIME_MED,\n  fff: DATETIME_FULL,\n  ffff: DATETIME_HUGE,\n  F: DATETIME_SHORT_WITH_SECONDS,\n  FF: DATETIME_MED_WITH_SECONDS,\n  FFF: DATETIME_FULL_WITH_SECONDS,\n  FFFF: DATETIME_HUGE_WITH_SECONDS\n};\n\n/**\n * @private\n */\n\nclass Formatter {\n  static create(locale, opts = {}) {\n    return new Formatter(locale, opts);\n  }\n  static parseFormat(fmt) {\n    // white-space is always considered a literal in user-provided formats\n    // the \" \" token has a special meaning (see unitForToken)\n\n    let current = null,\n      currentFull = \"\",\n      bracketed = false;\n    const splits = [];\n    for (let i = 0; i < fmt.length; i++) {\n      const c = fmt.charAt(i);\n      if (c === \"'\") {\n        // turn '' into a literal signal quote instead of just skipping the empty literal\n        if (currentFull.length > 0 || bracketed) {\n          splits.push({\n            literal: bracketed || /^\\s+$/.test(currentFull),\n            val: currentFull === \"\" ? \"'\" : currentFull\n          });\n        }\n        current = null;\n        currentFull = \"\";\n        bracketed = !bracketed;\n      } else if (bracketed) {\n        currentFull += c;\n      } else if (c === current) {\n        currentFull += c;\n      } else {\n        if (currentFull.length > 0) {\n          splits.push({\n            literal: /^\\s+$/.test(currentFull),\n            val: currentFull\n          });\n        }\n        currentFull = c;\n        current = c;\n      }\n    }\n    if (currentFull.length > 0) {\n      splits.push({\n        literal: bracketed || /^\\s+$/.test(currentFull),\n        val: currentFull\n      });\n    }\n    return splits;\n  }\n  static macroTokenToFormatOpts(token) {\n    return macroTokenToFormatOpts[token];\n  }\n  constructor(locale, formatOpts) {\n    this.opts = formatOpts;\n    this.loc = locale;\n    this.systemLoc = null;\n  }\n  formatWithSystemDefault(dt, opts) {\n    if (this.systemLoc === null) {\n      this.systemLoc = this.loc.redefaultToSystem();\n    }\n    const df = this.systemLoc.dtFormatter(dt, {\n      ...this.opts,\n      ...opts\n    });\n    return df.format();\n  }\n  dtFormatter(dt, opts = {}) {\n    return this.loc.dtFormatter(dt, {\n      ...this.opts,\n      ...opts\n    });\n  }\n  formatDateTime(dt, opts) {\n    return this.dtFormatter(dt, opts).format();\n  }\n  formatDateTimeParts(dt, opts) {\n    return this.dtFormatter(dt, opts).formatToParts();\n  }\n  formatInterval(interval, opts) {\n    const df = this.dtFormatter(interval.start, opts);\n    return df.dtf.formatRange(interval.start.toJSDate(), interval.end.toJSDate());\n  }\n  resolvedOptions(dt, opts) {\n    return this.dtFormatter(dt, opts).resolvedOptions();\n  }\n  num(n, p = 0, signDisplay = undefined) {\n    // we get some perf out of doing this here, annoyingly\n    if (this.opts.forceSimple) {\n      return padStart(n, p);\n    }\n    const opts = {\n      ...this.opts\n    };\n    if (p > 0) {\n      opts.padTo = p;\n    }\n    if (signDisplay) {\n      opts.signDisplay = signDisplay;\n    }\n    return this.loc.numberFormatter(opts).format(n);\n  }\n  formatDateTimeFromString(dt, fmt) {\n    const knownEnglish = this.loc.listingMode() === \"en\",\n      useDateTimeFormatter = this.loc.outputCalendar && this.loc.outputCalendar !== \"gregory\",\n      string = (opts, extract) => this.loc.extract(dt, opts, extract),\n      formatOffset = opts => {\n        if (dt.isOffsetFixed && dt.offset === 0 && opts.allowZ) {\n          return \"Z\";\n        }\n        return dt.isValid ? dt.zone.formatOffset(dt.ts, opts.format) : \"\";\n      },\n      meridiem = () => knownEnglish ? meridiemForDateTime(dt) : string({\n        hour: \"numeric\",\n        hourCycle: \"h12\"\n      }, \"dayperiod\"),\n      month = (length, standalone) => knownEnglish ? monthForDateTime(dt, length) : string(standalone ? {\n        month: length\n      } : {\n        month: length,\n        day: \"numeric\"\n      }, \"month\"),\n      weekday = (length, standalone) => knownEnglish ? weekdayForDateTime(dt, length) : string(standalone ? {\n        weekday: length\n      } : {\n        weekday: length,\n        month: \"long\",\n        day: \"numeric\"\n      }, \"weekday\"),\n      maybeMacro = token => {\n        const formatOpts = Formatter.macroTokenToFormatOpts(token);\n        if (formatOpts) {\n          return this.formatWithSystemDefault(dt, formatOpts);\n        } else {\n          return token;\n        }\n      },\n      era = length => knownEnglish ? eraForDateTime(dt, length) : string({\n        era: length\n      }, \"era\"),\n      tokenToString = token => {\n        // Where possible: https://cldr.unicode.org/translation/date-time/date-time-symbols\n        switch (token) {\n          // ms\n          case \"S\":\n            return this.num(dt.millisecond);\n          case \"u\":\n          // falls through\n          case \"SSS\":\n            return this.num(dt.millisecond, 3);\n          // seconds\n          case \"s\":\n            return this.num(dt.second);\n          case \"ss\":\n            return this.num(dt.second, 2);\n          // fractional seconds\n          case \"uu\":\n            return this.num(Math.floor(dt.millisecond / 10), 2);\n          case \"uuu\":\n            return this.num(Math.floor(dt.millisecond / 100));\n          // minutes\n          case \"m\":\n            return this.num(dt.minute);\n          case \"mm\":\n            return this.num(dt.minute, 2);\n          // hours\n          case \"h\":\n            return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12);\n          case \"hh\":\n            return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12, 2);\n          case \"H\":\n            return this.num(dt.hour);\n          case \"HH\":\n            return this.num(dt.hour, 2);\n          // offset\n          case \"Z\":\n            // like +6\n            return formatOffset({\n              format: \"narrow\",\n              allowZ: this.opts.allowZ\n            });\n          case \"ZZ\":\n            // like +06:00\n            return formatOffset({\n              format: \"short\",\n              allowZ: this.opts.allowZ\n            });\n          case \"ZZZ\":\n            // like +0600\n            return formatOffset({\n              format: \"techie\",\n              allowZ: this.opts.allowZ\n            });\n          case \"ZZZZ\":\n            // like EST\n            return dt.zone.offsetName(dt.ts, {\n              format: \"short\",\n              locale: this.loc.locale\n            });\n          case \"ZZZZZ\":\n            // like Eastern Standard Time\n            return dt.zone.offsetName(dt.ts, {\n              format: \"long\",\n              locale: this.loc.locale\n            });\n          // zone\n          case \"z\":\n            // like America/New_York\n            return dt.zoneName;\n          // meridiems\n          case \"a\":\n            return meridiem();\n          // dates\n          case \"d\":\n            return useDateTimeFormatter ? string({\n              day: \"numeric\"\n            }, \"day\") : this.num(dt.day);\n          case \"dd\":\n            return useDateTimeFormatter ? string({\n              day: \"2-digit\"\n            }, \"day\") : this.num(dt.day, 2);\n          // weekdays - standalone\n          case \"c\":\n            // like 1\n            return this.num(dt.weekday);\n          case \"ccc\":\n            // like 'Tues'\n            return weekday(\"short\", true);\n          case \"cccc\":\n            // like 'Tuesday'\n            return weekday(\"long\", true);\n          case \"ccccc\":\n            // like 'T'\n            return weekday(\"narrow\", true);\n          // weekdays - format\n          case \"E\":\n            // like 1\n            return this.num(dt.weekday);\n          case \"EEE\":\n            // like 'Tues'\n            return weekday(\"short\", false);\n          case \"EEEE\":\n            // like 'Tuesday'\n            return weekday(\"long\", false);\n          case \"EEEEE\":\n            // like 'T'\n            return weekday(\"narrow\", false);\n          // months - standalone\n          case \"L\":\n            // like 1\n            return useDateTimeFormatter ? string({\n              month: \"numeric\",\n              day: \"numeric\"\n            }, \"month\") : this.num(dt.month);\n          case \"LL\":\n            // like 01, doesn't seem to work\n            return useDateTimeFormatter ? string({\n              month: \"2-digit\",\n              day: \"numeric\"\n            }, \"month\") : this.num(dt.month, 2);\n          case \"LLL\":\n            // like Jan\n            return month(\"short\", true);\n          case \"LLLL\":\n            // like January\n            return month(\"long\", true);\n          case \"LLLLL\":\n            // like J\n            return month(\"narrow\", true);\n          // months - format\n          case \"M\":\n            // like 1\n            return useDateTimeFormatter ? string({\n              month: \"numeric\"\n            }, \"month\") : this.num(dt.month);\n          case \"MM\":\n            // like 01\n            return useDateTimeFormatter ? string({\n              month: \"2-digit\"\n            }, \"month\") : this.num(dt.month, 2);\n          case \"MMM\":\n            // like Jan\n            return month(\"short\", false);\n          case \"MMMM\":\n            // like January\n            return month(\"long\", false);\n          case \"MMMMM\":\n            // like J\n            return month(\"narrow\", false);\n          // years\n          case \"y\":\n            // like 2014\n            return useDateTimeFormatter ? string({\n              year: \"numeric\"\n            }, \"year\") : this.num(dt.year);\n          case \"yy\":\n            // like 14\n            return useDateTimeFormatter ? string({\n              year: \"2-digit\"\n            }, \"year\") : this.num(dt.year.toString().slice(-2), 2);\n          case \"yyyy\":\n            // like 0012\n            return useDateTimeFormatter ? string({\n              year: \"numeric\"\n            }, \"year\") : this.num(dt.year, 4);\n          case \"yyyyyy\":\n            // like 000012\n            return useDateTimeFormatter ? string({\n              year: \"numeric\"\n            }, \"year\") : this.num(dt.year, 6);\n          // eras\n          case \"G\":\n            // like AD\n            return era(\"short\");\n          case \"GG\":\n            // like Anno Domini\n            return era(\"long\");\n          case \"GGGGG\":\n            return era(\"narrow\");\n          case \"kk\":\n            return this.num(dt.weekYear.toString().slice(-2), 2);\n          case \"kkkk\":\n            return this.num(dt.weekYear, 4);\n          case \"W\":\n            return this.num(dt.weekNumber);\n          case \"WW\":\n            return this.num(dt.weekNumber, 2);\n          case \"n\":\n            return this.num(dt.localWeekNumber);\n          case \"nn\":\n            return this.num(dt.localWeekNumber, 2);\n          case \"ii\":\n            return this.num(dt.localWeekYear.toString().slice(-2), 2);\n          case \"iiii\":\n            return this.num(dt.localWeekYear, 4);\n          case \"o\":\n            return this.num(dt.ordinal);\n          case \"ooo\":\n            return this.num(dt.ordinal, 3);\n          case \"q\":\n            // like 1\n            return this.num(dt.quarter);\n          case \"qq\":\n            // like 01\n            return this.num(dt.quarter, 2);\n          case \"X\":\n            return this.num(Math.floor(dt.ts / 1000));\n          case \"x\":\n            return this.num(dt.ts);\n          default:\n            return maybeMacro(token);\n        }\n      };\n    return stringifyTokens(Formatter.parseFormat(fmt), tokenToString);\n  }\n  formatDurationFromString(dur, fmt) {\n    const invertLargest = this.opts.signMode === \"negativeLargestOnly\" ? -1 : 1;\n    const tokenToField = token => {\n        switch (token[0]) {\n          case \"S\":\n            return \"milliseconds\";\n          case \"s\":\n            return \"seconds\";\n          case \"m\":\n            return \"minutes\";\n          case \"h\":\n            return \"hours\";\n          case \"d\":\n            return \"days\";\n          case \"w\":\n            return \"weeks\";\n          case \"M\":\n            return \"months\";\n          case \"y\":\n            return \"years\";\n          default:\n            return null;\n        }\n      },\n      tokenToString = (lildur, info) => token => {\n        const mapped = tokenToField(token);\n        if (mapped) {\n          const inversionFactor = info.isNegativeDuration && mapped !== info.largestUnit ? invertLargest : 1;\n          let signDisplay;\n          if (this.opts.signMode === \"negativeLargestOnly\" && mapped !== info.largestUnit) {\n            signDisplay = \"never\";\n          } else if (this.opts.signMode === \"all\") {\n            signDisplay = \"always\";\n          } else {\n            // \"auto\" and \"negative\" are the same, but \"auto\" has better support\n            signDisplay = \"auto\";\n          }\n          return this.num(lildur.get(mapped) * inversionFactor, token.length, signDisplay);\n        } else {\n          return token;\n        }\n      },\n      tokens = Formatter.parseFormat(fmt),\n      realTokens = tokens.reduce((found, {\n        literal,\n        val\n      }) => literal ? found : found.concat(val), []),\n      collapsed = dur.shiftTo(...realTokens.map(tokenToField).filter(t => t)),\n      durationInfo = {\n        isNegativeDuration: collapsed < 0,\n        // this relies on \"collapsed\" being based on \"shiftTo\", which builds up the object\n        // in order\n        largestUnit: Object.keys(collapsed.values)[0]\n      };\n    return stringifyTokens(tokens, tokenToString(collapsed, durationInfo));\n  }\n}\n\n/*\n * This file handles parsing for well-specified formats. Here's how it works:\n * Two things go into parsing: a regex to match with and an extractor to take apart the groups in the match.\n * An extractor is just a function that takes a regex match array and returns a { year: ..., month: ... } object\n * parse() does the work of executing the regex and applying the extractor. It takes multiple regex/extractor pairs to try in sequence.\n * Extractors can take a \"cursor\" representing the offset in the match to look at. This makes it easy to combine extractors.\n * combineExtractors() does the work of combining them, keeping track of the cursor through multiple extractions.\n * Some extractions are super dumb and simpleParse and fromStrings help DRY them.\n */\n\nconst ianaRegex = /[A-Za-z_+-]{1,256}(?::?\\/[A-Za-z0-9_+-]{1,256}(?:\\/[A-Za-z0-9_+-]{1,256})?)?/;\nfunction combineRegexes(...regexes) {\n  const full = regexes.reduce((f, r) => f + r.source, \"\");\n  return RegExp(`^${full}$`);\n}\nfunction combineExtractors(...extractors) {\n  return m => extractors.reduce(([mergedVals, mergedZone, cursor], ex) => {\n    const [val, zone, next] = ex(m, cursor);\n    return [{\n      ...mergedVals,\n      ...val\n    }, zone || mergedZone, next];\n  }, [{}, null, 1]).slice(0, 2);\n}\nfunction parse(s, ...patterns) {\n  if (s == null) {\n    return [null, null];\n  }\n  for (const [regex, extractor] of patterns) {\n    const m = regex.exec(s);\n    if (m) {\n      return extractor(m);\n    }\n  }\n  return [null, null];\n}\nfunction simpleParse(...keys) {\n  return (match, cursor) => {\n    const ret = {};\n    let i;\n    for (i = 0; i < keys.length; i++) {\n      ret[keys[i]] = parseInteger(match[cursor + i]);\n    }\n    return [ret, null, cursor + i];\n  };\n}\n\n// ISO and SQL parsing\nconst offsetRegex = /(?:([Zz])|([+-]\\d\\d)(?::?(\\d\\d))?)/;\nconst isoExtendedZone = `(?:${offsetRegex.source}?(?:\\\\[(${ianaRegex.source})\\\\])?)?`;\nconst isoTimeBaseRegex = /(\\d\\d)(?::?(\\d\\d)(?::?(\\d\\d)(?:[.,](\\d{1,30}))?)?)?/;\nconst isoTimeRegex = RegExp(`${isoTimeBaseRegex.source}${isoExtendedZone}`);\nconst isoTimeExtensionRegex = RegExp(`(?:[Tt]${isoTimeRegex.source})?`);\nconst isoYmdRegex = /([+-]\\d{6}|\\d{4})(?:-?(\\d\\d)(?:-?(\\d\\d))?)?/;\nconst isoWeekRegex = /(\\d{4})-?W(\\d\\d)(?:-?(\\d))?/;\nconst isoOrdinalRegex = /(\\d{4})-?(\\d{3})/;\nconst extractISOWeekData = simpleParse(\"weekYear\", \"weekNumber\", \"weekDay\");\nconst extractISOOrdinalData = simpleParse(\"year\", \"ordinal\");\nconst sqlYmdRegex = /(\\d{4})-(\\d\\d)-(\\d\\d)/; // dumbed-down version of the ISO one\nconst sqlTimeRegex = RegExp(`${isoTimeBaseRegex.source} ?(?:${offsetRegex.source}|(${ianaRegex.source}))?`);\nconst sqlTimeExtensionRegex = RegExp(`(?: ${sqlTimeRegex.source})?`);\nfunction int(match, pos, fallback) {\n  const m = match[pos];\n  return isUndefined(m) ? fallback : parseInteger(m);\n}\nfunction extractISOYmd(match, cursor) {\n  const item = {\n    year: int(match, cursor),\n    month: int(match, cursor + 1, 1),\n    day: int(match, cursor + 2, 1)\n  };\n  return [item, null, cursor + 3];\n}\nfunction extractISOTime(match, cursor) {\n  const item = {\n    hours: int(match, cursor, 0),\n    minutes: int(match, cursor + 1, 0),\n    seconds: int(match, cursor + 2, 0),\n    milliseconds: parseMillis(match[cursor + 3])\n  };\n  return [item, null, cursor + 4];\n}\nfunction extractISOOffset(match, cursor) {\n  const local = !match[cursor] && !match[cursor + 1],\n    fullOffset = signedOffset(match[cursor + 1], match[cursor + 2]),\n    zone = local ? null : FixedOffsetZone.instance(fullOffset);\n  return [{}, zone, cursor + 3];\n}\nfunction extractIANAZone(match, cursor) {\n  const zone = match[cursor] ? IANAZone.create(match[cursor]) : null;\n  return [{}, zone, cursor + 1];\n}\n\n// ISO time parsing\n\nconst isoTimeOnly = RegExp(`^T?${isoTimeBaseRegex.source}$`);\n\n// ISO duration parsing\n\nconst isoDuration = /^-?P(?:(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)Y)?(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)M)?(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)W)?(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)D)?(?:T(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)H)?(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)M)?(?:(-?\\d{1,20})(?:[.,](-?\\d{1,20}))?S)?)?)$/;\nfunction extractISODuration(match) {\n  const [s, yearStr, monthStr, weekStr, dayStr, hourStr, minuteStr, secondStr, millisecondsStr] = match;\n  const hasNegativePrefix = s[0] === \"-\";\n  const negativeSeconds = secondStr && secondStr[0] === \"-\";\n  const maybeNegate = (num, force = false) => num !== undefined && (force || num && hasNegativePrefix) ? -num : num;\n  return [{\n    years: maybeNegate(parseFloating(yearStr)),\n    months: maybeNegate(parseFloating(monthStr)),\n    weeks: maybeNegate(parseFloating(weekStr)),\n    days: maybeNegate(parseFloating(dayStr)),\n    hours: maybeNegate(parseFloating(hourStr)),\n    minutes: maybeNegate(parseFloating(minuteStr)),\n    seconds: maybeNegate(parseFloating(secondStr), secondStr === \"-0\"),\n    milliseconds: maybeNegate(parseMillis(millisecondsStr), negativeSeconds)\n  }];\n}\n\n// These are a little braindead. EDT *should* tell us that we're in, say, America/New_York\n// and not just that we're in -240 *right now*. But since I don't think these are used that often\n// I'm just going to ignore that\nconst obsOffsets = {\n  GMT: 0,\n  EDT: -4 * 60,\n  EST: -5 * 60,\n  CDT: -5 * 60,\n  CST: -6 * 60,\n  MDT: -6 * 60,\n  MST: -7 * 60,\n  PDT: -7 * 60,\n  PST: -8 * 60\n};\nfunction fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) {\n  const result = {\n    year: yearStr.length === 2 ? untruncateYear(parseInteger(yearStr)) : parseInteger(yearStr),\n    month: monthsShort.indexOf(monthStr) + 1,\n    day: parseInteger(dayStr),\n    hour: parseInteger(hourStr),\n    minute: parseInteger(minuteStr)\n  };\n  if (secondStr) result.second = parseInteger(secondStr);\n  if (weekdayStr) {\n    result.weekday = weekdayStr.length > 3 ? weekdaysLong.indexOf(weekdayStr) + 1 : weekdaysShort.indexOf(weekdayStr) + 1;\n  }\n  return result;\n}\n\n// RFC 2822/5322\nconst rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\\s)?(\\d{1,2})\\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\\s(\\d{2,4})\\s(\\d\\d):(\\d\\d)(?::(\\d\\d))?\\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\\d\\d)(\\d\\d)))$/;\nfunction extractRFC2822(match) {\n  const [, weekdayStr, dayStr, monthStr, yearStr, hourStr, minuteStr, secondStr, obsOffset, milOffset, offHourStr, offMinuteStr] = match,\n    result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);\n  let offset;\n  if (obsOffset) {\n    offset = obsOffsets[obsOffset];\n  } else if (milOffset) {\n    offset = 0;\n  } else {\n    offset = signedOffset(offHourStr, offMinuteStr);\n  }\n  return [result, new FixedOffsetZone(offset)];\n}\nfunction preprocessRFC2822(s) {\n  // Remove comments and folding whitespace and replace multiple-spaces with a single space\n  return s.replace(/\\([^()]*\\)|[\\n\\t]/g, \" \").replace(/(\\s\\s+)/g, \" \").trim();\n}\n\n// http date\n\nconst rfc1123 = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\\d\\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\\d{4}) (\\d\\d):(\\d\\d):(\\d\\d) GMT$/,\n  rfc850 = /^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\\d\\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\\d\\d) (\\d\\d):(\\d\\d):(\\d\\d) GMT$/,\n  ascii = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \\d|\\d\\d) (\\d\\d):(\\d\\d):(\\d\\d) (\\d{4})$/;\nfunction extractRFC1123Or850(match) {\n  const [, weekdayStr, dayStr, monthStr, yearStr, hourStr, minuteStr, secondStr] = match,\n    result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);\n  return [result, FixedOffsetZone.utcInstance];\n}\nfunction extractASCII(match) {\n  const [, weekdayStr, monthStr, dayStr, hourStr, minuteStr, secondStr, yearStr] = match,\n    result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);\n  return [result, FixedOffsetZone.utcInstance];\n}\nconst isoYmdWithTimeExtensionRegex = combineRegexes(isoYmdRegex, isoTimeExtensionRegex);\nconst isoWeekWithTimeExtensionRegex = combineRegexes(isoWeekRegex, isoTimeExtensionRegex);\nconst isoOrdinalWithTimeExtensionRegex = combineRegexes(isoOrdinalRegex, isoTimeExtensionRegex);\nconst isoTimeCombinedRegex = combineRegexes(isoTimeRegex);\nconst extractISOYmdTimeAndOffset = combineExtractors(extractISOYmd, extractISOTime, extractISOOffset, extractIANAZone);\nconst extractISOWeekTimeAndOffset = combineExtractors(extractISOWeekData, extractISOTime, extractISOOffset, extractIANAZone);\nconst extractISOOrdinalDateAndTime = combineExtractors(extractISOOrdinalData, extractISOTime, extractISOOffset, extractIANAZone);\nconst extractISOTimeAndOffset = combineExtractors(extractISOTime, extractISOOffset, extractIANAZone);\n\n/*\n * @private\n */\n\nfunction parseISODate(s) {\n  return parse(s, [isoYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset], [isoWeekWithTimeExtensionRegex, extractISOWeekTimeAndOffset], [isoOrdinalWithTimeExtensionRegex, extractISOOrdinalDateAndTime], [isoTimeCombinedRegex, extractISOTimeAndOffset]);\n}\nfunction parseRFC2822Date(s) {\n  return parse(preprocessRFC2822(s), [rfc2822, extractRFC2822]);\n}\nfunction parseHTTPDate(s) {\n  return parse(s, [rfc1123, extractRFC1123Or850], [rfc850, extractRFC1123Or850], [ascii, extractASCII]);\n}\nfunction parseISODuration(s) {\n  return parse(s, [isoDuration, extractISODuration]);\n}\nconst extractISOTimeOnly = combineExtractors(extractISOTime);\nfunction parseISOTimeOnly(s) {\n  return parse(s, [isoTimeOnly, extractISOTimeOnly]);\n}\nconst sqlYmdWithTimeExtensionRegex = combineRegexes(sqlYmdRegex, sqlTimeExtensionRegex);\nconst sqlTimeCombinedRegex = combineRegexes(sqlTimeRegex);\nconst extractISOTimeOffsetAndIANAZone = combineExtractors(extractISOTime, extractISOOffset, extractIANAZone);\nfunction parseSQL(s) {\n  return parse(s, [sqlYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset], [sqlTimeCombinedRegex, extractISOTimeOffsetAndIANAZone]);\n}\n\nconst INVALID$2 = \"Invalid Duration\";\n\n// unit conversion constants\nconst lowOrderMatrix = {\n    weeks: {\n      days: 7,\n      hours: 7 * 24,\n      minutes: 7 * 24 * 60,\n      seconds: 7 * 24 * 60 * 60,\n      milliseconds: 7 * 24 * 60 * 60 * 1000\n    },\n    days: {\n      hours: 24,\n      minutes: 24 * 60,\n      seconds: 24 * 60 * 60,\n      milliseconds: 24 * 60 * 60 * 1000\n    },\n    hours: {\n      minutes: 60,\n      seconds: 60 * 60,\n      milliseconds: 60 * 60 * 1000\n    },\n    minutes: {\n      seconds: 60,\n      milliseconds: 60 * 1000\n    },\n    seconds: {\n      milliseconds: 1000\n    }\n  },\n  casualMatrix = {\n    years: {\n      quarters: 4,\n      months: 12,\n      weeks: 52,\n      days: 365,\n      hours: 365 * 24,\n      minutes: 365 * 24 * 60,\n      seconds: 365 * 24 * 60 * 60,\n      milliseconds: 365 * 24 * 60 * 60 * 1000\n    },\n    quarters: {\n      months: 3,\n      weeks: 13,\n      days: 91,\n      hours: 91 * 24,\n      minutes: 91 * 24 * 60,\n      seconds: 91 * 24 * 60 * 60,\n      milliseconds: 91 * 24 * 60 * 60 * 1000\n    },\n    months: {\n      weeks: 4,\n      days: 30,\n      hours: 30 * 24,\n      minutes: 30 * 24 * 60,\n      seconds: 30 * 24 * 60 * 60,\n      milliseconds: 30 * 24 * 60 * 60 * 1000\n    },\n    ...lowOrderMatrix\n  },\n  daysInYearAccurate = 146097.0 / 400,\n  daysInMonthAccurate = 146097.0 / 4800,\n  accurateMatrix = {\n    years: {\n      quarters: 4,\n      months: 12,\n      weeks: daysInYearAccurate / 7,\n      days: daysInYearAccurate,\n      hours: daysInYearAccurate * 24,\n      minutes: daysInYearAccurate * 24 * 60,\n      seconds: daysInYearAccurate * 24 * 60 * 60,\n      milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1000\n    },\n    quarters: {\n      months: 3,\n      weeks: daysInYearAccurate / 28,\n      days: daysInYearAccurate / 4,\n      hours: daysInYearAccurate * 24 / 4,\n      minutes: daysInYearAccurate * 24 * 60 / 4,\n      seconds: daysInYearAccurate * 24 * 60 * 60 / 4,\n      milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1000 / 4\n    },\n    months: {\n      weeks: daysInMonthAccurate / 7,\n      days: daysInMonthAccurate,\n      hours: daysInMonthAccurate * 24,\n      minutes: daysInMonthAccurate * 24 * 60,\n      seconds: daysInMonthAccurate * 24 * 60 * 60,\n      milliseconds: daysInMonthAccurate * 24 * 60 * 60 * 1000\n    },\n    ...lowOrderMatrix\n  };\n\n// units ordered by size\nconst orderedUnits$1 = [\"years\", \"quarters\", \"months\", \"weeks\", \"days\", \"hours\", \"minutes\", \"seconds\", \"milliseconds\"];\nconst reverseUnits = orderedUnits$1.slice(0).reverse();\n\n// clone really means \"create another instance just like this one, but with these changes\"\nfunction clone$1(dur, alts, clear = false) {\n  // deep merge for vals\n  const conf = {\n    values: clear ? alts.values : {\n      ...dur.values,\n      ...(alts.values || {})\n    },\n    loc: dur.loc.clone(alts.loc),\n    conversionAccuracy: alts.conversionAccuracy || dur.conversionAccuracy,\n    matrix: alts.matrix || dur.matrix\n  };\n  return new Duration(conf);\n}\nfunction durationToMillis(matrix, vals) {\n  var _vals$milliseconds;\n  let sum = (_vals$milliseconds = vals.milliseconds) != null ? _vals$milliseconds : 0;\n  for (const unit of reverseUnits.slice(1)) {\n    if (vals[unit]) {\n      sum += vals[unit] * matrix[unit][\"milliseconds\"];\n    }\n  }\n  return sum;\n}\n\n// NB: mutates parameters\nfunction normalizeValues(matrix, vals) {\n  // the logic below assumes the overall value of the duration is positive\n  // if this is not the case, factor is used to make it so\n  const factor = durationToMillis(matrix, vals) < 0 ? -1 : 1;\n  orderedUnits$1.reduceRight((previous, current) => {\n    if (!isUndefined(vals[current])) {\n      if (previous) {\n        const previousVal = vals[previous] * factor;\n        const conv = matrix[current][previous];\n\n        // if (previousVal < 0):\n        // lower order unit is negative (e.g. { years: 2, days: -2 })\n        // normalize this by reducing the higher order unit by the appropriate amount\n        // and increasing the lower order unit\n        // this can never make the higher order unit negative, because this function only operates\n        // on positive durations, so the amount of time represented by the lower order unit cannot\n        // be larger than the higher order unit\n        // else:\n        // lower order unit is positive (e.g. { years: 2, days: 450 } or { years: -2, days: 450 })\n        // in this case we attempt to convert as much as possible from the lower order unit into\n        // the higher order one\n        //\n        // Math.floor takes care of both of these cases, rounding away from 0\n        // if previousVal < 0 it makes the absolute value larger\n        // if previousVal >= it makes the absolute value smaller\n        const rollUp = Math.floor(previousVal / conv);\n        vals[current] += rollUp * factor;\n        vals[previous] -= rollUp * conv * factor;\n      }\n      return current;\n    } else {\n      return previous;\n    }\n  }, null);\n\n  // try to convert any decimals into smaller units if possible\n  // for example for { years: 2.5, days: 0, seconds: 0 } we want to get { years: 2, days: 182, hours: 12 }\n  orderedUnits$1.reduce((previous, current) => {\n    if (!isUndefined(vals[current])) {\n      if (previous) {\n        const fraction = vals[previous] % 1;\n        vals[previous] -= fraction;\n        vals[current] += fraction * matrix[previous][current];\n      }\n      return current;\n    } else {\n      return previous;\n    }\n  }, null);\n}\n\n// Remove all properties with a value of 0 from an object\nfunction removeZeroes(vals) {\n  const newVals = {};\n  for (const [key, value] of Object.entries(vals)) {\n    if (value !== 0) {\n      newVals[key] = value;\n    }\n  }\n  return newVals;\n}\n\n/**\n * A Duration object represents a period of time, like \"2 months\" or \"1 day, 1 hour\". Conceptually, it's just a map of units to their quantities, accompanied by some additional configuration and methods for creating, parsing, interrogating, transforming, and formatting them. They can be used on their own or in conjunction with other Luxon types; for example, you can use {@link DateTime#plus} to add a Duration object to a DateTime, producing another DateTime.\n *\n * Here is a brief overview of commonly used methods and getters in Duration:\n *\n * * **Creation** To create a Duration, use {@link Duration.fromMillis}, {@link Duration.fromObject}, or {@link Duration.fromISO}.\n * * **Unit values** See the {@link Duration#years}, {@link Duration#months}, {@link Duration#weeks}, {@link Duration#days}, {@link Duration#hours}, {@link Duration#minutes}, {@link Duration#seconds}, {@link Duration#milliseconds} accessors.\n * * **Configuration** See  {@link Duration#locale} and {@link Duration#numberingSystem} accessors.\n * * **Transformation** To create new Durations out of old ones use {@link Duration#plus}, {@link Duration#minus}, {@link Duration#normalize}, {@link Duration#set}, {@link Duration#reconfigure}, {@link Duration#shiftTo}, and {@link Duration#negate}.\n * * **Output** To convert the Duration into other representations, see {@link Duration#as}, {@link Duration#toISO}, {@link Duration#toFormat}, and {@link Duration#toJSON}\n *\n * There's are more methods documented below. In addition, for more information on subtler topics like internationalization and validity, see the external documentation.\n */\nclass Duration {\n  /**\n   * @private\n   */\n  constructor(config) {\n    const accurate = config.conversionAccuracy === \"longterm\" || false;\n    let matrix = accurate ? accurateMatrix : casualMatrix;\n    if (config.matrix) {\n      matrix = config.matrix;\n    }\n\n    /**\n     * @access private\n     */\n    this.values = config.values;\n    /**\n     * @access private\n     */\n    this.loc = config.loc || Locale.create();\n    /**\n     * @access private\n     */\n    this.conversionAccuracy = accurate ? \"longterm\" : \"casual\";\n    /**\n     * @access private\n     */\n    this.invalid = config.invalid || null;\n    /**\n     * @access private\n     */\n    this.matrix = matrix;\n    /**\n     * @access private\n     */\n    this.isLuxonDuration = true;\n  }\n\n  /**\n   * Create Duration from a number of milliseconds.\n   * @param {number} count of milliseconds\n   * @param {Object} opts - options for parsing\n   * @param {string} [opts.locale='en-US'] - the locale to use\n   * @param {string} opts.numberingSystem - the numbering system to use\n   * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use\n   * @return {Duration}\n   */\n  static fromMillis(count, opts) {\n    return Duration.fromObject({\n      milliseconds: count\n    }, opts);\n  }\n\n  /**\n   * Create a Duration from a JavaScript object with keys like 'years' and 'hours'.\n   * If this object is empty then a zero milliseconds duration is returned.\n   * @param {Object} obj - the object to create the DateTime from\n   * @param {number} obj.years\n   * @param {number} obj.quarters\n   * @param {number} obj.months\n   * @param {number} obj.weeks\n   * @param {number} obj.days\n   * @param {number} obj.hours\n   * @param {number} obj.minutes\n   * @param {number} obj.seconds\n   * @param {number} obj.milliseconds\n   * @param {Object} [opts=[]] - options for creating this Duration\n   * @param {string} [opts.locale='en-US'] - the locale to use\n   * @param {string} opts.numberingSystem - the numbering system to use\n   * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use\n   * @param {string} [opts.matrix=Object] - the custom conversion system to use\n   * @return {Duration}\n   */\n  static fromObject(obj, opts = {}) {\n    if (obj == null || typeof obj !== \"object\") {\n      throw new InvalidArgumentError(`Duration.fromObject: argument expected to be an object, got ${obj === null ? \"null\" : typeof obj}`);\n    }\n    return new Duration({\n      values: normalizeObject(obj, Duration.normalizeUnit),\n      loc: Locale.fromObject(opts),\n      conversionAccuracy: opts.conversionAccuracy,\n      matrix: opts.matrix\n    });\n  }\n\n  /**\n   * Create a Duration from DurationLike.\n   *\n   * @param {Object | number | Duration} durationLike\n   * One of:\n   * - object with keys like 'years' and 'hours'.\n   * - number representing milliseconds\n   * - Duration instance\n   * @return {Duration}\n   */\n  static fromDurationLike(durationLike) {\n    if (isNumber(durationLike)) {\n      return Duration.fromMillis(durationLike);\n    } else if (Duration.isDuration(durationLike)) {\n      return durationLike;\n    } else if (typeof durationLike === \"object\") {\n      return Duration.fromObject(durationLike);\n    } else {\n      throw new InvalidArgumentError(`Unknown duration argument ${durationLike} of type ${typeof durationLike}`);\n    }\n  }\n\n  /**\n   * Create a Duration from an ISO 8601 duration string.\n   * @param {string} text - text to parse\n   * @param {Object} opts - options for parsing\n   * @param {string} [opts.locale='en-US'] - the locale to use\n   * @param {string} opts.numberingSystem - the numbering system to use\n   * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use\n   * @param {string} [opts.matrix=Object] - the preset conversion system to use\n   * @see https://en.wikipedia.org/wiki/ISO_8601#Durations\n   * @example Duration.fromISO('P3Y6M1W4DT12H30M5S').toObject() //=> { years: 3, months: 6, weeks: 1, days: 4, hours: 12, minutes: 30, seconds: 5 }\n   * @example Duration.fromISO('PT23H').toObject() //=> { hours: 23 }\n   * @example Duration.fromISO('P5Y3M').toObject() //=> { years: 5, months: 3 }\n   * @return {Duration}\n   */\n  static fromISO(text, opts) {\n    const [parsed] = parseISODuration(text);\n    if (parsed) {\n      return Duration.fromObject(parsed, opts);\n    } else {\n      return Duration.invalid(\"unparsable\", `the input \"${text}\" can't be parsed as ISO 8601`);\n    }\n  }\n\n  /**\n   * Create a Duration from an ISO 8601 time string.\n   * @param {string} text - text to parse\n   * @param {Object} opts - options for parsing\n   * @param {string} [opts.locale='en-US'] - the locale to use\n   * @param {string} opts.numberingSystem - the numbering system to use\n   * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use\n   * @param {string} [opts.matrix=Object] - the conversion system to use\n   * @see https://en.wikipedia.org/wiki/ISO_8601#Times\n   * @example Duration.fromISOTime('11:22:33.444').toObject() //=> { hours: 11, minutes: 22, seconds: 33, milliseconds: 444 }\n   * @example Duration.fromISOTime('11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }\n   * @example Duration.fromISOTime('T11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }\n   * @example Duration.fromISOTime('1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }\n   * @example Duration.fromISOTime('T1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }\n   * @return {Duration}\n   */\n  static fromISOTime(text, opts) {\n    const [parsed] = parseISOTimeOnly(text);\n    if (parsed) {\n      return Duration.fromObject(parsed, opts);\n    } else {\n      return Duration.invalid(\"unparsable\", `the input \"${text}\" can't be parsed as ISO 8601`);\n    }\n  }\n\n  /**\n   * Create an invalid Duration.\n   * @param {string} reason - simple string of why this datetime is invalid. Should not contain parameters or anything else data-dependent\n   * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information\n   * @return {Duration}\n   */\n  static invalid(reason, explanation = null) {\n    if (!reason) {\n      throw new InvalidArgumentError(\"need to specify a reason the Duration is invalid\");\n    }\n    const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);\n    if (Settings.throwOnInvalid) {\n      throw new InvalidDurationError(invalid);\n    } else {\n      return new Duration({\n        invalid\n      });\n    }\n  }\n\n  /**\n   * @private\n   */\n  static normalizeUnit(unit) {\n    const normalized = {\n      year: \"years\",\n      years: \"years\",\n      quarter: \"quarters\",\n      quarters: \"quarters\",\n      month: \"months\",\n      months: \"months\",\n      week: \"weeks\",\n      weeks: \"weeks\",\n      day: \"days\",\n      days: \"days\",\n      hour: \"hours\",\n      hours: \"hours\",\n      minute: \"minutes\",\n      minutes: \"minutes\",\n      second: \"seconds\",\n      seconds: \"seconds\",\n      millisecond: \"milliseconds\",\n      milliseconds: \"milliseconds\"\n    }[unit ? unit.toLowerCase() : unit];\n    if (!normalized) throw new InvalidUnitError(unit);\n    return normalized;\n  }\n\n  /**\n   * Check if an object is a Duration. Works across context boundaries\n   * @param {object} o\n   * @return {boolean}\n   */\n  static isDuration(o) {\n    return o && o.isLuxonDuration || false;\n  }\n\n  /**\n   * Get  the locale of a Duration, such 'en-GB'\n   * @type {string}\n   */\n  get locale() {\n    return this.isValid ? this.loc.locale : null;\n  }\n\n  /**\n   * Get the numbering system of a Duration, such 'beng'. The numbering system is used when formatting the Duration\n   *\n   * @type {string}\n   */\n  get numberingSystem() {\n    return this.isValid ? this.loc.numberingSystem : null;\n  }\n\n  /**\n   * Returns a string representation of this Duration formatted according to the specified format string. You may use these tokens:\n   * * `S` for milliseconds\n   * * `s` for seconds\n   * * `m` for minutes\n   * * `h` for hours\n   * * `d` for days\n   * * `w` for weeks\n   * * `M` for months\n   * * `y` for years\n   * Notes:\n   * * Add padding by repeating the token, e.g. \"yy\" pads the years to two digits, \"hhhh\" pads the hours out to four digits\n   * * Tokens can be escaped by wrapping with single quotes.\n   * * The duration will be converted to the set of units in the format string using {@link Duration#shiftTo} and the Durations's conversion accuracy setting.\n   * @param {string} fmt - the format string\n   * @param {Object} opts - options\n   * @param {boolean} [opts.floor=true] - floor numerical values\n   * @param {'negative'|'all'|'negativeLargestOnly'} [opts.signMode=negative] - How to handle signs\n   * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat(\"y d s\") //=> \"1 6 2\"\n   * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat(\"yy dd sss\") //=> \"01 06 002\"\n   * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat(\"M S\") //=> \"12 518402000\"\n   * @example Duration.fromObject({ days: 6, seconds: 2 }).toFormat(\"d s\", { signMode: \"all\" }) //=> \"+6 +2\"\n   * @example Duration.fromObject({ days: -6, seconds: -2 }).toFormat(\"d s\", { signMode: \"all\" }) //=> \"-6 -2\"\n   * @example Duration.fromObject({ days: -6, seconds: -2 }).toFormat(\"d s\", { signMode: \"negativeLargestOnly\" }) //=> \"-6 2\"\n   * @return {string}\n   */\n  toFormat(fmt, opts = {}) {\n    // reverse-compat since 1.2; we always round down now, never up, and we do it by default\n    const fmtOpts = {\n      ...opts,\n      floor: opts.round !== false && opts.floor !== false\n    };\n    return this.isValid ? Formatter.create(this.loc, fmtOpts).formatDurationFromString(this, fmt) : INVALID$2;\n  }\n\n  /**\n   * Returns a string representation of a Duration with all units included.\n   * To modify its behavior, use `listStyle` and any Intl.NumberFormat option, though `unitDisplay` is especially relevant.\n   * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options\n   * @param {Object} opts - Formatting options. Accepts the same keys as the options parameter of the native `Intl.NumberFormat` constructor, as well as `listStyle`.\n   * @param {string} [opts.listStyle='narrow'] - How to format the merged list. Corresponds to the `style` property of the options parameter of the native `Intl.ListFormat` constructor.\n   * @param {boolean} [opts.showZeros=true] - Show all units previously used by the duration even if they are zero\n   * @example\n   * ```js\n   * var dur = Duration.fromObject({ months: 1, weeks: 0, hours: 5, minutes: 6 })\n   * dur.toHuman() //=> '1 month, 0 weeks, 5 hours, 6 minutes'\n   * dur.toHuman({ listStyle: \"long\" }) //=> '1 month, 0 weeks, 5 hours, and 6 minutes'\n   * dur.toHuman({ unitDisplay: \"short\" }) //=> '1 mth, 0 wks, 5 hr, 6 min'\n   * dur.toHuman({ showZeros: false }) //=> '1 month, 5 hours, 6 minutes'\n   * ```\n   */\n  toHuman(opts = {}) {\n    if (!this.isValid) return INVALID$2;\n    const showZeros = opts.showZeros !== false;\n    const l = orderedUnits$1.map(unit => {\n      const val = this.values[unit];\n      if (isUndefined(val) || val === 0 && !showZeros) {\n        return null;\n      }\n      return this.loc.numberFormatter({\n        style: \"unit\",\n        unitDisplay: \"long\",\n        ...opts,\n        unit: unit.slice(0, -1)\n      }).format(val);\n    }).filter(n => n);\n    return this.loc.listFormatter({\n      type: \"conjunction\",\n      style: opts.listStyle || \"narrow\",\n      ...opts\n    }).format(l);\n  }\n\n  /**\n   * Returns a JavaScript object with this Duration's values.\n   * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toObject() //=> { years: 1, days: 6, seconds: 2 }\n   * @return {Object}\n   */\n  toObject() {\n    if (!this.isValid) return {};\n    return {\n      ...this.values\n    };\n  }\n\n  /**\n   * Returns an ISO 8601-compliant string representation of this Duration.\n   * @see https://en.wikipedia.org/wiki/ISO_8601#Durations\n   * @example Duration.fromObject({ years: 3, seconds: 45 }).toISO() //=> 'P3YT45S'\n   * @example Duration.fromObject({ months: 4, seconds: 45 }).toISO() //=> 'P4MT45S'\n   * @example Duration.fromObject({ months: 5 }).toISO() //=> 'P5M'\n   * @example Duration.fromObject({ minutes: 5 }).toISO() //=> 'PT5M'\n   * @example Duration.fromObject({ milliseconds: 6 }).toISO() //=> 'PT0.006S'\n   * @return {string}\n   */\n  toISO() {\n    // we could use the formatter, but this is an easier way to get the minimum string\n    if (!this.isValid) return null;\n    let s = \"P\";\n    if (this.years !== 0) s += this.years + \"Y\";\n    if (this.months !== 0 || this.quarters !== 0) s += this.months + this.quarters * 3 + \"M\";\n    if (this.weeks !== 0) s += this.weeks + \"W\";\n    if (this.days !== 0) s += this.days + \"D\";\n    if (this.hours !== 0 || this.minutes !== 0 || this.seconds !== 0 || this.milliseconds !== 0) s += \"T\";\n    if (this.hours !== 0) s += this.hours + \"H\";\n    if (this.minutes !== 0) s += this.minutes + \"M\";\n    if (this.seconds !== 0 || this.milliseconds !== 0)\n      // this will handle \"floating point madness\" by removing extra decimal places\n      // https://stackoverflow.com/questions/588004/is-floating-point-math-broken\n      s += roundTo(this.seconds + this.milliseconds / 1000, 3) + \"S\";\n    if (s === \"P\") s += \"T0S\";\n    return s;\n  }\n\n  /**\n   * Returns an ISO 8601-compliant string representation of this Duration, formatted as a time of day.\n   * Note that this will return null if the duration is invalid, negative, or equal to or greater than 24 hours.\n   * @see https://en.wikipedia.org/wiki/ISO_8601#Times\n   * @param {Object} opts - options\n   * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0\n   * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0\n   * @param {boolean} [opts.includePrefix=false] - include the `T` prefix\n   * @param {string} [opts.format='extended'] - choose between the basic and extended format\n   * @example Duration.fromObject({ hours: 11 }).toISOTime() //=> '11:00:00.000'\n   * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressMilliseconds: true }) //=> '11:00:00'\n   * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressSeconds: true }) //=> '11:00'\n   * @example Duration.fromObject({ hours: 11 }).toISOTime({ includePrefix: true }) //=> 'T11:00:00.000'\n   * @example Duration.fromObject({ hours: 11 }).toISOTime({ format: 'basic' }) //=> '110000.000'\n   * @return {string}\n   */\n  toISOTime(opts = {}) {\n    if (!this.isValid) return null;\n    const millis = this.toMillis();\n    if (millis < 0 || millis >= 86400000) return null;\n    opts = {\n      suppressMilliseconds: false,\n      suppressSeconds: false,\n      includePrefix: false,\n      format: \"extended\",\n      ...opts,\n      includeOffset: false\n    };\n    const dateTime = DateTime.fromMillis(millis, {\n      zone: \"UTC\"\n    });\n    return dateTime.toISOTime(opts);\n  }\n\n  /**\n   * Returns an ISO 8601 representation of this Duration appropriate for use in JSON.\n   * @return {string}\n   */\n  toJSON() {\n    return this.toISO();\n  }\n\n  /**\n   * Returns an ISO 8601 representation of this Duration appropriate for use in debugging.\n   * @return {string}\n   */\n  toString() {\n    return this.toISO();\n  }\n\n  /**\n   * Returns a string representation of this Duration appropriate for the REPL.\n   * @return {string}\n   */\n  [Symbol.for(\"nodejs.util.inspect.custom\")]() {\n    if (this.isValid) {\n      return `Duration { values: ${JSON.stringify(this.values)} }`;\n    } else {\n      return `Duration { Invalid, reason: ${this.invalidReason} }`;\n    }\n  }\n\n  /**\n   * Returns an milliseconds value of this Duration.\n   * @return {number}\n   */\n  toMillis() {\n    if (!this.isValid) return NaN;\n    return durationToMillis(this.matrix, this.values);\n  }\n\n  /**\n   * Returns an milliseconds value of this Duration. Alias of {@link toMillis}\n   * @return {number}\n   */\n  valueOf() {\n    return this.toMillis();\n  }\n\n  /**\n   * Make this Duration longer by the specified amount. Return a newly-constructed Duration.\n   * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()\n   * @return {Duration}\n   */\n  plus(duration) {\n    if (!this.isValid) return this;\n    const dur = Duration.fromDurationLike(duration),\n      result = {};\n    for (const k of orderedUnits$1) {\n      if (hasOwnProperty(dur.values, k) || hasOwnProperty(this.values, k)) {\n        result[k] = dur.get(k) + this.get(k);\n      }\n    }\n    return clone$1(this, {\n      values: result\n    }, true);\n  }\n\n  /**\n   * Make this Duration shorter by the specified amount. Return a newly-constructed Duration.\n   * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()\n   * @return {Duration}\n   */\n  minus(duration) {\n    if (!this.isValid) return this;\n    const dur = Duration.fromDurationLike(duration);\n    return this.plus(dur.negate());\n  }\n\n  /**\n   * Scale this Duration by the specified amount. Return a newly-constructed Duration.\n   * @param {function} fn - The function to apply to each unit. Arity is 1 or 2: the value of the unit and, optionally, the unit name. Must return a number.\n   * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits(x => x * 2) //=> { hours: 2, minutes: 60 }\n   * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits((x, u) => u === \"hours\" ? x * 2 : x) //=> { hours: 2, minutes: 30 }\n   * @return {Duration}\n   */\n  mapUnits(fn) {\n    if (!this.isValid) return this;\n    const result = {};\n    for (const k of Object.keys(this.values)) {\n      result[k] = asNumber(fn(this.values[k], k));\n    }\n    return clone$1(this, {\n      values: result\n    }, true);\n  }\n\n  /**\n   * Get the value of unit.\n   * @param {string} unit - a unit such as 'minute' or 'day'\n   * @example Duration.fromObject({years: 2, days: 3}).get('years') //=> 2\n   * @example Duration.fromObject({years: 2, days: 3}).get('months') //=> 0\n   * @example Duration.fromObject({years: 2, days: 3}).get('days') //=> 3\n   * @return {number}\n   */\n  get(unit) {\n    return this[Duration.normalizeUnit(unit)];\n  }\n\n  /**\n   * \"Set\" the values of specified units. Return a newly-constructed Duration.\n   * @param {Object} values - a mapping of units to numbers\n   * @example dur.set({ years: 2017 })\n   * @example dur.set({ hours: 8, minutes: 30 })\n   * @return {Duration}\n   */\n  set(values) {\n    if (!this.isValid) return this;\n    const mixed = {\n      ...this.values,\n      ...normalizeObject(values, Duration.normalizeUnit)\n    };\n    return clone$1(this, {\n      values: mixed\n    });\n  }\n\n  /**\n   * \"Set\" the locale and/or numberingSystem.  Returns a newly-constructed Duration.\n   * @example dur.reconfigure({ locale: 'en-GB' })\n   * @return {Duration}\n   */\n  reconfigure({\n    locale,\n    numberingSystem,\n    conversionAccuracy,\n    matrix\n  } = {}) {\n    const loc = this.loc.clone({\n      locale,\n      numberingSystem\n    });\n    const opts = {\n      loc,\n      matrix,\n      conversionAccuracy\n    };\n    return clone$1(this, opts);\n  }\n\n  /**\n   * Return the length of the duration in the specified unit.\n   * @param {string} unit - a unit such as 'minutes' or 'days'\n   * @example Duration.fromObject({years: 1}).as('days') //=> 365\n   * @example Duration.fromObject({years: 1}).as('months') //=> 12\n   * @example Duration.fromObject({hours: 60}).as('days') //=> 2.5\n   * @return {number}\n   */\n  as(unit) {\n    return this.isValid ? this.shiftTo(unit).get(unit) : NaN;\n  }\n\n  /**\n   * Reduce this Duration to its canonical representation in its current units.\n   * Assuming the overall value of the Duration is positive, this means:\n   * - excessive values for lower-order units are converted to higher-order units (if possible, see first and second example)\n   * - negative lower-order units are converted to higher order units (there must be such a higher order unit, otherwise\n   *   the overall value would be negative, see third example)\n   * - fractional values for higher-order units are converted to lower-order units (if possible, see fourth example)\n   *\n   * If the overall value is negative, the result of this method is equivalent to `this.negate().normalize().negate()`.\n   * @example Duration.fromObject({ years: 2, days: 5000 }).normalize().toObject() //=> { years: 15, days: 255 }\n   * @example Duration.fromObject({ days: 5000 }).normalize().toObject() //=> { days: 5000 }\n   * @example Duration.fromObject({ hours: 12, minutes: -45 }).normalize().toObject() //=> { hours: 11, minutes: 15 }\n   * @example Duration.fromObject({ years: 2.5, days: 0, hours: 0 }).normalize().toObject() //=> { years: 2, days: 182, hours: 12 }\n   * @return {Duration}\n   */\n  normalize() {\n    if (!this.isValid) return this;\n    const vals = this.toObject();\n    normalizeValues(this.matrix, vals);\n    return clone$1(this, {\n      values: vals\n    }, true);\n  }\n\n  /**\n   * Rescale units to its largest representation\n   * @example Duration.fromObject({ milliseconds: 90000 }).rescale().toObject() //=> { minutes: 1, seconds: 30 }\n   * @return {Duration}\n   */\n  rescale() {\n    if (!this.isValid) return this;\n    const vals = removeZeroes(this.normalize().shiftToAll().toObject());\n    return clone$1(this, {\n      values: vals\n    }, true);\n  }\n\n  /**\n   * Convert this Duration into its representation in a different set of units.\n   * @example Duration.fromObject({ hours: 1, seconds: 30 }).shiftTo('minutes', 'milliseconds').toObject() //=> { minutes: 60, milliseconds: 30000 }\n   * @return {Duration}\n   */\n  shiftTo(...units) {\n    if (!this.isValid) return this;\n    if (units.length === 0) {\n      return this;\n    }\n    units = units.map(u => Duration.normalizeUnit(u));\n    const built = {},\n      accumulated = {},\n      vals = this.toObject();\n    let lastUnit;\n    for (const k of orderedUnits$1) {\n      if (units.indexOf(k) >= 0) {\n        lastUnit = k;\n        let own = 0;\n\n        // anything we haven't boiled down yet should get boiled to this unit\n        for (const ak in accumulated) {\n          own += this.matrix[ak][k] * accumulated[ak];\n          accumulated[ak] = 0;\n        }\n\n        // plus anything that's already in this unit\n        if (isNumber(vals[k])) {\n          own += vals[k];\n        }\n\n        // only keep the integer part for now in the hopes of putting any decimal part\n        // into a smaller unit later\n        const i = Math.trunc(own);\n        built[k] = i;\n        accumulated[k] = (own * 1000 - i * 1000) / 1000;\n\n        // otherwise, keep it in the wings to boil it later\n      } else if (isNumber(vals[k])) {\n        accumulated[k] = vals[k];\n      }\n    }\n\n    // anything leftover becomes the decimal for the last unit\n    // lastUnit must be defined since units is not empty\n    for (const key in accumulated) {\n      if (accumulated[key] !== 0) {\n        built[lastUnit] += key === lastUnit ? accumulated[key] : accumulated[key] / this.matrix[lastUnit][key];\n      }\n    }\n    normalizeValues(this.matrix, built);\n    return clone$1(this, {\n      values: built\n    }, true);\n  }\n\n  /**\n   * Shift this Duration to all available units.\n   * Same as shiftTo(\"years\", \"months\", \"weeks\", \"days\", \"hours\", \"minutes\", \"seconds\", \"milliseconds\")\n   * @return {Duration}\n   */\n  shiftToAll() {\n    if (!this.isValid) return this;\n    return this.shiftTo(\"years\", \"months\", \"weeks\", \"days\", \"hours\", \"minutes\", \"seconds\", \"milliseconds\");\n  }\n\n  /**\n   * Return the negative of this Duration.\n   * @example Duration.fromObject({ hours: 1, seconds: 30 }).negate().toObject() //=> { hours: -1, seconds: -30 }\n   * @return {Duration}\n   */\n  negate() {\n    if (!this.isValid) return this;\n    const negated = {};\n    for (const k of Object.keys(this.values)) {\n      negated[k] = this.values[k] === 0 ? 0 : -this.values[k];\n    }\n    return clone$1(this, {\n      values: negated\n    }, true);\n  }\n\n  /**\n   * Removes all units with values equal to 0 from this Duration.\n   * @example Duration.fromObject({ years: 2, days: 0, hours: 0, minutes: 0 }).removeZeros().toObject() //=> { years: 2 }\n   * @return {Duration}\n   */\n  removeZeros() {\n    if (!this.isValid) return this;\n    const vals = removeZeroes(this.values);\n    return clone$1(this, {\n      values: vals\n    }, true);\n  }\n\n  /**\n   * Get the years.\n   * @type {number}\n   */\n  get years() {\n    return this.isValid ? this.values.years || 0 : NaN;\n  }\n\n  /**\n   * Get the quarters.\n   * @type {number}\n   */\n  get quarters() {\n    return this.isValid ? this.values.quarters || 0 : NaN;\n  }\n\n  /**\n   * Get the months.\n   * @type {number}\n   */\n  get months() {\n    return this.isValid ? this.values.months || 0 : NaN;\n  }\n\n  /**\n   * Get the weeks\n   * @type {number}\n   */\n  get weeks() {\n    return this.isValid ? this.values.weeks || 0 : NaN;\n  }\n\n  /**\n   * Get the days.\n   * @type {number}\n   */\n  get days() {\n    return this.isValid ? this.values.days || 0 : NaN;\n  }\n\n  /**\n   * Get the hours.\n   * @type {number}\n   */\n  get hours() {\n    return this.isValid ? this.values.hours || 0 : NaN;\n  }\n\n  /**\n   * Get the minutes.\n   * @type {number}\n   */\n  get minutes() {\n    return this.isValid ? this.values.minutes || 0 : NaN;\n  }\n\n  /**\n   * Get the seconds.\n   * @return {number}\n   */\n  get seconds() {\n    return this.isValid ? this.values.seconds || 0 : NaN;\n  }\n\n  /**\n   * Get the milliseconds.\n   * @return {number}\n   */\n  get milliseconds() {\n    return this.isValid ? this.values.milliseconds || 0 : NaN;\n  }\n\n  /**\n   * Returns whether the Duration is invalid. Invalid durations are returned by diff operations\n   * on invalid DateTimes or Intervals.\n   * @return {boolean}\n   */\n  get isValid() {\n    return this.invalid === null;\n  }\n\n  /**\n   * Returns an error code if this Duration became invalid, or null if the Duration is valid\n   * @return {string}\n   */\n  get invalidReason() {\n    return this.invalid ? this.invalid.reason : null;\n  }\n\n  /**\n   * Returns an explanation of why this Duration became invalid, or null if the Duration is valid\n   * @type {string}\n   */\n  get invalidExplanation() {\n    return this.invalid ? this.invalid.explanation : null;\n  }\n\n  /**\n   * Equality check\n   * Two Durations are equal iff they have the same units and the same values for each unit.\n   * @param {Duration} other\n   * @return {boolean}\n   */\n  equals(other) {\n    if (!this.isValid || !other.isValid) {\n      return false;\n    }\n    if (!this.loc.equals(other.loc)) {\n      return false;\n    }\n    function eq(v1, v2) {\n      // Consider 0 and undefined as equal\n      if (v1 === undefined || v1 === 0) return v2 === undefined || v2 === 0;\n      return v1 === v2;\n    }\n    for (const u of orderedUnits$1) {\n      if (!eq(this.values[u], other.values[u])) {\n        return false;\n      }\n    }\n    return true;\n  }\n}\n\nconst INVALID$1 = \"Invalid Interval\";\n\n// checks if the start is equal to or before the end\nfunction validateStartEnd(start, end) {\n  if (!start || !start.isValid) {\n    return Interval.invalid(\"missing or invalid start\");\n  } else if (!end || !end.isValid) {\n    return Interval.invalid(\"missing or invalid end\");\n  } else if (end < start) {\n    return Interval.invalid(\"end before start\", `The end of an interval must be after its start, but you had start=${start.toISO()} and end=${end.toISO()}`);\n  } else {\n    return null;\n  }\n}\n\n/**\n * An Interval object represents a half-open interval of time, where each endpoint is a {@link DateTime}. Conceptually, it's a container for those two endpoints, accompanied by methods for creating, parsing, interrogating, comparing, transforming, and formatting them.\n *\n * Here is a brief overview of the most commonly used methods and getters in Interval:\n *\n * * **Creation** To create an Interval, use {@link Interval.fromDateTimes}, {@link Interval.after}, {@link Interval.before}, or {@link Interval.fromISO}.\n * * **Accessors** Use {@link Interval#start} and {@link Interval#end} to get the start and end.\n * * **Interrogation** To analyze the Interval, use {@link Interval#count}, {@link Interval#length}, {@link Interval#hasSame}, {@link Interval#contains}, {@link Interval#isAfter}, or {@link Interval#isBefore}.\n * * **Transformation** To create other Intervals out of this one, use {@link Interval#set}, {@link Interval#splitAt}, {@link Interval#splitBy}, {@link Interval#divideEqually}, {@link Interval.merge}, {@link Interval.xor}, {@link Interval#union}, {@link Interval#intersection}, or {@link Interval#difference}.\n * * **Comparison** To compare this Interval to another one, use {@link Interval#equals}, {@link Interval#overlaps}, {@link Interval#abutsStart}, {@link Interval#abutsEnd}, {@link Interval#engulfs}\n * * **Output** To convert the Interval into other representations, see {@link Interval#toString}, {@link Interval#toLocaleString}, {@link Interval#toISO}, {@link Interval#toISODate}, {@link Interval#toISOTime}, {@link Interval#toFormat}, and {@link Interval#toDuration}.\n */\nclass Interval {\n  /**\n   * @private\n   */\n  constructor(config) {\n    /**\n     * @access private\n     */\n    this.s = config.start;\n    /**\n     * @access private\n     */\n    this.e = config.end;\n    /**\n     * @access private\n     */\n    this.invalid = config.invalid || null;\n    /**\n     * @access private\n     */\n    this.isLuxonInterval = true;\n  }\n\n  /**\n   * Create an invalid Interval.\n   * @param {string} reason - simple string of why this Interval is invalid. Should not contain parameters or anything else data-dependent\n   * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information\n   * @return {Interval}\n   */\n  static invalid(reason, explanation = null) {\n    if (!reason) {\n      throw new InvalidArgumentError(\"need to specify a reason the Interval is invalid\");\n    }\n    const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);\n    if (Settings.throwOnInvalid) {\n      throw new InvalidIntervalError(invalid);\n    } else {\n      return new Interval({\n        invalid\n      });\n    }\n  }\n\n  /**\n   * Create an Interval from a start DateTime and an end DateTime. Inclusive of the start but not the end.\n   * @param {DateTime|Date|Object} start\n   * @param {DateTime|Date|Object} end\n   * @return {Interval}\n   */\n  static fromDateTimes(start, end) {\n    const builtStart = friendlyDateTime(start),\n      builtEnd = friendlyDateTime(end);\n    const validateError = validateStartEnd(builtStart, builtEnd);\n    if (validateError == null) {\n      return new Interval({\n        start: builtStart,\n        end: builtEnd\n      });\n    } else {\n      return validateError;\n    }\n  }\n\n  /**\n   * Create an Interval from a start DateTime and a Duration to extend to.\n   * @param {DateTime|Date|Object} start\n   * @param {Duration|Object|number} duration - the length of the Interval.\n   * @return {Interval}\n   */\n  static after(start, duration) {\n    const dur = Duration.fromDurationLike(duration),\n      dt = friendlyDateTime(start);\n    return Interval.fromDateTimes(dt, dt.plus(dur));\n  }\n\n  /**\n   * Create an Interval from an end DateTime and a Duration to extend backwards to.\n   * @param {DateTime|Date|Object} end\n   * @param {Duration|Object|number} duration - the length of the Interval.\n   * @return {Interval}\n   */\n  static before(end, duration) {\n    const dur = Duration.fromDurationLike(duration),\n      dt = friendlyDateTime(end);\n    return Interval.fromDateTimes(dt.minus(dur), dt);\n  }\n\n  /**\n   * Create an Interval from an ISO 8601 string.\n   * Accepts `<start>/<end>`, `<start>/<duration>`, and `<duration>/<end>` formats.\n   * @param {string} text - the ISO string to parse\n   * @param {Object} [opts] - options to pass {@link DateTime#fromISO} and optionally {@link Duration#fromISO}\n   * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals\n   * @return {Interval}\n   */\n  static fromISO(text, opts) {\n    const [s, e] = (text || \"\").split(\"/\", 2);\n    if (s && e) {\n      let start, startIsValid;\n      try {\n        start = DateTime.fromISO(s, opts);\n        startIsValid = start.isValid;\n      } catch (e) {\n        startIsValid = false;\n      }\n      let end, endIsValid;\n      try {\n        end = DateTime.fromISO(e, opts);\n        endIsValid = end.isValid;\n      } catch (e) {\n        endIsValid = false;\n      }\n      if (startIsValid && endIsValid) {\n        return Interval.fromDateTimes(start, end);\n      }\n      if (startIsValid) {\n        const dur = Duration.fromISO(e, opts);\n        if (dur.isValid) {\n          return Interval.after(start, dur);\n        }\n      } else if (endIsValid) {\n        const dur = Duration.fromISO(s, opts);\n        if (dur.isValid) {\n          return Interval.before(end, dur);\n        }\n      }\n    }\n    return Interval.invalid(\"unparsable\", `the input \"${text}\" can't be parsed as ISO 8601`);\n  }\n\n  /**\n   * Check if an object is an Interval. Works across context boundaries\n   * @param {object} o\n   * @return {boolean}\n   */\n  static isInterval(o) {\n    return o && o.isLuxonInterval || false;\n  }\n\n  /**\n   * Returns the start of the Interval\n   * @type {DateTime}\n   */\n  get start() {\n    return this.isValid ? this.s : null;\n  }\n\n  /**\n   * Returns the end of the Interval. This is the first instant which is not part of the interval\n   * (Interval is half-open).\n   * @type {DateTime}\n   */\n  get end() {\n    return this.isValid ? this.e : null;\n  }\n\n  /**\n   * Returns the last DateTime included in the interval (since end is not part of the interval)\n   * @type {DateTime}\n   */\n  get lastDateTime() {\n    return this.isValid ? this.e ? this.e.minus(1) : null : null;\n  }\n\n  /**\n   * Returns whether this Interval's end is at least its start, meaning that the Interval isn't 'backwards'.\n   * @type {boolean}\n   */\n  get isValid() {\n    return this.invalidReason === null;\n  }\n\n  /**\n   * Returns an error code if this Interval is invalid, or null if the Interval is valid\n   * @type {string}\n   */\n  get invalidReason() {\n    return this.invalid ? this.invalid.reason : null;\n  }\n\n  /**\n   * Returns an explanation of why this Interval became invalid, or null if the Interval is valid\n   * @type {string}\n   */\n  get invalidExplanation() {\n    return this.invalid ? this.invalid.explanation : null;\n  }\n\n  /**\n   * Returns the length of the Interval in the specified unit.\n   * @param {string} unit - the unit (such as 'hours' or 'days') to return the length in.\n   * @return {number}\n   */\n  length(unit = \"milliseconds\") {\n    return this.isValid ? this.toDuration(...[unit]).get(unit) : NaN;\n  }\n\n  /**\n   * Returns the count of minutes, hours, days, months, or years included in the Interval, even in part.\n   * Unlike {@link Interval#length} this counts sections of the calendar, not periods of time, e.g. specifying 'day'\n   * asks 'what dates are included in this interval?', not 'how many days long is this interval?'\n   * @param {string} [unit='milliseconds'] - the unit of time to count.\n   * @param {Object} opts - options\n   * @param {boolean} [opts.useLocaleWeeks=false] - If true, use weeks based on the locale, i.e. use the locale-dependent start of the week; this operation will always use the locale of the start DateTime\n   * @return {number}\n   */\n  count(unit = \"milliseconds\", opts) {\n    if (!this.isValid) return NaN;\n    const start = this.start.startOf(unit, opts);\n    let end;\n    if (opts != null && opts.useLocaleWeeks) {\n      end = this.end.reconfigure({\n        locale: start.locale\n      });\n    } else {\n      end = this.end;\n    }\n    end = end.startOf(unit, opts);\n    return Math.floor(end.diff(start, unit).get(unit)) + (end.valueOf() !== this.end.valueOf());\n  }\n\n  /**\n   * Returns whether this Interval's start and end are both in the same unit of time\n   * @param {string} unit - the unit of time to check sameness on\n   * @return {boolean}\n   */\n  hasSame(unit) {\n    return this.isValid ? this.isEmpty() || this.e.minus(1).hasSame(this.s, unit) : false;\n  }\n\n  /**\n   * Return whether this Interval has the same start and end DateTimes.\n   * @return {boolean}\n   */\n  isEmpty() {\n    return this.s.valueOf() === this.e.valueOf();\n  }\n\n  /**\n   * Return whether this Interval's start is after the specified DateTime.\n   * @param {DateTime} dateTime\n   * @return {boolean}\n   */\n  isAfter(dateTime) {\n    if (!this.isValid) return false;\n    return this.s > dateTime;\n  }\n\n  /**\n   * Return whether this Interval's end is before the specified DateTime.\n   * @param {DateTime} dateTime\n   * @return {boolean}\n   */\n  isBefore(dateTime) {\n    if (!this.isValid) return false;\n    return this.e <= dateTime;\n  }\n\n  /**\n   * Return whether this Interval contains the specified DateTime.\n   * @param {DateTime} dateTime\n   * @return {boolean}\n   */\n  contains(dateTime) {\n    if (!this.isValid) return false;\n    return this.s <= dateTime && this.e > dateTime;\n  }\n\n  /**\n   * \"Sets\" the start and/or end dates. Returns a newly-constructed Interval.\n   * @param {Object} values - the values to set\n   * @param {DateTime} values.start - the starting DateTime\n   * @param {DateTime} values.end - the ending DateTime\n   * @return {Interval}\n   */\n  set({\n    start,\n    end\n  } = {}) {\n    if (!this.isValid) return this;\n    return Interval.fromDateTimes(start || this.s, end || this.e);\n  }\n\n  /**\n   * Split this Interval at each of the specified DateTimes\n   * @param {...DateTime} dateTimes - the unit of time to count.\n   * @return {Array}\n   */\n  splitAt(...dateTimes) {\n    if (!this.isValid) return [];\n    const sorted = dateTimes.map(friendlyDateTime).filter(d => this.contains(d)).sort((a, b) => a.toMillis() - b.toMillis()),\n      results = [];\n    let {\n        s\n      } = this,\n      i = 0;\n    while (s < this.e) {\n      const added = sorted[i] || this.e,\n        next = +added > +this.e ? this.e : added;\n      results.push(Interval.fromDateTimes(s, next));\n      s = next;\n      i += 1;\n    }\n    return results;\n  }\n\n  /**\n   * Split this Interval into smaller Intervals, each of the specified length.\n   * Left over time is grouped into a smaller interval\n   * @param {Duration|Object|number} duration - The length of each resulting interval.\n   * @return {Array}\n   */\n  splitBy(duration) {\n    const dur = Duration.fromDurationLike(duration);\n    if (!this.isValid || !dur.isValid || dur.as(\"milliseconds\") === 0) {\n      return [];\n    }\n    let {\n        s\n      } = this,\n      idx = 1,\n      next;\n    const results = [];\n    while (s < this.e) {\n      const added = this.start.plus(dur.mapUnits(x => x * idx));\n      next = +added > +this.e ? this.e : added;\n      results.push(Interval.fromDateTimes(s, next));\n      s = next;\n      idx += 1;\n    }\n    return results;\n  }\n\n  /**\n   * Split this Interval into the specified number of smaller intervals.\n   * @param {number} numberOfParts - The number of Intervals to divide the Interval into.\n   * @return {Array}\n   */\n  divideEqually(numberOfParts) {\n    if (!this.isValid) return [];\n    return this.splitBy(this.length() / numberOfParts).slice(0, numberOfParts);\n  }\n\n  /**\n   * Return whether this Interval overlaps with the specified Interval\n   * @param {Interval} other\n   * @return {boolean}\n   */\n  overlaps(other) {\n    return this.e > other.s && this.s < other.e;\n  }\n\n  /**\n   * Return whether this Interval's end is adjacent to the specified Interval's start.\n   * @param {Interval} other\n   * @return {boolean}\n   */\n  abutsStart(other) {\n    if (!this.isValid) return false;\n    return +this.e === +other.s;\n  }\n\n  /**\n   * Return whether this Interval's start is adjacent to the specified Interval's end.\n   * @param {Interval} other\n   * @return {boolean}\n   */\n  abutsEnd(other) {\n    if (!this.isValid) return false;\n    return +other.e === +this.s;\n  }\n\n  /**\n   * Returns true if this Interval fully contains the specified Interval, specifically if the intersect (of this Interval and the other Interval) is equal to the other Interval; false otherwise.\n   * @param {Interval} other\n   * @return {boolean}\n   */\n  engulfs(other) {\n    if (!this.isValid) return false;\n    return this.s <= other.s && this.e >= other.e;\n  }\n\n  /**\n   * Return whether this Interval has the same start and end as the specified Interval.\n   * @param {Interval} other\n   * @return {boolean}\n   */\n  equals(other) {\n    if (!this.isValid || !other.isValid) {\n      return false;\n    }\n    return this.s.equals(other.s) && this.e.equals(other.e);\n  }\n\n  /**\n   * Return an Interval representing the intersection of this Interval and the specified Interval.\n   * Specifically, the resulting Interval has the maximum start time and the minimum end time of the two Intervals.\n   * Returns null if the intersection is empty, meaning, the intervals don't intersect.\n   * @param {Interval} other\n   * @return {Interval}\n   */\n  intersection(other) {\n    if (!this.isValid) return this;\n    const s = this.s > other.s ? this.s : other.s,\n      e = this.e < other.e ? this.e : other.e;\n    if (s >= e) {\n      return null;\n    } else {\n      return Interval.fromDateTimes(s, e);\n    }\n  }\n\n  /**\n   * Return an Interval representing the union of this Interval and the specified Interval.\n   * Specifically, the resulting Interval has the minimum start time and the maximum end time of the two Intervals.\n   * @param {Interval} other\n   * @return {Interval}\n   */\n  union(other) {\n    if (!this.isValid) return this;\n    const s = this.s < other.s ? this.s : other.s,\n      e = this.e > other.e ? this.e : other.e;\n    return Interval.fromDateTimes(s, e);\n  }\n\n  /**\n   * Merge an array of Intervals into an equivalent minimal set of Intervals.\n   * Combines overlapping and adjacent Intervals.\n   * The resulting array will contain the Intervals in ascending order, that is, starting with the earliest Interval\n   * and ending with the latest.\n   *\n   * @param {Array} intervals\n   * @return {Array}\n   */\n  static merge(intervals) {\n    const [found, final] = intervals.sort((a, b) => a.s - b.s).reduce(([sofar, current], item) => {\n      if (!current) {\n        return [sofar, item];\n      } else if (current.overlaps(item) || current.abutsStart(item)) {\n        return [sofar, current.union(item)];\n      } else {\n        return [sofar.concat([current]), item];\n      }\n    }, [[], null]);\n    if (final) {\n      found.push(final);\n    }\n    return found;\n  }\n\n  /**\n   * Return an array of Intervals representing the spans of time that only appear in one of the specified Intervals.\n   * @param {Array} intervals\n   * @return {Array}\n   */\n  static xor(intervals) {\n    let start = null,\n      currentCount = 0;\n    const results = [],\n      ends = intervals.map(i => [{\n        time: i.s,\n        type: \"s\"\n      }, {\n        time: i.e,\n        type: \"e\"\n      }]),\n      flattened = Array.prototype.concat(...ends),\n      arr = flattened.sort((a, b) => a.time - b.time);\n    for (const i of arr) {\n      currentCount += i.type === \"s\" ? 1 : -1;\n      if (currentCount === 1) {\n        start = i.time;\n      } else {\n        if (start && +start !== +i.time) {\n          results.push(Interval.fromDateTimes(start, i.time));\n        }\n        start = null;\n      }\n    }\n    return Interval.merge(results);\n  }\n\n  /**\n   * Return an Interval representing the span of time in this Interval that doesn't overlap with any of the specified Intervals.\n   * @param {...Interval} intervals\n   * @return {Array}\n   */\n  difference(...intervals) {\n    return Interval.xor([this].concat(intervals)).map(i => this.intersection(i)).filter(i => i && !i.isEmpty());\n  }\n\n  /**\n   * Returns a string representation of this Interval appropriate for debugging.\n   * @return {string}\n   */\n  toString() {\n    if (!this.isValid) return INVALID$1;\n    return `[${this.s.toISO()} – ${this.e.toISO()})`;\n  }\n\n  /**\n   * Returns a string representation of this Interval appropriate for the REPL.\n   * @return {string}\n   */\n  [Symbol.for(\"nodejs.util.inspect.custom\")]() {\n    if (this.isValid) {\n      return `Interval { start: ${this.s.toISO()}, end: ${this.e.toISO()} }`;\n    } else {\n      return `Interval { Invalid, reason: ${this.invalidReason} }`;\n    }\n  }\n\n  /**\n   * Returns a localized string representing this Interval. Accepts the same options as the\n   * Intl.DateTimeFormat constructor and any presets defined by Luxon, such as\n   * {@link DateTime.DATE_FULL} or {@link DateTime.TIME_SIMPLE}. The exact behavior of this method\n   * is browser-specific, but in general it will return an appropriate representation of the\n   * Interval in the assigned locale. Defaults to the system's locale if no locale has been\n   * specified.\n   * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat\n   * @param {Object} [formatOpts=DateTime.DATE_SHORT] - Either a DateTime preset or\n   * Intl.DateTimeFormat constructor options.\n   * @param {Object} opts - Options to override the configuration of the start DateTime.\n   * @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(); //=> 11/7/2022 – 11/8/2022\n   * @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(DateTime.DATE_FULL); //=> November 7 – 8, 2022\n   * @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(DateTime.DATE_FULL, { locale: 'fr-FR' }); //=> 7–8 novembre 2022\n   * @example Interval.fromISO('2022-11-07T17:00Z/2022-11-07T19:00Z').toLocaleString(DateTime.TIME_SIMPLE); //=> 6:00 – 8:00 PM\n   * @example Interval.fromISO('2022-11-07T17:00Z/2022-11-07T19:00Z').toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> Mon, Nov 07, 6:00 – 8:00 p\n   * @return {string}\n   */\n  toLocaleString(formatOpts = DATE_SHORT, opts = {}) {\n    return this.isValid ? Formatter.create(this.s.loc.clone(opts), formatOpts).formatInterval(this) : INVALID$1;\n  }\n\n  /**\n   * Returns an ISO 8601-compliant string representation of this Interval.\n   * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals\n   * @param {Object} opts - The same options as {@link DateTime#toISO}\n   * @return {string}\n   */\n  toISO(opts) {\n    if (!this.isValid) return INVALID$1;\n    return `${this.s.toISO(opts)}/${this.e.toISO(opts)}`;\n  }\n\n  /**\n   * Returns an ISO 8601-compliant string representation of date of this Interval.\n   * The time components are ignored.\n   * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals\n   * @return {string}\n   */\n  toISODate() {\n    if (!this.isValid) return INVALID$1;\n    return `${this.s.toISODate()}/${this.e.toISODate()}`;\n  }\n\n  /**\n   * Returns an ISO 8601-compliant string representation of time of this Interval.\n   * The date components are ignored.\n   * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals\n   * @param {Object} opts - The same options as {@link DateTime#toISO}\n   * @return {string}\n   */\n  toISOTime(opts) {\n    if (!this.isValid) return INVALID$1;\n    return `${this.s.toISOTime(opts)}/${this.e.toISOTime(opts)}`;\n  }\n\n  /**\n   * Returns a string representation of this Interval formatted according to the specified format\n   * string. **You may not want this.** See {@link Interval#toLocaleString} for a more flexible\n   * formatting tool.\n   * @param {string} dateFormat - The format string. This string formats the start and end time.\n   * See {@link DateTime#toFormat} for details.\n   * @param {Object} opts - Options.\n   * @param {string} [opts.separator =  ' – '] - A separator to place between the start and end\n   * representations.\n   * @return {string}\n   */\n  toFormat(dateFormat, {\n    separator = \" – \"\n  } = {}) {\n    if (!this.isValid) return INVALID$1;\n    return `${this.s.toFormat(dateFormat)}${separator}${this.e.toFormat(dateFormat)}`;\n  }\n\n  /**\n   * Return a Duration representing the time spanned by this interval.\n   * @param {string|string[]} [unit=['milliseconds']] - the unit or units (such as 'hours' or 'days') to include in the duration.\n   * @param {Object} opts - options that affect the creation of the Duration\n   * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use\n   * @example Interval.fromDateTimes(dt1, dt2).toDuration().toObject() //=> { milliseconds: 88489257 }\n   * @example Interval.fromDateTimes(dt1, dt2).toDuration('days').toObject() //=> { days: 1.0241812152777778 }\n   * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes']).toObject() //=> { hours: 24, minutes: 34.82095 }\n   * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes', 'seconds']).toObject() //=> { hours: 24, minutes: 34, seconds: 49.257 }\n   * @example Interval.fromDateTimes(dt1, dt2).toDuration('seconds').toObject() //=> { seconds: 88489.257 }\n   * @return {Duration}\n   */\n  toDuration(unit, opts) {\n    if (!this.isValid) {\n      return Duration.invalid(this.invalidReason);\n    }\n    return this.e.diff(this.s, unit, opts);\n  }\n\n  /**\n   * Run mapFn on the interval start and end, returning a new Interval from the resulting DateTimes\n   * @param {function} mapFn\n   * @return {Interval}\n   * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.toUTC())\n   * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.plus({ hours: 2 }))\n   */\n  mapEndpoints(mapFn) {\n    return Interval.fromDateTimes(mapFn(this.s), mapFn(this.e));\n  }\n}\n\n/**\n * The Info class contains static methods for retrieving general time and date related data. For example, it has methods for finding out if a time zone has a DST, for listing the months in any supported locale, and for discovering which of Luxon features are available in the current environment.\n */\nclass Info {\n  /**\n   * Return whether the specified zone contains a DST.\n   * @param {string|Zone} [zone='local'] - Zone to check. Defaults to the environment's local zone.\n   * @return {boolean}\n   */\n  static hasDST(zone = Settings.defaultZone) {\n    const proto = DateTime.now().setZone(zone).set({\n      month: 12\n    });\n    return !zone.isUniversal && proto.offset !== proto.set({\n      month: 6\n    }).offset;\n  }\n\n  /**\n   * Return whether the specified zone is a valid IANA specifier.\n   * @param {string} zone - Zone to check\n   * @return {boolean}\n   */\n  static isValidIANAZone(zone) {\n    return IANAZone.isValidZone(zone);\n  }\n\n  /**\n   * Converts the input into a {@link Zone} instance.\n   *\n   * * If `input` is already a Zone instance, it is returned unchanged.\n   * * If `input` is a string containing a valid time zone name, a Zone instance\n   *   with that name is returned.\n   * * If `input` is a string that doesn't refer to a known time zone, a Zone\n   *   instance with {@link Zone#isValid} == false is returned.\n   * * If `input is a number, a Zone instance with the specified fixed offset\n   *   in minutes is returned.\n   * * If `input` is `null` or `undefined`, the default zone is returned.\n   * @param {string|Zone|number} [input] - the value to be converted\n   * @return {Zone}\n   */\n  static normalizeZone(input) {\n    return normalizeZone(input, Settings.defaultZone);\n  }\n\n  /**\n   * Get the weekday on which the week starts according to the given locale.\n   * @param {Object} opts - options\n   * @param {string} [opts.locale] - the locale code\n   * @param {string} [opts.locObj=null] - an existing locale object to use\n   * @returns {number} the start of the week, 1 for Monday through 7 for Sunday\n   */\n  static getStartOfWeek({\n    locale = null,\n    locObj = null\n  } = {}) {\n    return (locObj || Locale.create(locale)).getStartOfWeek();\n  }\n\n  /**\n   * Get the minimum number of days necessary in a week before it is considered part of the next year according\n   * to the given locale.\n   * @param {Object} opts - options\n   * @param {string} [opts.locale] - the locale code\n   * @param {string} [opts.locObj=null] - an existing locale object to use\n   * @returns {number}\n   */\n  static getMinimumDaysInFirstWeek({\n    locale = null,\n    locObj = null\n  } = {}) {\n    return (locObj || Locale.create(locale)).getMinDaysInFirstWeek();\n  }\n\n  /**\n   * Get the weekdays, which are considered the weekend according to the given locale\n   * @param {Object} opts - options\n   * @param {string} [opts.locale] - the locale code\n   * @param {string} [opts.locObj=null] - an existing locale object to use\n   * @returns {number[]} an array of weekdays, 1 for Monday through 7 for Sunday\n   */\n  static getWeekendWeekdays({\n    locale = null,\n    locObj = null\n  } = {}) {\n    // copy the array, because we cache it internally\n    return (locObj || Locale.create(locale)).getWeekendDays().slice();\n  }\n\n  /**\n   * Return an array of standalone month names.\n   * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat\n   * @param {string} [length='long'] - the length of the month representation, such as \"numeric\", \"2-digit\", \"narrow\", \"short\", \"long\"\n   * @param {Object} opts - options\n   * @param {string} [opts.locale] - the locale code\n   * @param {string} [opts.numberingSystem=null] - the numbering system\n   * @param {string} [opts.locObj=null] - an existing locale object to use\n   * @param {string} [opts.outputCalendar='gregory'] - the calendar\n   * @example Info.months()[0] //=> 'January'\n   * @example Info.months('short')[0] //=> 'Jan'\n   * @example Info.months('numeric')[0] //=> '1'\n   * @example Info.months('short', { locale: 'fr-CA' } )[0] //=> 'janv.'\n   * @example Info.months('numeric', { locale: 'ar' })[0] //=> '١'\n   * @example Info.months('long', { outputCalendar: 'islamic' })[0] //=> 'Rabiʻ I'\n   * @return {Array}\n   */\n  static months(length = \"long\", {\n    locale = null,\n    numberingSystem = null,\n    locObj = null,\n    outputCalendar = \"gregory\"\n  } = {}) {\n    return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length);\n  }\n\n  /**\n   * Return an array of format month names.\n   * Format months differ from standalone months in that they're meant to appear next to the day of the month. In some languages, that\n   * changes the string.\n   * See {@link Info#months}\n   * @param {string} [length='long'] - the length of the month representation, such as \"numeric\", \"2-digit\", \"narrow\", \"short\", \"long\"\n   * @param {Object} opts - options\n   * @param {string} [opts.locale] - the locale code\n   * @param {string} [opts.numberingSystem=null] - the numbering system\n   * @param {string} [opts.locObj=null] - an existing locale object to use\n   * @param {string} [opts.outputCalendar='gregory'] - the calendar\n   * @return {Array}\n   */\n  static monthsFormat(length = \"long\", {\n    locale = null,\n    numberingSystem = null,\n    locObj = null,\n    outputCalendar = \"gregory\"\n  } = {}) {\n    return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length, true);\n  }\n\n  /**\n   * Return an array of standalone week names.\n   * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat\n   * @param {string} [length='long'] - the length of the weekday representation, such as \"narrow\", \"short\", \"long\".\n   * @param {Object} opts - options\n   * @param {string} [opts.locale] - the locale code\n   * @param {string} [opts.numberingSystem=null] - the numbering system\n   * @param {string} [opts.locObj=null] - an existing locale object to use\n   * @example Info.weekdays()[0] //=> 'Monday'\n   * @example Info.weekdays('short')[0] //=> 'Mon'\n   * @example Info.weekdays('short', { locale: 'fr-CA' })[0] //=> 'lun.'\n   * @example Info.weekdays('short', { locale: 'ar' })[0] //=> 'الاثنين'\n   * @return {Array}\n   */\n  static weekdays(length = \"long\", {\n    locale = null,\n    numberingSystem = null,\n    locObj = null\n  } = {}) {\n    return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length);\n  }\n\n  /**\n   * Return an array of format week names.\n   * Format weekdays differ from standalone weekdays in that they're meant to appear next to more date information. In some languages, that\n   * changes the string.\n   * See {@link Info#weekdays}\n   * @param {string} [length='long'] - the length of the month representation, such as \"narrow\", \"short\", \"long\".\n   * @param {Object} opts - options\n   * @param {string} [opts.locale=null] - the locale code\n   * @param {string} [opts.numberingSystem=null] - the numbering system\n   * @param {string} [opts.locObj=null] - an existing locale object to use\n   * @return {Array}\n   */\n  static weekdaysFormat(length = \"long\", {\n    locale = null,\n    numberingSystem = null,\n    locObj = null\n  } = {}) {\n    return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length, true);\n  }\n\n  /**\n   * Return an array of meridiems.\n   * @param {Object} opts - options\n   * @param {string} [opts.locale] - the locale code\n   * @example Info.meridiems() //=> [ 'AM', 'PM' ]\n   * @example Info.meridiems({ locale: 'my' }) //=> [ 'နံနက်', 'ညနေ' ]\n   * @return {Array}\n   */\n  static meridiems({\n    locale = null\n  } = {}) {\n    return Locale.create(locale).meridiems();\n  }\n\n  /**\n   * Return an array of eras, such as ['BC', 'AD']. The locale can be specified, but the calendar system is always Gregorian.\n   * @param {string} [length='short'] - the length of the era representation, such as \"short\" or \"long\".\n   * @param {Object} opts - options\n   * @param {string} [opts.locale] - the locale code\n   * @example Info.eras() //=> [ 'BC', 'AD' ]\n   * @example Info.eras('long') //=> [ 'Before Christ', 'Anno Domini' ]\n   * @example Info.eras('long', { locale: 'fr' }) //=> [ 'avant Jésus-Christ', 'après Jésus-Christ' ]\n   * @return {Array}\n   */\n  static eras(length = \"short\", {\n    locale = null\n  } = {}) {\n    return Locale.create(locale, null, \"gregory\").eras(length);\n  }\n\n  /**\n   * Return the set of available features in this environment.\n   * Some features of Luxon are not available in all environments. For example, on older browsers, relative time formatting support is not available. Use this function to figure out if that's the case.\n   * Keys:\n   * * `relative`: whether this environment supports relative time formatting\n   * * `localeWeek`: whether this environment supports different weekdays for the start of the week based on the locale\n   * @example Info.features() //=> { relative: false, localeWeek: true }\n   * @return {Object}\n   */\n  static features() {\n    return {\n      relative: hasRelative(),\n      localeWeek: hasLocaleWeekInfo()\n    };\n  }\n}\n\nfunction dayDiff(earlier, later) {\n  const utcDayStart = dt => dt.toUTC(0, {\n      keepLocalTime: true\n    }).startOf(\"day\").valueOf(),\n    ms = utcDayStart(later) - utcDayStart(earlier);\n  return Math.floor(Duration.fromMillis(ms).as(\"days\"));\n}\nfunction highOrderDiffs(cursor, later, units) {\n  const differs = [[\"years\", (a, b) => b.year - a.year], [\"quarters\", (a, b) => b.quarter - a.quarter + (b.year - a.year) * 4], [\"months\", (a, b) => b.month - a.month + (b.year - a.year) * 12], [\"weeks\", (a, b) => {\n    const days = dayDiff(a, b);\n    return (days - days % 7) / 7;\n  }], [\"days\", dayDiff]];\n  const results = {};\n  const earlier = cursor;\n  let lowestOrder, highWater;\n\n  /* This loop tries to diff using larger units first.\n     If we overshoot, we backtrack and try the next smaller unit.\n     \"cursor\" starts out at the earlier timestamp and moves closer and closer to \"later\"\n     as we use smaller and smaller units.\n     highWater keeps track of where we would be if we added one more of the smallest unit,\n     this is used later to potentially convert any difference smaller than the smallest higher order unit\n     into a fraction of that smallest higher order unit\n  */\n  for (const [unit, differ] of differs) {\n    if (units.indexOf(unit) >= 0) {\n      lowestOrder = unit;\n      results[unit] = differ(cursor, later);\n      highWater = earlier.plus(results);\n      if (highWater > later) {\n        // we overshot the end point, backtrack cursor by 1\n        results[unit]--;\n        cursor = earlier.plus(results);\n\n        // if we are still overshooting now, we need to backtrack again\n        // this happens in certain situations when diffing times in different zones,\n        // because this calculation ignores time zones\n        if (cursor > later) {\n          // keep the \"overshot by 1\" around as highWater\n          highWater = cursor;\n          // backtrack cursor by 1\n          results[unit]--;\n          cursor = earlier.plus(results);\n        }\n      } else {\n        cursor = highWater;\n      }\n    }\n  }\n  return [cursor, results, highWater, lowestOrder];\n}\nfunction diff (earlier, later, units, opts) {\n  let [cursor, results, highWater, lowestOrder] = highOrderDiffs(earlier, later, units);\n  const remainingMillis = later - cursor;\n  const lowerOrderUnits = units.filter(u => [\"hours\", \"minutes\", \"seconds\", \"milliseconds\"].indexOf(u) >= 0);\n  if (lowerOrderUnits.length === 0) {\n    if (highWater < later) {\n      highWater = cursor.plus({\n        [lowestOrder]: 1\n      });\n    }\n    if (highWater !== cursor) {\n      results[lowestOrder] = (results[lowestOrder] || 0) + remainingMillis / (highWater - cursor);\n    }\n  }\n  const duration = Duration.fromObject(results, opts);\n  if (lowerOrderUnits.length > 0) {\n    return Duration.fromMillis(remainingMillis, opts).shiftTo(...lowerOrderUnits).plus(duration);\n  } else {\n    return duration;\n  }\n}\n\nconst MISSING_FTP = \"missing Intl.DateTimeFormat.formatToParts support\";\nfunction intUnit(regex, post = i => i) {\n  return {\n    regex,\n    deser: ([s]) => post(parseDigits(s))\n  };\n}\nconst NBSP = String.fromCharCode(160);\nconst spaceOrNBSP = `[ ${NBSP}]`;\nconst spaceOrNBSPRegExp = new RegExp(spaceOrNBSP, \"g\");\nfunction fixListRegex(s) {\n  // make dots optional and also make them literal\n  // make space and non breakable space characters interchangeable\n  return s.replace(/\\./g, \"\\\\.?\").replace(spaceOrNBSPRegExp, spaceOrNBSP);\n}\nfunction stripInsensitivities(s) {\n  return s.replace(/\\./g, \"\") // ignore dots that were made optional\n  .replace(spaceOrNBSPRegExp, \" \") // interchange space and nbsp\n  .toLowerCase();\n}\nfunction oneOf(strings, startIndex) {\n  if (strings === null) {\n    return null;\n  } else {\n    return {\n      regex: RegExp(strings.map(fixListRegex).join(\"|\")),\n      deser: ([s]) => strings.findIndex(i => stripInsensitivities(s) === stripInsensitivities(i)) + startIndex\n    };\n  }\n}\nfunction offset(regex, groups) {\n  return {\n    regex,\n    deser: ([, h, m]) => signedOffset(h, m),\n    groups\n  };\n}\nfunction simple(regex) {\n  return {\n    regex,\n    deser: ([s]) => s\n  };\n}\nfunction escapeToken(value) {\n  return value.replace(/[\\-\\[\\]{}()*+?.,\\\\\\^$|#\\s]/g, \"\\\\$&\");\n}\n\n/**\n * @param token\n * @param {Locale} loc\n */\nfunction unitForToken(token, loc) {\n  const one = digitRegex(loc),\n    two = digitRegex(loc, \"{2}\"),\n    three = digitRegex(loc, \"{3}\"),\n    four = digitRegex(loc, \"{4}\"),\n    six = digitRegex(loc, \"{6}\"),\n    oneOrTwo = digitRegex(loc, \"{1,2}\"),\n    oneToThree = digitRegex(loc, \"{1,3}\"),\n    oneToSix = digitRegex(loc, \"{1,6}\"),\n    oneToNine = digitRegex(loc, \"{1,9}\"),\n    twoToFour = digitRegex(loc, \"{2,4}\"),\n    fourToSix = digitRegex(loc, \"{4,6}\"),\n    literal = t => ({\n      regex: RegExp(escapeToken(t.val)),\n      deser: ([s]) => s,\n      literal: true\n    }),\n    unitate = t => {\n      if (token.literal) {\n        return literal(t);\n      }\n      switch (t.val) {\n        // era\n        case \"G\":\n          return oneOf(loc.eras(\"short\"), 0);\n        case \"GG\":\n          return oneOf(loc.eras(\"long\"), 0);\n        // years\n        case \"y\":\n          return intUnit(oneToSix);\n        case \"yy\":\n          return intUnit(twoToFour, untruncateYear);\n        case \"yyyy\":\n          return intUnit(four);\n        case \"yyyyy\":\n          return intUnit(fourToSix);\n        case \"yyyyyy\":\n          return intUnit(six);\n        // months\n        case \"M\":\n          return intUnit(oneOrTwo);\n        case \"MM\":\n          return intUnit(two);\n        case \"MMM\":\n          return oneOf(loc.months(\"short\", true), 1);\n        case \"MMMM\":\n          return oneOf(loc.months(\"long\", true), 1);\n        case \"L\":\n          return intUnit(oneOrTwo);\n        case \"LL\":\n          return intUnit(two);\n        case \"LLL\":\n          return oneOf(loc.months(\"short\", false), 1);\n        case \"LLLL\":\n          return oneOf(loc.months(\"long\", false), 1);\n        // dates\n        case \"d\":\n          return intUnit(oneOrTwo);\n        case \"dd\":\n          return intUnit(two);\n        // ordinals\n        case \"o\":\n          return intUnit(oneToThree);\n        case \"ooo\":\n          return intUnit(three);\n        // time\n        case \"HH\":\n          return intUnit(two);\n        case \"H\":\n          return intUnit(oneOrTwo);\n        case \"hh\":\n          return intUnit(two);\n        case \"h\":\n          return intUnit(oneOrTwo);\n        case \"mm\":\n          return intUnit(two);\n        case \"m\":\n          return intUnit(oneOrTwo);\n        case \"q\":\n          return intUnit(oneOrTwo);\n        case \"qq\":\n          return intUnit(two);\n        case \"s\":\n          return intUnit(oneOrTwo);\n        case \"ss\":\n          return intUnit(two);\n        case \"S\":\n          return intUnit(oneToThree);\n        case \"SSS\":\n          return intUnit(three);\n        case \"u\":\n          return simple(oneToNine);\n        case \"uu\":\n          return simple(oneOrTwo);\n        case \"uuu\":\n          return intUnit(one);\n        // meridiem\n        case \"a\":\n          return oneOf(loc.meridiems(), 0);\n        // weekYear (k)\n        case \"kkkk\":\n          return intUnit(four);\n        case \"kk\":\n          return intUnit(twoToFour, untruncateYear);\n        // weekNumber (W)\n        case \"W\":\n          return intUnit(oneOrTwo);\n        case \"WW\":\n          return intUnit(two);\n        // weekdays\n        case \"E\":\n        case \"c\":\n          return intUnit(one);\n        case \"EEE\":\n          return oneOf(loc.weekdays(\"short\", false), 1);\n        case \"EEEE\":\n          return oneOf(loc.weekdays(\"long\", false), 1);\n        case \"ccc\":\n          return oneOf(loc.weekdays(\"short\", true), 1);\n        case \"cccc\":\n          return oneOf(loc.weekdays(\"long\", true), 1);\n        // offset/zone\n        case \"Z\":\n        case \"ZZ\":\n          return offset(new RegExp(`([+-]${oneOrTwo.source})(?::(${two.source}))?`), 2);\n        case \"ZZZ\":\n          return offset(new RegExp(`([+-]${oneOrTwo.source})(${two.source})?`), 2);\n        // we don't support ZZZZ (PST) or ZZZZZ (Pacific Standard Time) in parsing\n        // because we don't have any way to figure out what they are\n        case \"z\":\n          return simple(/[a-z_+-/]{1,256}?/i);\n        // this special-case \"token\" represents a place where a macro-token expanded into a white-space literal\n        // in this case we accept any non-newline white-space\n        case \" \":\n          return simple(/[^\\S\\n\\r]/);\n        default:\n          return literal(t);\n      }\n    };\n  const unit = unitate(token) || {\n    invalidReason: MISSING_FTP\n  };\n  unit.token = token;\n  return unit;\n}\nconst partTypeStyleToTokenVal = {\n  year: {\n    \"2-digit\": \"yy\",\n    numeric: \"yyyyy\"\n  },\n  month: {\n    numeric: \"M\",\n    \"2-digit\": \"MM\",\n    short: \"MMM\",\n    long: \"MMMM\"\n  },\n  day: {\n    numeric: \"d\",\n    \"2-digit\": \"dd\"\n  },\n  weekday: {\n    short: \"EEE\",\n    long: \"EEEE\"\n  },\n  dayperiod: \"a\",\n  dayPeriod: \"a\",\n  hour12: {\n    numeric: \"h\",\n    \"2-digit\": \"hh\"\n  },\n  hour24: {\n    numeric: \"H\",\n    \"2-digit\": \"HH\"\n  },\n  minute: {\n    numeric: \"m\",\n    \"2-digit\": \"mm\"\n  },\n  second: {\n    numeric: \"s\",\n    \"2-digit\": \"ss\"\n  },\n  timeZoneName: {\n    long: \"ZZZZZ\",\n    short: \"ZZZ\"\n  }\n};\nfunction tokenForPart(part, formatOpts, resolvedOpts) {\n  const {\n    type,\n    value\n  } = part;\n  if (type === \"literal\") {\n    const isSpace = /^\\s+$/.test(value);\n    return {\n      literal: !isSpace,\n      val: isSpace ? \" \" : value\n    };\n  }\n  const style = formatOpts[type];\n\n  // The user might have explicitly specified hour12 or hourCycle\n  // if so, respect their decision\n  // if not, refer back to the resolvedOpts, which are based on the locale\n  let actualType = type;\n  if (type === \"hour\") {\n    if (formatOpts.hour12 != null) {\n      actualType = formatOpts.hour12 ? \"hour12\" : \"hour24\";\n    } else if (formatOpts.hourCycle != null) {\n      if (formatOpts.hourCycle === \"h11\" || formatOpts.hourCycle === \"h12\") {\n        actualType = \"hour12\";\n      } else {\n        actualType = \"hour24\";\n      }\n    } else {\n      // tokens only differentiate between 24 hours or not,\n      // so we do not need to check hourCycle here, which is less supported anyways\n      actualType = resolvedOpts.hour12 ? \"hour12\" : \"hour24\";\n    }\n  }\n  let val = partTypeStyleToTokenVal[actualType];\n  if (typeof val === \"object\") {\n    val = val[style];\n  }\n  if (val) {\n    return {\n      literal: false,\n      val\n    };\n  }\n  return undefined;\n}\nfunction buildRegex(units) {\n  const re = units.map(u => u.regex).reduce((f, r) => `${f}(${r.source})`, \"\");\n  return [`^${re}$`, units];\n}\nfunction match(input, regex, handlers) {\n  const matches = input.match(regex);\n  if (matches) {\n    const all = {};\n    let matchIndex = 1;\n    for (const i in handlers) {\n      if (hasOwnProperty(handlers, i)) {\n        const h = handlers[i],\n          groups = h.groups ? h.groups + 1 : 1;\n        if (!h.literal && h.token) {\n          all[h.token.val[0]] = h.deser(matches.slice(matchIndex, matchIndex + groups));\n        }\n        matchIndex += groups;\n      }\n    }\n    return [matches, all];\n  } else {\n    return [matches, {}];\n  }\n}\nfunction dateTimeFromMatches(matches) {\n  const toField = token => {\n    switch (token) {\n      case \"S\":\n        return \"millisecond\";\n      case \"s\":\n        return \"second\";\n      case \"m\":\n        return \"minute\";\n      case \"h\":\n      case \"H\":\n        return \"hour\";\n      case \"d\":\n        return \"day\";\n      case \"o\":\n        return \"ordinal\";\n      case \"L\":\n      case \"M\":\n        return \"month\";\n      case \"y\":\n        return \"year\";\n      case \"E\":\n      case \"c\":\n        return \"weekday\";\n      case \"W\":\n        return \"weekNumber\";\n      case \"k\":\n        return \"weekYear\";\n      case \"q\":\n        return \"quarter\";\n      default:\n        return null;\n    }\n  };\n  let zone = null;\n  let specificOffset;\n  if (!isUndefined(matches.z)) {\n    zone = IANAZone.create(matches.z);\n  }\n  if (!isUndefined(matches.Z)) {\n    if (!zone) {\n      zone = new FixedOffsetZone(matches.Z);\n    }\n    specificOffset = matches.Z;\n  }\n  if (!isUndefined(matches.q)) {\n    matches.M = (matches.q - 1) * 3 + 1;\n  }\n  if (!isUndefined(matches.h)) {\n    if (matches.h < 12 && matches.a === 1) {\n      matches.h += 12;\n    } else if (matches.h === 12 && matches.a === 0) {\n      matches.h = 0;\n    }\n  }\n  if (matches.G === 0 && matches.y) {\n    matches.y = -matches.y;\n  }\n  if (!isUndefined(matches.u)) {\n    matches.S = parseMillis(matches.u);\n  }\n  const vals = Object.keys(matches).reduce((r, k) => {\n    const f = toField(k);\n    if (f) {\n      r[f] = matches[k];\n    }\n    return r;\n  }, {});\n  return [vals, zone, specificOffset];\n}\nlet dummyDateTimeCache = null;\nfunction getDummyDateTime() {\n  if (!dummyDateTimeCache) {\n    dummyDateTimeCache = DateTime.fromMillis(1555555555555);\n  }\n  return dummyDateTimeCache;\n}\nfunction maybeExpandMacroToken(token, locale) {\n  if (token.literal) {\n    return token;\n  }\n  const formatOpts = Formatter.macroTokenToFormatOpts(token.val);\n  const tokens = formatOptsToTokens(formatOpts, locale);\n  if (tokens == null || tokens.includes(undefined)) {\n    return token;\n  }\n  return tokens;\n}\nfunction expandMacroTokens(tokens, locale) {\n  return Array.prototype.concat(...tokens.map(t => maybeExpandMacroToken(t, locale)));\n}\n\n/**\n * @private\n */\n\nclass TokenParser {\n  constructor(locale, format) {\n    this.locale = locale;\n    this.format = format;\n    this.tokens = expandMacroTokens(Formatter.parseFormat(format), locale);\n    this.units = this.tokens.map(t => unitForToken(t, locale));\n    this.disqualifyingUnit = this.units.find(t => t.invalidReason);\n    if (!this.disqualifyingUnit) {\n      const [regexString, handlers] = buildRegex(this.units);\n      this.regex = RegExp(regexString, \"i\");\n      this.handlers = handlers;\n    }\n  }\n  explainFromTokens(input) {\n    if (!this.isValid) {\n      return {\n        input,\n        tokens: this.tokens,\n        invalidReason: this.invalidReason\n      };\n    } else {\n      const [rawMatches, matches] = match(input, this.regex, this.handlers),\n        [result, zone, specificOffset] = matches ? dateTimeFromMatches(matches) : [null, null, undefined];\n      if (hasOwnProperty(matches, \"a\") && hasOwnProperty(matches, \"H\")) {\n        throw new ConflictingSpecificationError(\"Can't include meridiem when specifying 24-hour format\");\n      }\n      return {\n        input,\n        tokens: this.tokens,\n        regex: this.regex,\n        rawMatches,\n        matches,\n        result,\n        zone,\n        specificOffset\n      };\n    }\n  }\n  get isValid() {\n    return !this.disqualifyingUnit;\n  }\n  get invalidReason() {\n    return this.disqualifyingUnit ? this.disqualifyingUnit.invalidReason : null;\n  }\n}\nfunction explainFromTokens(locale, input, format) {\n  const parser = new TokenParser(locale, format);\n  return parser.explainFromTokens(input);\n}\nfunction parseFromTokens(locale, input, format) {\n  const {\n    result,\n    zone,\n    specificOffset,\n    invalidReason\n  } = explainFromTokens(locale, input, format);\n  return [result, zone, specificOffset, invalidReason];\n}\nfunction formatOptsToTokens(formatOpts, locale) {\n  if (!formatOpts) {\n    return null;\n  }\n  const formatter = Formatter.create(locale, formatOpts);\n  const df = formatter.dtFormatter(getDummyDateTime());\n  const parts = df.formatToParts();\n  const resolvedOpts = df.resolvedOptions();\n  return parts.map(p => tokenForPart(p, formatOpts, resolvedOpts));\n}\n\nconst INVALID = \"Invalid DateTime\";\nconst MAX_DATE = 8.64e15;\nfunction unsupportedZone(zone) {\n  return new Invalid(\"unsupported zone\", `the zone \"${zone.name}\" is not supported`);\n}\n\n// we cache week data on the DT object and this intermediates the cache\n/**\n * @param {DateTime} dt\n */\nfunction possiblyCachedWeekData(dt) {\n  if (dt.weekData === null) {\n    dt.weekData = gregorianToWeek(dt.c);\n  }\n  return dt.weekData;\n}\n\n/**\n * @param {DateTime} dt\n */\nfunction possiblyCachedLocalWeekData(dt) {\n  if (dt.localWeekData === null) {\n    dt.localWeekData = gregorianToWeek(dt.c, dt.loc.getMinDaysInFirstWeek(), dt.loc.getStartOfWeek());\n  }\n  return dt.localWeekData;\n}\n\n// clone really means, \"make a new object with these modifications\". all \"setters\" really use this\n// to create a new object while only changing some of the properties\nfunction clone(inst, alts) {\n  const current = {\n    ts: inst.ts,\n    zone: inst.zone,\n    c: inst.c,\n    o: inst.o,\n    loc: inst.loc,\n    invalid: inst.invalid\n  };\n  return new DateTime({\n    ...current,\n    ...alts,\n    old: current\n  });\n}\n\n// find the right offset a given local time. The o input is our guess, which determines which\n// offset we'll pick in ambiguous cases (e.g. there are two 3 AMs b/c Fallback DST)\nfunction fixOffset(localTS, o, tz) {\n  // Our UTC time is just a guess because our offset is just a guess\n  let utcGuess = localTS - o * 60 * 1000;\n\n  // Test whether the zone matches the offset for this ts\n  const o2 = tz.offset(utcGuess);\n\n  // If so, offset didn't change and we're done\n  if (o === o2) {\n    return [utcGuess, o];\n  }\n\n  // If not, change the ts by the difference in the offset\n  utcGuess -= (o2 - o) * 60 * 1000;\n\n  // If that gives us the local time we want, we're done\n  const o3 = tz.offset(utcGuess);\n  if (o2 === o3) {\n    return [utcGuess, o2];\n  }\n\n  // If it's different, we're in a hole time. The offset has changed, but the we don't adjust the time\n  return [localTS - Math.min(o2, o3) * 60 * 1000, Math.max(o2, o3)];\n}\n\n// convert an epoch timestamp into a calendar object with the given offset\nfunction tsToObj(ts, offset) {\n  ts += offset * 60 * 1000;\n  const d = new Date(ts);\n  return {\n    year: d.getUTCFullYear(),\n    month: d.getUTCMonth() + 1,\n    day: d.getUTCDate(),\n    hour: d.getUTCHours(),\n    minute: d.getUTCMinutes(),\n    second: d.getUTCSeconds(),\n    millisecond: d.getUTCMilliseconds()\n  };\n}\n\n// convert a calendar object to a epoch timestamp\nfunction objToTS(obj, offset, zone) {\n  return fixOffset(objToLocalTS(obj), offset, zone);\n}\n\n// create a new DT instance by adding a duration, adjusting for DSTs\nfunction adjustTime(inst, dur) {\n  const oPre = inst.o,\n    year = inst.c.year + Math.trunc(dur.years),\n    month = inst.c.month + Math.trunc(dur.months) + Math.trunc(dur.quarters) * 3,\n    c = {\n      ...inst.c,\n      year,\n      month,\n      day: Math.min(inst.c.day, daysInMonth(year, month)) + Math.trunc(dur.days) + Math.trunc(dur.weeks) * 7\n    },\n    millisToAdd = Duration.fromObject({\n      years: dur.years - Math.trunc(dur.years),\n      quarters: dur.quarters - Math.trunc(dur.quarters),\n      months: dur.months - Math.trunc(dur.months),\n      weeks: dur.weeks - Math.trunc(dur.weeks),\n      days: dur.days - Math.trunc(dur.days),\n      hours: dur.hours,\n      minutes: dur.minutes,\n      seconds: dur.seconds,\n      milliseconds: dur.milliseconds\n    }).as(\"milliseconds\"),\n    localTS = objToLocalTS(c);\n  let [ts, o] = fixOffset(localTS, oPre, inst.zone);\n  if (millisToAdd !== 0) {\n    ts += millisToAdd;\n    // that could have changed the offset by going over a DST, but we want to keep the ts the same\n    o = inst.zone.offset(ts);\n  }\n  return {\n    ts,\n    o\n  };\n}\n\n// helper useful in turning the results of parsing into real dates\n// by handling the zone options\nfunction parseDataToDateTime(parsed, parsedZone, opts, format, text, specificOffset) {\n  const {\n    setZone,\n    zone\n  } = opts;\n  if (parsed && Object.keys(parsed).length !== 0 || parsedZone) {\n    const interpretationZone = parsedZone || zone,\n      inst = DateTime.fromObject(parsed, {\n        ...opts,\n        zone: interpretationZone,\n        specificOffset\n      });\n    return setZone ? inst : inst.setZone(zone);\n  } else {\n    return DateTime.invalid(new Invalid(\"unparsable\", `the input \"${text}\" can't be parsed as ${format}`));\n  }\n}\n\n// if you want to output a technical format (e.g. RFC 2822), this helper\n// helps handle the details\nfunction toTechFormat(dt, format, allowZ = true) {\n  return dt.isValid ? Formatter.create(Locale.create(\"en-US\"), {\n    allowZ,\n    forceSimple: true\n  }).formatDateTimeFromString(dt, format) : null;\n}\nfunction toISODate(o, extended, precision) {\n  const longFormat = o.c.year > 9999 || o.c.year < 0;\n  let c = \"\";\n  if (longFormat && o.c.year >= 0) c += \"+\";\n  c += padStart(o.c.year, longFormat ? 6 : 4);\n  if (precision === \"year\") return c;\n  if (extended) {\n    c += \"-\";\n    c += padStart(o.c.month);\n    if (precision === \"month\") return c;\n    c += \"-\";\n  } else {\n    c += padStart(o.c.month);\n    if (precision === \"month\") return c;\n  }\n  c += padStart(o.c.day);\n  return c;\n}\nfunction toISOTime(o, extended, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone, precision) {\n  let showSeconds = !suppressSeconds || o.c.millisecond !== 0 || o.c.second !== 0,\n    c = \"\";\n  switch (precision) {\n    case \"day\":\n    case \"month\":\n    case \"year\":\n      break;\n    default:\n      c += padStart(o.c.hour);\n      if (precision === \"hour\") break;\n      if (extended) {\n        c += \":\";\n        c += padStart(o.c.minute);\n        if (precision === \"minute\") break;\n        if (showSeconds) {\n          c += \":\";\n          c += padStart(o.c.second);\n        }\n      } else {\n        c += padStart(o.c.minute);\n        if (precision === \"minute\") break;\n        if (showSeconds) {\n          c += padStart(o.c.second);\n        }\n      }\n      if (precision === \"second\") break;\n      if (showSeconds && (!suppressMilliseconds || o.c.millisecond !== 0)) {\n        c += \".\";\n        c += padStart(o.c.millisecond, 3);\n      }\n  }\n  if (includeOffset) {\n    if (o.isOffsetFixed && o.offset === 0 && !extendedZone) {\n      c += \"Z\";\n    } else if (o.o < 0) {\n      c += \"-\";\n      c += padStart(Math.trunc(-o.o / 60));\n      c += \":\";\n      c += padStart(Math.trunc(-o.o % 60));\n    } else {\n      c += \"+\";\n      c += padStart(Math.trunc(o.o / 60));\n      c += \":\";\n      c += padStart(Math.trunc(o.o % 60));\n    }\n  }\n  if (extendedZone) {\n    c += \"[\" + o.zone.ianaName + \"]\";\n  }\n  return c;\n}\n\n// defaults for unspecified units in the supported calendars\nconst defaultUnitValues = {\n    month: 1,\n    day: 1,\n    hour: 0,\n    minute: 0,\n    second: 0,\n    millisecond: 0\n  },\n  defaultWeekUnitValues = {\n    weekNumber: 1,\n    weekday: 1,\n    hour: 0,\n    minute: 0,\n    second: 0,\n    millisecond: 0\n  },\n  defaultOrdinalUnitValues = {\n    ordinal: 1,\n    hour: 0,\n    minute: 0,\n    second: 0,\n    millisecond: 0\n  };\n\n// Units in the supported calendars, sorted by bigness\nconst orderedUnits = [\"year\", \"month\", \"day\", \"hour\", \"minute\", \"second\", \"millisecond\"],\n  orderedWeekUnits = [\"weekYear\", \"weekNumber\", \"weekday\", \"hour\", \"minute\", \"second\", \"millisecond\"],\n  orderedOrdinalUnits = [\"year\", \"ordinal\", \"hour\", \"minute\", \"second\", \"millisecond\"];\n\n// standardize case and plurality in units\nfunction normalizeUnit(unit) {\n  const normalized = {\n    year: \"year\",\n    years: \"year\",\n    month: \"month\",\n    months: \"month\",\n    day: \"day\",\n    days: \"day\",\n    hour: \"hour\",\n    hours: \"hour\",\n    minute: \"minute\",\n    minutes: \"minute\",\n    quarter: \"quarter\",\n    quarters: \"quarter\",\n    second: \"second\",\n    seconds: \"second\",\n    millisecond: \"millisecond\",\n    milliseconds: \"millisecond\",\n    weekday: \"weekday\",\n    weekdays: \"weekday\",\n    weeknumber: \"weekNumber\",\n    weeksnumber: \"weekNumber\",\n    weeknumbers: \"weekNumber\",\n    weekyear: \"weekYear\",\n    weekyears: \"weekYear\",\n    ordinal: \"ordinal\"\n  }[unit.toLowerCase()];\n  if (!normalized) throw new InvalidUnitError(unit);\n  return normalized;\n}\nfunction normalizeUnitWithLocalWeeks(unit) {\n  switch (unit.toLowerCase()) {\n    case \"localweekday\":\n    case \"localweekdays\":\n      return \"localWeekday\";\n    case \"localweeknumber\":\n    case \"localweeknumbers\":\n      return \"localWeekNumber\";\n    case \"localweekyear\":\n    case \"localweekyears\":\n      return \"localWeekYear\";\n    default:\n      return normalizeUnit(unit);\n  }\n}\n\n// cache offsets for zones based on the current timestamp when this function is\n// first called. When we are handling a datetime from components like (year,\n// month, day, hour) in a time zone, we need a guess about what the timezone\n// offset is so that we can convert into a UTC timestamp. One way is to find the\n// offset of now in the zone. The actual date may have a different offset (for\n// example, if we handle a date in June while we're in December in a zone that\n// observes DST), but we can check and adjust that.\n//\n// When handling many dates, calculating the offset for now every time is\n// expensive. It's just a guess, so we can cache the offset to use even if we\n// are right on a time change boundary (we'll just correct in the other\n// direction). Using a timestamp from first read is a slight optimization for\n// handling dates close to the current date, since those dates will usually be\n// in the same offset (we could set the timestamp statically, instead). We use a\n// single timestamp for all zones to make things a bit more predictable.\n//\n// This is safe for quickDT (used by local() and utc()) because we don't fill in\n// higher-order units from tsNow (as we do in fromObject, this requires that\n// offset is calculated from tsNow).\n/**\n * @param {Zone} zone\n * @return {number}\n */\nfunction guessOffsetForZone(zone) {\n  if (zoneOffsetTs === undefined) {\n    zoneOffsetTs = Settings.now();\n  }\n\n  // Do not cache anything but IANA zones, because it is not safe to do so.\n  // Guessing an offset which is not present in the zone can cause wrong results from fixOffset\n  if (zone.type !== \"iana\") {\n    return zone.offset(zoneOffsetTs);\n  }\n  const zoneName = zone.name;\n  let offsetGuess = zoneOffsetGuessCache.get(zoneName);\n  if (offsetGuess === undefined) {\n    offsetGuess = zone.offset(zoneOffsetTs);\n    zoneOffsetGuessCache.set(zoneName, offsetGuess);\n  }\n  return offsetGuess;\n}\n\n// this is a dumbed down version of fromObject() that runs about 60% faster\n// but doesn't do any validation, makes a bunch of assumptions about what units\n// are present, and so on.\nfunction quickDT(obj, opts) {\n  const zone = normalizeZone(opts.zone, Settings.defaultZone);\n  if (!zone.isValid) {\n    return DateTime.invalid(unsupportedZone(zone));\n  }\n  const loc = Locale.fromObject(opts);\n  let ts, o;\n\n  // assume we have the higher-order units\n  if (!isUndefined(obj.year)) {\n    for (const u of orderedUnits) {\n      if (isUndefined(obj[u])) {\n        obj[u] = defaultUnitValues[u];\n      }\n    }\n    const invalid = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj);\n    if (invalid) {\n      return DateTime.invalid(invalid);\n    }\n    const offsetProvis = guessOffsetForZone(zone);\n    [ts, o] = objToTS(obj, offsetProvis, zone);\n  } else {\n    ts = Settings.now();\n  }\n  return new DateTime({\n    ts,\n    zone,\n    loc,\n    o\n  });\n}\nfunction diffRelative(start, end, opts) {\n  const round = isUndefined(opts.round) ? true : opts.round,\n    rounding = isUndefined(opts.rounding) ? \"trunc\" : opts.rounding,\n    format = (c, unit) => {\n      c = roundTo(c, round || opts.calendary ? 0 : 2, opts.calendary ? \"round\" : rounding);\n      const formatter = end.loc.clone(opts).relFormatter(opts);\n      return formatter.format(c, unit);\n    },\n    differ = unit => {\n      if (opts.calendary) {\n        if (!end.hasSame(start, unit)) {\n          return end.startOf(unit).diff(start.startOf(unit), unit).get(unit);\n        } else return 0;\n      } else {\n        return end.diff(start, unit).get(unit);\n      }\n    };\n  if (opts.unit) {\n    return format(differ(opts.unit), opts.unit);\n  }\n  for (const unit of opts.units) {\n    const count = differ(unit);\n    if (Math.abs(count) >= 1) {\n      return format(count, unit);\n    }\n  }\n  return format(start > end ? -0 : 0, opts.units[opts.units.length - 1]);\n}\nfunction lastOpts(argList) {\n  let opts = {},\n    args;\n  if (argList.length > 0 && typeof argList[argList.length - 1] === \"object\") {\n    opts = argList[argList.length - 1];\n    args = Array.from(argList).slice(0, argList.length - 1);\n  } else {\n    args = Array.from(argList);\n  }\n  return [opts, args];\n}\n\n/**\n * Timestamp to use for cached zone offset guesses (exposed for test)\n */\nlet zoneOffsetTs;\n/**\n * Cache for zone offset guesses (exposed for test).\n *\n * This optimizes quickDT via guessOffsetForZone to avoid repeated calls of\n * zone.offset().\n */\nconst zoneOffsetGuessCache = new Map();\n\n/**\n * A DateTime is an immutable data structure representing a specific date and time and accompanying methods. It contains class and instance methods for creating, parsing, interrogating, transforming, and formatting them.\n *\n * A DateTime comprises of:\n * * A timestamp. Each DateTime instance refers to a specific millisecond of the Unix epoch.\n * * A time zone. Each instance is considered in the context of a specific zone (by default the local system's zone).\n * * Configuration properties that effect how output strings are formatted, such as `locale`, `numberingSystem`, and `outputCalendar`.\n *\n * Here is a brief overview of the most commonly used functionality it provides:\n *\n * * **Creation**: To create a DateTime from its components, use one of its factory class methods: {@link DateTime.local}, {@link DateTime.utc}, and (most flexibly) {@link DateTime.fromObject}. To create one from a standard string format, use {@link DateTime.fromISO}, {@link DateTime.fromHTTP}, and {@link DateTime.fromRFC2822}. To create one from a custom string format, use {@link DateTime.fromFormat}. To create one from a native JS date, use {@link DateTime.fromJSDate}.\n * * **Gregorian calendar and time**: To examine the Gregorian properties of a DateTime individually (i.e as opposed to collectively through {@link DateTime#toObject}), use the {@link DateTime#year}, {@link DateTime#month},\n * {@link DateTime#day}, {@link DateTime#hour}, {@link DateTime#minute}, {@link DateTime#second}, {@link DateTime#millisecond} accessors.\n * * **Week calendar**: For ISO week calendar attributes, see the {@link DateTime#weekYear}, {@link DateTime#weekNumber}, and {@link DateTime#weekday} accessors.\n * * **Configuration** See the {@link DateTime#locale} and {@link DateTime#numberingSystem} accessors.\n * * **Transformation**: To transform the DateTime into other DateTimes, use {@link DateTime#set}, {@link DateTime#reconfigure}, {@link DateTime#setZone}, {@link DateTime#setLocale}, {@link DateTime.plus}, {@link DateTime#minus}, {@link DateTime#endOf}, {@link DateTime#startOf}, {@link DateTime#toUTC}, and {@link DateTime#toLocal}.\n * * **Output**: To convert the DateTime to other representations, use the {@link DateTime#toRelative}, {@link DateTime#toRelativeCalendar}, {@link DateTime#toJSON}, {@link DateTime#toISO}, {@link DateTime#toHTTP}, {@link DateTime#toObject}, {@link DateTime#toRFC2822}, {@link DateTime#toString}, {@link DateTime#toLocaleString}, {@link DateTime#toFormat}, {@link DateTime#toMillis} and {@link DateTime#toJSDate}.\n *\n * There's plenty others documented below. In addition, for more information on subtler topics like internationalization, time zones, alternative calendars, validity, and so on, see the external documentation.\n */\nclass DateTime {\n  /**\n   * @access private\n   */\n  constructor(config) {\n    const zone = config.zone || Settings.defaultZone;\n    let invalid = config.invalid || (Number.isNaN(config.ts) ? new Invalid(\"invalid input\") : null) || (!zone.isValid ? unsupportedZone(zone) : null);\n    /**\n     * @access private\n     */\n    this.ts = isUndefined(config.ts) ? Settings.now() : config.ts;\n    let c = null,\n      o = null;\n    if (!invalid) {\n      const unchanged = config.old && config.old.ts === this.ts && config.old.zone.equals(zone);\n      if (unchanged) {\n        [c, o] = [config.old.c, config.old.o];\n      } else {\n        // If an offset has been passed and we have not been called from\n        // clone(), we can trust it and avoid the offset calculation.\n        const ot = isNumber(config.o) && !config.old ? config.o : zone.offset(this.ts);\n        c = tsToObj(this.ts, ot);\n        invalid = Number.isNaN(c.year) ? new Invalid(\"invalid input\") : null;\n        c = invalid ? null : c;\n        o = invalid ? null : ot;\n      }\n    }\n\n    /**\n     * @access private\n     */\n    this._zone = zone;\n    /**\n     * @access private\n     */\n    this.loc = config.loc || Locale.create();\n    /**\n     * @access private\n     */\n    this.invalid = invalid;\n    /**\n     * @access private\n     */\n    this.weekData = null;\n    /**\n     * @access private\n     */\n    this.localWeekData = null;\n    /**\n     * @access private\n     */\n    this.c = c;\n    /**\n     * @access private\n     */\n    this.o = o;\n    /**\n     * @access private\n     */\n    this.isLuxonDateTime = true;\n  }\n\n  // CONSTRUCT\n\n  /**\n   * Create a DateTime for the current instant, in the system's time zone.\n   *\n   * Use Settings to override these default values if needed.\n   * @example DateTime.now().toISO() //~> now in the ISO format\n   * @return {DateTime}\n   */\n  static now() {\n    return new DateTime({});\n  }\n\n  /**\n   * Create a local DateTime\n   * @param {number} [year] - The calendar year. If omitted (as in, call `local()` with no arguments), the current time will be used\n   * @param {number} [month=1] - The month, 1-indexed\n   * @param {number} [day=1] - The day of the month, 1-indexed\n   * @param {number} [hour=0] - The hour of the day, in 24-hour time\n   * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59\n   * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59\n   * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999\n   * @example DateTime.local()                                  //~> now\n   * @example DateTime.local({ zone: \"America/New_York\" })      //~> now, in US east coast time\n   * @example DateTime.local(2017)                              //~> 2017-01-01T00:00:00\n   * @example DateTime.local(2017, 3)                           //~> 2017-03-01T00:00:00\n   * @example DateTime.local(2017, 3, 12, { locale: \"fr\" })     //~> 2017-03-12T00:00:00, with a French locale\n   * @example DateTime.local(2017, 3, 12, 5)                    //~> 2017-03-12T05:00:00\n   * @example DateTime.local(2017, 3, 12, 5, { zone: \"utc\" })   //~> 2017-03-12T05:00:00, in UTC\n   * @example DateTime.local(2017, 3, 12, 5, 45)                //~> 2017-03-12T05:45:00\n   * @example DateTime.local(2017, 3, 12, 5, 45, 10)            //~> 2017-03-12T05:45:10\n   * @example DateTime.local(2017, 3, 12, 5, 45, 10, 765)       //~> 2017-03-12T05:45:10.765\n   * @return {DateTime}\n   */\n  static local() {\n    const [opts, args] = lastOpts(arguments),\n      [year, month, day, hour, minute, second, millisecond] = args;\n    return quickDT({\n      year,\n      month,\n      day,\n      hour,\n      minute,\n      second,\n      millisecond\n    }, opts);\n  }\n\n  /**\n   * Create a DateTime in UTC\n   * @param {number} [year] - The calendar year. If omitted (as in, call `utc()` with no arguments), the current time will be used\n   * @param {number} [month=1] - The month, 1-indexed\n   * @param {number} [day=1] - The day of the month\n   * @param {number} [hour=0] - The hour of the day, in 24-hour time\n   * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59\n   * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59\n   * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999\n   * @param {Object} options - configuration options for the DateTime\n   * @param {string} [options.locale] - a locale to set on the resulting DateTime instance\n   * @param {string} [options.outputCalendar] - the output calendar to set on the resulting DateTime instance\n   * @param {string} [options.numberingSystem] - the numbering system to set on the resulting DateTime instance\n   * @param {string} [options.weekSettings] - the week settings to set on the resulting DateTime instance\n   * @example DateTime.utc()                                              //~> now\n   * @example DateTime.utc(2017)                                          //~> 2017-01-01T00:00:00Z\n   * @example DateTime.utc(2017, 3)                                       //~> 2017-03-01T00:00:00Z\n   * @example DateTime.utc(2017, 3, 12)                                   //~> 2017-03-12T00:00:00Z\n   * @example DateTime.utc(2017, 3, 12, 5)                                //~> 2017-03-12T05:00:00Z\n   * @example DateTime.utc(2017, 3, 12, 5, 45)                            //~> 2017-03-12T05:45:00Z\n   * @example DateTime.utc(2017, 3, 12, 5, 45, { locale: \"fr\" })          //~> 2017-03-12T05:45:00Z with a French locale\n   * @example DateTime.utc(2017, 3, 12, 5, 45, 10)                        //~> 2017-03-12T05:45:10Z\n   * @example DateTime.utc(2017, 3, 12, 5, 45, 10, 765, { locale: \"fr\" }) //~> 2017-03-12T05:45:10.765Z with a French locale\n   * @return {DateTime}\n   */\n  static utc() {\n    const [opts, args] = lastOpts(arguments),\n      [year, month, day, hour, minute, second, millisecond] = args;\n    opts.zone = FixedOffsetZone.utcInstance;\n    return quickDT({\n      year,\n      month,\n      day,\n      hour,\n      minute,\n      second,\n      millisecond\n    }, opts);\n  }\n\n  /**\n   * Create a DateTime from a JavaScript Date object. Uses the default zone.\n   * @param {Date} date - a JavaScript Date object\n   * @param {Object} options - configuration options for the DateTime\n   * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into\n   * @return {DateTime}\n   */\n  static fromJSDate(date, options = {}) {\n    const ts = isDate(date) ? date.valueOf() : NaN;\n    if (Number.isNaN(ts)) {\n      return DateTime.invalid(\"invalid input\");\n    }\n    const zoneToUse = normalizeZone(options.zone, Settings.defaultZone);\n    if (!zoneToUse.isValid) {\n      return DateTime.invalid(unsupportedZone(zoneToUse));\n    }\n    return new DateTime({\n      ts: ts,\n      zone: zoneToUse,\n      loc: Locale.fromObject(options)\n    });\n  }\n\n  /**\n   * Create a DateTime from a number of milliseconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone.\n   * @param {number} milliseconds - a number of milliseconds since 1970 UTC\n   * @param {Object} options - configuration options for the DateTime\n   * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into\n   * @param {string} [options.locale] - a locale to set on the resulting DateTime instance\n   * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance\n   * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance\n   * @param {string} options.weekSettings - the week settings to set on the resulting DateTime instance\n   * @return {DateTime}\n   */\n  static fromMillis(milliseconds, options = {}) {\n    if (!isNumber(milliseconds)) {\n      throw new InvalidArgumentError(`fromMillis requires a numerical input, but received a ${typeof milliseconds} with value ${milliseconds}`);\n    } else if (milliseconds < -MAX_DATE || milliseconds > MAX_DATE) {\n      // this isn't perfect because we can still end up out of range because of additional shifting, but it's a start\n      return DateTime.invalid(\"Timestamp out of range\");\n    } else {\n      return new DateTime({\n        ts: milliseconds,\n        zone: normalizeZone(options.zone, Settings.defaultZone),\n        loc: Locale.fromObject(options)\n      });\n    }\n  }\n\n  /**\n   * Create a DateTime from a number of seconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone.\n   * @param {number} seconds - a number of seconds since 1970 UTC\n   * @param {Object} options - configuration options for the DateTime\n   * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into\n   * @param {string} [options.locale] - a locale to set on the resulting DateTime instance\n   * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance\n   * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance\n   * @param {string} options.weekSettings - the week settings to set on the resulting DateTime instance\n   * @return {DateTime}\n   */\n  static fromSeconds(seconds, options = {}) {\n    if (!isNumber(seconds)) {\n      throw new InvalidArgumentError(\"fromSeconds requires a numerical input\");\n    } else {\n      return new DateTime({\n        ts: seconds * 1000,\n        zone: normalizeZone(options.zone, Settings.defaultZone),\n        loc: Locale.fromObject(options)\n      });\n    }\n  }\n\n  /**\n   * Create a DateTime from a JavaScript object with keys like 'year' and 'hour' with reasonable defaults.\n   * @param {Object} obj - the object to create the DateTime from\n   * @param {number} obj.year - a year, such as 1987\n   * @param {number} obj.month - a month, 1-12\n   * @param {number} obj.day - a day of the month, 1-31, depending on the month\n   * @param {number} obj.ordinal - day of the year, 1-365 or 366\n   * @param {number} obj.weekYear - an ISO week year\n   * @param {number} obj.weekNumber - an ISO week number, between 1 and 52 or 53, depending on the year\n   * @param {number} obj.weekday - an ISO weekday, 1-7, where 1 is Monday and 7 is Sunday\n   * @param {number} obj.localWeekYear - a week year, according to the locale\n   * @param {number} obj.localWeekNumber - a week number, between 1 and 52 or 53, depending on the year, according to the locale\n   * @param {number} obj.localWeekday - a weekday, 1-7, where 1 is the first and 7 is the last day of the week, according to the locale\n   * @param {number} obj.hour - hour of the day, 0-23\n   * @param {number} obj.minute - minute of the hour, 0-59\n   * @param {number} obj.second - second of the minute, 0-59\n   * @param {number} obj.millisecond - millisecond of the second, 0-999\n   * @param {Object} opts - options for creating this DateTime\n   * @param {string|Zone} [opts.zone='local'] - interpret the numbers in the context of a particular zone. Can take any value taken as the first argument to setZone()\n   * @param {string} [opts.locale='system\\'s locale'] - a locale to set on the resulting DateTime instance\n   * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance\n   * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance\n   * @param {string} opts.weekSettings - the week settings to set on the resulting DateTime instance\n   * @example DateTime.fromObject({ year: 1982, month: 5, day: 25}).toISODate() //=> '1982-05-25'\n   * @example DateTime.fromObject({ year: 1982 }).toISODate() //=> '1982-01-01'\n   * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }) //~> today at 10:26:06\n   * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'utc' }),\n   * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'local' })\n   * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'America/New_York' })\n   * @example DateTime.fromObject({ weekYear: 2016, weekNumber: 2, weekday: 3 }).toISODate() //=> '2016-01-13'\n   * @example DateTime.fromObject({ localWeekYear: 2022, localWeekNumber: 1, localWeekday: 1 }, { locale: \"en-US\" }).toISODate() //=> '2021-12-26'\n   * @return {DateTime}\n   */\n  static fromObject(obj, opts = {}) {\n    obj = obj || {};\n    const zoneToUse = normalizeZone(opts.zone, Settings.defaultZone);\n    if (!zoneToUse.isValid) {\n      return DateTime.invalid(unsupportedZone(zoneToUse));\n    }\n    const loc = Locale.fromObject(opts);\n    const normalized = normalizeObject(obj, normalizeUnitWithLocalWeeks);\n    const {\n      minDaysInFirstWeek,\n      startOfWeek\n    } = usesLocalWeekValues(normalized, loc);\n    const tsNow = Settings.now(),\n      offsetProvis = !isUndefined(opts.specificOffset) ? opts.specificOffset : zoneToUse.offset(tsNow),\n      containsOrdinal = !isUndefined(normalized.ordinal),\n      containsGregorYear = !isUndefined(normalized.year),\n      containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day),\n      containsGregor = containsGregorYear || containsGregorMD,\n      definiteWeekDef = normalized.weekYear || normalized.weekNumber;\n\n    // cases:\n    // just a weekday -> this week's instance of that weekday, no worries\n    // (gregorian data or ordinal) + (weekYear or weekNumber) -> error\n    // (gregorian month or day) + ordinal -> error\n    // otherwise just use weeks or ordinals or gregorian, depending on what's specified\n\n    if ((containsGregor || containsOrdinal) && definiteWeekDef) {\n      throw new ConflictingSpecificationError(\"Can't mix weekYear/weekNumber units with year/month/day or ordinals\");\n    }\n    if (containsGregorMD && containsOrdinal) {\n      throw new ConflictingSpecificationError(\"Can't mix ordinal dates with month/day\");\n    }\n    const useWeekData = definiteWeekDef || normalized.weekday && !containsGregor;\n\n    // configure ourselves to deal with gregorian dates or week stuff\n    let units,\n      defaultValues,\n      objNow = tsToObj(tsNow, offsetProvis);\n    if (useWeekData) {\n      units = orderedWeekUnits;\n      defaultValues = defaultWeekUnitValues;\n      objNow = gregorianToWeek(objNow, minDaysInFirstWeek, startOfWeek);\n    } else if (containsOrdinal) {\n      units = orderedOrdinalUnits;\n      defaultValues = defaultOrdinalUnitValues;\n      objNow = gregorianToOrdinal(objNow);\n    } else {\n      units = orderedUnits;\n      defaultValues = defaultUnitValues;\n    }\n\n    // set default values for missing stuff\n    let foundFirst = false;\n    for (const u of units) {\n      const v = normalized[u];\n      if (!isUndefined(v)) {\n        foundFirst = true;\n      } else if (foundFirst) {\n        normalized[u] = defaultValues[u];\n      } else {\n        normalized[u] = objNow[u];\n      }\n    }\n\n    // make sure the values we have are in range\n    const higherOrderInvalid = useWeekData ? hasInvalidWeekData(normalized, minDaysInFirstWeek, startOfWeek) : containsOrdinal ? hasInvalidOrdinalData(normalized) : hasInvalidGregorianData(normalized),\n      invalid = higherOrderInvalid || hasInvalidTimeData(normalized);\n    if (invalid) {\n      return DateTime.invalid(invalid);\n    }\n\n    // compute the actual time\n    const gregorian = useWeekData ? weekToGregorian(normalized, minDaysInFirstWeek, startOfWeek) : containsOrdinal ? ordinalToGregorian(normalized) : normalized,\n      [tsFinal, offsetFinal] = objToTS(gregorian, offsetProvis, zoneToUse),\n      inst = new DateTime({\n        ts: tsFinal,\n        zone: zoneToUse,\n        o: offsetFinal,\n        loc\n      });\n\n    // gregorian data + weekday serves only to validate\n    if (normalized.weekday && containsGregor && obj.weekday !== inst.weekday) {\n      return DateTime.invalid(\"mismatched weekday\", `you can't specify both a weekday of ${normalized.weekday} and a date of ${inst.toISO()}`);\n    }\n    if (!inst.isValid) {\n      return DateTime.invalid(inst.invalid);\n    }\n    return inst;\n  }\n\n  /**\n   * Create a DateTime from an ISO 8601 string\n   * @param {string} text - the ISO string\n   * @param {Object} opts - options to affect the creation\n   * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the time to this zone\n   * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one\n   * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance\n   * @param {string} [opts.outputCalendar] - the output calendar to set on the resulting DateTime instance\n   * @param {string} [opts.numberingSystem] - the numbering system to set on the resulting DateTime instance\n   * @param {string} [opts.weekSettings] - the week settings to set on the resulting DateTime instance\n   * @example DateTime.fromISO('2016-05-25T09:08:34.123')\n   * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00')\n   * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00', {setZone: true})\n   * @example DateTime.fromISO('2016-05-25T09:08:34.123', {zone: 'utc'})\n   * @example DateTime.fromISO('2016-W05-4')\n   * @return {DateTime}\n   */\n  static fromISO(text, opts = {}) {\n    const [vals, parsedZone] = parseISODate(text);\n    return parseDataToDateTime(vals, parsedZone, opts, \"ISO 8601\", text);\n  }\n\n  /**\n   * Create a DateTime from an RFC 2822 string\n   * @param {string} text - the RFC 2822 string\n   * @param {Object} opts - options to affect the creation\n   * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since the offset is always specified in the string itself, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in.\n   * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one\n   * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance\n   * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance\n   * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance\n   * @param {string} opts.weekSettings - the week settings to set on the resulting DateTime instance\n   * @example DateTime.fromRFC2822('25 Nov 2016 13:23:12 GMT')\n   * @example DateTime.fromRFC2822('Fri, 25 Nov 2016 13:23:12 +0600')\n   * @example DateTime.fromRFC2822('25 Nov 2016 13:23 Z')\n   * @return {DateTime}\n   */\n  static fromRFC2822(text, opts = {}) {\n    const [vals, parsedZone] = parseRFC2822Date(text);\n    return parseDataToDateTime(vals, parsedZone, opts, \"RFC 2822\", text);\n  }\n\n  /**\n   * Create a DateTime from an HTTP header date\n   * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1\n   * @param {string} text - the HTTP header date\n   * @param {Object} opts - options to affect the creation\n   * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since HTTP dates are always in UTC, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in.\n   * @param {boolean} [opts.setZone=false] - override the zone with the fixed-offset zone specified in the string. For HTTP dates, this is always UTC, so this option is equivalent to setting the `zone` option to 'utc', but this option is included for consistency with similar methods.\n   * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance\n   * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance\n   * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance\n   * @param {string} opts.weekSettings - the week settings to set on the resulting DateTime instance\n   * @example DateTime.fromHTTP('Sun, 06 Nov 1994 08:49:37 GMT')\n   * @example DateTime.fromHTTP('Sunday, 06-Nov-94 08:49:37 GMT')\n   * @example DateTime.fromHTTP('Sun Nov  6 08:49:37 1994')\n   * @return {DateTime}\n   */\n  static fromHTTP(text, opts = {}) {\n    const [vals, parsedZone] = parseHTTPDate(text);\n    return parseDataToDateTime(vals, parsedZone, opts, \"HTTP\", opts);\n  }\n\n  /**\n   * Create a DateTime from an input string and format string.\n   * Defaults to en-US if no locale has been specified, regardless of the system's locale. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/parsing?id=table-of-tokens).\n   * @param {string} text - the string to parse\n   * @param {string} fmt - the format the string is expected to be in (see the link below for the formats)\n   * @param {Object} opts - options to affect the creation\n   * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone\n   * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one\n   * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale\n   * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system\n   * @param {string} opts.weekSettings - the week settings to set on the resulting DateTime instance\n   * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance\n   * @return {DateTime}\n   */\n  static fromFormat(text, fmt, opts = {}) {\n    if (isUndefined(text) || isUndefined(fmt)) {\n      throw new InvalidArgumentError(\"fromFormat requires an input string and a format\");\n    }\n    const {\n        locale = null,\n        numberingSystem = null\n      } = opts,\n      localeToUse = Locale.fromOpts({\n        locale,\n        numberingSystem,\n        defaultToEN: true\n      }),\n      [vals, parsedZone, specificOffset, invalid] = parseFromTokens(localeToUse, text, fmt);\n    if (invalid) {\n      return DateTime.invalid(invalid);\n    } else {\n      return parseDataToDateTime(vals, parsedZone, opts, `format ${fmt}`, text, specificOffset);\n    }\n  }\n\n  /**\n   * @deprecated use fromFormat instead\n   */\n  static fromString(text, fmt, opts = {}) {\n    return DateTime.fromFormat(text, fmt, opts);\n  }\n\n  /**\n   * Create a DateTime from a SQL date, time, or datetime\n   * Defaults to en-US if no locale has been specified, regardless of the system's locale\n   * @param {string} text - the string to parse\n   * @param {Object} opts - options to affect the creation\n   * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone\n   * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one\n   * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale\n   * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system\n   * @param {string} opts.weekSettings - the week settings to set on the resulting DateTime instance\n   * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance\n   * @example DateTime.fromSQL('2017-05-15')\n   * @example DateTime.fromSQL('2017-05-15 09:12:34')\n   * @example DateTime.fromSQL('2017-05-15 09:12:34.342')\n   * @example DateTime.fromSQL('2017-05-15 09:12:34.342+06:00')\n   * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles')\n   * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles', { setZone: true })\n   * @example DateTime.fromSQL('2017-05-15 09:12:34.342', { zone: 'America/Los_Angeles' })\n   * @example DateTime.fromSQL('09:12:34.342')\n   * @return {DateTime}\n   */\n  static fromSQL(text, opts = {}) {\n    const [vals, parsedZone] = parseSQL(text);\n    return parseDataToDateTime(vals, parsedZone, opts, \"SQL\", text);\n  }\n\n  /**\n   * Create an invalid DateTime.\n   * @param {string} reason - simple string of why this DateTime is invalid. Should not contain parameters or anything else data-dependent.\n   * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information\n   * @return {DateTime}\n   */\n  static invalid(reason, explanation = null) {\n    if (!reason) {\n      throw new InvalidArgumentError(\"need to specify a reason the DateTime is invalid\");\n    }\n    const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);\n    if (Settings.throwOnInvalid) {\n      throw new InvalidDateTimeError(invalid);\n    } else {\n      return new DateTime({\n        invalid\n      });\n    }\n  }\n\n  /**\n   * Check if an object is an instance of DateTime. Works across context boundaries\n   * @param {object} o\n   * @return {boolean}\n   */\n  static isDateTime(o) {\n    return o && o.isLuxonDateTime || false;\n  }\n\n  /**\n   * Produce the format string for a set of options\n   * @param formatOpts\n   * @param localeOpts\n   * @returns {string}\n   */\n  static parseFormatForOpts(formatOpts, localeOpts = {}) {\n    const tokenList = formatOptsToTokens(formatOpts, Locale.fromObject(localeOpts));\n    return !tokenList ? null : tokenList.map(t => t ? t.val : null).join(\"\");\n  }\n\n  /**\n   * Produce the the fully expanded format token for the locale\n   * Does NOT quote characters, so quoted tokens will not round trip correctly\n   * @param fmt\n   * @param localeOpts\n   * @returns {string}\n   */\n  static expandFormat(fmt, localeOpts = {}) {\n    const expanded = expandMacroTokens(Formatter.parseFormat(fmt), Locale.fromObject(localeOpts));\n    return expanded.map(t => t.val).join(\"\");\n  }\n  static resetCache() {\n    zoneOffsetTs = undefined;\n    zoneOffsetGuessCache.clear();\n  }\n\n  // INFO\n\n  /**\n   * Get the value of unit.\n   * @param {string} unit - a unit such as 'minute' or 'day'\n   * @example DateTime.local(2017, 7, 4).get('month'); //=> 7\n   * @example DateTime.local(2017, 7, 4).get('day'); //=> 4\n   * @return {number}\n   */\n  get(unit) {\n    return this[unit];\n  }\n\n  /**\n   * Returns whether the DateTime is valid. Invalid DateTimes occur when:\n   * * The DateTime was created from invalid calendar information, such as the 13th month or February 30\n   * * The DateTime was created by an operation on another invalid date\n   * @type {boolean}\n   */\n  get isValid() {\n    return this.invalid === null;\n  }\n\n  /**\n   * Returns an error code if this DateTime is invalid, or null if the DateTime is valid\n   * @type {string}\n   */\n  get invalidReason() {\n    return this.invalid ? this.invalid.reason : null;\n  }\n\n  /**\n   * Returns an explanation of why this DateTime became invalid, or null if the DateTime is valid\n   * @type {string}\n   */\n  get invalidExplanation() {\n    return this.invalid ? this.invalid.explanation : null;\n  }\n\n  /**\n   * Get the locale of a DateTime, such 'en-GB'. The locale is used when formatting the DateTime\n   *\n   * @type {string}\n   */\n  get locale() {\n    return this.isValid ? this.loc.locale : null;\n  }\n\n  /**\n   * Get the numbering system of a DateTime, such 'beng'. The numbering system is used when formatting the DateTime\n   *\n   * @type {string}\n   */\n  get numberingSystem() {\n    return this.isValid ? this.loc.numberingSystem : null;\n  }\n\n  /**\n   * Get the output calendar of a DateTime, such 'islamic'. The output calendar is used when formatting the DateTime\n   *\n   * @type {string}\n   */\n  get outputCalendar() {\n    return this.isValid ? this.loc.outputCalendar : null;\n  }\n\n  /**\n   * Get the time zone associated with this DateTime.\n   * @type {Zone}\n   */\n  get zone() {\n    return this._zone;\n  }\n\n  /**\n   * Get the name of the time zone.\n   * @type {string}\n   */\n  get zoneName() {\n    return this.isValid ? this.zone.name : null;\n  }\n\n  /**\n   * Get the year\n   * @example DateTime.local(2017, 5, 25).year //=> 2017\n   * @type {number}\n   */\n  get year() {\n    return this.isValid ? this.c.year : NaN;\n  }\n\n  /**\n   * Get the quarter\n   * @example DateTime.local(2017, 5, 25).quarter //=> 2\n   * @type {number}\n   */\n  get quarter() {\n    return this.isValid ? Math.ceil(this.c.month / 3) : NaN;\n  }\n\n  /**\n   * Get the month (1-12).\n   * @example DateTime.local(2017, 5, 25).month //=> 5\n   * @type {number}\n   */\n  get month() {\n    return this.isValid ? this.c.month : NaN;\n  }\n\n  /**\n   * Get the day of the month (1-30ish).\n   * @example DateTime.local(2017, 5, 25).day //=> 25\n   * @type {number}\n   */\n  get day() {\n    return this.isValid ? this.c.day : NaN;\n  }\n\n  /**\n   * Get the hour of the day (0-23).\n   * @example DateTime.local(2017, 5, 25, 9).hour //=> 9\n   * @type {number}\n   */\n  get hour() {\n    return this.isValid ? this.c.hour : NaN;\n  }\n\n  /**\n   * Get the minute of the hour (0-59).\n   * @example DateTime.local(2017, 5, 25, 9, 30).minute //=> 30\n   * @type {number}\n   */\n  get minute() {\n    return this.isValid ? this.c.minute : NaN;\n  }\n\n  /**\n   * Get the second of the minute (0-59).\n   * @example DateTime.local(2017, 5, 25, 9, 30, 52).second //=> 52\n   * @type {number}\n   */\n  get second() {\n    return this.isValid ? this.c.second : NaN;\n  }\n\n  /**\n   * Get the millisecond of the second (0-999).\n   * @example DateTime.local(2017, 5, 25, 9, 30, 52, 654).millisecond //=> 654\n   * @type {number}\n   */\n  get millisecond() {\n    return this.isValid ? this.c.millisecond : NaN;\n  }\n\n  /**\n   * Get the week year\n   * @see https://en.wikipedia.org/wiki/ISO_week_date\n   * @example DateTime.local(2014, 12, 31).weekYear //=> 2015\n   * @type {number}\n   */\n  get weekYear() {\n    return this.isValid ? possiblyCachedWeekData(this).weekYear : NaN;\n  }\n\n  /**\n   * Get the week number of the week year (1-52ish).\n   * @see https://en.wikipedia.org/wiki/ISO_week_date\n   * @example DateTime.local(2017, 5, 25).weekNumber //=> 21\n   * @type {number}\n   */\n  get weekNumber() {\n    return this.isValid ? possiblyCachedWeekData(this).weekNumber : NaN;\n  }\n\n  /**\n   * Get the day of the week.\n   * 1 is Monday and 7 is Sunday\n   * @see https://en.wikipedia.org/wiki/ISO_week_date\n   * @example DateTime.local(2014, 11, 31).weekday //=> 4\n   * @type {number}\n   */\n  get weekday() {\n    return this.isValid ? possiblyCachedWeekData(this).weekday : NaN;\n  }\n\n  /**\n   * Returns true if this date is on a weekend according to the locale, false otherwise\n   * @returns {boolean}\n   */\n  get isWeekend() {\n    return this.isValid && this.loc.getWeekendDays().includes(this.weekday);\n  }\n\n  /**\n   * Get the day of the week according to the locale.\n   * 1 is the first day of the week and 7 is the last day of the week.\n   * If the locale assigns Sunday as the first day of the week, then a date which is a Sunday will return 1,\n   * @returns {number}\n   */\n  get localWeekday() {\n    return this.isValid ? possiblyCachedLocalWeekData(this).weekday : NaN;\n  }\n\n  /**\n   * Get the week number of the week year according to the locale. Different locales assign week numbers differently,\n   * because the week can start on different days of the week (see localWeekday) and because a different number of days\n   * is required for a week to count as the first week of a year.\n   * @returns {number}\n   */\n  get localWeekNumber() {\n    return this.isValid ? possiblyCachedLocalWeekData(this).weekNumber : NaN;\n  }\n\n  /**\n   * Get the week year according to the locale. Different locales assign week numbers (and therefor week years)\n   * differently, see localWeekNumber.\n   * @returns {number}\n   */\n  get localWeekYear() {\n    return this.isValid ? possiblyCachedLocalWeekData(this).weekYear : NaN;\n  }\n\n  /**\n   * Get the ordinal (meaning the day of the year)\n   * @example DateTime.local(2017, 5, 25).ordinal //=> 145\n   * @type {number|DateTime}\n   */\n  get ordinal() {\n    return this.isValid ? gregorianToOrdinal(this.c).ordinal : NaN;\n  }\n\n  /**\n   * Get the human readable short month name, such as 'Oct'.\n   * Defaults to the system's locale if no locale has been specified\n   * @example DateTime.local(2017, 10, 30).monthShort //=> Oct\n   * @type {string}\n   */\n  get monthShort() {\n    return this.isValid ? Info.months(\"short\", {\n      locObj: this.loc\n    })[this.month - 1] : null;\n  }\n\n  /**\n   * Get the human readable long month name, such as 'October'.\n   * Defaults to the system's locale if no locale has been specified\n   * @example DateTime.local(2017, 10, 30).monthLong //=> October\n   * @type {string}\n   */\n  get monthLong() {\n    return this.isValid ? Info.months(\"long\", {\n      locObj: this.loc\n    })[this.month - 1] : null;\n  }\n\n  /**\n   * Get the human readable short weekday, such as 'Mon'.\n   * Defaults to the system's locale if no locale has been specified\n   * @example DateTime.local(2017, 10, 30).weekdayShort //=> Mon\n   * @type {string}\n   */\n  get weekdayShort() {\n    return this.isValid ? Info.weekdays(\"short\", {\n      locObj: this.loc\n    })[this.weekday - 1] : null;\n  }\n\n  /**\n   * Get the human readable long weekday, such as 'Monday'.\n   * Defaults to the system's locale if no locale has been specified\n   * @example DateTime.local(2017, 10, 30).weekdayLong //=> Monday\n   * @type {string}\n   */\n  get weekdayLong() {\n    return this.isValid ? Info.weekdays(\"long\", {\n      locObj: this.loc\n    })[this.weekday - 1] : null;\n  }\n\n  /**\n   * Get the UTC offset of this DateTime in minutes\n   * @example DateTime.now().offset //=> -240\n   * @example DateTime.utc().offset //=> 0\n   * @type {number}\n   */\n  get offset() {\n    return this.isValid ? +this.o : NaN;\n  }\n\n  /**\n   * Get the short human name for the zone's current offset, for example \"EST\" or \"EDT\".\n   * Defaults to the system's locale if no locale has been specified\n   * @type {string}\n   */\n  get offsetNameShort() {\n    if (this.isValid) {\n      return this.zone.offsetName(this.ts, {\n        format: \"short\",\n        locale: this.locale\n      });\n    } else {\n      return null;\n    }\n  }\n\n  /**\n   * Get the long human name for the zone's current offset, for example \"Eastern Standard Time\" or \"Eastern Daylight Time\".\n   * Defaults to the system's locale if no locale has been specified\n   * @type {string}\n   */\n  get offsetNameLong() {\n    if (this.isValid) {\n      return this.zone.offsetName(this.ts, {\n        format: \"long\",\n        locale: this.locale\n      });\n    } else {\n      return null;\n    }\n  }\n\n  /**\n   * Get whether this zone's offset ever changes, as in a DST.\n   * @type {boolean}\n   */\n  get isOffsetFixed() {\n    return this.isValid ? this.zone.isUniversal : null;\n  }\n\n  /**\n   * Get whether the DateTime is in a DST.\n   * @type {boolean}\n   */\n  get isInDST() {\n    if (this.isOffsetFixed) {\n      return false;\n    } else {\n      return this.offset > this.set({\n        month: 1,\n        day: 1\n      }).offset || this.offset > this.set({\n        month: 5\n      }).offset;\n    }\n  }\n\n  /**\n   * Get those DateTimes which have the same local time as this DateTime, but a different offset from UTC\n   * in this DateTime's zone. During DST changes local time can be ambiguous, for example\n   * `2023-10-29T02:30:00` in `Europe/Berlin` can have offset `+01:00` or `+02:00`.\n   * This method will return both possible DateTimes if this DateTime's local time is ambiguous.\n   * @returns {DateTime[]}\n   */\n  getPossibleOffsets() {\n    if (!this.isValid || this.isOffsetFixed) {\n      return [this];\n    }\n    const dayMs = 86400000;\n    const minuteMs = 60000;\n    const localTS = objToLocalTS(this.c);\n    const oEarlier = this.zone.offset(localTS - dayMs);\n    const oLater = this.zone.offset(localTS + dayMs);\n    const o1 = this.zone.offset(localTS - oEarlier * minuteMs);\n    const o2 = this.zone.offset(localTS - oLater * minuteMs);\n    if (o1 === o2) {\n      return [this];\n    }\n    const ts1 = localTS - o1 * minuteMs;\n    const ts2 = localTS - o2 * minuteMs;\n    const c1 = tsToObj(ts1, o1);\n    const c2 = tsToObj(ts2, o2);\n    if (c1.hour === c2.hour && c1.minute === c2.minute && c1.second === c2.second && c1.millisecond === c2.millisecond) {\n      return [clone(this, {\n        ts: ts1\n      }), clone(this, {\n        ts: ts2\n      })];\n    }\n    return [this];\n  }\n\n  /**\n   * Returns true if this DateTime is in a leap year, false otherwise\n   * @example DateTime.local(2016).isInLeapYear //=> true\n   * @example DateTime.local(2013).isInLeapYear //=> false\n   * @type {boolean}\n   */\n  get isInLeapYear() {\n    return isLeapYear(this.year);\n  }\n\n  /**\n   * Returns the number of days in this DateTime's month\n   * @example DateTime.local(2016, 2).daysInMonth //=> 29\n   * @example DateTime.local(2016, 3).daysInMonth //=> 31\n   * @type {number}\n   */\n  get daysInMonth() {\n    return daysInMonth(this.year, this.month);\n  }\n\n  /**\n   * Returns the number of days in this DateTime's year\n   * @example DateTime.local(2016).daysInYear //=> 366\n   * @example DateTime.local(2013).daysInYear //=> 365\n   * @type {number}\n   */\n  get daysInYear() {\n    return this.isValid ? daysInYear(this.year) : NaN;\n  }\n\n  /**\n   * Returns the number of weeks in this DateTime's year\n   * @see https://en.wikipedia.org/wiki/ISO_week_date\n   * @example DateTime.local(2004).weeksInWeekYear //=> 53\n   * @example DateTime.local(2013).weeksInWeekYear //=> 52\n   * @type {number}\n   */\n  get weeksInWeekYear() {\n    return this.isValid ? weeksInWeekYear(this.weekYear) : NaN;\n  }\n\n  /**\n   * Returns the number of weeks in this DateTime's local week year\n   * @example DateTime.local(2020, 6, {locale: 'en-US'}).weeksInLocalWeekYear //=> 52\n   * @example DateTime.local(2020, 6, {locale: 'de-DE'}).weeksInLocalWeekYear //=> 53\n   * @type {number}\n   */\n  get weeksInLocalWeekYear() {\n    return this.isValid ? weeksInWeekYear(this.localWeekYear, this.loc.getMinDaysInFirstWeek(), this.loc.getStartOfWeek()) : NaN;\n  }\n\n  /**\n   * Returns the resolved Intl options for this DateTime.\n   * This is useful in understanding the behavior of formatting methods\n   * @param {Object} opts - the same options as toLocaleString\n   * @return {Object}\n   */\n  resolvedLocaleOptions(opts = {}) {\n    const {\n      locale,\n      numberingSystem,\n      calendar\n    } = Formatter.create(this.loc.clone(opts), opts).resolvedOptions(this);\n    return {\n      locale,\n      numberingSystem,\n      outputCalendar: calendar\n    };\n  }\n\n  // TRANSFORM\n\n  /**\n   * \"Set\" the DateTime's zone to UTC. Returns a newly-constructed DateTime.\n   *\n   * Equivalent to {@link DateTime#setZone}('utc')\n   * @param {number} [offset=0] - optionally, an offset from UTC in minutes\n   * @param {Object} [opts={}] - options to pass to `setZone()`\n   * @return {DateTime}\n   */\n  toUTC(offset = 0, opts = {}) {\n    return this.setZone(FixedOffsetZone.instance(offset), opts);\n  }\n\n  /**\n   * \"Set\" the DateTime's zone to the host's local zone. Returns a newly-constructed DateTime.\n   *\n   * Equivalent to `setZone('local')`\n   * @return {DateTime}\n   */\n  toLocal() {\n    return this.setZone(Settings.defaultZone);\n  }\n\n  /**\n   * \"Set\" the DateTime's zone to specified zone. Returns a newly-constructed DateTime.\n   *\n   * By default, the setter keeps the underlying time the same (as in, the same timestamp), but the new instance will report different local times and consider DSTs when making computations, as with {@link DateTime#plus}. You may wish to use {@link DateTime#toLocal} and {@link DateTime#toUTC} which provide simple convenience wrappers for commonly used zones.\n   * @param {string|Zone} [zone='local'] - a zone identifier. As a string, that can be any IANA zone supported by the host environment, or a fixed-offset name of the form 'UTC+3', or the strings 'local' or 'utc'. You may also supply an instance of a {@link DateTime#Zone} class.\n   * @param {Object} opts - options\n   * @param {boolean} [opts.keepLocalTime=false] - If true, adjust the underlying time so that the local time stays the same, but in the target zone. You should rarely need this.\n   * @return {DateTime}\n   */\n  setZone(zone, {\n    keepLocalTime = false,\n    keepCalendarTime = false\n  } = {}) {\n    zone = normalizeZone(zone, Settings.defaultZone);\n    if (zone.equals(this.zone)) {\n      return this;\n    } else if (!zone.isValid) {\n      return DateTime.invalid(unsupportedZone(zone));\n    } else {\n      let newTS = this.ts;\n      if (keepLocalTime || keepCalendarTime) {\n        const offsetGuess = zone.offset(this.ts);\n        const asObj = this.toObject();\n        [newTS] = objToTS(asObj, offsetGuess, zone);\n      }\n      return clone(this, {\n        ts: newTS,\n        zone\n      });\n    }\n  }\n\n  /**\n   * \"Set\" the locale, numberingSystem, or outputCalendar. Returns a newly-constructed DateTime.\n   * @param {Object} properties - the properties to set\n   * @example DateTime.local(2017, 5, 25).reconfigure({ locale: 'en-GB' })\n   * @return {DateTime}\n   */\n  reconfigure({\n    locale,\n    numberingSystem,\n    outputCalendar\n  } = {}) {\n    const loc = this.loc.clone({\n      locale,\n      numberingSystem,\n      outputCalendar\n    });\n    return clone(this, {\n      loc\n    });\n  }\n\n  /**\n   * \"Set\" the locale. Returns a newly-constructed DateTime.\n   * Just a convenient alias for reconfigure({ locale })\n   * @example DateTime.local(2017, 5, 25).setLocale('en-GB')\n   * @return {DateTime}\n   */\n  setLocale(locale) {\n    return this.reconfigure({\n      locale\n    });\n  }\n\n  /**\n   * \"Set\" the values of specified units. Returns a newly-constructed DateTime.\n   * You can only set units with this method; for \"setting\" metadata, see {@link DateTime#reconfigure} and {@link DateTime#setZone}.\n   *\n   * This method also supports setting locale-based week units, i.e. `localWeekday`, `localWeekNumber` and `localWeekYear`.\n   * They cannot be mixed with ISO-week units like `weekday`.\n   * @param {Object} values - a mapping of units to numbers\n   * @example dt.set({ year: 2017 })\n   * @example dt.set({ hour: 8, minute: 30 })\n   * @example dt.set({ weekday: 5 })\n   * @example dt.set({ year: 2005, ordinal: 234 })\n   * @return {DateTime}\n   */\n  set(values) {\n    if (!this.isValid) return this;\n    const normalized = normalizeObject(values, normalizeUnitWithLocalWeeks);\n    const {\n      minDaysInFirstWeek,\n      startOfWeek\n    } = usesLocalWeekValues(normalized, this.loc);\n    const settingWeekStuff = !isUndefined(normalized.weekYear) || !isUndefined(normalized.weekNumber) || !isUndefined(normalized.weekday),\n      containsOrdinal = !isUndefined(normalized.ordinal),\n      containsGregorYear = !isUndefined(normalized.year),\n      containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day),\n      containsGregor = containsGregorYear || containsGregorMD,\n      definiteWeekDef = normalized.weekYear || normalized.weekNumber;\n    if ((containsGregor || containsOrdinal) && definiteWeekDef) {\n      throw new ConflictingSpecificationError(\"Can't mix weekYear/weekNumber units with year/month/day or ordinals\");\n    }\n    if (containsGregorMD && containsOrdinal) {\n      throw new ConflictingSpecificationError(\"Can't mix ordinal dates with month/day\");\n    }\n    let mixed;\n    if (settingWeekStuff) {\n      mixed = weekToGregorian({\n        ...gregorianToWeek(this.c, minDaysInFirstWeek, startOfWeek),\n        ...normalized\n      }, minDaysInFirstWeek, startOfWeek);\n    } else if (!isUndefined(normalized.ordinal)) {\n      mixed = ordinalToGregorian({\n        ...gregorianToOrdinal(this.c),\n        ...normalized\n      });\n    } else {\n      mixed = {\n        ...this.toObject(),\n        ...normalized\n      };\n\n      // if we didn't set the day but we ended up on an overflow date,\n      // use the last day of the right month\n      if (isUndefined(normalized.day)) {\n        mixed.day = Math.min(daysInMonth(mixed.year, mixed.month), mixed.day);\n      }\n    }\n    const [ts, o] = objToTS(mixed, this.o, this.zone);\n    return clone(this, {\n      ts,\n      o\n    });\n  }\n\n  /**\n   * Add a period of time to this DateTime and return the resulting DateTime\n   *\n   * Adding hours, minutes, seconds, or milliseconds increases the timestamp by the right number of milliseconds. Adding days, months, or years shifts the calendar, accounting for DSTs and leap years along the way. Thus, `dt.plus({ hours: 24 })` may result in a different time than `dt.plus({ days: 1 })` if there's a DST shift in between.\n   * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()\n   * @example DateTime.now().plus(123) //~> in 123 milliseconds\n   * @example DateTime.now().plus({ minutes: 15 }) //~> in 15 minutes\n   * @example DateTime.now().plus({ days: 1 }) //~> this time tomorrow\n   * @example DateTime.now().plus({ days: -1 }) //~> this time yesterday\n   * @example DateTime.now().plus({ hours: 3, minutes: 13 }) //~> in 3 hr, 13 min\n   * @example DateTime.now().plus(Duration.fromObject({ hours: 3, minutes: 13 })) //~> in 3 hr, 13 min\n   * @return {DateTime}\n   */\n  plus(duration) {\n    if (!this.isValid) return this;\n    const dur = Duration.fromDurationLike(duration);\n    return clone(this, adjustTime(this, dur));\n  }\n\n  /**\n   * Subtract a period of time to this DateTime and return the resulting DateTime\n   * See {@link DateTime#plus}\n   * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()\n   @return {DateTime}\n   */\n  minus(duration) {\n    if (!this.isValid) return this;\n    const dur = Duration.fromDurationLike(duration).negate();\n    return clone(this, adjustTime(this, dur));\n  }\n\n  /**\n   * \"Set\" this DateTime to the beginning of a unit of time.\n   * @param {string} unit - The unit to go to the beginning of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'.\n   * @param {Object} opts - options\n   * @param {boolean} [opts.useLocaleWeeks=false] - If true, use weeks based on the locale, i.e. use the locale-dependent start of the week\n   * @example DateTime.local(2014, 3, 3).startOf('month').toISODate(); //=> '2014-03-01'\n   * @example DateTime.local(2014, 3, 3).startOf('year').toISODate(); //=> '2014-01-01'\n   * @example DateTime.local(2014, 3, 3).startOf('week').toISODate(); //=> '2014-03-03', weeks always start on Mondays\n   * @example DateTime.local(2014, 3, 3, 5, 30).startOf('day').toISOTime(); //=> '00:00.000-05:00'\n   * @example DateTime.local(2014, 3, 3, 5, 30).startOf('hour').toISOTime(); //=> '05:00:00.000-05:00'\n   * @return {DateTime}\n   */\n  startOf(unit, {\n    useLocaleWeeks = false\n  } = {}) {\n    if (!this.isValid) return this;\n    const o = {},\n      normalizedUnit = Duration.normalizeUnit(unit);\n    switch (normalizedUnit) {\n      case \"years\":\n        o.month = 1;\n      // falls through\n      case \"quarters\":\n      case \"months\":\n        o.day = 1;\n      // falls through\n      case \"weeks\":\n      case \"days\":\n        o.hour = 0;\n      // falls through\n      case \"hours\":\n        o.minute = 0;\n      // falls through\n      case \"minutes\":\n        o.second = 0;\n      // falls through\n      case \"seconds\":\n        o.millisecond = 0;\n        break;\n      // no default, invalid units throw in normalizeUnit()\n    }\n\n    if (normalizedUnit === \"weeks\") {\n      if (useLocaleWeeks) {\n        const startOfWeek = this.loc.getStartOfWeek();\n        const {\n          weekday\n        } = this;\n        if (weekday < startOfWeek) {\n          o.weekNumber = this.weekNumber - 1;\n        }\n        o.weekday = startOfWeek;\n      } else {\n        o.weekday = 1;\n      }\n    }\n    if (normalizedUnit === \"quarters\") {\n      const q = Math.ceil(this.month / 3);\n      o.month = (q - 1) * 3 + 1;\n    }\n    return this.set(o);\n  }\n\n  /**\n   * \"Set\" this DateTime to the end (meaning the last millisecond) of a unit of time\n   * @param {string} unit - The unit to go to the end of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'.\n   * @param {Object} opts - options\n   * @param {boolean} [opts.useLocaleWeeks=false] - If true, use weeks based on the locale, i.e. use the locale-dependent start of the week\n   * @example DateTime.local(2014, 3, 3).endOf('month').toISO(); //=> '2014-03-31T23:59:59.999-05:00'\n   * @example DateTime.local(2014, 3, 3).endOf('year').toISO(); //=> '2014-12-31T23:59:59.999-05:00'\n   * @example DateTime.local(2014, 3, 3).endOf('week').toISO(); // => '2014-03-09T23:59:59.999-05:00', weeks start on Mondays\n   * @example DateTime.local(2014, 3, 3, 5, 30).endOf('day').toISO(); //=> '2014-03-03T23:59:59.999-05:00'\n   * @example DateTime.local(2014, 3, 3, 5, 30).endOf('hour').toISO(); //=> '2014-03-03T05:59:59.999-05:00'\n   * @return {DateTime}\n   */\n  endOf(unit, opts) {\n    return this.isValid ? this.plus({\n      [unit]: 1\n    }).startOf(unit, opts).minus(1) : this;\n  }\n\n  // OUTPUT\n\n  /**\n   * Returns a string representation of this DateTime formatted according to the specified format string.\n   * **You may not want this.** See {@link DateTime#toLocaleString} for a more flexible formatting tool. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/formatting?id=table-of-tokens).\n   * Defaults to en-US if no locale has been specified, regardless of the system's locale.\n   * @param {string} fmt - the format string\n   * @param {Object} opts - opts to override the configuration options on this DateTime\n   * @example DateTime.now().toFormat('yyyy LLL dd') //=> '2017 Apr 22'\n   * @example DateTime.now().setLocale('fr').toFormat('yyyy LLL dd') //=> '2017 avr. 22'\n   * @example DateTime.now().toFormat('yyyy LLL dd', { locale: \"fr\" }) //=> '2017 avr. 22'\n   * @example DateTime.now().toFormat(\"HH 'hours and' mm 'minutes'\") //=> '20 hours and 55 minutes'\n   * @return {string}\n   */\n  toFormat(fmt, opts = {}) {\n    return this.isValid ? Formatter.create(this.loc.redefaultToEN(opts)).formatDateTimeFromString(this, fmt) : INVALID;\n  }\n\n  /**\n   * Returns a localized string representing this date. Accepts the same options as the Intl.DateTimeFormat constructor and any presets defined by Luxon, such as `DateTime.DATE_FULL` or `DateTime.TIME_SIMPLE`.\n   * The exact behavior of this method is browser-specific, but in general it will return an appropriate representation\n   * of the DateTime in the assigned locale.\n   * Defaults to the system's locale if no locale has been specified\n   * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat\n   * @param formatOpts {Object} - Intl.DateTimeFormat constructor options and configuration options\n   * @param {Object} opts - opts to override the configuration options on this DateTime\n   * @example DateTime.now().toLocaleString(); //=> 4/20/2017\n   * @example DateTime.now().setLocale('en-gb').toLocaleString(); //=> '20/04/2017'\n   * @example DateTime.now().toLocaleString(DateTime.DATE_FULL); //=> 'April 20, 2017'\n   * @example DateTime.now().toLocaleString(DateTime.DATE_FULL, { locale: 'fr' }); //=> '28 août 2022'\n   * @example DateTime.now().toLocaleString(DateTime.TIME_SIMPLE); //=> '11:32 AM'\n   * @example DateTime.now().toLocaleString(DateTime.DATETIME_SHORT); //=> '4/20/2017, 11:32 AM'\n   * @example DateTime.now().toLocaleString({ weekday: 'long', month: 'long', day: '2-digit' }); //=> 'Thursday, April 20'\n   * @example DateTime.now().toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> 'Thu, Apr 20, 11:27 AM'\n   * @example DateTime.now().toLocaleString({ hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }); //=> '11:32'\n   * @return {string}\n   */\n  toLocaleString(formatOpts = DATE_SHORT, opts = {}) {\n    return this.isValid ? Formatter.create(this.loc.clone(opts), formatOpts).formatDateTime(this) : INVALID;\n  }\n\n  /**\n   * Returns an array of format \"parts\", meaning individual tokens along with metadata. This is allows callers to post-process individual sections of the formatted output.\n   * Defaults to the system's locale if no locale has been specified\n   * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/formatToParts\n   * @param opts {Object} - Intl.DateTimeFormat constructor options, same as `toLocaleString`.\n   * @example DateTime.now().toLocaleParts(); //=> [\n   *                                   //=>   { type: 'day', value: '25' },\n   *                                   //=>   { type: 'literal', value: '/' },\n   *                                   //=>   { type: 'month', value: '05' },\n   *                                   //=>   { type: 'literal', value: '/' },\n   *                                   //=>   { type: 'year', value: '1982' }\n   *                                   //=> ]\n   */\n  toLocaleParts(opts = {}) {\n    return this.isValid ? Formatter.create(this.loc.clone(opts), opts).formatDateTimeParts(this) : [];\n  }\n\n  /**\n   * Returns an ISO 8601-compliant string representation of this DateTime\n   * @param {Object} opts - options\n   * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0\n   * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0\n   * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'\n   * @param {boolean} [opts.extendedZone=false] - add the time zone format extension\n   * @param {string} [opts.format='extended'] - choose between the basic and extended format\n   * @param {string} [opts.precision='milliseconds'] - truncate output to desired presicion: 'years', 'months', 'days', 'hours', 'minutes', 'seconds' or 'milliseconds'. When precision and suppressSeconds or suppressMilliseconds are used together, precision sets the maximum unit shown in the output, however seconds or milliseconds will still be suppressed if they are 0.\n   * @example DateTime.utc(1983, 5, 25).toISO() //=> '1982-05-25T00:00:00.000Z'\n   * @example DateTime.now().toISO() //=> '2017-04-22T20:47:05.335-04:00'\n   * @example DateTime.now().toISO({ includeOffset: false }) //=> '2017-04-22T20:47:05.335'\n   * @example DateTime.now().toISO({ format: 'basic' }) //=> '20170422T204705.335-0400'\n   * @example DateTime.now().toISO({ precision: 'day' }) //=> '2017-04-22Z'\n   * @example DateTime.now().toISO({ precision: 'minute' }) //=> '2017-04-22T20:47Z'\n   * @return {string|null}\n   */\n  toISO({\n    format = \"extended\",\n    suppressSeconds = false,\n    suppressMilliseconds = false,\n    includeOffset = true,\n    extendedZone = false,\n    precision = \"milliseconds\"\n  } = {}) {\n    if (!this.isValid) {\n      return null;\n    }\n    precision = normalizeUnit(precision);\n    const ext = format === \"extended\";\n    let c = toISODate(this, ext, precision);\n    if (orderedUnits.indexOf(precision) >= 3) c += \"T\";\n    c += toISOTime(this, ext, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone, precision);\n    return c;\n  }\n\n  /**\n   * Returns an ISO 8601-compliant string representation of this DateTime's date component\n   * @param {Object} opts - options\n   * @param {string} [opts.format='extended'] - choose between the basic and extended format\n   * @param {string} [opts.precision='day'] - truncate output to desired precision: 'years', 'months', or 'days'.\n   * @example DateTime.utc(1982, 5, 25).toISODate() //=> '1982-05-25'\n   * @example DateTime.utc(1982, 5, 25).toISODate({ format: 'basic' }) //=> '19820525'\n   * @example DateTime.utc(1982, 5, 25).toISODate({ precision: 'month' }) //=> '1982-05'\n   * @return {string|null}\n   */\n  toISODate({\n    format = \"extended\",\n    precision = \"day\"\n  } = {}) {\n    if (!this.isValid) {\n      return null;\n    }\n    return toISODate(this, format === \"extended\", normalizeUnit(precision));\n  }\n\n  /**\n   * Returns an ISO 8601-compliant string representation of this DateTime's week date\n   * @example DateTime.utc(1982, 5, 25).toISOWeekDate() //=> '1982-W21-2'\n   * @return {string}\n   */\n  toISOWeekDate() {\n    return toTechFormat(this, \"kkkk-'W'WW-c\");\n  }\n\n  /**\n   * Returns an ISO 8601-compliant string representation of this DateTime's time component\n   * @param {Object} opts - options\n   * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0\n   * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0\n   * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'\n   * @param {boolean} [opts.extendedZone=true] - add the time zone format extension\n   * @param {boolean} [opts.includePrefix=false] - include the `T` prefix\n   * @param {string} [opts.format='extended'] - choose between the basic and extended format\n   * @param {string} [opts.precision='milliseconds'] - truncate output to desired presicion: 'hours', 'minutes', 'seconds' or 'milliseconds'. When precision and suppressSeconds or suppressMilliseconds are used together, precision sets the maximum unit shown in the output, however seconds or milliseconds will still be suppressed if they are 0.\n   * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime() //=> '07:34:19.361Z'\n   * @example DateTime.utc().set({ hour: 7, minute: 34, seconds: 0, milliseconds: 0 }).toISOTime({ suppressSeconds: true }) //=> '07:34Z'\n   * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ format: 'basic' }) //=> '073419.361Z'\n   * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ includePrefix: true }) //=> 'T07:34:19.361Z'\n   * @example DateTime.utc().set({ hour: 7, minute: 34, second: 56 }).toISOTime({ precision: 'minute' }) //=> '07:34Z'\n   * @return {string}\n   */\n  toISOTime({\n    suppressMilliseconds = false,\n    suppressSeconds = false,\n    includeOffset = true,\n    includePrefix = false,\n    extendedZone = false,\n    format = \"extended\",\n    precision = \"milliseconds\"\n  } = {}) {\n    if (!this.isValid) {\n      return null;\n    }\n    precision = normalizeUnit(precision);\n    let c = includePrefix && orderedUnits.indexOf(precision) >= 3 ? \"T\" : \"\";\n    return c + toISOTime(this, format === \"extended\", suppressSeconds, suppressMilliseconds, includeOffset, extendedZone, precision);\n  }\n\n  /**\n   * Returns an RFC 2822-compatible string representation of this DateTime\n   * @example DateTime.utc(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 +0000'\n   * @example DateTime.local(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 -0400'\n   * @return {string}\n   */\n  toRFC2822() {\n    return toTechFormat(this, \"EEE, dd LLL yyyy HH:mm:ss ZZZ\", false);\n  }\n\n  /**\n   * Returns a string representation of this DateTime appropriate for use in HTTP headers. The output is always expressed in GMT.\n   * Specifically, the string conforms to RFC 1123.\n   * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1\n   * @example DateTime.utc(2014, 7, 13).toHTTP() //=> 'Sun, 13 Jul 2014 00:00:00 GMT'\n   * @example DateTime.utc(2014, 7, 13, 19).toHTTP() //=> 'Sun, 13 Jul 2014 19:00:00 GMT'\n   * @return {string}\n   */\n  toHTTP() {\n    return toTechFormat(this.toUTC(), \"EEE, dd LLL yyyy HH:mm:ss 'GMT'\");\n  }\n\n  /**\n   * Returns a string representation of this DateTime appropriate for use in SQL Date\n   * @example DateTime.utc(2014, 7, 13).toSQLDate() //=> '2014-07-13'\n   * @return {string|null}\n   */\n  toSQLDate() {\n    if (!this.isValid) {\n      return null;\n    }\n    return toISODate(this, true);\n  }\n\n  /**\n   * Returns a string representation of this DateTime appropriate for use in SQL Time\n   * @param {Object} opts - options\n   * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset.\n   * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'\n   * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00'\n   * @example DateTime.utc().toSQL() //=> '05:15:16.345'\n   * @example DateTime.now().toSQL() //=> '05:15:16.345 -04:00'\n   * @example DateTime.now().toSQL({ includeOffset: false }) //=> '05:15:16.345'\n   * @example DateTime.now().toSQL({ includeZone: false }) //=> '05:15:16.345 America/New_York'\n   * @return {string}\n   */\n  toSQLTime({\n    includeOffset = true,\n    includeZone = false,\n    includeOffsetSpace = true\n  } = {}) {\n    let fmt = \"HH:mm:ss.SSS\";\n    if (includeZone || includeOffset) {\n      if (includeOffsetSpace) {\n        fmt += \" \";\n      }\n      if (includeZone) {\n        fmt += \"z\";\n      } else if (includeOffset) {\n        fmt += \"ZZ\";\n      }\n    }\n    return toTechFormat(this, fmt, true);\n  }\n\n  /**\n   * Returns a string representation of this DateTime appropriate for use in SQL DateTime\n   * @param {Object} opts - options\n   * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset.\n   * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'\n   * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00'\n   * @example DateTime.utc(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 Z'\n   * @example DateTime.local(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 -04:00'\n   * @example DateTime.local(2014, 7, 13).toSQL({ includeOffset: false }) //=> '2014-07-13 00:00:00.000'\n   * @example DateTime.local(2014, 7, 13).toSQL({ includeZone: true }) //=> '2014-07-13 00:00:00.000 America/New_York'\n   * @return {string}\n   */\n  toSQL(opts = {}) {\n    if (!this.isValid) {\n      return null;\n    }\n    return `${this.toSQLDate()} ${this.toSQLTime(opts)}`;\n  }\n\n  /**\n   * Returns a string representation of this DateTime appropriate for debugging\n   * @return {string}\n   */\n  toString() {\n    return this.isValid ? this.toISO() : INVALID;\n  }\n\n  /**\n   * Returns a string representation of this DateTime appropriate for the REPL.\n   * @return {string}\n   */\n  [Symbol.for(\"nodejs.util.inspect.custom\")]() {\n    if (this.isValid) {\n      return `DateTime { ts: ${this.toISO()}, zone: ${this.zone.name}, locale: ${this.locale} }`;\n    } else {\n      return `DateTime { Invalid, reason: ${this.invalidReason} }`;\n    }\n  }\n\n  /**\n   * Returns the epoch milliseconds of this DateTime. Alias of {@link DateTime#toMillis}\n   * @return {number}\n   */\n  valueOf() {\n    return this.toMillis();\n  }\n\n  /**\n   * Returns the epoch milliseconds of this DateTime.\n   * @return {number}\n   */\n  toMillis() {\n    return this.isValid ? this.ts : NaN;\n  }\n\n  /**\n   * Returns the epoch seconds (including milliseconds in the fractional part) of this DateTime.\n   * @return {number}\n   */\n  toSeconds() {\n    return this.isValid ? this.ts / 1000 : NaN;\n  }\n\n  /**\n   * Returns the epoch seconds (as a whole number) of this DateTime.\n   * @return {number}\n   */\n  toUnixInteger() {\n    return this.isValid ? Math.floor(this.ts / 1000) : NaN;\n  }\n\n  /**\n   * Returns an ISO 8601 representation of this DateTime appropriate for use in JSON.\n   * @return {string}\n   */\n  toJSON() {\n    return this.toISO();\n  }\n\n  /**\n   * Returns a BSON serializable equivalent to this DateTime.\n   * @return {Date}\n   */\n  toBSON() {\n    return this.toJSDate();\n  }\n\n  /**\n   * Returns a JavaScript object with this DateTime's year, month, day, and so on.\n   * @param opts - options for generating the object\n   * @param {boolean} [opts.includeConfig=false] - include configuration attributes in the output\n   * @example DateTime.now().toObject() //=> { year: 2017, month: 4, day: 22, hour: 20, minute: 49, second: 42, millisecond: 268 }\n   * @return {Object}\n   */\n  toObject(opts = {}) {\n    if (!this.isValid) return {};\n    const base = {\n      ...this.c\n    };\n    if (opts.includeConfig) {\n      base.outputCalendar = this.outputCalendar;\n      base.numberingSystem = this.loc.numberingSystem;\n      base.locale = this.loc.locale;\n    }\n    return base;\n  }\n\n  /**\n   * Returns a JavaScript Date equivalent to this DateTime.\n   * @return {Date}\n   */\n  toJSDate() {\n    return new Date(this.isValid ? this.ts : NaN);\n  }\n\n  // COMPARE\n\n  /**\n   * Return the difference between two DateTimes as a Duration.\n   * @param {DateTime} otherDateTime - the DateTime to compare this one to\n   * @param {string|string[]} [unit=['milliseconds']] - the unit or array of units (such as 'hours' or 'days') to include in the duration.\n   * @param {Object} opts - options that affect the creation of the Duration\n   * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use\n   * @example\n   * var i1 = DateTime.fromISO('1982-05-25T09:45'),\n   *     i2 = DateTime.fromISO('1983-10-14T10:30');\n   * i2.diff(i1).toObject() //=> { milliseconds: 43807500000 }\n   * i2.diff(i1, 'hours').toObject() //=> { hours: 12168.75 }\n   * i2.diff(i1, ['months', 'days']).toObject() //=> { months: 16, days: 19.03125 }\n   * i2.diff(i1, ['months', 'days', 'hours']).toObject() //=> { months: 16, days: 19, hours: 0.75 }\n   * @return {Duration}\n   */\n  diff(otherDateTime, unit = \"milliseconds\", opts = {}) {\n    if (!this.isValid || !otherDateTime.isValid) {\n      return Duration.invalid(\"created by diffing an invalid DateTime\");\n    }\n    const durOpts = {\n      locale: this.locale,\n      numberingSystem: this.numberingSystem,\n      ...opts\n    };\n    const units = maybeArray(unit).map(Duration.normalizeUnit),\n      otherIsLater = otherDateTime.valueOf() > this.valueOf(),\n      earlier = otherIsLater ? this : otherDateTime,\n      later = otherIsLater ? otherDateTime : this,\n      diffed = diff(earlier, later, units, durOpts);\n    return otherIsLater ? diffed.negate() : diffed;\n  }\n\n  /**\n   * Return the difference between this DateTime and right now.\n   * See {@link DateTime#diff}\n   * @param {string|string[]} [unit=['milliseconds']] - the unit or units units (such as 'hours' or 'days') to include in the duration\n   * @param {Object} opts - options that affect the creation of the Duration\n   * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use\n   * @return {Duration}\n   */\n  diffNow(unit = \"milliseconds\", opts = {}) {\n    return this.diff(DateTime.now(), unit, opts);\n  }\n\n  /**\n   * Return an Interval spanning between this DateTime and another DateTime\n   * @param {DateTime} otherDateTime - the other end point of the Interval\n   * @return {Interval|DateTime}\n   */\n  until(otherDateTime) {\n    return this.isValid ? Interval.fromDateTimes(this, otherDateTime) : this;\n  }\n\n  /**\n   * Return whether this DateTime is in the same unit of time as another DateTime.\n   * Higher-order units must also be identical for this function to return `true`.\n   * Note that time zones are **ignored** in this comparison, which compares the **local** calendar time. Use {@link DateTime#setZone} to convert one of the dates if needed.\n   * @param {DateTime} otherDateTime - the other DateTime\n   * @param {string} unit - the unit of time to check sameness on\n   * @param {Object} opts - options\n   * @param {boolean} [opts.useLocaleWeeks=false] - If true, use weeks based on the locale, i.e. use the locale-dependent start of the week; only the locale of this DateTime is used\n   * @example DateTime.now().hasSame(otherDT, 'day'); //~> true if otherDT is in the same current calendar day\n   * @return {boolean}\n   */\n  hasSame(otherDateTime, unit, opts) {\n    if (!this.isValid) return false;\n    const inputMs = otherDateTime.valueOf();\n    const adjustedToZone = this.setZone(otherDateTime.zone, {\n      keepLocalTime: true\n    });\n    return adjustedToZone.startOf(unit, opts) <= inputMs && inputMs <= adjustedToZone.endOf(unit, opts);\n  }\n\n  /**\n   * Equality check\n   * Two DateTimes are equal if and only if they represent the same millisecond, have the same zone and location, and are both valid.\n   * To compare just the millisecond values, use `+dt1 === +dt2`.\n   * @param {DateTime} other - the other DateTime\n   * @return {boolean}\n   */\n  equals(other) {\n    return this.isValid && other.isValid && this.valueOf() === other.valueOf() && this.zone.equals(other.zone) && this.loc.equals(other.loc);\n  }\n\n  /**\n   * Returns a string representation of a this time relative to now, such as \"in two days\". Can only internationalize if your\n   * platform supports Intl.RelativeTimeFormat. Rounds towards zero by default.\n   * @param {Object} options - options that affect the output\n   * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now.\n   * @param {string} [options.style=\"long\"] - the style of units, must be \"long\", \"short\", or \"narrow\"\n   * @param {string|string[]} options.unit - use a specific unit or array of units; if omitted, or an array, the method will pick the best unit. Use an array or one of \"years\", \"quarters\", \"months\", \"weeks\", \"days\", \"hours\", \"minutes\", or \"seconds\"\n   * @param {boolean} [options.round=true] - whether to round the numbers in the output.\n   * @param {string} [options.rounding=\"trunc\"] - rounding method to use when rounding the numbers in the output. Can be \"trunc\" (toward zero), \"expand\" (away from zero), \"round\", \"floor\", or \"ceil\".\n   * @param {number} [options.padding=0] - padding in milliseconds. This allows you to round up the result if it fits inside the threshold. Don't use in combination with {round: false} because the decimal output will include the padding.\n   * @param {string} options.locale - override the locale of this DateTime\n   * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this\n   * @example DateTime.now().plus({ days: 1 }).toRelative() //=> \"in 1 day\"\n   * @example DateTime.now().setLocale(\"es\").toRelative({ days: 1 }) //=> \"dentro de 1 día\"\n   * @example DateTime.now().plus({ days: 1 }).toRelative({ locale: \"fr\" }) //=> \"dans 23 heures\"\n   * @example DateTime.now().minus({ days: 2 }).toRelative() //=> \"2 days ago\"\n   * @example DateTime.now().minus({ days: 2 }).toRelative({ unit: \"hours\" }) //=> \"48 hours ago\"\n   * @example DateTime.now().minus({ hours: 36 }).toRelative({ round: false }) //=> \"1.5 days ago\"\n   */\n  toRelative(options = {}) {\n    if (!this.isValid) return null;\n    const base = options.base || DateTime.fromObject({}, {\n        zone: this.zone\n      }),\n      padding = options.padding ? this < base ? -options.padding : options.padding : 0;\n    let units = [\"years\", \"months\", \"days\", \"hours\", \"minutes\", \"seconds\"];\n    let unit = options.unit;\n    if (Array.isArray(options.unit)) {\n      units = options.unit;\n      unit = undefined;\n    }\n    return diffRelative(base, this.plus(padding), {\n      ...options,\n      numeric: \"always\",\n      units,\n      unit\n    });\n  }\n\n  /**\n   * Returns a string representation of this date relative to today, such as \"yesterday\" or \"next month\".\n   * Only internationalizes on platforms that supports Intl.RelativeTimeFormat.\n   * @param {Object} options - options that affect the output\n   * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now.\n   * @param {string} options.locale - override the locale of this DateTime\n   * @param {string} options.unit - use a specific unit; if omitted, the method will pick the unit. Use one of \"years\", \"quarters\", \"months\", \"weeks\", or \"days\"\n   * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this\n   * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar() //=> \"tomorrow\"\n   * @example DateTime.now().setLocale(\"es\").plus({ days: 1 }).toRelative() //=> \"\"mañana\"\n   * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar({ locale: \"fr\" }) //=> \"demain\"\n   * @example DateTime.now().minus({ days: 2 }).toRelativeCalendar() //=> \"2 days ago\"\n   */\n  toRelativeCalendar(options = {}) {\n    if (!this.isValid) return null;\n    return diffRelative(options.base || DateTime.fromObject({}, {\n      zone: this.zone\n    }), this, {\n      ...options,\n      numeric: \"auto\",\n      units: [\"years\", \"months\", \"days\"],\n      calendary: true\n    });\n  }\n\n  /**\n   * Return the min of several date times\n   * @param {...DateTime} dateTimes - the DateTimes from which to choose the minimum\n   * @return {DateTime} the min DateTime, or undefined if called with no argument\n   */\n  static min(...dateTimes) {\n    if (!dateTimes.every(DateTime.isDateTime)) {\n      throw new InvalidArgumentError(\"min requires all arguments be DateTimes\");\n    }\n    return bestBy(dateTimes, i => i.valueOf(), Math.min);\n  }\n\n  /**\n   * Return the max of several date times\n   * @param {...DateTime} dateTimes - the DateTimes from which to choose the maximum\n   * @return {DateTime} the max DateTime, or undefined if called with no argument\n   */\n  static max(...dateTimes) {\n    if (!dateTimes.every(DateTime.isDateTime)) {\n      throw new InvalidArgumentError(\"max requires all arguments be DateTimes\");\n    }\n    return bestBy(dateTimes, i => i.valueOf(), Math.max);\n  }\n\n  // MISC\n\n  /**\n   * Explain how a string would be parsed by fromFormat()\n   * @param {string} text - the string to parse\n   * @param {string} fmt - the format the string is expected to be in (see description)\n   * @param {Object} options - options taken by fromFormat()\n   * @return {Object}\n   */\n  static fromFormatExplain(text, fmt, options = {}) {\n    const {\n        locale = null,\n        numberingSystem = null\n      } = options,\n      localeToUse = Locale.fromOpts({\n        locale,\n        numberingSystem,\n        defaultToEN: true\n      });\n    return explainFromTokens(localeToUse, text, fmt);\n  }\n\n  /**\n   * @deprecated use fromFormatExplain instead\n   */\n  static fromStringExplain(text, fmt, options = {}) {\n    return DateTime.fromFormatExplain(text, fmt, options);\n  }\n\n  /**\n   * Build a parser for `fmt` using the given locale. This parser can be passed\n   * to {@link DateTime.fromFormatParser} to a parse a date in this format. This\n   * can be used to optimize cases where many dates need to be parsed in a\n   * specific format.\n   *\n   * @param {String} fmt - the format the string is expected to be in (see\n   * description)\n   * @param {Object} options - options used to set locale and numberingSystem\n   * for parser\n   * @returns {TokenParser} - opaque object to be used\n   */\n  static buildFormatParser(fmt, options = {}) {\n    const {\n        locale = null,\n        numberingSystem = null\n      } = options,\n      localeToUse = Locale.fromOpts({\n        locale,\n        numberingSystem,\n        defaultToEN: true\n      });\n    return new TokenParser(localeToUse, fmt);\n  }\n\n  /**\n   * Create a DateTime from an input string and format parser.\n   *\n   * The format parser must have been created with the same locale as this call.\n   *\n   * @param {String} text - the string to parse\n   * @param {TokenParser} formatParser - parser from {@link DateTime.buildFormatParser}\n   * @param {Object} opts - options taken by fromFormat()\n   * @returns {DateTime}\n   */\n  static fromFormatParser(text, formatParser, opts = {}) {\n    if (isUndefined(text) || isUndefined(formatParser)) {\n      throw new InvalidArgumentError(\"fromFormatParser requires an input string and a format parser\");\n    }\n    const {\n        locale = null,\n        numberingSystem = null\n      } = opts,\n      localeToUse = Locale.fromOpts({\n        locale,\n        numberingSystem,\n        defaultToEN: true\n      });\n    if (!localeToUse.equals(formatParser.locale)) {\n      throw new InvalidArgumentError(`fromFormatParser called with a locale of ${localeToUse}, ` + `but the format parser was created for ${formatParser.locale}`);\n    }\n    const {\n      result,\n      zone,\n      specificOffset,\n      invalidReason\n    } = formatParser.explainFromTokens(text);\n    if (invalidReason) {\n      return DateTime.invalid(invalidReason);\n    } else {\n      return parseDataToDateTime(result, zone, opts, `format ${formatParser.format}`, text, specificOffset);\n    }\n  }\n\n  // FORMAT PRESETS\n\n  /**\n   * {@link DateTime#toLocaleString} format like 10/14/1983\n   * @type {Object}\n   */\n  static get DATE_SHORT() {\n    return DATE_SHORT;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like 'Oct 14, 1983'\n   * @type {Object}\n   */\n  static get DATE_MED() {\n    return DATE_MED;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like 'Fri, Oct 14, 1983'\n   * @type {Object}\n   */\n  static get DATE_MED_WITH_WEEKDAY() {\n    return DATE_MED_WITH_WEEKDAY;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like 'October 14, 1983'\n   * @type {Object}\n   */\n  static get DATE_FULL() {\n    return DATE_FULL;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like 'Tuesday, October 14, 1983'\n   * @type {Object}\n   */\n  static get DATE_HUGE() {\n    return DATE_HUGE;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like '09:30 AM'. Only 12-hour if the locale is.\n   * @type {Object}\n   */\n  static get TIME_SIMPLE() {\n    return TIME_SIMPLE;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like '09:30:23 AM'. Only 12-hour if the locale is.\n   * @type {Object}\n   */\n  static get TIME_WITH_SECONDS() {\n    return TIME_WITH_SECONDS;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like '09:30:23 AM EDT'. Only 12-hour if the locale is.\n   * @type {Object}\n   */\n  static get TIME_WITH_SHORT_OFFSET() {\n    return TIME_WITH_SHORT_OFFSET;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like '09:30:23 AM Eastern Daylight Time'. Only 12-hour if the locale is.\n   * @type {Object}\n   */\n  static get TIME_WITH_LONG_OFFSET() {\n    return TIME_WITH_LONG_OFFSET;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like '09:30', always 24-hour.\n   * @type {Object}\n   */\n  static get TIME_24_SIMPLE() {\n    return TIME_24_SIMPLE;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like '09:30:23', always 24-hour.\n   * @type {Object}\n   */\n  static get TIME_24_WITH_SECONDS() {\n    return TIME_24_WITH_SECONDS;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like '09:30:23 EDT', always 24-hour.\n   * @type {Object}\n   */\n  static get TIME_24_WITH_SHORT_OFFSET() {\n    return TIME_24_WITH_SHORT_OFFSET;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like '09:30:23 Eastern Daylight Time', always 24-hour.\n   * @type {Object}\n   */\n  static get TIME_24_WITH_LONG_OFFSET() {\n    return TIME_24_WITH_LONG_OFFSET;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30 AM'. Only 12-hour if the locale is.\n   * @type {Object}\n   */\n  static get DATETIME_SHORT() {\n    return DATETIME_SHORT;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30:33 AM'. Only 12-hour if the locale is.\n   * @type {Object}\n   */\n  static get DATETIME_SHORT_WITH_SECONDS() {\n    return DATETIME_SHORT_WITH_SECONDS;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30 AM'. Only 12-hour if the locale is.\n   * @type {Object}\n   */\n  static get DATETIME_MED() {\n    return DATETIME_MED;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30:33 AM'. Only 12-hour if the locale is.\n   * @type {Object}\n   */\n  static get DATETIME_MED_WITH_SECONDS() {\n    return DATETIME_MED_WITH_SECONDS;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like 'Fri, 14 Oct 1983, 9:30 AM'. Only 12-hour if the locale is.\n   * @type {Object}\n   */\n  static get DATETIME_MED_WITH_WEEKDAY() {\n    return DATETIME_MED_WITH_WEEKDAY;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30 AM EDT'. Only 12-hour if the locale is.\n   * @type {Object}\n   */\n  static get DATETIME_FULL() {\n    return DATETIME_FULL;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30:33 AM EDT'. Only 12-hour if the locale is.\n   * @type {Object}\n   */\n  static get DATETIME_FULL_WITH_SECONDS() {\n    return DATETIME_FULL_WITH_SECONDS;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30 AM Eastern Daylight Time'. Only 12-hour if the locale is.\n   * @type {Object}\n   */\n  static get DATETIME_HUGE() {\n    return DATETIME_HUGE;\n  }\n\n  /**\n   * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30:33 AM Eastern Daylight Time'. Only 12-hour if the locale is.\n   * @type {Object}\n   */\n  static get DATETIME_HUGE_WITH_SECONDS() {\n    return DATETIME_HUGE_WITH_SECONDS;\n  }\n}\n\n/**\n * @private\n */\nfunction friendlyDateTime(dateTimeish) {\n  if (DateTime.isDateTime(dateTimeish)) {\n    return dateTimeish;\n  } else if (dateTimeish && dateTimeish.valueOf && isNumber(dateTimeish.valueOf())) {\n    return DateTime.fromJSDate(dateTimeish);\n  } else if (dateTimeish && typeof dateTimeish === \"object\") {\n    return DateTime.fromObject(dateTimeish);\n  } else {\n    throw new InvalidArgumentError(`Unknown datetime argument: ${dateTimeish}, of type ${typeof dateTimeish}`);\n  }\n}\n\nconst VERSION = \"3.7.2\";\n\nexports.DateTime = DateTime;\nexports.Duration = Duration;\nexports.FixedOffsetZone = FixedOffsetZone;\nexports.IANAZone = IANAZone;\nexports.Info = Info;\nexports.Interval = Interval;\nexports.InvalidZone = InvalidZone;\nexports.Settings = Settings;\nexports.SystemZone = SystemZone;\nexports.VERSION = VERSION;\nexports.Zone = Zone;\n//# sourceMappingURL=luxon.js.map\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CronDate = exports.DAYS_IN_MONTH = exports.DateMathOp = exports.TimeUnit = void 0;\nconst luxon_1 = require(\"luxon\");\nvar TimeUnit;\n(function (TimeUnit) {\n    TimeUnit[\"Second\"] = \"Second\";\n    TimeUnit[\"Minute\"] = \"Minute\";\n    TimeUnit[\"Hour\"] = \"Hour\";\n    TimeUnit[\"Day\"] = \"Day\";\n    TimeUnit[\"Month\"] = \"Month\";\n    TimeUnit[\"Year\"] = \"Year\";\n})(TimeUnit || (exports.TimeUnit = TimeUnit = {}));\nvar DateMathOp;\n(function (DateMathOp) {\n    DateMathOp[\"Add\"] = \"Add\";\n    DateMathOp[\"Subtract\"] = \"Subtract\";\n})(DateMathOp || (exports.DateMathOp = DateMathOp = {}));\nexports.DAYS_IN_MONTH = Object.freeze([31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]);\n/**\n * CronDate class that wraps the Luxon DateTime object to provide\n * a consistent API for working with dates and times in the context of cron.\n */\nclass CronDate {\n    #date;\n    #dstStart = null;\n    #dstEnd = null;\n    /**\n     * Maps the verb to the appropriate method\n     */\n    #verbMap = {\n        add: {\n            [TimeUnit.Year]: this.addYear.bind(this),\n            [TimeUnit.Month]: this.addMonth.bind(this),\n            [TimeUnit.Day]: this.addDay.bind(this),\n            [TimeUnit.Hour]: this.addHour.bind(this),\n            [TimeUnit.Minute]: this.addMinute.bind(this),\n            [TimeUnit.Second]: this.addSecond.bind(this),\n        },\n        subtract: {\n            [TimeUnit.Year]: this.subtractYear.bind(this),\n            [TimeUnit.Month]: this.subtractMonth.bind(this),\n            [TimeUnit.Day]: this.subtractDay.bind(this),\n            [TimeUnit.Hour]: this.subtractHour.bind(this),\n            [TimeUnit.Minute]: this.subtractMinute.bind(this),\n            [TimeUnit.Second]: this.subtractSecond.bind(this),\n        },\n    };\n    /**\n     * Constructs a new CronDate instance.\n     * @param {CronDate | Date | number | string} [timestamp] - The timestamp to initialize the CronDate with.\n     * @param {string} [tz] - The timezone to use for the CronDate.\n     */\n    constructor(timestamp, tz) {\n        const dateOpts = { zone: tz };\n        // Initialize the internal DateTime object based on the type of timestamp provided.\n        if (!timestamp) {\n            this.#date = luxon_1.DateTime.local();\n        }\n        else if (timestamp instanceof CronDate) {\n            this.#date = timestamp.#date;\n            this.#dstStart = timestamp.#dstStart;\n            this.#dstEnd = timestamp.#dstEnd;\n        }\n        else if (timestamp instanceof Date) {\n            this.#date = luxon_1.DateTime.fromJSDate(timestamp, dateOpts);\n        }\n        else if (typeof timestamp === 'number') {\n            this.#date = luxon_1.DateTime.fromMillis(timestamp, dateOpts);\n        }\n        else {\n            this.#date = luxon_1.DateTime.fromISO(timestamp, dateOpts);\n            this.#date.isValid || (this.#date = luxon_1.DateTime.fromRFC2822(timestamp, dateOpts));\n            this.#date.isValid || (this.#date = luxon_1.DateTime.fromSQL(timestamp, dateOpts));\n            this.#date.isValid || (this.#date = luxon_1.DateTime.fromFormat(timestamp, 'EEE, d MMM yyyy HH:mm:ss', dateOpts));\n        }\n        // Check for valid DateTime and throw an error if not valid.\n        if (!this.#date.isValid) {\n            throw new Error(`CronDate: unhandled timestamp: ${timestamp}`);\n        }\n        // Set the timezone if it is provided and different from the current zone.\n        if (tz && tz !== this.#date.zoneName) {\n            this.#date = this.#date.setZone(tz);\n        }\n    }\n    /**\n     * Determines if the given year is a leap year.\n     * @param {number} year - The year to check\n     * @returns {boolean} - True if the year is a leap year, false otherwise\n     * @private\n     */\n    static #isLeapYear(year) {\n        return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;\n    }\n    /**\n     * Returns daylight savings start time.\n     * @returns {number | null}\n     */\n    get dstStart() {\n        return this.#dstStart;\n    }\n    /**\n     * Sets daylight savings start time.\n     * @param {number | null} value\n     */\n    set dstStart(value) {\n        this.#dstStart = value;\n    }\n    /**\n     * Returns daylight savings end time.\n     * @returns {number | null}\n     */\n    get dstEnd() {\n        return this.#dstEnd;\n    }\n    /**\n     * Sets daylight savings end time.\n     * @param {number | null} value\n     */\n    set dstEnd(value) {\n        this.#dstEnd = value;\n    }\n    /**\n     * Adds one year to the current CronDate.\n     */\n    addYear() {\n        this.#date = this.#date.plus({ years: 1 });\n    }\n    /**\n     * Adds one month to the current CronDate.\n     */\n    addMonth() {\n        this.#date = this.#date.plus({ months: 1 }).startOf('month');\n    }\n    /**\n     * Adds one day to the current CronDate.\n     */\n    addDay() {\n        this.#date = this.#date.plus({ days: 1 }).startOf('day');\n    }\n    /**\n     * Adds one hour to the current CronDate.\n     */\n    addHour() {\n        this.#date = this.#date.plus({ hours: 1 }).startOf('hour');\n    }\n    /**\n     * Adds one minute to the current CronDate.\n     */\n    addMinute() {\n        this.#date = this.#date.plus({ minutes: 1 }).startOf('minute');\n    }\n    /**\n     * Adds one second to the current CronDate.\n     */\n    addSecond() {\n        this.#date = this.#date.plus({ seconds: 1 });\n    }\n    /**\n     * Subtracts one year from the current CronDate.\n     */\n    subtractYear() {\n        this.#date = this.#date.minus({ years: 1 });\n    }\n    /**\n     * Subtracts one month from the current CronDate.\n     * If the month is 1, it will subtract one year instead.\n     */\n    subtractMonth() {\n        this.#date = this.#date.minus({ months: 1 }).endOf('month').startOf('second');\n    }\n    /**\n     * Subtracts one day from the current CronDate.\n     * If the day is 1, it will subtract one month instead.\n     */\n    subtractDay() {\n        this.#date = this.#date.minus({ days: 1 }).endOf('day').startOf('second');\n    }\n    /**\n     * Subtracts one hour from the current CronDate.\n     * If the hour is 0, it will subtract one day instead.\n     */\n    subtractHour() {\n        this.#date = this.#date.minus({ hours: 1 }).endOf('hour').startOf('second');\n    }\n    /**\n     * Subtracts one minute from the current CronDate.\n     * If the minute is 0, it will subtract one hour instead.\n     */\n    subtractMinute() {\n        this.#date = this.#date.minus({ minutes: 1 }).endOf('minute').startOf('second');\n    }\n    /**\n     * Subtracts one second from the current CronDate.\n     * If the second is 0, it will subtract one minute instead.\n     */\n    subtractSecond() {\n        this.#date = this.#date.minus({ seconds: 1 });\n    }\n    /**\n     * Adds a unit of time to the current CronDate.\n     * @param {TimeUnit} unit\n     */\n    addUnit(unit) {\n        this.#verbMap.add[unit]();\n    }\n    /**\n     * Subtracts a unit of time from the current CronDate.\n     * @param {TimeUnit} unit\n     */\n    subtractUnit(unit) {\n        this.#verbMap.subtract[unit]();\n    }\n    /**\n     * Handles a math operation.\n     * @param {DateMathOp} verb - {'add' | 'subtract'}\n     * @param {TimeUnit} unit - {'year' | 'month' | 'day' | 'hour' | 'minute' | 'second'}\n     */\n    invokeDateOperation(verb, unit) {\n        if (verb === DateMathOp.Add) {\n            this.addUnit(unit);\n            return;\n        }\n        if (verb === DateMathOp.Subtract) {\n            this.subtractUnit(unit);\n            return;\n        }\n        /* istanbul ignore next - this would only happen if an end user call the handleMathOp with an invalid verb */\n        throw new Error(`Invalid verb: ${verb}`);\n    }\n    /**\n     * Returns the day.\n     * @returns {number}\n     */\n    getDate() {\n        return this.#date.day;\n    }\n    /**\n     * Returns the year.\n     * @returns {number}\n     */\n    getFullYear() {\n        return this.#date.year;\n    }\n    /**\n     * Returns the day of the week.\n     * @returns {number}\n     */\n    getDay() {\n        const weekday = this.#date.weekday;\n        return weekday === 7 ? 0 : weekday;\n    }\n    /**\n     * Returns the month.\n     * @returns {number}\n     */\n    getMonth() {\n        return this.#date.month - 1;\n    }\n    /**\n     * Returns the hour.\n     * @returns {number}\n     */\n    getHours() {\n        return this.#date.hour;\n    }\n    /**\n     * Returns the minutes.\n     * @returns {number}\n     */\n    getMinutes() {\n        return this.#date.minute;\n    }\n    /**\n     * Returns the seconds.\n     * @returns {number}\n     */\n    getSeconds() {\n        return this.#date.second;\n    }\n    /**\n     * Returns the milliseconds.\n     * @returns {number}\n     */\n    getMilliseconds() {\n        return this.#date.millisecond;\n    }\n    /**\n     * Returns the timezone offset from UTC in minutes (e.g. UTC+2 => 120).\n     * Useful for detecting DST transition days.\n     *\n     * @returns {number} UTC offset in minutes\n     */\n    getUTCOffset() {\n        return this.#date.offset;\n    }\n    /**\n     * Sets the time to the start of the day (00:00:00.000) in the current timezone.\n     */\n    setStartOfDay() {\n        this.#date = this.#date.startOf('day');\n    }\n    /**\n     * Sets the time to the end of the day (23:59:59.999) in the current timezone.\n     */\n    setEndOfDay() {\n        this.#date = this.#date.endOf('day');\n    }\n    /**\n     * Returns the time.\n     * @returns {number}\n     */\n    getTime() {\n        return this.#date.valueOf();\n    }\n    /**\n     * Returns the UTC day.\n     * @returns {number}\n     */\n    getUTCDate() {\n        return this.#getUTC().day;\n    }\n    /**\n     * Returns the UTC year.\n     * @returns {number}\n     */\n    getUTCFullYear() {\n        return this.#getUTC().year;\n    }\n    /**\n     * Returns the UTC day of the week.\n     * @returns {number}\n     */\n    getUTCDay() {\n        const weekday = this.#getUTC().weekday;\n        return weekday === 7 ? 0 : weekday;\n    }\n    /**\n     * Returns the UTC month.\n     * @returns {number}\n     */\n    getUTCMonth() {\n        return this.#getUTC().month - 1;\n    }\n    /**\n     * Returns the UTC hour.\n     * @returns {number}\n     */\n    getUTCHours() {\n        return this.#getUTC().hour;\n    }\n    /**\n     * Returns the UTC minutes.\n     * @returns {number}\n     */\n    getUTCMinutes() {\n        return this.#getUTC().minute;\n    }\n    /**\n     * Returns the UTC seconds.\n     * @returns {number}\n     */\n    getUTCSeconds() {\n        return this.#getUTC().second;\n    }\n    /**\n     * Returns the UTC milliseconds.\n     * @returns {string | null}\n     */\n    toISOString() {\n        return this.#date.toUTC().toISO();\n    }\n    /**\n     * Returns the date as a JSON string.\n     * @returns {string | null}\n     */\n    toJSON() {\n        return this.#date.toJSON();\n    }\n    /**\n     * Sets the day.\n     * @param d\n     */\n    setDate(d) {\n        this.#date = this.#date.set({ day: d });\n    }\n    /**\n     * Sets the year.\n     * @param y\n     */\n    setFullYear(y) {\n        this.#date = this.#date.set({ year: y });\n    }\n    /**\n     * Sets the day of the week.\n     * @param d\n     */\n    setDay(d) {\n        this.#date = this.#date.set({ weekday: d });\n    }\n    /**\n     * Sets the month.\n     * @param m\n     */\n    setMonth(m) {\n        this.#date = this.#date.set({ month: m + 1 });\n    }\n    /**\n     * Sets the hour.\n     * @param h\n     */\n    setHours(h) {\n        this.#date = this.#date.set({ hour: h });\n    }\n    /**\n     * Sets the minutes.\n     * @param m\n     */\n    setMinutes(m) {\n        this.#date = this.#date.set({ minute: m });\n    }\n    /**\n     * Sets the seconds.\n     * @param s\n     */\n    setSeconds(s) {\n        this.#date = this.#date.set({ second: s });\n    }\n    /**\n     * Sets the milliseconds.\n     * @param s\n     */\n    setMilliseconds(s) {\n        this.#date = this.#date.set({ millisecond: s });\n    }\n    /**\n     * Returns the date as a string.\n     * @returns {string}\n     */\n    toString() {\n        return this.toDate().toString();\n    }\n    /**\n     * Returns the date as a Date object.\n     * @returns {Date}\n     */\n    toDate() {\n        return this.#date.toJSDate();\n    }\n    /**\n     * Returns true if the day is the last day of the month.\n     * @returns {boolean}\n     */\n    isLastDayOfMonth() {\n        const { day, month } = this.#date;\n        // Special handling for February in leap years\n        if (month === 2) {\n            const isLeap = CronDate.#isLeapYear(this.#date.year);\n            return day === exports.DAYS_IN_MONTH[month - 1] - (isLeap ? 0 : 1);\n        }\n        // For other months, check against the static map\n        return day === exports.DAYS_IN_MONTH[month - 1];\n    }\n    /**\n     * Returns true if the day is the last weekday of the month.\n     * @returns {boolean}\n     */\n    isLastWeekdayOfMonth() {\n        const { day, month } = this.#date;\n        // Get the last day of the current month\n        let lastDay;\n        if (month === 2) {\n            // Special handling for February\n            lastDay = exports.DAYS_IN_MONTH[month - 1] - (CronDate.#isLeapYear(this.#date.year) ? 0 : 1);\n        }\n        else {\n            lastDay = exports.DAYS_IN_MONTH[month - 1];\n        }\n        // Check if the current day is within 7 days of the end of the month\n        return day > lastDay - 7;\n    }\n    /**\n     * Primarily for internal use.\n     * @param {DateMathOp} op - The operation to perform.\n     * @param {TimeUnit} unit - The unit of time to use.\n     * @param {number} [hoursLength] - The length of the hours. Required when unit is not month or day.\n     */\n    applyDateOperation(op, unit, hoursLength) {\n        if (unit === TimeUnit.Month || unit === TimeUnit.Day) {\n            this.invokeDateOperation(op, unit);\n            return;\n        }\n        const previousHour = this.getHours();\n        this.invokeDateOperation(op, unit);\n        const currentHour = this.getHours();\n        const diff = currentHour - previousHour;\n        if (diff === 2) {\n            if (hoursLength !== 24) {\n                this.dstStart = currentHour;\n            }\n        }\n        else if (diff === 0 && this.getMinutes() === 0 && this.getSeconds() === 0) {\n            if (hoursLength !== 24) {\n                this.dstEnd = currentHour;\n            }\n        }\n    }\n    /**\n     * Returns the UTC date.\n     * @private\n     * @returns {DateTime}\n     */\n    #getUTC() {\n        return this.#date.toUTC();\n    }\n}\nexports.CronDate = CronDate;\nexports.default = CronDate;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CronMonth = void 0;\nconst CronDate_1 = require(\"../CronDate\");\nconst CronField_1 = require(\"./CronField\");\nconst MIN_MONTH = 1;\nconst MAX_MONTH = 12;\nconst MONTH_CHARS = Object.freeze([]);\n/**\n * Represents the \"day of the month\" field within a cron expression.\n * @class CronDayOfMonth\n * @extends CronField\n */\nclass CronMonth extends CronField_1.CronField {\n    static get min() {\n        return MIN_MONTH;\n    }\n    static get max() {\n        return MAX_MONTH;\n    }\n    static get chars() {\n        return MONTH_CHARS;\n    }\n    static get daysInMonth() {\n        return CronDate_1.DAYS_IN_MONTH;\n    }\n    /**\n     * CronDayOfMonth constructor. Initializes the \"day of the month\" field with the provided values.\n     * @param {MonthRange[]} values - Values for the \"day of the month\" field\n     * @param {CronFieldOptions} [options] - Options provided by the parser\n     */\n    constructor(values, options) {\n        super(values, options);\n        this.validate();\n    }\n    /**\n     * Returns an array of allowed values for the \"day of the month\" field.\n     * @returns {MonthRange[]}\n     */\n    get values() {\n        return super.values;\n    }\n}\nexports.CronMonth = CronMonth;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CronSecond = void 0;\nconst CronField_1 = require(\"./CronField\");\nconst MIN_SECOND = 0;\nconst MAX_SECOND = 59;\nconst SECOND_CHARS = Object.freeze([]);\n/**\n * Represents the \"second\" field within a cron expression.\n * @class CronSecond\n * @extends CronField\n */\nclass CronSecond extends CronField_1.CronField {\n    static get min() {\n        return MIN_SECOND;\n    }\n    static get max() {\n        return MAX_SECOND;\n    }\n    static get chars() {\n        return SECOND_CHARS;\n    }\n    /**\n     * CronSecond constructor. Initializes the \"second\" field with the provided values.\n     * @param {SixtyRange[]} values - Values for the \"second\" field\n     * @param {CronFieldOptions} [options] - Options provided by the parser\n     */\n    constructor(values, options) {\n        super(values, options);\n        this.validate();\n    }\n    /**\n     * Returns an array of allowed values for the \"second\" field.\n     * @returns {SixtyRange[]}\n     */\n    get values() {\n        return super.values;\n    }\n}\nexports.CronSecond = CronSecond;\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n    if (k2 === undefined) k2 = k;\n    var desc = Object.getOwnPropertyDescriptor(m, k);\n    if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n      desc = { enumerable: true, get: function() { return m[k]; } };\n    }\n    Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n    if (k2 === undefined) k2 = k;\n    o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n    for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./types\"), exports);\n__exportStar(require(\"./CronDayOfMonth\"), exports);\n__exportStar(require(\"./CronDayOfWeek\"), exports);\n__exportStar(require(\"./CronField\"), exports);\n__exportStar(require(\"./CronHour\"), exports);\n__exportStar(require(\"./CronMinute\"), exports);\n__exportStar(require(\"./CronMonth\"), exports);\n__exportStar(require(\"./CronSecond\"), exports);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CronFieldCollection = void 0;\nconst fields_1 = require(\"./fields\");\n/**\n * Represents a complete set of cron fields.\n * @class CronFieldCollection\n */\nclass CronFieldCollection {\n    #second;\n    #minute;\n    #hour;\n    #dayOfMonth;\n    #month;\n    #dayOfWeek;\n    /**\n     * Creates a new CronFieldCollection instance by partially overriding fields from an existing one.\n     * @param {CronFieldCollection} base - The base CronFieldCollection to copy fields from\n     * @param {CronFieldOverride} fields - The fields to override, can be CronField instances or raw values\n     * @returns {CronFieldCollection} A new CronFieldCollection instance\n     * @example\n     * const base = new CronFieldCollection({\n     *   second: new CronSecond([0]),\n     *   minute: new CronMinute([0]),\n     *   hour: new CronHour([12]),\n     *   dayOfMonth: new CronDayOfMonth([1]),\n     *   month: new CronMonth([1]),\n     *   dayOfWeek: new CronDayOfWeek([1])\n     * });\n     *\n     * // Using CronField instances\n     * const modified1 = CronFieldCollection.from(base, {\n     *   hour: new CronHour([15]),\n     *   minute: new CronMinute([30])\n     * });\n     *\n     * // Using raw values\n     * const modified2 = CronFieldCollection.from(base, {\n     *   hour: [15],        // Will create new CronHour\n     *   minute: [30]       // Will create new CronMinute\n     * });\n     */\n    static from(base, fields) {\n        return new CronFieldCollection({\n            second: this.resolveField(fields_1.CronSecond, base.second, fields.second),\n            minute: this.resolveField(fields_1.CronMinute, base.minute, fields.minute),\n            hour: this.resolveField(fields_1.CronHour, base.hour, fields.hour),\n            dayOfMonth: this.resolveField(fields_1.CronDayOfMonth, base.dayOfMonth, fields.dayOfMonth),\n            month: this.resolveField(fields_1.CronMonth, base.month, fields.month),\n            dayOfWeek: this.resolveField(fields_1.CronDayOfWeek, base.dayOfWeek, fields.dayOfWeek),\n        });\n    }\n    /**\n     * Resolves a field value, either using the provided CronField instance or creating a new one from raw values.\n     * @param constructor - The constructor for creating new field instances\n     * @param baseField - The base field to use if no override is provided\n     * @param fieldValue - The override value, either a CronField instance or raw values\n     * @returns The resolved CronField instance\n     * @private\n     */\n    static resolveField(constructor, baseField, fieldValue) {\n        if (!fieldValue) {\n            return baseField;\n        }\n        if (fieldValue instanceof fields_1.CronField) {\n            return fieldValue;\n        }\n        return new constructor(fieldValue);\n    }\n    /**\n     * CronFieldCollection constructor. Initializes the cron fields with the provided values.\n     * @param {CronFields} param0 - The cron fields values\n     * @throws {Error} if validation fails\n     * @example\n     * const cronFields = new CronFieldCollection({\n     *   second: new CronSecond([0]),\n     *   minute: new CronMinute([0, 30]),\n     *   hour: new CronHour([9]),\n     *   dayOfMonth: new CronDayOfMonth([15]),\n     *   month: new CronMonth([1]),\n     *   dayOfWeek: new CronDayOfTheWeek([1, 2, 3, 4, 5]),\n     * })\n     *\n     * console.log(cronFields.second.values); // [0]\n     * console.log(cronFields.minute.values); // [0, 30]\n     * console.log(cronFields.hour.values); // [9]\n     * console.log(cronFields.dayOfMonth.values); // [15]\n     * console.log(cronFields.month.values); // [1]\n     * console.log(cronFields.dayOfWeek.values); // [1, 2, 3, 4, 5]\n     */\n    constructor({ second, minute, hour, dayOfMonth, month, dayOfWeek }) {\n        if (!second) {\n            throw new Error('Validation error, Field second is missing');\n        }\n        if (!minute) {\n            throw new Error('Validation error, Field minute is missing');\n        }\n        if (!hour) {\n            throw new Error('Validation error, Field hour is missing');\n        }\n        if (!dayOfMonth) {\n            throw new Error('Validation error, Field dayOfMonth is missing');\n        }\n        if (!month) {\n            throw new Error('Validation error, Field month is missing');\n        }\n        if (!dayOfWeek) {\n            throw new Error('Validation error, Field dayOfWeek is missing');\n        }\n        if (month.values.length === 1 && !dayOfMonth.hasLastChar) {\n            if (!(parseInt(dayOfMonth.values[0], 10) <= fields_1.CronMonth.daysInMonth[month.values[0] - 1])) {\n                throw new Error('Invalid explicit day of month definition');\n            }\n        }\n        this.#second = second;\n        this.#minute = minute;\n        this.#hour = hour;\n        this.#month = month;\n        this.#dayOfWeek = dayOfWeek;\n        this.#dayOfMonth = dayOfMonth;\n    }\n    /**\n     * Returns the second field.\n     * @returns {CronSecond}\n     */\n    get second() {\n        return this.#second;\n    }\n    /**\n     * Returns the minute field.\n     * @returns {CronMinute}\n     */\n    get minute() {\n        return this.#minute;\n    }\n    /**\n     * Returns the hour field.\n     * @returns {CronHour}\n     */\n    get hour() {\n        return this.#hour;\n    }\n    /**\n     * Returns the day of the month field.\n     * @returns {CronDayOfMonth}\n     */\n    get dayOfMonth() {\n        return this.#dayOfMonth;\n    }\n    /**\n     * Returns the month field.\n     * @returns {CronMonth}\n     */\n    get month() {\n        return this.#month;\n    }\n    /**\n     * Returns the day of the week field.\n     * @returns {CronDayOfWeek}\n     */\n    get dayOfWeek() {\n        return this.#dayOfWeek;\n    }\n    /**\n     * Returns a string representation of the cron fields.\n     * @param {(number | CronChars)[]} input - The cron fields values\n     * @static\n     * @returns {FieldRange[]} - The compacted cron fields\n     */\n    static compactField(input) {\n        if (input.length === 0) {\n            return [];\n        }\n        // Initialize the output array and current IFieldRange\n        const output = [];\n        let current = undefined;\n        input.forEach((item, i, arr) => {\n            // If the current FieldRange is undefined, create a new one with the current item as the start.\n            if (current === undefined) {\n                current = { start: item, count: 1 };\n                return;\n            }\n            // Cache the previous and next items in the array.\n            const prevItem = arr[i - 1] || current.start;\n            const nextItem = arr[i + 1];\n            // If the current item is 'L' or 'W', push the current FieldRange to the output and\n            // create a new FieldRange with the current item as the start.\n            // 'L' and 'W' characters are special cases that need to be handled separately.\n            if (item === 'L' || item === 'W') {\n                output.push(current);\n                output.push({ start: item, count: 1 });\n                current = undefined;\n                return;\n            }\n            // If the current step is undefined and there is a next item, update the current IFieldRange.\n            // This block checks if the current step needs to be updated and does so if needed.\n            if (current.step === undefined && nextItem !== undefined) {\n                const step = item - prevItem;\n                const nextStep = nextItem - item;\n                // If the current step is less or equal to the next step, update the current FieldRange to include the current item.\n                if (step <= nextStep) {\n                    current = { ...current, count: 2, end: item, step };\n                    return;\n                }\n                current.step = 1;\n            }\n            // If the difference between the current item and the current end is equal to the current step,\n            // update the current IFieldRange's count and end.\n            // This block checks if the current item is part of the current range and updates the range accordingly.\n            if (item - (current.end ?? 0) === current.step) {\n                current.count++;\n                current.end = item;\n            }\n            else {\n                // If the count is 1, push a new FieldRange with the current start.\n                // This handles the case where the current range has only one element.\n                if (current.count === 1) {\n                    // If the count is 2, push two separate IFieldRanges, one for each element.\n                    output.push({ start: current.start, count: 1 });\n                }\n                else if (current.count === 2) {\n                    output.push({ start: current.start, count: 1 });\n                    // current.end can never be undefined here but typescript doesn't know that\n                    // this is why we ?? it and then ignore the prevItem in the coverage\n                    output.push({\n                        start: current.end ?? /* istanbul ignore next - see above */ prevItem,\n                        count: 1,\n                    });\n                }\n                else {\n                    // Otherwise, push the current FieldRange to the output.\n                    output.push(current);\n                }\n                // Reset the current FieldRange with the current item as the start.\n                current = { start: item, count: 1 };\n            }\n        });\n        // Push the final IFieldRange, if any, to the output array.\n        if (current) {\n            output.push(current);\n        }\n        return output;\n    }\n    /**\n     * Handles a single range.\n     * @param {CronField} field - The cron field to stringify\n     * @param {FieldRange} range {start: number, end: number, step: number, count: number} The range to handle.\n     * @param {number} max The maximum value for the field.\n     * @returns {string | null} The stringified range or null if it cannot be stringified.\n     * @private\n     */\n    static #handleSingleRange(field, range, max) {\n        const step = range.step;\n        if (!step) {\n            return null;\n        }\n        if (step === 1 && range.start === field.min && range.end && range.end >= max) {\n            return field.hasQuestionMarkChar ? '?' : '*';\n        }\n        if (step !== 1 && range.start === field.min && range.end && range.end >= max - step + 1) {\n            return `*/${step}`;\n        }\n        return null;\n    }\n    /**\n     * Handles multiple ranges.\n     * @param {FieldRange} range {start: number, end: number, step: number, count: number} The range to handle.\n     * @param {number} max The maximum value for the field.\n     * @returns {string} The stringified range.\n     * @private\n     */\n    static #handleMultipleRanges(range, max) {\n        const step = range.step;\n        if (step === 1) {\n            return `${range.start}-${range.end}`;\n        }\n        const multiplier = range.start === 0 ? range.count - 1 : range.count;\n        /* istanbul ignore if */\n        if (!step) {\n            throw new Error('Unexpected range step');\n        }\n        /* istanbul ignore if */\n        if (!range.end) {\n            throw new Error('Unexpected range end');\n        }\n        if (step * multiplier > range.end) {\n            const mapFn = (_, index) => {\n                /* istanbul ignore if */\n                if (typeof range.start !== 'number') {\n                    throw new Error('Unexpected range start');\n                }\n                return index % step === 0 ? range.start + index : null;\n            };\n            /* istanbul ignore if */\n            if (typeof range.start !== 'number') {\n                throw new Error('Unexpected range start');\n            }\n            const seed = { length: range.end - range.start + 1 };\n            return Array.from(seed, mapFn)\n                .filter((value) => value !== null)\n                .join(',');\n        }\n        return range.end === max - step + 1 ? `${range.start}/${step}` : `${range.start}-${range.end}/${step}`;\n    }\n    /**\n     * Returns a string representation of the cron fields.\n     * @param {CronField} field - The cron field to stringify\n     * @static\n     * @returns {string} - The stringified cron field\n     */\n    stringifyField(field) {\n        let max = field.max;\n        let values = field.values;\n        if (field instanceof fields_1.CronDayOfWeek) {\n            max = 6;\n            const dayOfWeek = this.#dayOfWeek.values;\n            values = dayOfWeek[dayOfWeek.length - 1] === 7 ? dayOfWeek.slice(0, -1) : dayOfWeek;\n        }\n        if (field instanceof fields_1.CronDayOfMonth) {\n            max = this.#month.values.length === 1 ? fields_1.CronMonth.daysInMonth[this.#month.values[0] - 1] : field.max;\n        }\n        const ranges = CronFieldCollection.compactField(values);\n        if (ranges.length === 1) {\n            const singleRangeResult = CronFieldCollection.#handleSingleRange(field, ranges[0], max);\n            if (singleRangeResult) {\n                return singleRangeResult;\n            }\n        }\n        return ranges\n            .map((range) => {\n            const value = range.count === 1 ? range.start.toString() : CronFieldCollection.#handleMultipleRanges(range, max);\n            if (field instanceof fields_1.CronDayOfWeek && field.nthDay > 0) {\n                return `${value}#${field.nthDay}`;\n            }\n            return value;\n        })\n            .join(',');\n    }\n    /**\n     * Returns a string representation of the cron field values.\n     * @param {boolean} includeSeconds - Whether to include seconds in the output\n     * @returns {string} The formatted cron string\n     */\n    stringify(includeSeconds = false) {\n        const arr = [];\n        if (includeSeconds) {\n            arr.push(this.stringifyField(this.#second)); // second\n        }\n        arr.push(this.stringifyField(this.#minute), // minute\n        this.stringifyField(this.#hour), // hour\n        this.stringifyField(this.#dayOfMonth), // dayOfMonth\n        this.stringifyField(this.#month), // month\n        this.stringifyField(this.#dayOfWeek));\n        return arr.join(' ');\n    }\n    /**\n     * Returns a serialized representation of the cron fields values.\n     * @returns {SerializedCronFields} An object containing the cron field values\n     */\n    serialize() {\n        return {\n            second: this.#second.serialize(),\n            minute: this.#minute.serialize(),\n            hour: this.#hour.serialize(),\n            dayOfMonth: this.#dayOfMonth.serialize(),\n            month: this.#month.serialize(),\n            dayOfWeek: this.#dayOfWeek.serialize(),\n        };\n    }\n}\nexports.CronFieldCollection = CronFieldCollection;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CronExpression = exports.LOOPS_LIMIT_EXCEEDED_ERROR_MESSAGE = exports.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE = void 0;\nconst CronDate_1 = require(\"./CronDate\");\n/**\n * Error message for when the current date is outside the specified time span.\n */\nexports.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE = 'Out of the time span range';\n/**\n * Error message for when the loop limit is exceeded during iteration.\n */\nexports.LOOPS_LIMIT_EXCEEDED_ERROR_MESSAGE = 'Invalid expression, loop limit exceeded';\n/**\n * Cron iteration loop safety limit\n */\nconst LOOP_LIMIT = 10000;\n/**\n * Class representing a Cron expression.\n */\nclass CronExpression {\n    #options;\n    #tz;\n    #currentDate;\n    #startDate;\n    #endDate;\n    #fields;\n    #dstTransitionDayKey = null;\n    #isDstTransitionDay = false;\n    /**\n     * Creates a new CronExpression instance.\n     *\n     * @param {CronFieldCollection} fields - Cron fields.\n     * @param {CronExpressionOptions} options - Parser options.\n     */\n    constructor(fields, options) {\n        this.#options = options;\n        this.#tz = options.tz;\n        this.#startDate = options.startDate ? new CronDate_1.CronDate(options.startDate, this.#tz) : null;\n        this.#endDate = options.endDate ? new CronDate_1.CronDate(options.endDate, this.#tz) : null;\n        let currentDateValue = options.currentDate ?? options.startDate;\n        if (currentDateValue) {\n            const tempCurrentDate = new CronDate_1.CronDate(currentDateValue, this.#tz);\n            if (this.#startDate && tempCurrentDate.getTime() < this.#startDate.getTime()) {\n                currentDateValue = this.#startDate;\n            }\n            else if (this.#endDate && tempCurrentDate.getTime() > this.#endDate.getTime()) {\n                currentDateValue = this.#endDate;\n            }\n        }\n        this.#currentDate = new CronDate_1.CronDate(currentDateValue, this.#tz);\n        this.#fields = fields;\n    }\n    /**\n     * Getter for the cron fields.\n     *\n     * @returns {CronFieldCollection} Cron fields.\n     */\n    get fields() {\n        return this.#fields;\n    }\n    /**\n     * Converts cron fields back to a CronExpression instance.\n     *\n     * @public\n     * @param {Record<string, number[]>} fields - The input cron fields object.\n     * @param {CronExpressionOptions} [options] - Optional parsing options.\n     * @returns {CronExpression} - A new CronExpression instance.\n     */\n    static fieldsToExpression(fields, options) {\n        return new CronExpression(fields, options || {});\n    }\n    /**\n     * Checks if the given value matches any element in the sequence.\n     *\n     * @param {number} value - The value to be matched.\n     * @param {number[]} sequence - The sequence to be checked against.\n     * @returns {boolean} - True if the value matches an element in the sequence; otherwise, false.\n     * @memberof CronExpression\n     * @private\n     */\n    static #matchSchedule(value, sequence) {\n        return sequence.some((element) => element === value);\n    }\n    /**\n     * Returns the minimum or maximum value from the given array of numbers.\n     *\n     * @param {number[]} values - An array of numbers.\n     * @param {boolean} reverse - If true, returns the maximum value; otherwise, returns the minimum value.\n     * @returns {number} - The minimum or maximum value.\n     */\n    #getMinOrMax(values, reverse) {\n        return values[reverse ? values.length - 1 : 0];\n    }\n    /**\n     * Checks whether the given date falls on a DST transition day in its timezone.\n     *\n     * This is used to disable certain “direct set” fast paths on DST days, because setting the hour\n     * directly may land on a non-existent or repeated local time. We cache the result per calendar day\n     * to keep iteration overhead low.\n     *\n     * @param {CronDate} currentDate - Date to check (in the cron timezone)\n     * @returns {boolean} True when the day has a DST transition\n     * @private\n     */\n    #checkDstTransition(currentDate) {\n        // Cache per calendar day (in the cron date's timezone) to avoid repeated work inside the iteration loop.\n        const key = `${currentDate.getFullYear()}-${currentDate.getMonth() + 1}-${currentDate.getDate()}`;\n        if (this.#dstTransitionDayKey === key) {\n            return this.#isDstTransitionDay;\n        }\n        const startOfDay = new CronDate_1.CronDate(currentDate);\n        startOfDay.setStartOfDay();\n        const endOfDay = new CronDate_1.CronDate(currentDate);\n        endOfDay.setEndOfDay();\n        this.#dstTransitionDayKey = key;\n        this.#isDstTransitionDay = startOfDay.getUTCOffset() !== endOfDay.getUTCOffset();\n        return this.#isDstTransitionDay;\n    }\n    /**\n     * Moves the date to the next/previous allowed second value. If there is no remaining allowed second\n     * within the current minute, rolls to the next/previous minute and resets seconds to the min/max allowed.\n     *\n     * @param {CronDate} currentDate - Mutable date being iterated\n     * @param {DateMathOp} dateMathVerb - Add/Subtract depending on direction\n     * @param {boolean} reverse - When true, iterating backwards\n     * @private\n     */\n    #moveToNextSecond(currentDate, dateMathVerb, reverse) {\n        const seconds = this.#fields.second.values;\n        const currentSecond = currentDate.getSeconds();\n        const nextSecond = this.#fields.second.findNearestValue(currentSecond, reverse);\n        if (nextSecond !== null) {\n            currentDate.setSeconds(nextSecond);\n            return;\n        }\n        // Roll over to the next/previous minute and start from the min/max allowed second.\n        currentDate.applyDateOperation(dateMathVerb, CronDate_1.TimeUnit.Minute, this.#fields.hour.values.length);\n        currentDate.setSeconds(this.#getMinOrMax(seconds, reverse));\n    }\n    /**\n     * Moves the date to the next/previous allowed minute value and resets seconds to the min/max allowed.\n     * If there is no remaining allowed minute within the current hour, rolls to the next/previous hour and\n     * resets minutes/seconds to their extrema.\n     *\n     * @param {CronDate} currentDate - Mutable date being iterated\n     * @param {DateMathOp} dateMathVerb - Add/Subtract depending on direction\n     * @param {boolean} reverse - When true, iterating backwards\n     * @private\n     */\n    #moveToNextMinute(currentDate, dateMathVerb, reverse) {\n        const minutes = this.#fields.minute.values;\n        const seconds = this.#fields.second.values;\n        const currentMinute = currentDate.getMinutes();\n        const nextMinute = this.#fields.minute.findNearestValue(currentMinute, reverse);\n        if (nextMinute !== null) {\n            currentDate.setMinutes(nextMinute);\n            currentDate.setSeconds(this.#getMinOrMax(seconds, reverse));\n            return;\n        }\n        // Roll over to the next/previous hour and start from the min/max allowed minute/second.\n        currentDate.applyDateOperation(dateMathVerb, CronDate_1.TimeUnit.Hour, this.#fields.hour.values.length);\n        currentDate.setMinutes(this.#getMinOrMax(minutes, reverse));\n        currentDate.setSeconds(this.#getMinOrMax(seconds, reverse));\n    }\n    /**\n     * Determines if the current date matches the last specified weekday of the month.\n     *\n     * @param {Array<(number|string)>} expressions - An array of expressions containing weekdays and \"L\" for the last weekday.\n     * @param {CronDate} currentDate - The current date object.\n     * @returns {boolean} - True if the current date matches the last specified weekday of the month; otherwise, false.\n     * @memberof CronExpression\n     * @private\n     */\n    static #isLastWeekdayOfMonthMatch(expressions, currentDate) {\n        const isLastWeekdayOfMonth = currentDate.isLastWeekdayOfMonth();\n        return expressions.some((expression) => {\n            // The first character represents the weekday\n            const weekday = parseInt(expression.toString().charAt(0), 10) % 7;\n            if (Number.isNaN(weekday)) {\n                throw new Error(`Invalid last weekday of the month expression: ${expression}`);\n            }\n            // Check if the current date matches the last specified weekday of the month\n            return currentDate.getDay() === weekday && isLastWeekdayOfMonth;\n        });\n    }\n    /**\n     * Find the next scheduled date based on the cron expression.\n     * @returns {CronDate} - The next scheduled date or an ES6 compatible iterator object.\n     * @memberof CronExpression\n     * @public\n     */\n    next() {\n        return this.#findSchedule();\n    }\n    /**\n     * Find the previous scheduled date based on the cron expression.\n     * @returns {CronDate} - The previous scheduled date or an ES6 compatible iterator object.\n     * @memberof CronExpression\n     * @public\n     */\n    prev() {\n        return this.#findSchedule(true);\n    }\n    /**\n     * Check if there is a next scheduled date based on the current date and cron expression.\n     * @returns {boolean} - Returns true if there is a next scheduled date, false otherwise.\n     * @memberof CronExpression\n     * @public\n     */\n    hasNext() {\n        const current = this.#currentDate;\n        try {\n            this.#findSchedule();\n            return true;\n        }\n        catch {\n            return false;\n        }\n        finally {\n            this.#currentDate = current;\n        }\n    }\n    /**\n     * Check if there is a previous scheduled date based on the current date and cron expression.\n     * @returns {boolean} - Returns true if there is a previous scheduled date, false otherwise.\n     * @memberof CronExpression\n     * @public\n     */\n    hasPrev() {\n        const current = this.#currentDate;\n        try {\n            this.#findSchedule(true);\n            return true;\n        }\n        catch {\n            return false;\n        }\n        finally {\n            this.#currentDate = current;\n        }\n    }\n    /**\n     * Iterate over a specified number of steps and optionally execute a callback function for each step.\n     * @param {number} steps - The number of steps to iterate. Positive value iterates forward, negative value iterates backward.\n     * @returns {CronDate[]} - An array of iterator fields or CronDate objects.\n     * @memberof CronExpression\n     * @public\n     */\n    take(limit) {\n        const items = [];\n        if (limit >= 0) {\n            for (let i = 0; i < limit; i++) {\n                try {\n                    items.push(this.next());\n                }\n                catch {\n                    return items;\n                }\n            }\n        }\n        else {\n            for (let i = 0; i > limit; i--) {\n                try {\n                    items.push(this.prev());\n                }\n                catch {\n                    return items;\n                }\n            }\n        }\n        return items;\n    }\n    /**\n     * Reset the iterators current date to a new date or the initial date.\n     * @param {Date | CronDate} [newDate] - Optional new date to reset to. If not provided, it will reset to the initial date.\n     * @memberof CronExpression\n     * @public\n     */\n    reset(newDate) {\n        this.#currentDate = new CronDate_1.CronDate(newDate || this.#options.currentDate);\n    }\n    /**\n     * Generate a string representation of the cron expression.\n     * @param {boolean} [includeSeconds=false] - Whether to include the seconds field in the string representation.\n     * @returns {string} - The string representation of the cron expression.\n     * @memberof CronExpression\n     * @public\n     */\n    stringify(includeSeconds = false) {\n        return this.#fields.stringify(includeSeconds);\n    }\n    /**\n     * Check if the cron expression includes the given date\n     * @param {Date|CronDate} date\n     * @returns {boolean}\n     */\n    includesDate(date) {\n        const { second, minute, hour, month } = this.#fields;\n        const dt = new CronDate_1.CronDate(date, this.#tz);\n        // Check basic time fields first\n        if (!second.values.includes(dt.getSeconds()) ||\n            !minute.values.includes(dt.getMinutes()) ||\n            !hour.values.includes(dt.getHours()) ||\n            !month.values.includes((dt.getMonth() + 1))) {\n            return false;\n        }\n        // Check day of month and day of week using the same logic as #findSchedule\n        if (!this.#matchDayOfMonth(dt)) {\n            return false;\n        }\n        // Check nth day of week if specified\n        if (this.#fields.dayOfWeek.nthDay > 0) {\n            const weekInMonth = Math.ceil(dt.getDate() / 7);\n            if (weekInMonth !== this.#fields.dayOfWeek.nthDay) {\n                return false;\n            }\n        }\n        return true;\n    }\n    /**\n     * Returns the string representation of the cron expression.\n     * @returns {CronDate} - The next schedule date.\n     */\n    toString() {\n        /* istanbul ignore next - should be impossible under normal use to trigger the or branch */\n        return this.#options.expression || this.stringify(true);\n    }\n    /**\n     * Determines if the given date matches the cron expression's day of month and day of week fields.\n     *\n     * The function checks the following rules:\n     * Rule 1: If both \"day of month\" and \"day of week\" are restricted (not wildcard), then one or both must match the current day.\n     * Rule 2: If \"day of month\" is restricted and \"day of week\" is not restricted, then \"day of month\" must match the current day.\n     * Rule 3: If \"day of month\" is a wildcard, \"day of week\" is not a wildcard, and \"day of week\" matches the current day, then the match is accepted.\n     * If none of the rules match, the match is rejected.\n     *\n     * @param {CronDate} currentDate - The current date to be evaluated against the cron expression.\n     * @returns {boolean} Returns true if the current date matches the cron expression's day of month and day of week fields, otherwise false.\n     * @memberof CronExpression\n     * @private\n     */\n    #matchDayOfMonth(currentDate) {\n        // Check if day of month and day of week fields are wildcards or restricted (not wildcard).\n        const isDayOfMonthWildcardMatch = this.#fields.dayOfMonth.isWildcard;\n        const isRestrictedDayOfMonth = !isDayOfMonthWildcardMatch;\n        const isDayOfWeekWildcardMatch = this.#fields.dayOfWeek.isWildcard;\n        const isRestrictedDayOfWeek = !isDayOfWeekWildcardMatch;\n        // Calculate if the current date matches the day of month and day of week fields.\n        const matchedDOM = CronExpression.#matchSchedule(currentDate.getDate(), this.#fields.dayOfMonth.values) ||\n            (this.#fields.dayOfMonth.hasLastChar && currentDate.isLastDayOfMonth());\n        const matchedDOW = CronExpression.#matchSchedule(currentDate.getDay(), this.#fields.dayOfWeek.values) ||\n            (this.#fields.dayOfWeek.hasLastChar &&\n                CronExpression.#isLastWeekdayOfMonthMatch(this.#fields.dayOfWeek.values, currentDate));\n        // Rule 1: Both \"day of month\" and \"day of week\" are restricted; one or both must match the current day.\n        if (isRestrictedDayOfMonth && isRestrictedDayOfWeek && (matchedDOM || matchedDOW)) {\n            return true;\n        }\n        // Rule 2: \"day of month\" restricted and \"day of week\" not restricted; \"day of month\" must match the current day.\n        if (matchedDOM && !isRestrictedDayOfWeek) {\n            return true;\n        }\n        // Rule 3: \"day of month\" is a wildcard, \"day of week\" is not a wildcard, and \"day of week\" matches the current day.\n        if (isDayOfMonthWildcardMatch && !isDayOfWeekWildcardMatch && matchedDOW) {\n            return true;\n        }\n        // If none of the rules match, the match is rejected.\n        return false;\n    }\n    /**\n     * Determines if the current hour matches the cron expression.\n     *\n     * @param {CronDate} currentDate - The current date object.\n     * @param {DateMathOp} dateMathVerb - The date math operation enumeration value.\n     * @param {boolean} reverse - A flag indicating whether the matching should be done in reverse order.\n     * @returns {boolean} - True if the current hour matches the cron expression; otherwise, false.\n     */\n    #matchHour(currentDate, dateMathVerb, reverse) {\n        const hourValues = this.#fields.hour.values;\n        const hours = hourValues;\n        const currentHour = currentDate.getHours();\n        const isMatch = CronExpression.#matchSchedule(currentHour, hourValues);\n        const isDstStart = currentDate.dstStart === currentHour;\n        const isDstEnd = currentDate.dstEnd === currentHour;\n        // DST start: if the scheduled hour is skipped (e.g. 03:00 doesn't exist),\n        // accept the next existing hour when it corresponds to the skipped one.\n        if (isDstStart) {\n            if (CronExpression.#matchSchedule(currentHour - 1, hourValues)) {\n                return true;\n            }\n            currentDate.invokeDateOperation(dateMathVerb, CronDate_1.TimeUnit.Hour);\n            return false;\n        }\n        // DST end: avoid returning the repeated hour twice when searching forward.\n        if (isDstEnd && !reverse) {\n            currentDate.dstEnd = null;\n            currentDate.applyDateOperation(CronDate_1.DateMathOp.Add, CronDate_1.TimeUnit.Hour, hours.length);\n            return false;\n        }\n        if (isMatch) {\n            return true;\n        }\n        // Normal mismatch: if there's no remaining matching hour in this day, jump a whole day first\n        // to avoid scanning hour-by-hour across the day boundary.\n        currentDate.dstStart = null;\n        const nextHour = this.#fields.hour.findNearestValue(currentHour, reverse);\n        if (nextHour === null) {\n            currentDate.applyDateOperation(dateMathVerb, CronDate_1.TimeUnit.Day, hours.length);\n            return false;\n        }\n        // Fast path: jump directly to the next/previous matching hour and reset lower units.\n        //\n        // On DST transition days, setting the hour directly can land on a non-existent/repeated local time,\n        // which breaks the existing DST handling that relies on `applyDateOperation()` to set `dstStart/dstEnd`.\n        // For those days, fall back to stepping hour-by-hour to preserve correctness.\n        if (this.#checkDstTransition(currentDate)) {\n            const steps = reverse ? currentHour - nextHour : nextHour - currentHour;\n            for (let i = 0; i < steps; i++) {\n                currentDate.applyDateOperation(dateMathVerb, CronDate_1.TimeUnit.Hour, hours.length);\n            }\n        }\n        else {\n            currentDate.setHours(nextHour);\n        }\n        currentDate.setMinutes(this.#getMinOrMax(this.#fields.minute.values, reverse));\n        currentDate.setSeconds(this.#getMinOrMax(this.#fields.second.values, reverse));\n        return false;\n    }\n    /**\n     * Validates the current date against the start and end dates of the cron expression.\n     * If the current date is outside the specified time span, an error is thrown.\n     *\n     * @param currentDate {CronDate} - The current date to validate.\n     * @throws {Error} If the current date is outside the specified time span.\n     * @private\n     */\n    #validateTimeSpan(currentDate) {\n        if (!this.#startDate && !this.#endDate) {\n            return;\n        }\n        const currentTime = currentDate.getTime();\n        if (this.#startDate && currentTime < this.#startDate.getTime()) {\n            throw new Error(exports.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE);\n        }\n        if (this.#endDate && currentTime > this.#endDate.getTime()) {\n            throw new Error(exports.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE);\n        }\n    }\n    /**\n     * Finds the next or previous schedule based on the cron expression.\n     *\n     * @param {boolean} [reverse=false] - If true, finds the previous schedule; otherwise, finds the next schedule.\n     * @returns {CronDate} - The next or previous schedule date.\n     * @private\n     */\n    #findSchedule(reverse = false) {\n        const dateMathVerb = reverse ? CronDate_1.DateMathOp.Subtract : CronDate_1.DateMathOp.Add;\n        const currentDate = new CronDate_1.CronDate(this.#currentDate);\n        const startTimestamp = currentDate.getTime();\n        let stepCount = 0;\n        while (++stepCount < LOOP_LIMIT) {\n            this.#validateTimeSpan(currentDate);\n            if (!this.#matchDayOfMonth(currentDate)) {\n                currentDate.applyDateOperation(dateMathVerb, CronDate_1.TimeUnit.Day, this.#fields.hour.values.length);\n                continue;\n            }\n            if (!(this.#fields.dayOfWeek.nthDay <= 0 || Math.ceil(currentDate.getDate() / 7) === this.#fields.dayOfWeek.nthDay)) {\n                currentDate.applyDateOperation(dateMathVerb, CronDate_1.TimeUnit.Day, this.#fields.hour.values.length);\n                continue;\n            }\n            if (!CronExpression.#matchSchedule(currentDate.getMonth() + 1, this.#fields.month.values)) {\n                currentDate.applyDateOperation(dateMathVerb, CronDate_1.TimeUnit.Month, this.#fields.hour.values.length);\n                continue;\n            }\n            if (!this.#matchHour(currentDate, dateMathVerb, reverse)) {\n                continue;\n            }\n            if (!CronExpression.#matchSchedule(currentDate.getMinutes(), this.#fields.minute.values)) {\n                this.#moveToNextMinute(currentDate, dateMathVerb, reverse);\n                continue;\n            }\n            if (!CronExpression.#matchSchedule(currentDate.getSeconds(), this.#fields.second.values)) {\n                this.#moveToNextSecond(currentDate, dateMathVerb, reverse);\n                continue;\n            }\n            if (startTimestamp === currentDate.getTime()) {\n                if (dateMathVerb === 'Add' || currentDate.getMilliseconds() === 0) {\n                    currentDate.applyDateOperation(dateMathVerb, CronDate_1.TimeUnit.Second, this.#fields.hour.values.length);\n                }\n                continue;\n            }\n            break;\n        }\n        /* istanbul ignore next - should be impossible under normal use to trigger the branch */\n        if (stepCount > LOOP_LIMIT) {\n            throw new Error(exports.LOOPS_LIMIT_EXCEEDED_ERROR_MESSAGE);\n        }\n        if (currentDate.getMilliseconds() !== 0) {\n            currentDate.setMilliseconds(0);\n        }\n        this.#currentDate = currentDate;\n        return currentDate;\n    }\n    /**\n     * Returns an iterator for iterating through future CronDate instances\n     *\n     * @name Symbol.iterator\n     * @memberof CronExpression\n     * @returns {Iterator<CronDate>} An iterator object for CronExpression that returns CronDate values.\n     */\n    [Symbol.iterator]() {\n        return {\n            next: () => {\n                const schedule = this.#findSchedule();\n                return { value: schedule, done: !this.hasNext() };\n            },\n        };\n    }\n}\nexports.CronExpression = CronExpression;\nexports.default = CronExpression;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.seededRandom = seededRandom;\n/**\n * Computes a numeric hash from a given string\n * @param {string} str A value to hash\n * @returns {number} A numeric hash computed from the given value\n */\nfunction xfnv1a(str) {\n    let h = 2166136261 >>> 0;\n    for (let i = 0; i < str.length; i++) {\n        h ^= str.charCodeAt(i);\n        h = Math.imul(h, 16777619);\n    }\n    return () => h >>> 0;\n}\n/**\n * Initialize a new PRNG using a given seed\n * @param {number} seed The seed used to initialize the PRNG\n * @returns {PRNG} A random number generator\n */\nfunction mulberry32(seed) {\n    return () => {\n        let t = (seed += 0x6d2b79f5);\n        t = Math.imul(t ^ (t >>> 15), t | 1);\n        t ^= t + Math.imul(t ^ (t >>> 7), t | 61);\n        return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n    };\n}\n/**\n * Generates a PRNG using a given seed. When not provided, the seed is randomly generated\n * @param {string} str A string to derive the seed from\n * @returns {PRNG} A random number generator correctly seeded\n */\nfunction seededRandom(str) {\n    const seed = str ? xfnv1a(str)() : Math.floor(Math.random() * 10_000_000_000);\n    return mulberry32(seed);\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CronExpressionParser = exports.DayOfWeek = exports.Months = exports.CronUnit = exports.PredefinedExpressions = void 0;\nconst CronFieldCollection_1 = require(\"./CronFieldCollection\");\nconst CronExpression_1 = require(\"./CronExpression\");\nconst random_1 = require(\"./utils/random\");\nconst fields_1 = require(\"./fields\");\nvar PredefinedExpressions;\n(function (PredefinedExpressions) {\n    PredefinedExpressions[\"@yearly\"] = \"0 0 0 1 1 *\";\n    PredefinedExpressions[\"@annually\"] = \"0 0 0 1 1 *\";\n    PredefinedExpressions[\"@monthly\"] = \"0 0 0 1 * *\";\n    PredefinedExpressions[\"@weekly\"] = \"0 0 0 * * 0\";\n    PredefinedExpressions[\"@daily\"] = \"0 0 0 * * *\";\n    PredefinedExpressions[\"@hourly\"] = \"0 0 * * * *\";\n    PredefinedExpressions[\"@minutely\"] = \"0 * * * * *\";\n    PredefinedExpressions[\"@secondly\"] = \"* * * * * *\";\n    PredefinedExpressions[\"@weekdays\"] = \"0 0 0 * * 1-5\";\n    PredefinedExpressions[\"@weekends\"] = \"0 0 0 * * 0,6\";\n})(PredefinedExpressions || (exports.PredefinedExpressions = PredefinedExpressions = {}));\nvar CronUnit;\n(function (CronUnit) {\n    CronUnit[\"Second\"] = \"Second\";\n    CronUnit[\"Minute\"] = \"Minute\";\n    CronUnit[\"Hour\"] = \"Hour\";\n    CronUnit[\"DayOfMonth\"] = \"DayOfMonth\";\n    CronUnit[\"Month\"] = \"Month\";\n    CronUnit[\"DayOfWeek\"] = \"DayOfWeek\";\n})(CronUnit || (exports.CronUnit = CronUnit = {}));\n// these need to be lowercase for the parser to work\nvar Months;\n(function (Months) {\n    Months[Months[\"jan\"] = 1] = \"jan\";\n    Months[Months[\"feb\"] = 2] = \"feb\";\n    Months[Months[\"mar\"] = 3] = \"mar\";\n    Months[Months[\"apr\"] = 4] = \"apr\";\n    Months[Months[\"may\"] = 5] = \"may\";\n    Months[Months[\"jun\"] = 6] = \"jun\";\n    Months[Months[\"jul\"] = 7] = \"jul\";\n    Months[Months[\"aug\"] = 8] = \"aug\";\n    Months[Months[\"sep\"] = 9] = \"sep\";\n    Months[Months[\"oct\"] = 10] = \"oct\";\n    Months[Months[\"nov\"] = 11] = \"nov\";\n    Months[Months[\"dec\"] = 12] = \"dec\";\n})(Months || (exports.Months = Months = {}));\n// these need to be lowercase for the parser to work\nvar DayOfWeek;\n(function (DayOfWeek) {\n    DayOfWeek[DayOfWeek[\"sun\"] = 0] = \"sun\";\n    DayOfWeek[DayOfWeek[\"mon\"] = 1] = \"mon\";\n    DayOfWeek[DayOfWeek[\"tue\"] = 2] = \"tue\";\n    DayOfWeek[DayOfWeek[\"wed\"] = 3] = \"wed\";\n    DayOfWeek[DayOfWeek[\"thu\"] = 4] = \"thu\";\n    DayOfWeek[DayOfWeek[\"fri\"] = 5] = \"fri\";\n    DayOfWeek[DayOfWeek[\"sat\"] = 6] = \"sat\";\n})(DayOfWeek || (exports.DayOfWeek = DayOfWeek = {}));\n/**\n * Static class that parses a cron expression and returns a CronExpression object.\n * @static\n * @class CronExpressionParser\n */\nclass CronExpressionParser {\n    /**\n     * Parses a cron expression and returns a CronExpression object.\n     * @param {string} expression - The cron expression to parse.\n     * @param {CronExpressionOptions} [options={}] - The options to use when parsing the expression.\n     * @param {boolean} [options.strict=false] - If true, will throw an error if the expression contains both dayOfMonth and dayOfWeek.\n     * @param {CronDate} [options.currentDate=new CronDate(undefined, 'UTC')] - The date to use when calculating the next/previous occurrence.\n     *\n     * @returns {CronExpression} A CronExpression object.\n     */\n    static parse(expression, options = {}) {\n        const { strict = false, hashSeed } = options;\n        const rand = (0, random_1.seededRandom)(hashSeed);\n        expression = PredefinedExpressions[expression] || expression;\n        const rawFields = CronExpressionParser.#getRawFields(expression, strict);\n        if (!(rawFields.dayOfMonth === '*' || rawFields.dayOfWeek === '*' || !strict)) {\n            throw new Error('Cannot use both dayOfMonth and dayOfWeek together in strict mode!');\n        }\n        const second = CronExpressionParser.#parseField(CronUnit.Second, rawFields.second, fields_1.CronSecond.constraints, rand);\n        const minute = CronExpressionParser.#parseField(CronUnit.Minute, rawFields.minute, fields_1.CronMinute.constraints, rand);\n        const hour = CronExpressionParser.#parseField(CronUnit.Hour, rawFields.hour, fields_1.CronHour.constraints, rand);\n        const month = CronExpressionParser.#parseField(CronUnit.Month, rawFields.month, fields_1.CronMonth.constraints, rand);\n        const dayOfMonth = CronExpressionParser.#parseField(CronUnit.DayOfMonth, rawFields.dayOfMonth, fields_1.CronDayOfMonth.constraints, rand);\n        const { dayOfWeek: _dayOfWeek, nthDayOfWeek } = CronExpressionParser.#parseNthDay(rawFields.dayOfWeek);\n        const dayOfWeek = CronExpressionParser.#parseField(CronUnit.DayOfWeek, _dayOfWeek, fields_1.CronDayOfWeek.constraints, rand);\n        const fields = new CronFieldCollection_1.CronFieldCollection({\n            second: new fields_1.CronSecond(second, { rawValue: rawFields.second }),\n            minute: new fields_1.CronMinute(minute, { rawValue: rawFields.minute }),\n            hour: new fields_1.CronHour(hour, { rawValue: rawFields.hour }),\n            dayOfMonth: new fields_1.CronDayOfMonth(dayOfMonth, { rawValue: rawFields.dayOfMonth }),\n            month: new fields_1.CronMonth(month, { rawValue: rawFields.month }),\n            dayOfWeek: new fields_1.CronDayOfWeek(dayOfWeek, { rawValue: rawFields.dayOfWeek, nthDayOfWeek }),\n        });\n        return new CronExpression_1.CronExpression(fields, { ...options, expression });\n    }\n    /**\n     * Get the raw fields from a cron expression.\n     * @param {string} expression - The cron expression to parse.\n     * @param {boolean} strict - If true, will throw an error if the expression contains both dayOfMonth and dayOfWeek.\n     * @private\n     * @returns {RawCronFields} The raw fields.\n     */\n    static #getRawFields(expression, strict) {\n        if (strict && !expression.length) {\n            throw new Error('Invalid cron expression');\n        }\n        expression = expression || '0 * * * * *';\n        const atoms = expression.trim().split(/\\s+/);\n        if (strict && atoms.length < 6) {\n            throw new Error('Invalid cron expression, expected 6 fields');\n        }\n        if (atoms.length > 6) {\n            throw new Error('Invalid cron expression, too many fields');\n        }\n        const defaults = ['*', '*', '*', '*', '*', '0'];\n        if (atoms.length < defaults.length) {\n            atoms.unshift(...defaults.slice(atoms.length));\n        }\n        const [second, minute, hour, dayOfMonth, month, dayOfWeek] = atoms;\n        return { second, minute, hour, dayOfMonth, month, dayOfWeek };\n    }\n    /**\n     * Parse a field from a cron expression.\n     * @param {CronUnit} field - The field to parse.\n     * @param {string} value - The value of the field.\n     * @param {CronConstraints} constraints - The constraints for the field.\n     * @private\n     * @returns {(number | string)[]} The parsed field.\n     */\n    static #parseField(field, value, constraints, rand) {\n        // Replace aliases for month and dayOfWeek\n        if (field === CronUnit.Month || field === CronUnit.DayOfWeek) {\n            value = value.replace(/[a-z]{3}/gi, (match) => {\n                match = match.toLowerCase();\n                const replacer = Months[match] || DayOfWeek[match];\n                if (replacer === undefined) {\n                    throw new Error(`Validation error, cannot resolve alias \"${match}\"`);\n                }\n                return replacer.toString();\n            });\n        }\n        // Check for valid characters\n        if (!constraints.validChars.test(value)) {\n            throw new Error(`Invalid characters, got value: ${value}`);\n        }\n        value = this.#parseWildcard(value, constraints);\n        value = this.#parseHashed(value, constraints, rand);\n        return this.#parseSequence(field, value, constraints);\n    }\n    /**\n     * Parse a wildcard from a cron expression.\n     * @param {string} value - The value to parse.\n     * @param {CronConstraints} constraints - The constraints for the field.\n     * @private\n     */\n    static #parseWildcard(value, constraints) {\n        return value.replace(/[*?]/g, constraints.min + '-' + constraints.max);\n    }\n    /**\n     * Parse a hashed value from a cron expression.\n     * @param {string} value - The value to parse.\n     * @param {CronConstraints} constraints - The constraints for the field.\n     * @param {PRNG} rand - The random number generator to use.\n     * @private\n     */\n    static #parseHashed(value, constraints, rand) {\n        const randomValue = rand();\n        return value.replace(/H(?:\\((\\d+)-(\\d+)\\))?(?:\\/(\\d+))?/g, (_, min, max, step) => {\n            // H(range)/step\n            if (min && max && step) {\n                const minNum = parseInt(min, 10);\n                const maxNum = parseInt(max, 10);\n                const stepNum = parseInt(step, 10);\n                if (minNum > maxNum) {\n                    throw new Error(`Invalid range: ${minNum}-${maxNum}, min > max`);\n                }\n                if (stepNum <= 0) {\n                    throw new Error(`Invalid step: ${stepNum}, must be positive`);\n                }\n                const minStart = Math.max(minNum, constraints.min);\n                const offset = Math.floor(randomValue * stepNum);\n                const values = [];\n                for (let i = Math.floor(minStart / stepNum) * stepNum + offset; i <= maxNum; i += stepNum) {\n                    if (i >= minStart) {\n                        values.push(i);\n                    }\n                }\n                return values.join(',');\n            }\n            // H(range)\n            else if (min && max) {\n                const minNum = parseInt(min, 10);\n                const maxNum = parseInt(max, 10);\n                if (minNum > maxNum) {\n                    throw new Error(`Invalid range: ${minNum}-${maxNum}, min > max`);\n                }\n                return String(Math.floor(randomValue * (maxNum - minNum + 1)) + minNum);\n            }\n            // H/step\n            else if (step) {\n                const stepNum = parseInt(step, 10);\n                // Validate step\n                if (stepNum <= 0) {\n                    throw new Error(`Invalid step: ${stepNum}, must be positive`);\n                }\n                const offset = Math.floor(randomValue * stepNum);\n                const values = [];\n                for (let i = Math.floor(constraints.min / stepNum) * stepNum + offset; i <= constraints.max; i += stepNum) {\n                    if (i >= constraints.min) {\n                        values.push(i);\n                    }\n                }\n                return values.join(',');\n            }\n            // H\n            else {\n                return String(Math.floor(randomValue * (constraints.max - constraints.min + 1) + constraints.min));\n            }\n        });\n    }\n    /**\n     * Parse a sequence from a cron expression.\n     * @param {CronUnit} field - The field to parse.\n     * @param {string} val - The sequence to parse.\n     * @param {CronConstraints} constraints - The constraints for the field.\n     * @private\n     */\n    static #parseSequence(field, val, constraints) {\n        const stack = [];\n        function handleResult(result, constraints) {\n            if (Array.isArray(result)) {\n                stack.push(...result);\n            }\n            else {\n                if (CronExpressionParser.#isValidConstraintChar(constraints, result)) {\n                    stack.push(result);\n                }\n                else {\n                    const v = parseInt(result.toString(), 10);\n                    const isValid = v >= constraints.min && v <= constraints.max;\n                    if (!isValid) {\n                        throw new Error(`Constraint error, got value ${result} expected range ${constraints.min}-${constraints.max}`);\n                    }\n                    stack.push(field === CronUnit.DayOfWeek ? v % 7 : result);\n                }\n            }\n        }\n        const atoms = val.split(',');\n        atoms.forEach((atom) => {\n            if (!(atom.length > 0)) {\n                throw new Error('Invalid list value format');\n            }\n            handleResult(CronExpressionParser.#parseRepeat(field, atom, constraints), constraints);\n        });\n        return stack;\n    }\n    /**\n     * Parse repeat from a cron expression.\n     * @param {CronUnit} field - The field to parse.\n     * @param {string} val - The repeat to parse.\n     * @param {CronConstraints} constraints - The constraints for the field.\n     * @private\n     * @returns {(number | string)[]} The parsed repeat.\n     */\n    static #parseRepeat(field, val, constraints) {\n        const atoms = val.split('/');\n        if (atoms.length > 2) {\n            throw new Error(`Invalid repeat: ${val}`);\n        }\n        if (atoms.length === 2) {\n            if (!isNaN(parseInt(atoms[0], 10))) {\n                atoms[0] = `${atoms[0]}-${constraints.max}`;\n            }\n            return CronExpressionParser.#parseRange(field, atoms[0], parseInt(atoms[1], 10), constraints);\n        }\n        return CronExpressionParser.#parseRange(field, val, 1, constraints);\n    }\n    /**\n     * Validate a cron range.\n     * @param {number} min - The minimum value of the range.\n     * @param {number} max - The maximum value of the range.\n     * @param {CronConstraints} constraints - The constraints for the field.\n     * @private\n     * @returns {void}\n     * @throws {Error} Throws an error if the range is invalid.\n     */\n    static #validateRange(min, max, constraints) {\n        const isValid = !isNaN(min) && !isNaN(max) && min >= constraints.min && max <= constraints.max;\n        if (!isValid) {\n            throw new Error(`Constraint error, got range ${min}-${max} expected range ${constraints.min}-${constraints.max}`);\n        }\n        if (min > max) {\n            throw new Error(`Invalid range: ${min}-${max}, min(${min}) > max(${max})`);\n        }\n    }\n    /**\n     * Validate a cron repeat interval.\n     * @param {number} repeatInterval - The repeat interval to validate.\n     * @private\n     * @returns {void}\n     * @throws {Error} Throws an error if the repeat interval is invalid.\n     */\n    static #validateRepeatInterval(repeatInterval) {\n        if (!(!isNaN(repeatInterval) && repeatInterval > 0)) {\n            throw new Error(`Constraint error, cannot repeat at every ${repeatInterval} time.`);\n        }\n    }\n    /**\n     * Create a range from a cron expression.\n     * @param {CronUnit} field - The field to parse.\n     * @param {number} min - The minimum value of the range.\n     * @param {number} max - The maximum value of the range.\n     * @param {number} repeatInterval - The repeat interval of the range.\n     * @private\n     * @returns {number[]} The created range.\n     */\n    static #createRange(field, min, max, repeatInterval) {\n        const stack = [];\n        if (field === CronUnit.DayOfWeek && max % 7 === 0) {\n            stack.push(0);\n        }\n        for (let index = min; index <= max; index += repeatInterval) {\n            if (stack.indexOf(index) === -1) {\n                stack.push(index);\n            }\n        }\n        return stack;\n    }\n    /**\n     * Parse a range from a cron expression.\n     * @param {CronUnit} field - The field to parse.\n     * @param {string} val - The range to parse.\n     * @param {number} repeatInterval - The repeat interval of the range.\n     * @param {CronConstraints} constraints - The constraints for the field.\n     * @private\n     * @returns {number[] | string[] | number | string} The parsed range.\n     */\n    static #parseRange(field, val, repeatInterval, constraints) {\n        const atoms = val.split('-');\n        if (atoms.length <= 1) {\n            return isNaN(+val) ? val : +val;\n        }\n        const [min, max] = atoms.map((num) => parseInt(num, 10));\n        this.#validateRange(min, max, constraints);\n        this.#validateRepeatInterval(repeatInterval);\n        // Create range\n        return this.#createRange(field, min, max, repeatInterval);\n    }\n    /**\n     * Parse a cron expression.\n     * @param {string} val - The cron expression to parse.\n     * @private\n     * @returns {string} The parsed cron expression.\n     */\n    static #parseNthDay(val) {\n        const atoms = val.split('#');\n        if (atoms.length <= 1) {\n            return { dayOfWeek: atoms[0] };\n        }\n        const nthValue = +atoms[atoms.length - 1];\n        const matches = val.match(/([,-/])/);\n        if (matches !== null) {\n            throw new Error(`Constraint error, invalid dayOfWeek \\`#\\` and \\`${matches?.[0]}\\` special characters are incompatible`);\n        }\n        if (!(atoms.length <= 2 && !isNaN(nthValue) && nthValue >= 1 && nthValue <= 5)) {\n            throw new Error('Constraint error, invalid dayOfWeek occurrence number (#)');\n        }\n        return { dayOfWeek: atoms[0], nthDayOfWeek: nthValue };\n    }\n    /**\n     * Checks if a character is valid for a field.\n     * @param {CronConstraints} constraints - The constraints for the field.\n     * @param {string | number} value - The value to check.\n     * @private\n     * @returns {boolean} Whether the character is valid for the field.\n     */\n    static #isValidConstraintChar(constraints, value) {\n        return constraints.chars.some((char) => value.toString().includes(char));\n    }\n}\nexports.CronExpressionParser = CronExpressionParser;\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n    if (k2 === undefined) k2 = k;\n    var desc = Object.getOwnPropertyDescriptor(m, k);\n    if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n      desc = { enumerable: true, get: function() { return m[k]; } };\n    }\n    Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n    if (k2 === undefined) k2 = k;\n    o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n    Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n    o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || (function () {\n    var ownKeys = function(o) {\n        ownKeys = Object.getOwnPropertyNames || function (o) {\n            var ar = [];\n            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;\n            return ar;\n        };\n        return ownKeys(o);\n    };\n    return function (mod) {\n        if (mod && mod.__esModule) return mod;\n        var result = {};\n        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== \"default\") __createBinding(result, mod, k[i]);\n        __setModuleDefault(result, mod);\n        return result;\n    };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CronFileParser = void 0;\nconst CronExpressionParser_1 = require(\"./CronExpressionParser\");\n/**\n * Parser for crontab files that handles both synchronous and asynchronous operations.\n */\nclass CronFileParser {\n    /**\n     * Parse a crontab file asynchronously\n     * @param filePath Path to crontab file\n     * @returns Promise resolving to parse results\n     * @throws If file cannot be read\n     */\n    static async parseFile(filePath) {\n        const { readFile } = await Promise.resolve().then(() => __importStar(require('fs/promises')));\n        const data = await readFile(filePath, 'utf8');\n        return CronFileParser.#parseContent(data);\n    }\n    /**\n     * Parse a crontab file synchronously\n     * @param filePath Path to crontab file\n     * @returns Parse results\n     * @throws If file cannot be read\n     */\n    static parseFileSync(filePath) {\n        // eslint-disable-next-line @typescript-eslint/no-require-imports\n        const { readFileSync } = require('fs');\n        const data = readFileSync(filePath, 'utf8');\n        return CronFileParser.#parseContent(data);\n    }\n    /**\n     * Internal method to parse crontab file content\n     * @private\n     */\n    static #parseContent(data) {\n        const blocks = data.split('\\n');\n        const result = {\n            variables: {},\n            expressions: [],\n            errors: {},\n        };\n        for (const block of blocks) {\n            const entry = block.trim();\n            if (entry.length === 0 || entry.startsWith('#')) {\n                continue;\n            }\n            const variableMatch = entry.match(/^(.*)=(.*)$/);\n            if (variableMatch) {\n                const [, key, value] = variableMatch;\n                result.variables[key] = value.replace(/[\"']/g, ''); // Remove quotes\n                continue;\n            }\n            try {\n                const parsedEntry = CronFileParser.#parseEntry(entry);\n                result.expressions.push(parsedEntry.interval);\n            }\n            catch (err) {\n                result.errors[entry] = err;\n            }\n        }\n        return result;\n    }\n    /**\n     * Parse a single crontab entry\n     * @private\n     */\n    static #parseEntry(entry) {\n        const atoms = entry.split(' ');\n        return {\n            interval: CronExpressionParser_1.CronExpressionParser.parse(atoms.slice(0, 5).join(' ')),\n            command: atoms.slice(5, atoms.length),\n        };\n    }\n}\nexports.CronFileParser = CronFileParser;\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n    if (k2 === undefined) k2 = k;\n    var desc = Object.getOwnPropertyDescriptor(m, k);\n    if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n      desc = { enumerable: true, get: function() { return m[k]; } };\n    }\n    Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n    if (k2 === undefined) k2 = k;\n    o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n    for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CronFileParser = exports.CronExpressionParser = exports.CronExpression = exports.CronFieldCollection = exports.CronDate = void 0;\n/* istanbul ignore file */\nconst CronExpressionParser_1 = require(\"./CronExpressionParser\");\nvar CronDate_1 = require(\"./CronDate\");\nObject.defineProperty(exports, \"CronDate\", { enumerable: true, get: function () { return CronDate_1.CronDate; } });\nvar CronFieldCollection_1 = require(\"./CronFieldCollection\");\nObject.defineProperty(exports, \"CronFieldCollection\", { enumerable: true, get: function () { return CronFieldCollection_1.CronFieldCollection; } });\nvar CronExpression_1 = require(\"./CronExpression\");\nObject.defineProperty(exports, \"CronExpression\", { enumerable: true, get: function () { return CronExpression_1.CronExpression; } });\nvar CronExpressionParser_2 = require(\"./CronExpressionParser\");\nObject.defineProperty(exports, \"CronExpressionParser\", { enumerable: true, get: function () { return CronExpressionParser_2.CronExpressionParser; } });\nvar CronFileParser_1 = require(\"./CronFileParser\");\nObject.defineProperty(exports, \"CronFileParser\", { enumerable: true, get: function () { return CronFileParser_1.CronFileParser; } });\n__exportStar(require(\"./fields\"), exports);\nexports.default = CronExpressionParser_1.CronExpressionParser;\n","import { z } from \"zod\";\nimport { getWorkflowRunHandle } from \"@keystrokehq/action\";\nimport { requiredDisplayTextSchema } from \"@keystrokehq/shared\";\n//#region src/workflow-step-invocation.ts\nfunction executeWorkflowStep(state) {\n\tconst handle = getWorkflowRunHandle();\n\tif (!handle?.workflowRunner) throw new Error(`Workflow \"${state.workflow.slug}\" can only be called as a step inside a running workflow. Run it standalone with executeWorkflow(...).`);\n\treturn handle.workflowRunner(state.workflow, state.input, { callSiteId: state.callSiteId });\n}\nfunction createWorkflowStepInvocation(state) {\n\treturn {\n\t\t__site(callSiteId) {\n\t\t\treturn createWorkflowStepInvocation({\n\t\t\t\t...state,\n\t\t\t\tcallSiteId\n\t\t\t});\n\t\t},\n\t\tthen(onfulfilled, onrejected) {\n\t\t\treturn executeWorkflowStep(state).then(onfulfilled, onrejected);\n\t\t}\n\t};\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: requiredDisplayTextSchema,\n\tdescription: requiredDisplayTextSchema,\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\tconst body = def.run;\n\tconst workflow = {\n\t\t...result.data,\n\t\t[WORKFLOW]: true\n\t};\n\tworkflow.run = ((input, ctx) => {\n\t\tif (ctx !== void 0) return body(input, ctx);\n\t\treturn createWorkflowStepInvocation({\n\t\t\tworkflow,\n\t\t\tinput\n\t\t});\n\t});\n\treturn workflow;\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\nexport { workflowCoreSchema as i, WORKFLOW as n, isWorkflow as r, defineWorkflow as t };\n\n//# sourceMappingURL=define-workflow-BBoZgWI5.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];\n/** When set, console output is mirrored into the active trace sink. */\nconst captureEnabled = new AsyncLocalStorage();\nconst originals = /* @__PURE__ */ new Map();\nlet installed = false;\nlet activeCaptures = 0;\nfunction mapConsoleLevel(level) {\n\tif (level === \"log\") return \"info\";\n\treturn level;\n}\nfunction installConsoleShim() {\n\tif (installed) return;\n\tinstalled = true;\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\tif (captureEnabled.getStore() !== true) return;\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}\nfunction uninstallConsoleShim() {\n\tif (!installed || activeCaptures > 0) return;\n\tfor (const level of CONSOLE_LEVELS) {\n\t\tconst original = originals.get(level);\n\t\tif (original) console[level] = original;\n\t}\n\toriginals.clear();\n\tinstalled = false;\n}\n/**\n* Mirror console output into the active tracing sink for the duration of `fn`.\n* Safe under concurrency: one process-wide shim + AsyncLocalStorage, so\n* overlapping captures do not stack wrappers or duplicate sink writes.\n*/\nasync function captureConsole(fn) {\n\tinstallConsoleShim();\n\tactiveCaptures += 1;\n\ttry {\n\t\treturn await captureEnabled.run(true, fn);\n\t} finally {\n\t\tactiveCaptures -= 1;\n\t\tuninstallConsoleShim();\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","const entityKind = Symbol.for(\"drizzle:entityKind\");\nconst hasOwnEntityKind = Symbol.for(\"drizzle:hasOwnEntityKind\");\nfunction is(value, type) {\n  if (!value || typeof value !== \"object\") {\n    return false;\n  }\n  if (value instanceof type) {\n    return true;\n  }\n  if (!Object.prototype.hasOwnProperty.call(type, entityKind)) {\n    throw new Error(\n      `Class \"${type.name ?? \"<unknown>\"}\" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`\n    );\n  }\n  let cls = Object.getPrototypeOf(value).constructor;\n  if (cls) {\n    while (cls) {\n      if (entityKind in cls && cls[entityKind] === type[entityKind]) {\n        return true;\n      }\n      cls = Object.getPrototypeOf(cls);\n    }\n  }\n  return false;\n}\nexport {\n  entityKind,\n  hasOwnEntityKind,\n  is\n};\n//# sourceMappingURL=entity.js.map","import { entityKind } from \"./entity.js\";\nclass Column {\n  constructor(table, config) {\n    this.table = table;\n    this.config = config;\n    this.name = config.name;\n    this.keyAsName = config.keyAsName;\n    this.notNull = config.notNull;\n    this.default = config.default;\n    this.defaultFn = config.defaultFn;\n    this.onUpdateFn = config.onUpdateFn;\n    this.hasDefault = config.hasDefault;\n    this.primary = config.primaryKey;\n    this.isUnique = config.isUnique;\n    this.uniqueName = config.uniqueName;\n    this.uniqueType = config.uniqueType;\n    this.dataType = config.dataType;\n    this.columnType = config.columnType;\n    this.generated = config.generated;\n    this.generatedIdentity = config.generatedIdentity;\n  }\n  static [entityKind] = \"Column\";\n  name;\n  keyAsName;\n  primary;\n  notNull;\n  default;\n  defaultFn;\n  onUpdateFn;\n  hasDefault;\n  isUnique;\n  uniqueName;\n  uniqueType;\n  dataType;\n  columnType;\n  enumValues = void 0;\n  generated = void 0;\n  generatedIdentity = void 0;\n  config;\n  mapFromDriverValue(value) {\n    return value;\n  }\n  mapToDriverValue(value) {\n    return value;\n  }\n  // ** @internal */\n  shouldDisableInsert() {\n    return this.config.generated !== void 0 && this.config.generated.type !== \"byDefault\";\n  }\n}\nexport {\n  Column\n};\n//# sourceMappingURL=column.js.map","import { entityKind } from \"./entity.js\";\nclass ColumnBuilder {\n  static [entityKind] = \"ColumnBuilder\";\n  config;\n  constructor(name, dataType, columnType) {\n    this.config = {\n      name,\n      keyAsName: name === \"\",\n      notNull: false,\n      default: void 0,\n      hasDefault: false,\n      primaryKey: false,\n      isUnique: false,\n      uniqueName: void 0,\n      uniqueType: void 0,\n      dataType,\n      columnType,\n      generated: void 0\n    };\n  }\n  /**\n   * Changes the data type of the column. Commonly used with `json` columns. Also, useful for branded types.\n   *\n   * @example\n   * ```ts\n   * const users = pgTable('users', {\n   * \tid: integer('id').$type<UserId>().primaryKey(),\n   * \tdetails: json('details').$type<UserDetails>().notNull(),\n   * });\n   * ```\n   */\n  $type() {\n    return this;\n  }\n  /**\n   * Adds a `not null` clause to the column definition.\n   *\n   * Affects the `select` model of the table - columns *without* `not null` will be nullable on select.\n   */\n  notNull() {\n    this.config.notNull = true;\n    return this;\n  }\n  /**\n   * Adds a `default <value>` clause to the column definition.\n   *\n   * Affects the `insert` model of the table - columns *with* `default` are optional on insert.\n   *\n   * If you need to set a dynamic default value, use {@link $defaultFn} instead.\n   */\n  default(value) {\n    this.config.default = value;\n    this.config.hasDefault = true;\n    return this;\n  }\n  /**\n   * Adds a dynamic default value to the column.\n   * The function will be called when the row is inserted, and the returned value will be used as the column value.\n   *\n   * **Note:** This value does not affect the `drizzle-kit` behavior, it is only used at runtime in `drizzle-orm`.\n   */\n  $defaultFn(fn) {\n    this.config.defaultFn = fn;\n    this.config.hasDefault = true;\n    return this;\n  }\n  /**\n   * Alias for {@link $defaultFn}.\n   */\n  $default = this.$defaultFn;\n  /**\n   * Adds a dynamic update value to the column.\n   * The function will be called when the row is updated, and the returned value will be used as the column value if none is provided.\n   * If no `default` (or `$defaultFn`) value is provided, the function will be called when the row is inserted as well, and the returned value will be used as the column value.\n   *\n   * **Note:** This value does not affect the `drizzle-kit` behavior, it is only used at runtime in `drizzle-orm`.\n   */\n  $onUpdateFn(fn) {\n    this.config.onUpdateFn = fn;\n    this.config.hasDefault = true;\n    return this;\n  }\n  /**\n   * Alias for {@link $onUpdateFn}.\n   */\n  $onUpdate = this.$onUpdateFn;\n  /**\n   * Adds a `primary key` clause to the column definition. This implicitly makes the column `not null`.\n   *\n   * In SQLite, `integer primary key` implicitly makes the column auto-incrementing.\n   */\n  primaryKey() {\n    this.config.primaryKey = true;\n    this.config.notNull = true;\n    return this;\n  }\n  /** @internal Sets the name of the column to the key within the table definition if a name was not given. */\n  setName(name) {\n    if (this.config.name !== \"\") return;\n    this.config.name = name;\n  }\n}\nexport {\n  ColumnBuilder\n};\n//# sourceMappingURL=column-builder.js.map","const TableName = Symbol.for(\"drizzle:Name\");\nexport {\n  TableName\n};\n//# sourceMappingURL=table.utils.js.map","import { entityKind } from \"../entity.js\";\nimport { TableName } from \"../table.utils.js\";\nclass ForeignKeyBuilder {\n  static [entityKind] = \"PgForeignKeyBuilder\";\n  /** @internal */\n  reference;\n  /** @internal */\n  _onUpdate = \"no action\";\n  /** @internal */\n  _onDelete = \"no action\";\n  constructor(config, actions) {\n    this.reference = () => {\n      const { name, columns, foreignColumns } = config();\n      return { name, columns, foreignTable: foreignColumns[0].table, foreignColumns };\n    };\n    if (actions) {\n      this._onUpdate = actions.onUpdate;\n      this._onDelete = actions.onDelete;\n    }\n  }\n  onUpdate(action) {\n    this._onUpdate = action === void 0 ? \"no action\" : action;\n    return this;\n  }\n  onDelete(action) {\n    this._onDelete = action === void 0 ? \"no action\" : action;\n    return this;\n  }\n  /** @internal */\n  build(table) {\n    return new ForeignKey(table, this);\n  }\n}\nclass ForeignKey {\n  constructor(table, builder) {\n    this.table = table;\n    this.reference = builder.reference;\n    this.onUpdate = builder._onUpdate;\n    this.onDelete = builder._onDelete;\n  }\n  static [entityKind] = \"PgForeignKey\";\n  reference;\n  onUpdate;\n  onDelete;\n  getName() {\n    const { name, columns, foreignColumns } = this.reference();\n    const columnNames = columns.map((column) => column.name);\n    const foreignColumnNames = foreignColumns.map((column) => column.name);\n    const chunks = [\n      this.table[TableName],\n      ...columnNames,\n      foreignColumns[0].table[TableName],\n      ...foreignColumnNames\n    ];\n    return name ?? `${chunks.join(\"_\")}_fk`;\n  }\n}\nfunction foreignKey(config) {\n  function mappedConfig() {\n    const { name, columns, foreignColumns } = config;\n    return {\n      name,\n      columns,\n      foreignColumns\n    };\n  }\n  return new ForeignKeyBuilder(mappedConfig);\n}\nexport {\n  ForeignKey,\n  ForeignKeyBuilder,\n  foreignKey\n};\n//# sourceMappingURL=foreign-keys.js.map","function iife(fn, ...args) {\n  return fn(...args);\n}\nexport {\n  iife\n};\n//# sourceMappingURL=tracing-utils.js.map","import { entityKind } from \"../entity.js\";\nimport { TableName } from \"../table.utils.js\";\nfunction unique(name) {\n  return new UniqueOnConstraintBuilder(name);\n}\nfunction uniqueKeyName(table, columns) {\n  return `${table[TableName]}_${columns.join(\"_\")}_unique`;\n}\nclass UniqueConstraintBuilder {\n  constructor(columns, name) {\n    this.name = name;\n    this.columns = columns;\n  }\n  static [entityKind] = \"PgUniqueConstraintBuilder\";\n  /** @internal */\n  columns;\n  /** @internal */\n  nullsNotDistinctConfig = false;\n  nullsNotDistinct() {\n    this.nullsNotDistinctConfig = true;\n    return this;\n  }\n  /** @internal */\n  build(table) {\n    return new UniqueConstraint(table, this.columns, this.nullsNotDistinctConfig, this.name);\n  }\n}\nclass UniqueOnConstraintBuilder {\n  static [entityKind] = \"PgUniqueOnConstraintBuilder\";\n  /** @internal */\n  name;\n  constructor(name) {\n    this.name = name;\n  }\n  on(...columns) {\n    return new UniqueConstraintBuilder(columns, this.name);\n  }\n}\nclass UniqueConstraint {\n  constructor(table, columns, nullsNotDistinct, name) {\n    this.table = table;\n    this.columns = columns;\n    this.name = name ?? uniqueKeyName(this.table, this.columns.map((column) => column.name));\n    this.nullsNotDistinct = nullsNotDistinct;\n  }\n  static [entityKind] = \"PgUniqueConstraint\";\n  columns;\n  name;\n  nullsNotDistinct = false;\n  getName() {\n    return this.name;\n  }\n}\nexport {\n  UniqueConstraint,\n  UniqueConstraintBuilder,\n  UniqueOnConstraintBuilder,\n  unique,\n  uniqueKeyName\n};\n//# sourceMappingURL=unique-constraint.js.map","function parsePgArrayValue(arrayString, startFrom, inQuotes) {\n  for (let i = startFrom; i < arrayString.length; i++) {\n    const char = arrayString[i];\n    if (char === \"\\\\\") {\n      i++;\n      continue;\n    }\n    if (char === '\"') {\n      return [arrayString.slice(startFrom, i).replace(/\\\\/g, \"\"), i + 1];\n    }\n    if (inQuotes) {\n      continue;\n    }\n    if (char === \",\" || char === \"}\") {\n      return [arrayString.slice(startFrom, i).replace(/\\\\/g, \"\"), i];\n    }\n  }\n  return [arrayString.slice(startFrom).replace(/\\\\/g, \"\"), arrayString.length];\n}\nfunction parsePgNestedArray(arrayString, startFrom = 0) {\n  const result = [];\n  let i = startFrom;\n  let lastCharIsComma = false;\n  while (i < arrayString.length) {\n    const char = arrayString[i];\n    if (char === \",\") {\n      if (lastCharIsComma || i === startFrom) {\n        result.push(\"\");\n      }\n      lastCharIsComma = true;\n      i++;\n      continue;\n    }\n    lastCharIsComma = false;\n    if (char === \"\\\\\") {\n      i += 2;\n      continue;\n    }\n    if (char === '\"') {\n      const [value2, startFrom2] = parsePgArrayValue(arrayString, i + 1, true);\n      result.push(value2);\n      i = startFrom2;\n      continue;\n    }\n    if (char === \"}\") {\n      return [result, i + 1];\n    }\n    if (char === \"{\") {\n      const [value2, startFrom2] = parsePgNestedArray(arrayString, i + 1);\n      result.push(value2);\n      i = startFrom2;\n      continue;\n    }\n    const [value, newStartFrom] = parsePgArrayValue(arrayString, i, false);\n    result.push(value);\n    i = newStartFrom;\n  }\n  return [result, i];\n}\nfunction parsePgArray(arrayString) {\n  const [result] = parsePgNestedArray(arrayString, 1);\n  return result;\n}\nfunction makePgArray(array) {\n  return `{${array.map((item) => {\n    if (Array.isArray(item)) {\n      return makePgArray(item);\n    }\n    if (typeof item === \"string\") {\n      return `\"${item.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"')}\"`;\n    }\n    return `${item}`;\n  }).join(\",\")}}`;\n}\nexport {\n  makePgArray,\n  parsePgArray,\n  parsePgNestedArray\n};\n//# sourceMappingURL=array.js.map","import { ColumnBuilder } from \"../../column-builder.js\";\nimport { Column } from \"../../column.js\";\nimport { entityKind, is } from \"../../entity.js\";\nimport { ForeignKeyBuilder } from \"../foreign-keys.js\";\nimport { iife } from \"../../tracing-utils.js\";\nimport { uniqueKeyName } from \"../unique-constraint.js\";\nimport { makePgArray, parsePgArray } from \"../utils/array.js\";\nclass PgColumnBuilder extends ColumnBuilder {\n  foreignKeyConfigs = [];\n  static [entityKind] = \"PgColumnBuilder\";\n  array(size) {\n    return new PgArrayBuilder(this.config.name, this, size);\n  }\n  references(ref, actions = {}) {\n    this.foreignKeyConfigs.push({ ref, actions });\n    return this;\n  }\n  unique(name, config) {\n    this.config.isUnique = true;\n    this.config.uniqueName = name;\n    this.config.uniqueType = config?.nulls;\n    return this;\n  }\n  generatedAlwaysAs(as) {\n    this.config.generated = {\n      as,\n      type: \"always\",\n      mode: \"stored\"\n    };\n    return this;\n  }\n  /** @internal */\n  buildForeignKeys(column, table) {\n    return this.foreignKeyConfigs.map(({ ref, actions }) => {\n      return iife(\n        (ref2, actions2) => {\n          const builder = new ForeignKeyBuilder(() => {\n            const foreignColumn = ref2();\n            return { columns: [column], foreignColumns: [foreignColumn] };\n          });\n          if (actions2.onUpdate) {\n            builder.onUpdate(actions2.onUpdate);\n          }\n          if (actions2.onDelete) {\n            builder.onDelete(actions2.onDelete);\n          }\n          return builder.build(table);\n        },\n        ref,\n        actions\n      );\n    });\n  }\n  /** @internal */\n  buildExtraConfigColumn(table) {\n    return new ExtraConfigColumn(table, this.config);\n  }\n}\nclass PgColumn extends Column {\n  constructor(table, config) {\n    if (!config.uniqueName) {\n      config.uniqueName = uniqueKeyName(table, [config.name]);\n    }\n    super(table, config);\n    this.table = table;\n  }\n  static [entityKind] = \"PgColumn\";\n}\nclass ExtraConfigColumn extends PgColumn {\n  static [entityKind] = \"ExtraConfigColumn\";\n  getSQLType() {\n    return this.getSQLType();\n  }\n  indexConfig = {\n    order: this.config.order ?? \"asc\",\n    nulls: this.config.nulls ?? \"last\",\n    opClass: this.config.opClass\n  };\n  defaultConfig = {\n    order: \"asc\",\n    nulls: \"last\",\n    opClass: void 0\n  };\n  asc() {\n    this.indexConfig.order = \"asc\";\n    return this;\n  }\n  desc() {\n    this.indexConfig.order = \"desc\";\n    return this;\n  }\n  nullsFirst() {\n    this.indexConfig.nulls = \"first\";\n    return this;\n  }\n  nullsLast() {\n    this.indexConfig.nulls = \"last\";\n    return this;\n  }\n  /**\n   * ### PostgreSQL documentation quote\n   *\n   * > An operator class with optional parameters can be specified for each column of an index.\n   * The operator class identifies the operators to be used by the index for that column.\n   * For example, a B-tree index on four-byte integers would use the int4_ops class;\n   * this operator class includes comparison functions for four-byte integers.\n   * In practice the default operator class for the column's data type is usually sufficient.\n   * The main point of having operator classes is that for some data types, there could be more than one meaningful ordering.\n   * For example, we might want to sort a complex-number data type either by absolute value or by real part.\n   * We could do this by defining two operator classes for the data type and then selecting the proper class when creating an index.\n   * More information about operator classes check:\n   *\n   * ### Useful links\n   * https://www.postgresql.org/docs/current/sql-createindex.html\n   *\n   * https://www.postgresql.org/docs/current/indexes-opclass.html\n   *\n   * https://www.postgresql.org/docs/current/xindex.html\n   *\n   * ### Additional types\n   * If you have the `pg_vector` extension installed in your database, you can use the\n   * `vector_l2_ops`, `vector_ip_ops`, `vector_cosine_ops`, `vector_l1_ops`, `bit_hamming_ops`, `bit_jaccard_ops`, `halfvec_l2_ops`, `sparsevec_l2_ops` options, which are predefined types.\n   *\n   * **You can always specify any string you want in the operator class, in case Drizzle doesn't have it natively in its types**\n   *\n   * @param opClass\n   * @returns\n   */\n  op(opClass) {\n    this.indexConfig.opClass = opClass;\n    return this;\n  }\n}\nclass IndexedColumn {\n  static [entityKind] = \"IndexedColumn\";\n  constructor(name, keyAsName, type, indexConfig) {\n    this.name = name;\n    this.keyAsName = keyAsName;\n    this.type = type;\n    this.indexConfig = indexConfig;\n  }\n  name;\n  keyAsName;\n  type;\n  indexConfig;\n}\nclass PgArrayBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgArrayBuilder\";\n  constructor(name, baseBuilder, size) {\n    super(name, \"array\", \"PgArray\");\n    this.config.baseBuilder = baseBuilder;\n    this.config.size = size;\n  }\n  /** @internal */\n  build(table) {\n    const baseColumn = this.config.baseBuilder.build(table);\n    return new PgArray(\n      table,\n      this.config,\n      baseColumn\n    );\n  }\n}\nclass PgArray extends PgColumn {\n  constructor(table, config, baseColumn, range) {\n    super(table, config);\n    this.baseColumn = baseColumn;\n    this.range = range;\n    this.size = config.size;\n  }\n  size;\n  static [entityKind] = \"PgArray\";\n  getSQLType() {\n    return `${this.baseColumn.getSQLType()}[${typeof this.size === \"number\" ? this.size : \"\"}]`;\n  }\n  mapFromDriverValue(value) {\n    if (typeof value === \"string\") {\n      value = parsePgArray(value);\n    }\n    return value.map((v) => this.baseColumn.mapFromDriverValue(v));\n  }\n  mapToDriverValue(value, isNestedArray = false) {\n    const a = value.map(\n      (v) => v === null ? null : is(this.baseColumn, PgArray) ? this.baseColumn.mapToDriverValue(v, true) : this.baseColumn.mapToDriverValue(v)\n    );\n    if (isNestedArray) return a;\n    return makePgArray(a);\n  }\n}\nexport {\n  ExtraConfigColumn,\n  IndexedColumn,\n  PgArray,\n  PgArrayBuilder,\n  PgColumn,\n  PgColumnBuilder\n};\n//# sourceMappingURL=common.js.map","import { entityKind } from \"../../entity.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgEnumObjectColumnBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgEnumObjectColumnBuilder\";\n  constructor(name, enumInstance) {\n    super(name, \"string\", \"PgEnumObjectColumn\");\n    this.config.enum = enumInstance;\n  }\n  /** @internal */\n  build(table) {\n    return new PgEnumObjectColumn(\n      table,\n      this.config\n    );\n  }\n}\nclass PgEnumObjectColumn extends PgColumn {\n  static [entityKind] = \"PgEnumObjectColumn\";\n  enum;\n  enumValues = this.config.enum.enumValues;\n  constructor(table, config) {\n    super(table, config);\n    this.enum = config.enum;\n  }\n  getSQLType() {\n    return this.enum.enumName;\n  }\n}\nconst isPgEnumSym = Symbol.for(\"drizzle:isPgEnum\");\nfunction isPgEnum(obj) {\n  return !!obj && typeof obj === \"function\" && isPgEnumSym in obj && obj[isPgEnumSym] === true;\n}\nclass PgEnumColumnBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgEnumColumnBuilder\";\n  constructor(name, enumInstance) {\n    super(name, \"string\", \"PgEnumColumn\");\n    this.config.enum = enumInstance;\n  }\n  /** @internal */\n  build(table) {\n    return new PgEnumColumn(\n      table,\n      this.config\n    );\n  }\n}\nclass PgEnumColumn extends PgColumn {\n  static [entityKind] = \"PgEnumColumn\";\n  enum = this.config.enum;\n  enumValues = this.config.enum.enumValues;\n  constructor(table, config) {\n    super(table, config);\n    this.enum = config.enum;\n  }\n  getSQLType() {\n    return this.enum.enumName;\n  }\n}\nfunction pgEnum(enumName, input) {\n  return Array.isArray(input) ? pgEnumWithSchema(enumName, [...input], void 0) : pgEnumObjectWithSchema(enumName, input, void 0);\n}\nfunction pgEnumWithSchema(enumName, values, schema) {\n  const enumInstance = Object.assign(\n    (name) => new PgEnumColumnBuilder(name ?? \"\", enumInstance),\n    {\n      enumName,\n      enumValues: values,\n      schema,\n      [isPgEnumSym]: true\n    }\n  );\n  return enumInstance;\n}\nfunction pgEnumObjectWithSchema(enumName, values, schema) {\n  const enumInstance = Object.assign(\n    (name) => new PgEnumObjectColumnBuilder(name ?? \"\", enumInstance),\n    {\n      enumName,\n      enumValues: Object.values(values),\n      schema,\n      [isPgEnumSym]: true\n    }\n  );\n  return enumInstance;\n}\nexport {\n  PgEnumColumn,\n  PgEnumColumnBuilder,\n  PgEnumObjectColumn,\n  PgEnumObjectColumnBuilder,\n  isPgEnum,\n  pgEnum,\n  pgEnumObjectWithSchema,\n  pgEnumWithSchema\n};\n//# sourceMappingURL=enum.js.map","import { entityKind } from \"./entity.js\";\nclass Subquery {\n  static [entityKind] = \"Subquery\";\n  constructor(sql, fields, alias, isWith = false, usedTables = []) {\n    this._ = {\n      brand: \"Subquery\",\n      sql,\n      selectedFields: fields,\n      alias,\n      isWith,\n      usedTables\n    };\n  }\n  // getSQL(): SQL<unknown> {\n  // \treturn new SQL([this]);\n  // }\n}\nclass WithSubquery extends Subquery {\n  static [entityKind] = \"WithSubquery\";\n}\nexport {\n  Subquery,\n  WithSubquery\n};\n//# sourceMappingURL=subquery.js.map","import { iife } from \"./tracing-utils.js\";\nimport { npmVersion } from \"./version.js\";\nlet otel;\nlet rawTracer;\nconst tracer = {\n  startActiveSpan(name, fn) {\n    if (!otel) {\n      return fn();\n    }\n    if (!rawTracer) {\n      rawTracer = otel.trace.getTracer(\"drizzle-orm\", npmVersion);\n    }\n    return iife(\n      (otel2, rawTracer2) => rawTracer2.startActiveSpan(\n        name,\n        (span) => {\n          try {\n            return fn(span);\n          } catch (e) {\n            span.setStatus({\n              code: otel2.SpanStatusCode.ERROR,\n              message: e instanceof Error ? e.message : \"Unknown error\"\n              // eslint-disable-line no-instanceof/no-instanceof\n            });\n            throw e;\n          } finally {\n            span.end();\n          }\n        }\n      ),\n      otel,\n      rawTracer\n    );\n  }\n};\nexport {\n  tracer\n};\n//# sourceMappingURL=tracing.js.map","const ViewBaseConfig = Symbol.for(\"drizzle:ViewBaseConfig\");\nexport {\n  ViewBaseConfig\n};\n//# sourceMappingURL=view-common.js.map","import { entityKind } from \"./entity.js\";\nimport { TableName } from \"./table.utils.js\";\nconst Schema = Symbol.for(\"drizzle:Schema\");\nconst Columns = Symbol.for(\"drizzle:Columns\");\nconst ExtraConfigColumns = Symbol.for(\"drizzle:ExtraConfigColumns\");\nconst OriginalName = Symbol.for(\"drizzle:OriginalName\");\nconst BaseName = Symbol.for(\"drizzle:BaseName\");\nconst IsAlias = Symbol.for(\"drizzle:IsAlias\");\nconst ExtraConfigBuilder = Symbol.for(\"drizzle:ExtraConfigBuilder\");\nconst IsDrizzleTable = Symbol.for(\"drizzle:IsDrizzleTable\");\nclass Table {\n  static [entityKind] = \"Table\";\n  /** @internal */\n  static Symbol = {\n    Name: TableName,\n    Schema,\n    OriginalName,\n    Columns,\n    ExtraConfigColumns,\n    BaseName,\n    IsAlias,\n    ExtraConfigBuilder\n  };\n  /**\n   * @internal\n   * Can be changed if the table is aliased.\n   */\n  [TableName];\n  /**\n   * @internal\n   * Used to store the original name of the table, before any aliasing.\n   */\n  [OriginalName];\n  /** @internal */\n  [Schema];\n  /** @internal */\n  [Columns];\n  /** @internal */\n  [ExtraConfigColumns];\n  /**\n   *  @internal\n   * Used to store the table name before the transformation via the `tableCreator` functions.\n   */\n  [BaseName];\n  /** @internal */\n  [IsAlias] = false;\n  /** @internal */\n  [IsDrizzleTable] = true;\n  /** @internal */\n  [ExtraConfigBuilder] = void 0;\n  constructor(name, schema, baseName) {\n    this[TableName] = this[OriginalName] = name;\n    this[Schema] = schema;\n    this[BaseName] = baseName;\n  }\n}\nfunction isTable(table) {\n  return typeof table === \"object\" && table !== null && IsDrizzleTable in table;\n}\nfunction getTableName(table) {\n  return table[TableName];\n}\nfunction getTableUniqueName(table) {\n  return `${table[Schema] ?? \"public\"}.${table[TableName]}`;\n}\nexport {\n  BaseName,\n  Columns,\n  ExtraConfigBuilder,\n  ExtraConfigColumns,\n  IsAlias,\n  OriginalName,\n  Schema,\n  Table,\n  getTableName,\n  getTableUniqueName,\n  isTable\n};\n//# sourceMappingURL=table.js.map","import { entityKind, is } from \"../entity.js\";\nimport { isPgEnum } from \"../pg-core/columns/enum.js\";\nimport { Subquery } from \"../subquery.js\";\nimport { tracer } from \"../tracing.js\";\nimport { ViewBaseConfig } from \"../view-common.js\";\nimport { Column } from \"../column.js\";\nimport { IsAlias, Table } from \"../table.js\";\nclass FakePrimitiveParam {\n  static [entityKind] = \"FakePrimitiveParam\";\n}\nfunction isSQLWrapper(value) {\n  return value !== null && value !== void 0 && typeof value.getSQL === \"function\";\n}\nfunction mergeQueries(queries) {\n  const result = { sql: \"\", params: [] };\n  for (const query of queries) {\n    result.sql += query.sql;\n    result.params.push(...query.params);\n    if (query.typings?.length) {\n      if (!result.typings) {\n        result.typings = [];\n      }\n      result.typings.push(...query.typings);\n    }\n  }\n  return result;\n}\nclass StringChunk {\n  static [entityKind] = \"StringChunk\";\n  value;\n  constructor(value) {\n    this.value = Array.isArray(value) ? value : [value];\n  }\n  getSQL() {\n    return new SQL([this]);\n  }\n}\nclass SQL {\n  constructor(queryChunks) {\n    this.queryChunks = queryChunks;\n    for (const chunk of queryChunks) {\n      if (is(chunk, Table)) {\n        const schemaName = chunk[Table.Symbol.Schema];\n        this.usedTables.push(\n          schemaName === void 0 ? chunk[Table.Symbol.Name] : schemaName + \".\" + chunk[Table.Symbol.Name]\n        );\n      }\n    }\n  }\n  static [entityKind] = \"SQL\";\n  /** @internal */\n  decoder = noopDecoder;\n  shouldInlineParams = false;\n  /** @internal */\n  usedTables = [];\n  append(query) {\n    this.queryChunks.push(...query.queryChunks);\n    return this;\n  }\n  toQuery(config) {\n    return tracer.startActiveSpan(\"drizzle.buildSQL\", (span) => {\n      const query = this.buildQueryFromSourceParams(this.queryChunks, config);\n      span?.setAttributes({\n        \"drizzle.query.text\": query.sql,\n        \"drizzle.query.params\": JSON.stringify(query.params)\n      });\n      return query;\n    });\n  }\n  buildQueryFromSourceParams(chunks, _config) {\n    const config = Object.assign({}, _config, {\n      inlineParams: _config.inlineParams || this.shouldInlineParams,\n      paramStartIndex: _config.paramStartIndex || { value: 0 }\n    });\n    const {\n      casing,\n      escapeName,\n      escapeParam,\n      prepareTyping,\n      inlineParams,\n      paramStartIndex\n    } = config;\n    return mergeQueries(chunks.map((chunk) => {\n      if (is(chunk, StringChunk)) {\n        return { sql: chunk.value.join(\"\"), params: [] };\n      }\n      if (is(chunk, Name)) {\n        return { sql: escapeName(chunk.value), params: [] };\n      }\n      if (chunk === void 0) {\n        return { sql: \"\", params: [] };\n      }\n      if (Array.isArray(chunk)) {\n        const result = [new StringChunk(\"(\")];\n        for (const [i, p] of chunk.entries()) {\n          result.push(p);\n          if (i < chunk.length - 1) {\n            result.push(new StringChunk(\", \"));\n          }\n        }\n        result.push(new StringChunk(\")\"));\n        return this.buildQueryFromSourceParams(result, config);\n      }\n      if (is(chunk, SQL)) {\n        return this.buildQueryFromSourceParams(chunk.queryChunks, {\n          ...config,\n          inlineParams: inlineParams || chunk.shouldInlineParams\n        });\n      }\n      if (is(chunk, Table)) {\n        const schemaName = chunk[Table.Symbol.Schema];\n        const tableName = chunk[Table.Symbol.Name];\n        return {\n          sql: schemaName === void 0 || chunk[IsAlias] ? escapeName(tableName) : escapeName(schemaName) + \".\" + escapeName(tableName),\n          params: []\n        };\n      }\n      if (is(chunk, Column)) {\n        const columnName = casing.getColumnCasing(chunk);\n        if (_config.invokeSource === \"indexes\") {\n          return { sql: escapeName(columnName), params: [] };\n        }\n        const schemaName = chunk.table[Table.Symbol.Schema];\n        return {\n          sql: chunk.table[IsAlias] || schemaName === void 0 ? escapeName(chunk.table[Table.Symbol.Name]) + \".\" + escapeName(columnName) : escapeName(schemaName) + \".\" + escapeName(chunk.table[Table.Symbol.Name]) + \".\" + escapeName(columnName),\n          params: []\n        };\n      }\n      if (is(chunk, View)) {\n        const schemaName = chunk[ViewBaseConfig].schema;\n        const viewName = chunk[ViewBaseConfig].name;\n        return {\n          sql: schemaName === void 0 || chunk[ViewBaseConfig].isAlias ? escapeName(viewName) : escapeName(schemaName) + \".\" + escapeName(viewName),\n          params: []\n        };\n      }\n      if (is(chunk, Param)) {\n        if (is(chunk.value, Placeholder)) {\n          return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: [\"none\"] };\n        }\n        const mappedValue = chunk.value === null ? null : chunk.encoder.mapToDriverValue(chunk.value);\n        if (is(mappedValue, SQL)) {\n          return this.buildQueryFromSourceParams([mappedValue], config);\n        }\n        if (inlineParams) {\n          return { sql: this.mapInlineParam(mappedValue, config), params: [] };\n        }\n        let typings = [\"none\"];\n        if (prepareTyping) {\n          typings = [prepareTyping(chunk.encoder)];\n        }\n        return { sql: escapeParam(paramStartIndex.value++, mappedValue), params: [mappedValue], typings };\n      }\n      if (is(chunk, Placeholder)) {\n        return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: [\"none\"] };\n      }\n      if (is(chunk, SQL.Aliased) && chunk.fieldAlias !== void 0) {\n        return { sql: escapeName(chunk.fieldAlias), params: [] };\n      }\n      if (is(chunk, Subquery)) {\n        if (chunk._.isWith) {\n          return { sql: escapeName(chunk._.alias), params: [] };\n        }\n        return this.buildQueryFromSourceParams([\n          new StringChunk(\"(\"),\n          chunk._.sql,\n          new StringChunk(\") \"),\n          new Name(chunk._.alias)\n        ], config);\n      }\n      if (isPgEnum(chunk)) {\n        if (chunk.schema) {\n          return { sql: escapeName(chunk.schema) + \".\" + escapeName(chunk.enumName), params: [] };\n        }\n        return { sql: escapeName(chunk.enumName), params: [] };\n      }\n      if (isSQLWrapper(chunk)) {\n        if (chunk.shouldOmitSQLParens?.()) {\n          return this.buildQueryFromSourceParams([chunk.getSQL()], config);\n        }\n        return this.buildQueryFromSourceParams([\n          new StringChunk(\"(\"),\n          chunk.getSQL(),\n          new StringChunk(\")\")\n        ], config);\n      }\n      if (inlineParams) {\n        return { sql: this.mapInlineParam(chunk, config), params: [] };\n      }\n      return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: [\"none\"] };\n    }));\n  }\n  mapInlineParam(chunk, { escapeString }) {\n    if (chunk === null) {\n      return \"null\";\n    }\n    if (typeof chunk === \"number\" || typeof chunk === \"boolean\") {\n      return chunk.toString();\n    }\n    if (typeof chunk === \"string\") {\n      return escapeString(chunk);\n    }\n    if (typeof chunk === \"object\") {\n      const mappedValueAsString = chunk.toString();\n      if (mappedValueAsString === \"[object Object]\") {\n        return escapeString(JSON.stringify(chunk));\n      }\n      return escapeString(mappedValueAsString);\n    }\n    throw new Error(\"Unexpected param value: \" + chunk);\n  }\n  getSQL() {\n    return this;\n  }\n  as(alias) {\n    if (alias === void 0) {\n      return this;\n    }\n    return new SQL.Aliased(this, alias);\n  }\n  mapWith(decoder) {\n    this.decoder = typeof decoder === \"function\" ? { mapFromDriverValue: decoder } : decoder;\n    return this;\n  }\n  inlineParams() {\n    this.shouldInlineParams = true;\n    return this;\n  }\n  /**\n   * This method is used to conditionally include a part of the query.\n   *\n   * @param condition - Condition to check\n   * @returns itself if the condition is `true`, otherwise `undefined`\n   */\n  if(condition) {\n    return condition ? this : void 0;\n  }\n}\nclass Name {\n  constructor(value) {\n    this.value = value;\n  }\n  static [entityKind] = \"Name\";\n  brand;\n  getSQL() {\n    return new SQL([this]);\n  }\n}\nfunction name(value) {\n  return new Name(value);\n}\nfunction isDriverValueEncoder(value) {\n  return typeof value === \"object\" && value !== null && \"mapToDriverValue\" in value && typeof value.mapToDriverValue === \"function\";\n}\nconst noopDecoder = {\n  mapFromDriverValue: (value) => value\n};\nconst noopEncoder = {\n  mapToDriverValue: (value) => value\n};\nconst noopMapper = {\n  ...noopDecoder,\n  ...noopEncoder\n};\nclass Param {\n  /**\n   * @param value - Parameter value\n   * @param encoder - Encoder to convert the value to a driver parameter\n   */\n  constructor(value, encoder = noopEncoder) {\n    this.value = value;\n    this.encoder = encoder;\n  }\n  static [entityKind] = \"Param\";\n  brand;\n  getSQL() {\n    return new SQL([this]);\n  }\n}\nfunction param(value, encoder) {\n  return new Param(value, encoder);\n}\nfunction sql(strings, ...params) {\n  const queryChunks = [];\n  if (params.length > 0 || strings.length > 0 && strings[0] !== \"\") {\n    queryChunks.push(new StringChunk(strings[0]));\n  }\n  for (const [paramIndex, param2] of params.entries()) {\n    queryChunks.push(param2, new StringChunk(strings[paramIndex + 1]));\n  }\n  return new SQL(queryChunks);\n}\n((sql2) => {\n  function empty() {\n    return new SQL([]);\n  }\n  sql2.empty = empty;\n  function fromList(list) {\n    return new SQL(list);\n  }\n  sql2.fromList = fromList;\n  function raw(str) {\n    return new SQL([new StringChunk(str)]);\n  }\n  sql2.raw = raw;\n  function join(chunks, separator) {\n    const result = [];\n    for (const [i, chunk] of chunks.entries()) {\n      if (i > 0 && separator !== void 0) {\n        result.push(separator);\n      }\n      result.push(chunk);\n    }\n    return new SQL(result);\n  }\n  sql2.join = join;\n  function identifier(value) {\n    return new Name(value);\n  }\n  sql2.identifier = identifier;\n  function placeholder2(name2) {\n    return new Placeholder(name2);\n  }\n  sql2.placeholder = placeholder2;\n  function param2(value, encoder) {\n    return new Param(value, encoder);\n  }\n  sql2.param = param2;\n})(sql || (sql = {}));\n((SQL2) => {\n  class Aliased {\n    constructor(sql2, fieldAlias) {\n      this.sql = sql2;\n      this.fieldAlias = fieldAlias;\n    }\n    static [entityKind] = \"SQL.Aliased\";\n    /** @internal */\n    isSelectionField = false;\n    getSQL() {\n      return this.sql;\n    }\n    /** @internal */\n    clone() {\n      return new Aliased(this.sql, this.fieldAlias);\n    }\n  }\n  SQL2.Aliased = Aliased;\n})(SQL || (SQL = {}));\nclass Placeholder {\n  constructor(name2) {\n    this.name = name2;\n  }\n  static [entityKind] = \"Placeholder\";\n  getSQL() {\n    return new SQL([this]);\n  }\n}\nfunction placeholder(name2) {\n  return new Placeholder(name2);\n}\nfunction fillPlaceholders(params, values) {\n  return params.map((p) => {\n    if (is(p, Placeholder)) {\n      if (!(p.name in values)) {\n        throw new Error(`No value for placeholder \"${p.name}\" was provided`);\n      }\n      return values[p.name];\n    }\n    if (is(p, Param) && is(p.value, Placeholder)) {\n      if (!(p.value.name in values)) {\n        throw new Error(`No value for placeholder \"${p.value.name}\" was provided`);\n      }\n      return p.encoder.mapToDriverValue(values[p.value.name]);\n    }\n    return p;\n  });\n}\nconst IsDrizzleView = Symbol.for(\"drizzle:IsDrizzleView\");\nclass View {\n  static [entityKind] = \"View\";\n  /** @internal */\n  [ViewBaseConfig];\n  /** @internal */\n  [IsDrizzleView] = true;\n  constructor({ name: name2, schema, selectedFields, query }) {\n    this[ViewBaseConfig] = {\n      name: name2,\n      originalName: name2,\n      schema,\n      selectedFields,\n      query,\n      isExisting: !query,\n      isAlias: false\n    };\n  }\n  getSQL() {\n    return new SQL([this]);\n  }\n}\nfunction isView(view) {\n  return typeof view === \"object\" && view !== null && IsDrizzleView in view;\n}\nfunction getViewName(view) {\n  return view[ViewBaseConfig].name;\n}\nColumn.prototype.getSQL = function() {\n  return new SQL([this]);\n};\nTable.prototype.getSQL = function() {\n  return new SQL([this]);\n};\nSubquery.prototype.getSQL = function() {\n  return new SQL([this]);\n};\nexport {\n  FakePrimitiveParam,\n  Name,\n  Param,\n  Placeholder,\n  SQL,\n  StringChunk,\n  View,\n  fillPlaceholders,\n  getViewName,\n  isDriverValueEncoder,\n  isSQLWrapper,\n  isView,\n  name,\n  noopDecoder,\n  noopEncoder,\n  noopMapper,\n  param,\n  placeholder,\n  sql\n};\n//# sourceMappingURL=sql.js.map","import { entityKind } from \"../entity.js\";\nclass CheckBuilder {\n  constructor(name, value) {\n    this.name = name;\n    this.value = value;\n  }\n  static [entityKind] = \"PgCheckBuilder\";\n  brand;\n  /** @internal */\n  build(table) {\n    return new Check(table, this);\n  }\n}\nclass Check {\n  constructor(table, builder) {\n    this.table = table;\n    this.name = builder.name;\n    this.value = builder.value;\n  }\n  static [entityKind] = \"PgCheck\";\n  name;\n  value;\n}\nfunction check(name, value) {\n  return new CheckBuilder(name, value);\n}\nexport {\n  Check,\n  CheckBuilder,\n  check\n};\n//# sourceMappingURL=checks.js.map","import { Column } from \"./column.js\";\nimport { is } from \"./entity.js\";\nimport { Param, SQL, View } from \"./sql/sql.js\";\nimport { Subquery } from \"./subquery.js\";\nimport { getTableName, Table } from \"./table.js\";\nimport { ViewBaseConfig } from \"./view-common.js\";\nfunction mapResultRow(columns, row, joinsNotNullableMap) {\n  const nullifyMap = {};\n  const result = columns.reduce(\n    (result2, { path, field }, columnIndex) => {\n      let decoder;\n      if (is(field, Column)) {\n        decoder = field;\n      } else if (is(field, SQL)) {\n        decoder = field.decoder;\n      } else if (is(field, Subquery)) {\n        decoder = field._.sql.decoder;\n      } else {\n        decoder = field.sql.decoder;\n      }\n      let node = result2;\n      for (const [pathChunkIndex, pathChunk] of path.entries()) {\n        if (pathChunkIndex < path.length - 1) {\n          if (!(pathChunk in node)) {\n            node[pathChunk] = {};\n          }\n          node = node[pathChunk];\n        } else {\n          const rawValue = row[columnIndex];\n          const value = node[pathChunk] = rawValue === null ? null : decoder.mapFromDriverValue(rawValue);\n          if (joinsNotNullableMap && is(field, Column) && path.length === 2) {\n            const objectName = path[0];\n            if (!(objectName in nullifyMap)) {\n              nullifyMap[objectName] = value === null ? getTableName(field.table) : false;\n            } else if (typeof nullifyMap[objectName] === \"string\" && nullifyMap[objectName] !== getTableName(field.table)) {\n              nullifyMap[objectName] = false;\n            }\n          }\n        }\n      }\n      return result2;\n    },\n    {}\n  );\n  if (joinsNotNullableMap && Object.keys(nullifyMap).length > 0) {\n    for (const [objectName, tableName] of Object.entries(nullifyMap)) {\n      if (typeof tableName === \"string\" && !joinsNotNullableMap[tableName]) {\n        result[objectName] = null;\n      }\n    }\n  }\n  return result;\n}\nfunction orderSelectedFields(fields, pathPrefix) {\n  return Object.entries(fields).reduce((result, [name, field]) => {\n    if (typeof name !== \"string\") {\n      return result;\n    }\n    const newPath = pathPrefix ? [...pathPrefix, name] : [name];\n    if (is(field, Column) || is(field, SQL) || is(field, SQL.Aliased) || is(field, Subquery)) {\n      result.push({ path: newPath, field });\n    } else if (is(field, Table)) {\n      result.push(...orderSelectedFields(field[Table.Symbol.Columns], newPath));\n    } else {\n      result.push(...orderSelectedFields(field, newPath));\n    }\n    return result;\n  }, []);\n}\nfunction haveSameKeys(left, right) {\n  const leftKeys = Object.keys(left);\n  const rightKeys = Object.keys(right);\n  if (leftKeys.length !== rightKeys.length) {\n    return false;\n  }\n  for (const [index, key] of leftKeys.entries()) {\n    if (key !== rightKeys[index]) {\n      return false;\n    }\n  }\n  return true;\n}\nfunction mapUpdateSet(table, values) {\n  const entries = Object.entries(values).filter(([, value]) => value !== void 0).map(([key, value]) => {\n    if (is(value, SQL) || is(value, Column)) {\n      return [key, value];\n    } else {\n      return [key, new Param(value, table[Table.Symbol.Columns][key])];\n    }\n  });\n  if (entries.length === 0) {\n    throw new Error(\"No values to set\");\n  }\n  return Object.fromEntries(entries);\n}\nfunction applyMixins(baseClass, extendedClasses) {\n  for (const extendedClass of extendedClasses) {\n    for (const name of Object.getOwnPropertyNames(extendedClass.prototype)) {\n      if (name === \"constructor\") continue;\n      Object.defineProperty(\n        baseClass.prototype,\n        name,\n        Object.getOwnPropertyDescriptor(extendedClass.prototype, name) || /* @__PURE__ */ Object.create(null)\n      );\n    }\n  }\n}\nfunction getTableColumns(table) {\n  return table[Table.Symbol.Columns];\n}\nfunction getViewSelectedFields(view) {\n  return view[ViewBaseConfig].selectedFields;\n}\nfunction getTableLikeName(table) {\n  return is(table, Subquery) ? table._.alias : is(table, View) ? table[ViewBaseConfig].name : is(table, SQL) ? void 0 : table[Table.Symbol.IsAlias] ? table[Table.Symbol.Name] : table[Table.Symbol.BaseName];\n}\nfunction getColumnNameAndConfig(a, b) {\n  return {\n    name: typeof a === \"string\" && a.length > 0 ? a : \"\",\n    config: typeof a === \"object\" ? a : b\n  };\n}\nconst _ = {};\nconst __ = {};\nfunction isConfig(data) {\n  if (typeof data !== \"object\" || data === null) return false;\n  if (data.constructor.name !== \"Object\") return false;\n  if (\"logger\" in data) {\n    const type = typeof data[\"logger\"];\n    if (type !== \"boolean\" && (type !== \"object\" || typeof data[\"logger\"][\"logQuery\"] !== \"function\") && type !== \"undefined\") return false;\n    return true;\n  }\n  if (\"schema\" in data) {\n    const type = typeof data[\"schema\"];\n    if (type !== \"object\" && type !== \"undefined\") return false;\n    return true;\n  }\n  if (\"casing\" in data) {\n    const type = typeof data[\"casing\"];\n    if (type !== \"string\" && type !== \"undefined\") return false;\n    return true;\n  }\n  if (\"mode\" in data) {\n    if (data[\"mode\"] !== \"default\" || data[\"mode\"] !== \"planetscale\" || data[\"mode\"] !== void 0) return false;\n    return true;\n  }\n  if (\"connection\" in data) {\n    const type = typeof data[\"connection\"];\n    if (type !== \"string\" && type !== \"object\" && type !== \"undefined\") return false;\n    return true;\n  }\n  if (\"client\" in data) {\n    const type = typeof data[\"client\"];\n    if (type !== \"object\" && type !== \"function\" && type !== \"undefined\") return false;\n    return true;\n  }\n  if (Object.keys(data).length === 0) return true;\n  return false;\n}\nconst textDecoder = typeof TextDecoder === \"undefined\" ? null : new TextDecoder();\nexport {\n  applyMixins,\n  getColumnNameAndConfig,\n  getTableColumns,\n  getTableLikeName,\n  getViewSelectedFields,\n  haveSameKeys,\n  isConfig,\n  mapResultRow,\n  mapUpdateSet,\n  orderSelectedFields,\n  textDecoder\n};\n//# sourceMappingURL=utils.js.map","import { entityKind } from \"../../entity.js\";\nimport { PgColumnBuilder } from \"./common.js\";\nclass PgIntColumnBaseBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgIntColumnBaseBuilder\";\n  generatedAlwaysAsIdentity(sequence) {\n    if (sequence) {\n      const { name, ...options } = sequence;\n      this.config.generatedIdentity = {\n        type: \"always\",\n        sequenceName: name,\n        sequenceOptions: options\n      };\n    } else {\n      this.config.generatedIdentity = {\n        type: \"always\"\n      };\n    }\n    this.config.hasDefault = true;\n    this.config.notNull = true;\n    return this;\n  }\n  generatedByDefaultAsIdentity(sequence) {\n    if (sequence) {\n      const { name, ...options } = sequence;\n      this.config.generatedIdentity = {\n        type: \"byDefault\",\n        sequenceName: name,\n        sequenceOptions: options\n      };\n    } else {\n      this.config.generatedIdentity = {\n        type: \"byDefault\"\n      };\n    }\n    this.config.hasDefault = true;\n    this.config.notNull = true;\n    return this;\n  }\n}\nexport {\n  PgIntColumnBaseBuilder\n};\n//# sourceMappingURL=int.common.js.map","import { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\nimport { PgColumn } from \"./common.js\";\nimport { PgIntColumnBaseBuilder } from \"./int.common.js\";\nclass PgBigInt53Builder extends PgIntColumnBaseBuilder {\n  static [entityKind] = \"PgBigInt53Builder\";\n  constructor(name) {\n    super(name, \"number\", \"PgBigInt53\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgBigInt53(table, this.config);\n  }\n}\nclass PgBigInt53 extends PgColumn {\n  static [entityKind] = \"PgBigInt53\";\n  getSQLType() {\n    return \"bigint\";\n  }\n  mapFromDriverValue(value) {\n    if (typeof value === \"number\") {\n      return value;\n    }\n    return Number(value);\n  }\n}\nclass PgBigInt64Builder extends PgIntColumnBaseBuilder {\n  static [entityKind] = \"PgBigInt64Builder\";\n  constructor(name) {\n    super(name, \"bigint\", \"PgBigInt64\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgBigInt64(\n      table,\n      this.config\n    );\n  }\n}\nclass PgBigInt64 extends PgColumn {\n  static [entityKind] = \"PgBigInt64\";\n  getSQLType() {\n    return \"bigint\";\n  }\n  // eslint-disable-next-line unicorn/prefer-native-coercion-functions\n  mapFromDriverValue(value) {\n    return BigInt(value);\n  }\n}\nfunction bigint(a, b) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  if (config.mode === \"number\") {\n    return new PgBigInt53Builder(name);\n  }\n  return new PgBigInt64Builder(name);\n}\nexport {\n  PgBigInt53,\n  PgBigInt53Builder,\n  PgBigInt64,\n  PgBigInt64Builder,\n  bigint\n};\n//# sourceMappingURL=bigint.js.map","import { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgBigSerial53Builder extends PgColumnBuilder {\n  static [entityKind] = \"PgBigSerial53Builder\";\n  constructor(name) {\n    super(name, \"number\", \"PgBigSerial53\");\n    this.config.hasDefault = true;\n    this.config.notNull = true;\n  }\n  /** @internal */\n  build(table) {\n    return new PgBigSerial53(\n      table,\n      this.config\n    );\n  }\n}\nclass PgBigSerial53 extends PgColumn {\n  static [entityKind] = \"PgBigSerial53\";\n  getSQLType() {\n    return \"bigserial\";\n  }\n  mapFromDriverValue(value) {\n    if (typeof value === \"number\") {\n      return value;\n    }\n    return Number(value);\n  }\n}\nclass PgBigSerial64Builder extends PgColumnBuilder {\n  static [entityKind] = \"PgBigSerial64Builder\";\n  constructor(name) {\n    super(name, \"bigint\", \"PgBigSerial64\");\n    this.config.hasDefault = true;\n  }\n  /** @internal */\n  build(table) {\n    return new PgBigSerial64(\n      table,\n      this.config\n    );\n  }\n}\nclass PgBigSerial64 extends PgColumn {\n  static [entityKind] = \"PgBigSerial64\";\n  getSQLType() {\n    return \"bigserial\";\n  }\n  // eslint-disable-next-line unicorn/prefer-native-coercion-functions\n  mapFromDriverValue(value) {\n    return BigInt(value);\n  }\n}\nfunction bigserial(a, b) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  if (config.mode === \"number\") {\n    return new PgBigSerial53Builder(name);\n  }\n  return new PgBigSerial64Builder(name);\n}\nexport {\n  PgBigSerial53,\n  PgBigSerial53Builder,\n  PgBigSerial64,\n  PgBigSerial64Builder,\n  bigserial\n};\n//# sourceMappingURL=bigserial.js.map","import { entityKind } from \"../../entity.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgBooleanBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgBooleanBuilder\";\n  constructor(name) {\n    super(name, \"boolean\", \"PgBoolean\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgBoolean(table, this.config);\n  }\n}\nclass PgBoolean extends PgColumn {\n  static [entityKind] = \"PgBoolean\";\n  getSQLType() {\n    return \"boolean\";\n  }\n}\nfunction boolean(name) {\n  return new PgBooleanBuilder(name ?? \"\");\n}\nexport {\n  PgBoolean,\n  PgBooleanBuilder,\n  boolean\n};\n//# sourceMappingURL=boolean.js.map","import { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgCharBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgCharBuilder\";\n  constructor(name, config) {\n    super(name, \"string\", \"PgChar\");\n    this.config.length = config.length;\n    this.config.enumValues = config.enum;\n  }\n  /** @internal */\n  build(table) {\n    return new PgChar(\n      table,\n      this.config\n    );\n  }\n}\nclass PgChar extends PgColumn {\n  static [entityKind] = \"PgChar\";\n  length = this.config.length;\n  enumValues = this.config.enumValues;\n  getSQLType() {\n    return this.length === void 0 ? `char` : `char(${this.length})`;\n  }\n}\nfunction char(a, b = {}) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  return new PgCharBuilder(name, config);\n}\nexport {\n  PgChar,\n  PgCharBuilder,\n  char\n};\n//# sourceMappingURL=char.js.map","import { entityKind } from \"../../entity.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgCidrBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgCidrBuilder\";\n  constructor(name) {\n    super(name, \"string\", \"PgCidr\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgCidr(table, this.config);\n  }\n}\nclass PgCidr extends PgColumn {\n  static [entityKind] = \"PgCidr\";\n  getSQLType() {\n    return \"cidr\";\n  }\n}\nfunction cidr(name) {\n  return new PgCidrBuilder(name ?? \"\");\n}\nexport {\n  PgCidr,\n  PgCidrBuilder,\n  cidr\n};\n//# sourceMappingURL=cidr.js.map","import { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgCustomColumnBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgCustomColumnBuilder\";\n  constructor(name, fieldConfig, customTypeParams) {\n    super(name, \"custom\", \"PgCustomColumn\");\n    this.config.fieldConfig = fieldConfig;\n    this.config.customTypeParams = customTypeParams;\n  }\n  /** @internal */\n  build(table) {\n    return new PgCustomColumn(\n      table,\n      this.config\n    );\n  }\n}\nclass PgCustomColumn extends PgColumn {\n  static [entityKind] = \"PgCustomColumn\";\n  sqlName;\n  mapTo;\n  mapFrom;\n  constructor(table, config) {\n    super(table, config);\n    this.sqlName = config.customTypeParams.dataType(config.fieldConfig);\n    this.mapTo = config.customTypeParams.toDriver;\n    this.mapFrom = config.customTypeParams.fromDriver;\n  }\n  getSQLType() {\n    return this.sqlName;\n  }\n  mapFromDriverValue(value) {\n    return typeof this.mapFrom === \"function\" ? this.mapFrom(value) : value;\n  }\n  mapToDriverValue(value) {\n    return typeof this.mapTo === \"function\" ? this.mapTo(value) : value;\n  }\n}\nfunction customType(customTypeParams) {\n  return (a, b) => {\n    const { name, config } = getColumnNameAndConfig(a, b);\n    return new PgCustomColumnBuilder(name, config, customTypeParams);\n  };\n}\nexport {\n  PgCustomColumn,\n  PgCustomColumnBuilder,\n  customType\n};\n//# sourceMappingURL=custom.js.map","import { entityKind } from \"../../entity.js\";\nimport { sql } from \"../../sql/sql.js\";\nimport { PgColumnBuilder } from \"./common.js\";\nclass PgDateColumnBaseBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgDateColumnBaseBuilder\";\n  defaultNow() {\n    return this.default(sql`now()`);\n  }\n}\nexport {\n  PgDateColumnBaseBuilder\n};\n//# sourceMappingURL=date.common.js.map","import { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\nimport { PgColumn } from \"./common.js\";\nimport { PgDateColumnBaseBuilder } from \"./date.common.js\";\nclass PgDateBuilder extends PgDateColumnBaseBuilder {\n  static [entityKind] = \"PgDateBuilder\";\n  constructor(name) {\n    super(name, \"date\", \"PgDate\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgDate(table, this.config);\n  }\n}\nclass PgDate extends PgColumn {\n  static [entityKind] = \"PgDate\";\n  getSQLType() {\n    return \"date\";\n  }\n  mapFromDriverValue(value) {\n    if (typeof value === \"string\") return new Date(value);\n    return value;\n  }\n  mapToDriverValue(value) {\n    return value.toISOString();\n  }\n}\nclass PgDateStringBuilder extends PgDateColumnBaseBuilder {\n  static [entityKind] = \"PgDateStringBuilder\";\n  constructor(name) {\n    super(name, \"string\", \"PgDateString\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgDateString(\n      table,\n      this.config\n    );\n  }\n}\nclass PgDateString extends PgColumn {\n  static [entityKind] = \"PgDateString\";\n  getSQLType() {\n    return \"date\";\n  }\n  mapFromDriverValue(value) {\n    if (typeof value === \"string\") return value;\n    return value.toISOString().slice(0, -14);\n  }\n}\nfunction date(a, b) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  if (config?.mode === \"date\") {\n    return new PgDateBuilder(name);\n  }\n  return new PgDateStringBuilder(name);\n}\nexport {\n  PgDate,\n  PgDateBuilder,\n  PgDateString,\n  PgDateStringBuilder,\n  date\n};\n//# sourceMappingURL=date.js.map","import { entityKind } from \"../../entity.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgDoublePrecisionBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgDoublePrecisionBuilder\";\n  constructor(name) {\n    super(name, \"number\", \"PgDoublePrecision\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgDoublePrecision(\n      table,\n      this.config\n    );\n  }\n}\nclass PgDoublePrecision extends PgColumn {\n  static [entityKind] = \"PgDoublePrecision\";\n  getSQLType() {\n    return \"double precision\";\n  }\n  mapFromDriverValue(value) {\n    if (typeof value === \"string\") {\n      return Number.parseFloat(value);\n    }\n    return value;\n  }\n}\nfunction doublePrecision(name) {\n  return new PgDoublePrecisionBuilder(name ?? \"\");\n}\nexport {\n  PgDoublePrecision,\n  PgDoublePrecisionBuilder,\n  doublePrecision\n};\n//# sourceMappingURL=double-precision.js.map","import { entityKind } from \"../../entity.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgInetBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgInetBuilder\";\n  constructor(name) {\n    super(name, \"string\", \"PgInet\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgInet(table, this.config);\n  }\n}\nclass PgInet extends PgColumn {\n  static [entityKind] = \"PgInet\";\n  getSQLType() {\n    return \"inet\";\n  }\n}\nfunction inet(name) {\n  return new PgInetBuilder(name ?? \"\");\n}\nexport {\n  PgInet,\n  PgInetBuilder,\n  inet\n};\n//# sourceMappingURL=inet.js.map","import { entityKind } from \"../../entity.js\";\nimport { PgColumn } from \"./common.js\";\nimport { PgIntColumnBaseBuilder } from \"./int.common.js\";\nclass PgIntegerBuilder extends PgIntColumnBaseBuilder {\n  static [entityKind] = \"PgIntegerBuilder\";\n  constructor(name) {\n    super(name, \"number\", \"PgInteger\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgInteger(table, this.config);\n  }\n}\nclass PgInteger extends PgColumn {\n  static [entityKind] = \"PgInteger\";\n  getSQLType() {\n    return \"integer\";\n  }\n  mapFromDriverValue(value) {\n    if (typeof value === \"string\") {\n      return Number.parseInt(value);\n    }\n    return value;\n  }\n}\nfunction integer(name) {\n  return new PgIntegerBuilder(name ?? \"\");\n}\nexport {\n  PgInteger,\n  PgIntegerBuilder,\n  integer\n};\n//# sourceMappingURL=integer.js.map","import { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgIntervalBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgIntervalBuilder\";\n  constructor(name, intervalConfig) {\n    super(name, \"string\", \"PgInterval\");\n    this.config.intervalConfig = intervalConfig;\n  }\n  /** @internal */\n  build(table) {\n    return new PgInterval(table, this.config);\n  }\n}\nclass PgInterval extends PgColumn {\n  static [entityKind] = \"PgInterval\";\n  fields = this.config.intervalConfig.fields;\n  precision = this.config.intervalConfig.precision;\n  getSQLType() {\n    const fields = this.fields ? ` ${this.fields}` : \"\";\n    const precision = this.precision ? `(${this.precision})` : \"\";\n    return `interval${fields}${precision}`;\n  }\n}\nfunction interval(a, b = {}) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  return new PgIntervalBuilder(name, config);\n}\nexport {\n  PgInterval,\n  PgIntervalBuilder,\n  interval\n};\n//# sourceMappingURL=interval.js.map","import { entityKind } from \"../../entity.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgJsonBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgJsonBuilder\";\n  constructor(name) {\n    super(name, \"json\", \"PgJson\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgJson(table, this.config);\n  }\n}\nclass PgJson extends PgColumn {\n  static [entityKind] = \"PgJson\";\n  constructor(table, config) {\n    super(table, config);\n  }\n  getSQLType() {\n    return \"json\";\n  }\n  mapToDriverValue(value) {\n    return JSON.stringify(value);\n  }\n  mapFromDriverValue(value) {\n    if (typeof value === \"string\") {\n      try {\n        return JSON.parse(value);\n      } catch {\n        return value;\n      }\n    }\n    return value;\n  }\n}\nfunction json(name) {\n  return new PgJsonBuilder(name ?? \"\");\n}\nexport {\n  PgJson,\n  PgJsonBuilder,\n  json\n};\n//# sourceMappingURL=json.js.map","import { entityKind } from \"../../entity.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgJsonbBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgJsonbBuilder\";\n  constructor(name) {\n    super(name, \"json\", \"PgJsonb\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgJsonb(table, this.config);\n  }\n}\nclass PgJsonb extends PgColumn {\n  static [entityKind] = \"PgJsonb\";\n  constructor(table, config) {\n    super(table, config);\n  }\n  getSQLType() {\n    return \"jsonb\";\n  }\n  mapToDriverValue(value) {\n    return JSON.stringify(value);\n  }\n  mapFromDriverValue(value) {\n    if (typeof value === \"string\") {\n      try {\n        return JSON.parse(value);\n      } catch {\n        return value;\n      }\n    }\n    return value;\n  }\n}\nfunction jsonb(name) {\n  return new PgJsonbBuilder(name ?? \"\");\n}\nexport {\n  PgJsonb,\n  PgJsonbBuilder,\n  jsonb\n};\n//# sourceMappingURL=jsonb.js.map","import { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgLineBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgLineBuilder\";\n  constructor(name) {\n    super(name, \"array\", \"PgLine\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgLineTuple(\n      table,\n      this.config\n    );\n  }\n}\nclass PgLineTuple extends PgColumn {\n  static [entityKind] = \"PgLine\";\n  getSQLType() {\n    return \"line\";\n  }\n  mapFromDriverValue(value) {\n    const [a, b, c] = value.slice(1, -1).split(\",\");\n    return [Number.parseFloat(a), Number.parseFloat(b), Number.parseFloat(c)];\n  }\n  mapToDriverValue(value) {\n    return `{${value[0]},${value[1]},${value[2]}}`;\n  }\n}\nclass PgLineABCBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgLineABCBuilder\";\n  constructor(name) {\n    super(name, \"json\", \"PgLineABC\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgLineABC(\n      table,\n      this.config\n    );\n  }\n}\nclass PgLineABC extends PgColumn {\n  static [entityKind] = \"PgLineABC\";\n  getSQLType() {\n    return \"line\";\n  }\n  mapFromDriverValue(value) {\n    const [a, b, c] = value.slice(1, -1).split(\",\");\n    return { a: Number.parseFloat(a), b: Number.parseFloat(b), c: Number.parseFloat(c) };\n  }\n  mapToDriverValue(value) {\n    return `{${value.a},${value.b},${value.c}}`;\n  }\n}\nfunction line(a, b) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  if (!config?.mode || config.mode === \"tuple\") {\n    return new PgLineBuilder(name);\n  }\n  return new PgLineABCBuilder(name);\n}\nexport {\n  PgLineABC,\n  PgLineABCBuilder,\n  PgLineBuilder,\n  PgLineTuple,\n  line\n};\n//# sourceMappingURL=line.js.map","import { entityKind } from \"../../entity.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgMacaddrBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgMacaddrBuilder\";\n  constructor(name) {\n    super(name, \"string\", \"PgMacaddr\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgMacaddr(table, this.config);\n  }\n}\nclass PgMacaddr extends PgColumn {\n  static [entityKind] = \"PgMacaddr\";\n  getSQLType() {\n    return \"macaddr\";\n  }\n}\nfunction macaddr(name) {\n  return new PgMacaddrBuilder(name ?? \"\");\n}\nexport {\n  PgMacaddr,\n  PgMacaddrBuilder,\n  macaddr\n};\n//# sourceMappingURL=macaddr.js.map","import { entityKind } from \"../../entity.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgMacaddr8Builder extends PgColumnBuilder {\n  static [entityKind] = \"PgMacaddr8Builder\";\n  constructor(name) {\n    super(name, \"string\", \"PgMacaddr8\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgMacaddr8(table, this.config);\n  }\n}\nclass PgMacaddr8 extends PgColumn {\n  static [entityKind] = \"PgMacaddr8\";\n  getSQLType() {\n    return \"macaddr8\";\n  }\n}\nfunction macaddr8(name) {\n  return new PgMacaddr8Builder(name ?? \"\");\n}\nexport {\n  PgMacaddr8,\n  PgMacaddr8Builder,\n  macaddr8\n};\n//# sourceMappingURL=macaddr8.js.map","import { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgNumericBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgNumericBuilder\";\n  constructor(name, precision, scale) {\n    super(name, \"string\", \"PgNumeric\");\n    this.config.precision = precision;\n    this.config.scale = scale;\n  }\n  /** @internal */\n  build(table) {\n    return new PgNumeric(table, this.config);\n  }\n}\nclass PgNumeric extends PgColumn {\n  static [entityKind] = \"PgNumeric\";\n  precision;\n  scale;\n  constructor(table, config) {\n    super(table, config);\n    this.precision = config.precision;\n    this.scale = config.scale;\n  }\n  mapFromDriverValue(value) {\n    if (typeof value === \"string\") return value;\n    return String(value);\n  }\n  getSQLType() {\n    if (this.precision !== void 0 && this.scale !== void 0) {\n      return `numeric(${this.precision}, ${this.scale})`;\n    } else if (this.precision === void 0) {\n      return \"numeric\";\n    } else {\n      return `numeric(${this.precision})`;\n    }\n  }\n}\nclass PgNumericNumberBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgNumericNumberBuilder\";\n  constructor(name, precision, scale) {\n    super(name, \"number\", \"PgNumericNumber\");\n    this.config.precision = precision;\n    this.config.scale = scale;\n  }\n  /** @internal */\n  build(table) {\n    return new PgNumericNumber(\n      table,\n      this.config\n    );\n  }\n}\nclass PgNumericNumber extends PgColumn {\n  static [entityKind] = \"PgNumericNumber\";\n  precision;\n  scale;\n  constructor(table, config) {\n    super(table, config);\n    this.precision = config.precision;\n    this.scale = config.scale;\n  }\n  mapFromDriverValue(value) {\n    if (typeof value === \"number\") return value;\n    return Number(value);\n  }\n  mapToDriverValue = String;\n  getSQLType() {\n    if (this.precision !== void 0 && this.scale !== void 0) {\n      return `numeric(${this.precision}, ${this.scale})`;\n    } else if (this.precision === void 0) {\n      return \"numeric\";\n    } else {\n      return `numeric(${this.precision})`;\n    }\n  }\n}\nclass PgNumericBigIntBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgNumericBigIntBuilder\";\n  constructor(name, precision, scale) {\n    super(name, \"bigint\", \"PgNumericBigInt\");\n    this.config.precision = precision;\n    this.config.scale = scale;\n  }\n  /** @internal */\n  build(table) {\n    return new PgNumericBigInt(\n      table,\n      this.config\n    );\n  }\n}\nclass PgNumericBigInt extends PgColumn {\n  static [entityKind] = \"PgNumericBigInt\";\n  precision;\n  scale;\n  constructor(table, config) {\n    super(table, config);\n    this.precision = config.precision;\n    this.scale = config.scale;\n  }\n  mapFromDriverValue = BigInt;\n  mapToDriverValue = String;\n  getSQLType() {\n    if (this.precision !== void 0 && this.scale !== void 0) {\n      return `numeric(${this.precision}, ${this.scale})`;\n    } else if (this.precision === void 0) {\n      return \"numeric\";\n    } else {\n      return `numeric(${this.precision})`;\n    }\n  }\n}\nfunction numeric(a, b) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  const mode = config?.mode;\n  return mode === \"number\" ? new PgNumericNumberBuilder(name, config?.precision, config?.scale) : mode === \"bigint\" ? new PgNumericBigIntBuilder(name, config?.precision, config?.scale) : new PgNumericBuilder(name, config?.precision, config?.scale);\n}\nconst decimal = numeric;\nexport {\n  PgNumeric,\n  PgNumericBigInt,\n  PgNumericBigIntBuilder,\n  PgNumericBuilder,\n  PgNumericNumber,\n  PgNumericNumberBuilder,\n  decimal,\n  numeric\n};\n//# sourceMappingURL=numeric.js.map","import { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgPointTupleBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgPointTupleBuilder\";\n  constructor(name) {\n    super(name, \"array\", \"PgPointTuple\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgPointTuple(\n      table,\n      this.config\n    );\n  }\n}\nclass PgPointTuple extends PgColumn {\n  static [entityKind] = \"PgPointTuple\";\n  getSQLType() {\n    return \"point\";\n  }\n  mapFromDriverValue(value) {\n    if (typeof value === \"string\") {\n      const [x, y] = value.slice(1, -1).split(\",\");\n      return [Number.parseFloat(x), Number.parseFloat(y)];\n    }\n    return [value.x, value.y];\n  }\n  mapToDriverValue(value) {\n    return `(${value[0]},${value[1]})`;\n  }\n}\nclass PgPointObjectBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgPointObjectBuilder\";\n  constructor(name) {\n    super(name, \"json\", \"PgPointObject\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgPointObject(\n      table,\n      this.config\n    );\n  }\n}\nclass PgPointObject extends PgColumn {\n  static [entityKind] = \"PgPointObject\";\n  getSQLType() {\n    return \"point\";\n  }\n  mapFromDriverValue(value) {\n    if (typeof value === \"string\") {\n      const [x, y] = value.slice(1, -1).split(\",\");\n      return { x: Number.parseFloat(x), y: Number.parseFloat(y) };\n    }\n    return value;\n  }\n  mapToDriverValue(value) {\n    return `(${value.x},${value.y})`;\n  }\n}\nfunction point(a, b) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  if (!config?.mode || config.mode === \"tuple\") {\n    return new PgPointTupleBuilder(name);\n  }\n  return new PgPointObjectBuilder(name);\n}\nexport {\n  PgPointObject,\n  PgPointObjectBuilder,\n  PgPointTuple,\n  PgPointTupleBuilder,\n  point\n};\n//# sourceMappingURL=point.js.map","function hexToBytes(hex) {\n  const bytes = [];\n  for (let c = 0; c < hex.length; c += 2) {\n    bytes.push(Number.parseInt(hex.slice(c, c + 2), 16));\n  }\n  return new Uint8Array(bytes);\n}\nfunction bytesToFloat64(bytes, offset) {\n  const buffer = new ArrayBuffer(8);\n  const view = new DataView(buffer);\n  for (let i = 0; i < 8; i++) {\n    view.setUint8(i, bytes[offset + i]);\n  }\n  return view.getFloat64(0, true);\n}\nfunction parseEWKB(hex) {\n  const bytes = hexToBytes(hex);\n  let offset = 0;\n  const byteOrder = bytes[offset];\n  offset += 1;\n  const view = new DataView(bytes.buffer);\n  const geomType = view.getUint32(offset, byteOrder === 1);\n  offset += 4;\n  let _srid;\n  if (geomType & 536870912) {\n    _srid = view.getUint32(offset, byteOrder === 1);\n    offset += 4;\n  }\n  if ((geomType & 65535) === 1) {\n    const x = bytesToFloat64(bytes, offset);\n    offset += 8;\n    const y = bytesToFloat64(bytes, offset);\n    offset += 8;\n    return [x, y];\n  }\n  throw new Error(\"Unsupported geometry type\");\n}\nexport {\n  parseEWKB\n};\n//# sourceMappingURL=utils.js.map","import { entityKind } from \"../../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../../utils.js\";\nimport { PgColumn, PgColumnBuilder } from \"../common.js\";\nimport { parseEWKB } from \"./utils.js\";\nclass PgGeometryBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgGeometryBuilder\";\n  constructor(name) {\n    super(name, \"array\", \"PgGeometry\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgGeometry(\n      table,\n      this.config\n    );\n  }\n}\nclass PgGeometry extends PgColumn {\n  static [entityKind] = \"PgGeometry\";\n  getSQLType() {\n    return \"geometry(point)\";\n  }\n  mapFromDriverValue(value) {\n    return parseEWKB(value);\n  }\n  mapToDriverValue(value) {\n    return `point(${value[0]} ${value[1]})`;\n  }\n}\nclass PgGeometryObjectBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgGeometryObjectBuilder\";\n  constructor(name) {\n    super(name, \"json\", \"PgGeometryObject\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgGeometryObject(\n      table,\n      this.config\n    );\n  }\n}\nclass PgGeometryObject extends PgColumn {\n  static [entityKind] = \"PgGeometryObject\";\n  getSQLType() {\n    return \"geometry(point)\";\n  }\n  mapFromDriverValue(value) {\n    const parsed = parseEWKB(value);\n    return { x: parsed[0], y: parsed[1] };\n  }\n  mapToDriverValue(value) {\n    return `point(${value.x} ${value.y})`;\n  }\n}\nfunction geometry(a, b) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  if (!config?.mode || config.mode === \"tuple\") {\n    return new PgGeometryBuilder(name);\n  }\n  return new PgGeometryObjectBuilder(name);\n}\nexport {\n  PgGeometry,\n  PgGeometryBuilder,\n  PgGeometryObject,\n  PgGeometryObjectBuilder,\n  geometry\n};\n//# sourceMappingURL=geometry.js.map","import { entityKind } from \"../../entity.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgRealBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgRealBuilder\";\n  constructor(name, length) {\n    super(name, \"number\", \"PgReal\");\n    this.config.length = length;\n  }\n  /** @internal */\n  build(table) {\n    return new PgReal(table, this.config);\n  }\n}\nclass PgReal extends PgColumn {\n  static [entityKind] = \"PgReal\";\n  constructor(table, config) {\n    super(table, config);\n  }\n  getSQLType() {\n    return \"real\";\n  }\n  mapFromDriverValue = (value) => {\n    if (typeof value === \"string\") {\n      return Number.parseFloat(value);\n    }\n    return value;\n  };\n}\nfunction real(name) {\n  return new PgRealBuilder(name ?? \"\");\n}\nexport {\n  PgReal,\n  PgRealBuilder,\n  real\n};\n//# sourceMappingURL=real.js.map","import { entityKind } from \"../../entity.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgSerialBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgSerialBuilder\";\n  constructor(name) {\n    super(name, \"number\", \"PgSerial\");\n    this.config.hasDefault = true;\n    this.config.notNull = true;\n  }\n  /** @internal */\n  build(table) {\n    return new PgSerial(table, this.config);\n  }\n}\nclass PgSerial extends PgColumn {\n  static [entityKind] = \"PgSerial\";\n  getSQLType() {\n    return \"serial\";\n  }\n}\nfunction serial(name) {\n  return new PgSerialBuilder(name ?? \"\");\n}\nexport {\n  PgSerial,\n  PgSerialBuilder,\n  serial\n};\n//# sourceMappingURL=serial.js.map","import { entityKind } from \"../../entity.js\";\nimport { PgColumn } from \"./common.js\";\nimport { PgIntColumnBaseBuilder } from \"./int.common.js\";\nclass PgSmallIntBuilder extends PgIntColumnBaseBuilder {\n  static [entityKind] = \"PgSmallIntBuilder\";\n  constructor(name) {\n    super(name, \"number\", \"PgSmallInt\");\n  }\n  /** @internal */\n  build(table) {\n    return new PgSmallInt(table, this.config);\n  }\n}\nclass PgSmallInt extends PgColumn {\n  static [entityKind] = \"PgSmallInt\";\n  getSQLType() {\n    return \"smallint\";\n  }\n  mapFromDriverValue = (value) => {\n    if (typeof value === \"string\") {\n      return Number(value);\n    }\n    return value;\n  };\n}\nfunction smallint(name) {\n  return new PgSmallIntBuilder(name ?? \"\");\n}\nexport {\n  PgSmallInt,\n  PgSmallIntBuilder,\n  smallint\n};\n//# sourceMappingURL=smallint.js.map","import { entityKind } from \"../../entity.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgSmallSerialBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgSmallSerialBuilder\";\n  constructor(name) {\n    super(name, \"number\", \"PgSmallSerial\");\n    this.config.hasDefault = true;\n    this.config.notNull = true;\n  }\n  /** @internal */\n  build(table) {\n    return new PgSmallSerial(\n      table,\n      this.config\n    );\n  }\n}\nclass PgSmallSerial extends PgColumn {\n  static [entityKind] = \"PgSmallSerial\";\n  getSQLType() {\n    return \"smallserial\";\n  }\n}\nfunction smallserial(name) {\n  return new PgSmallSerialBuilder(name ?? \"\");\n}\nexport {\n  PgSmallSerial,\n  PgSmallSerialBuilder,\n  smallserial\n};\n//# sourceMappingURL=smallserial.js.map","import { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgTextBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgTextBuilder\";\n  constructor(name, config) {\n    super(name, \"string\", \"PgText\");\n    this.config.enumValues = config.enum;\n  }\n  /** @internal */\n  build(table) {\n    return new PgText(table, this.config);\n  }\n}\nclass PgText extends PgColumn {\n  static [entityKind] = \"PgText\";\n  enumValues = this.config.enumValues;\n  getSQLType() {\n    return \"text\";\n  }\n}\nfunction text(a, b = {}) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  return new PgTextBuilder(name, config);\n}\nexport {\n  PgText,\n  PgTextBuilder,\n  text\n};\n//# sourceMappingURL=text.js.map","import { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\nimport { PgColumn } from \"./common.js\";\nimport { PgDateColumnBaseBuilder } from \"./date.common.js\";\nclass PgTimeBuilder extends PgDateColumnBaseBuilder {\n  constructor(name, withTimezone, precision) {\n    super(name, \"string\", \"PgTime\");\n    this.withTimezone = withTimezone;\n    this.precision = precision;\n    this.config.withTimezone = withTimezone;\n    this.config.precision = precision;\n  }\n  static [entityKind] = \"PgTimeBuilder\";\n  /** @internal */\n  build(table) {\n    return new PgTime(table, this.config);\n  }\n}\nclass PgTime extends PgColumn {\n  static [entityKind] = \"PgTime\";\n  withTimezone;\n  precision;\n  constructor(table, config) {\n    super(table, config);\n    this.withTimezone = config.withTimezone;\n    this.precision = config.precision;\n  }\n  getSQLType() {\n    const precision = this.precision === void 0 ? \"\" : `(${this.precision})`;\n    return `time${precision}${this.withTimezone ? \" with time zone\" : \"\"}`;\n  }\n}\nfunction time(a, b = {}) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  return new PgTimeBuilder(name, config.withTimezone ?? false, config.precision);\n}\nexport {\n  PgTime,\n  PgTimeBuilder,\n  time\n};\n//# sourceMappingURL=time.js.map","import { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\nimport { PgColumn } from \"./common.js\";\nimport { PgDateColumnBaseBuilder } from \"./date.common.js\";\nclass PgTimestampBuilder extends PgDateColumnBaseBuilder {\n  static [entityKind] = \"PgTimestampBuilder\";\n  constructor(name, withTimezone, precision) {\n    super(name, \"date\", \"PgTimestamp\");\n    this.config.withTimezone = withTimezone;\n    this.config.precision = precision;\n  }\n  /** @internal */\n  build(table) {\n    return new PgTimestamp(table, this.config);\n  }\n}\nclass PgTimestamp extends PgColumn {\n  static [entityKind] = \"PgTimestamp\";\n  withTimezone;\n  precision;\n  constructor(table, config) {\n    super(table, config);\n    this.withTimezone = config.withTimezone;\n    this.precision = config.precision;\n  }\n  getSQLType() {\n    const precision = this.precision === void 0 ? \"\" : ` (${this.precision})`;\n    return `timestamp${precision}${this.withTimezone ? \" with time zone\" : \"\"}`;\n  }\n  mapFromDriverValue(value) {\n    if (typeof value === \"string\") return new Date(this.withTimezone ? value : value + \"+0000\");\n    return value;\n  }\n  mapToDriverValue = (value) => {\n    return value.toISOString();\n  };\n}\nclass PgTimestampStringBuilder extends PgDateColumnBaseBuilder {\n  static [entityKind] = \"PgTimestampStringBuilder\";\n  constructor(name, withTimezone, precision) {\n    super(name, \"string\", \"PgTimestampString\");\n    this.config.withTimezone = withTimezone;\n    this.config.precision = precision;\n  }\n  /** @internal */\n  build(table) {\n    return new PgTimestampString(\n      table,\n      this.config\n    );\n  }\n}\nclass PgTimestampString extends PgColumn {\n  static [entityKind] = \"PgTimestampString\";\n  withTimezone;\n  precision;\n  constructor(table, config) {\n    super(table, config);\n    this.withTimezone = config.withTimezone;\n    this.precision = config.precision;\n  }\n  getSQLType() {\n    const precision = this.precision === void 0 ? \"\" : `(${this.precision})`;\n    return `timestamp${precision}${this.withTimezone ? \" with time zone\" : \"\"}`;\n  }\n  mapFromDriverValue(value) {\n    if (typeof value === \"string\") return value;\n    const shortened = value.toISOString().slice(0, -1).replace(\"T\", \" \");\n    if (this.withTimezone) {\n      const offset = value.getTimezoneOffset();\n      const sign = offset <= 0 ? \"+\" : \"-\";\n      return `${shortened}${sign}${Math.floor(Math.abs(offset) / 60).toString().padStart(2, \"0\")}`;\n    }\n    return shortened;\n  }\n}\nfunction timestamp(a, b = {}) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  if (config?.mode === \"string\") {\n    return new PgTimestampStringBuilder(name, config.withTimezone ?? false, config.precision);\n  }\n  return new PgTimestampBuilder(name, config?.withTimezone ?? false, config?.precision);\n}\nexport {\n  PgTimestamp,\n  PgTimestampBuilder,\n  PgTimestampString,\n  PgTimestampStringBuilder,\n  timestamp\n};\n//# sourceMappingURL=timestamp.js.map","import { entityKind } from \"../../entity.js\";\nimport { sql } from \"../../sql/sql.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgUUIDBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgUUIDBuilder\";\n  constructor(name) {\n    super(name, \"string\", \"PgUUID\");\n  }\n  /**\n   * Adds `default gen_random_uuid()` to the column definition.\n   */\n  defaultRandom() {\n    return this.default(sql`gen_random_uuid()`);\n  }\n  /** @internal */\n  build(table) {\n    return new PgUUID(table, this.config);\n  }\n}\nclass PgUUID extends PgColumn {\n  static [entityKind] = \"PgUUID\";\n  getSQLType() {\n    return \"uuid\";\n  }\n}\nfunction uuid(name) {\n  return new PgUUIDBuilder(name ?? \"\");\n}\nexport {\n  PgUUID,\n  PgUUIDBuilder,\n  uuid\n};\n//# sourceMappingURL=uuid.js.map","import { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\nimport { PgColumn, PgColumnBuilder } from \"./common.js\";\nclass PgVarcharBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgVarcharBuilder\";\n  constructor(name, config) {\n    super(name, \"string\", \"PgVarchar\");\n    this.config.length = config.length;\n    this.config.enumValues = config.enum;\n  }\n  /** @internal */\n  build(table) {\n    return new PgVarchar(\n      table,\n      this.config\n    );\n  }\n}\nclass PgVarchar extends PgColumn {\n  static [entityKind] = \"PgVarchar\";\n  length = this.config.length;\n  enumValues = this.config.enumValues;\n  getSQLType() {\n    return this.length === void 0 ? `varchar` : `varchar(${this.length})`;\n  }\n}\nfunction varchar(a, b = {}) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  return new PgVarcharBuilder(name, config);\n}\nexport {\n  PgVarchar,\n  PgVarcharBuilder,\n  varchar\n};\n//# sourceMappingURL=varchar.js.map","import { entityKind } from \"../../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../../utils.js\";\nimport { PgColumn, PgColumnBuilder } from \"../common.js\";\nclass PgBinaryVectorBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgBinaryVectorBuilder\";\n  constructor(name, config) {\n    super(name, \"string\", \"PgBinaryVector\");\n    this.config.dimensions = config.dimensions;\n  }\n  /** @internal */\n  build(table) {\n    return new PgBinaryVector(\n      table,\n      this.config\n    );\n  }\n}\nclass PgBinaryVector extends PgColumn {\n  static [entityKind] = \"PgBinaryVector\";\n  dimensions = this.config.dimensions;\n  getSQLType() {\n    return `bit(${this.dimensions})`;\n  }\n}\nfunction bit(a, b) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  return new PgBinaryVectorBuilder(name, config);\n}\nexport {\n  PgBinaryVector,\n  PgBinaryVectorBuilder,\n  bit\n};\n//# sourceMappingURL=bit.js.map","import { entityKind } from \"../../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../../utils.js\";\nimport { PgColumn, PgColumnBuilder } from \"../common.js\";\nclass PgHalfVectorBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgHalfVectorBuilder\";\n  constructor(name, config) {\n    super(name, \"array\", \"PgHalfVector\");\n    this.config.dimensions = config.dimensions;\n  }\n  /** @internal */\n  build(table) {\n    return new PgHalfVector(\n      table,\n      this.config\n    );\n  }\n}\nclass PgHalfVector extends PgColumn {\n  static [entityKind] = \"PgHalfVector\";\n  dimensions = this.config.dimensions;\n  getSQLType() {\n    return `halfvec(${this.dimensions})`;\n  }\n  mapToDriverValue(value) {\n    return JSON.stringify(value);\n  }\n  mapFromDriverValue(value) {\n    return value.slice(1, -1).split(\",\").map((v) => Number.parseFloat(v));\n  }\n}\nfunction halfvec(a, b) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  return new PgHalfVectorBuilder(name, config);\n}\nexport {\n  PgHalfVector,\n  PgHalfVectorBuilder,\n  halfvec\n};\n//# sourceMappingURL=halfvec.js.map","import { entityKind } from \"../../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../../utils.js\";\nimport { PgColumn, PgColumnBuilder } from \"../common.js\";\nclass PgSparseVectorBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgSparseVectorBuilder\";\n  constructor(name, config) {\n    super(name, \"string\", \"PgSparseVector\");\n    this.config.dimensions = config.dimensions;\n  }\n  /** @internal */\n  build(table) {\n    return new PgSparseVector(\n      table,\n      this.config\n    );\n  }\n}\nclass PgSparseVector extends PgColumn {\n  static [entityKind] = \"PgSparseVector\";\n  dimensions = this.config.dimensions;\n  getSQLType() {\n    return `sparsevec(${this.dimensions})`;\n  }\n}\nfunction sparsevec(a, b) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  return new PgSparseVectorBuilder(name, config);\n}\nexport {\n  PgSparseVector,\n  PgSparseVectorBuilder,\n  sparsevec\n};\n//# sourceMappingURL=sparsevec.js.map","import { entityKind } from \"../../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../../utils.js\";\nimport { PgColumn, PgColumnBuilder } from \"../common.js\";\nclass PgVectorBuilder extends PgColumnBuilder {\n  static [entityKind] = \"PgVectorBuilder\";\n  constructor(name, config) {\n    super(name, \"array\", \"PgVector\");\n    this.config.dimensions = config.dimensions;\n  }\n  /** @internal */\n  build(table) {\n    return new PgVector(\n      table,\n      this.config\n    );\n  }\n}\nclass PgVector extends PgColumn {\n  static [entityKind] = \"PgVector\";\n  dimensions = this.config.dimensions;\n  getSQLType() {\n    return `vector(${this.dimensions})`;\n  }\n  mapToDriverValue(value) {\n    return JSON.stringify(value);\n  }\n  mapFromDriverValue(value) {\n    return value.slice(1, -1).split(\",\").map((v) => Number.parseFloat(v));\n  }\n}\nfunction vector(a, b) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  return new PgVectorBuilder(name, config);\n}\nexport {\n  PgVector,\n  PgVectorBuilder,\n  vector\n};\n//# sourceMappingURL=vector.js.map","import { bigint } from \"./bigint.js\";\nimport { bigserial } from \"./bigserial.js\";\nimport { boolean } from \"./boolean.js\";\nimport { char } from \"./char.js\";\nimport { cidr } from \"./cidr.js\";\nimport { customType } from \"./custom.js\";\nimport { date } from \"./date.js\";\nimport { doublePrecision } from \"./double-precision.js\";\nimport { inet } from \"./inet.js\";\nimport { integer } from \"./integer.js\";\nimport { interval } from \"./interval.js\";\nimport { json } from \"./json.js\";\nimport { jsonb } from \"./jsonb.js\";\nimport { line } from \"./line.js\";\nimport { macaddr } from \"./macaddr.js\";\nimport { macaddr8 } from \"./macaddr8.js\";\nimport { numeric } from \"./numeric.js\";\nimport { point } from \"./point.js\";\nimport { geometry } from \"./postgis_extension/geometry.js\";\nimport { real } from \"./real.js\";\nimport { serial } from \"./serial.js\";\nimport { smallint } from \"./smallint.js\";\nimport { smallserial } from \"./smallserial.js\";\nimport { text } from \"./text.js\";\nimport { time } from \"./time.js\";\nimport { timestamp } from \"./timestamp.js\";\nimport { uuid } from \"./uuid.js\";\nimport { varchar } from \"./varchar.js\";\nimport { bit } from \"./vector_extension/bit.js\";\nimport { halfvec } from \"./vector_extension/halfvec.js\";\nimport { sparsevec } from \"./vector_extension/sparsevec.js\";\nimport { vector } from \"./vector_extension/vector.js\";\nfunction getPgColumnBuilders() {\n  return {\n    bigint,\n    bigserial,\n    boolean,\n    char,\n    cidr,\n    customType,\n    date,\n    doublePrecision,\n    inet,\n    integer,\n    interval,\n    json,\n    jsonb,\n    line,\n    macaddr,\n    macaddr8,\n    numeric,\n    point,\n    geometry,\n    real,\n    serial,\n    smallint,\n    smallserial,\n    text,\n    time,\n    timestamp,\n    uuid,\n    varchar,\n    bit,\n    halfvec,\n    sparsevec,\n    vector\n  };\n}\nexport {\n  getPgColumnBuilders\n};\n//# sourceMappingURL=all.js.map","import { entityKind } from \"../entity.js\";\nimport { Table } from \"../table.js\";\nimport { getPgColumnBuilders } from \"./columns/all.js\";\nconst InlineForeignKeys = Symbol.for(\"drizzle:PgInlineForeignKeys\");\nconst EnableRLS = Symbol.for(\"drizzle:EnableRLS\");\nclass PgTable extends Table {\n  static [entityKind] = \"PgTable\";\n  /** @internal */\n  static Symbol = Object.assign({}, Table.Symbol, {\n    InlineForeignKeys,\n    EnableRLS\n  });\n  /**@internal */\n  [InlineForeignKeys] = [];\n  /** @internal */\n  [EnableRLS] = false;\n  /** @internal */\n  [Table.Symbol.ExtraConfigBuilder] = void 0;\n  /** @internal */\n  [Table.Symbol.ExtraConfigColumns] = {};\n}\nfunction pgTableWithSchema(name, columns, extraConfig, schema, baseName = name) {\n  const rawTable = new PgTable(name, schema, baseName);\n  const parsedColumns = typeof columns === \"function\" ? columns(getPgColumnBuilders()) : columns;\n  const builtColumns = Object.fromEntries(\n    Object.entries(parsedColumns).map(([name2, colBuilderBase]) => {\n      const colBuilder = colBuilderBase;\n      colBuilder.setName(name2);\n      const column = colBuilder.build(rawTable);\n      rawTable[InlineForeignKeys].push(...colBuilder.buildForeignKeys(column, rawTable));\n      return [name2, column];\n    })\n  );\n  const builtColumnsForExtraConfig = Object.fromEntries(\n    Object.entries(parsedColumns).map(([name2, colBuilderBase]) => {\n      const colBuilder = colBuilderBase;\n      colBuilder.setName(name2);\n      const column = colBuilder.buildExtraConfigColumn(rawTable);\n      return [name2, column];\n    })\n  );\n  const table = Object.assign(rawTable, builtColumns);\n  table[Table.Symbol.Columns] = builtColumns;\n  table[Table.Symbol.ExtraConfigColumns] = builtColumnsForExtraConfig;\n  if (extraConfig) {\n    table[PgTable.Symbol.ExtraConfigBuilder] = extraConfig;\n  }\n  return Object.assign(table, {\n    enableRLS: () => {\n      table[PgTable.Symbol.EnableRLS] = true;\n      return table;\n    }\n  });\n}\nconst pgTable = (name, columns, extraConfig) => {\n  return pgTableWithSchema(name, columns, extraConfig, void 0);\n};\nfunction pgTableCreator(customizeTableName) {\n  return (name, columns, extraConfig) => {\n    return pgTableWithSchema(customizeTableName(name), columns, extraConfig, void 0, name);\n  };\n}\nexport {\n  EnableRLS,\n  InlineForeignKeys,\n  PgTable,\n  pgTable,\n  pgTableCreator,\n  pgTableWithSchema\n};\n//# sourceMappingURL=table.js.map","import { SQL } from \"../sql/sql.js\";\nimport { entityKind, is } from \"../entity.js\";\nimport { IndexedColumn } from \"./columns/index.js\";\nclass IndexBuilderOn {\n  constructor(unique, name) {\n    this.unique = unique;\n    this.name = name;\n  }\n  static [entityKind] = \"PgIndexBuilderOn\";\n  on(...columns) {\n    return new IndexBuilder(\n      columns.map((it) => {\n        if (is(it, SQL)) {\n          return it;\n        }\n        it = it;\n        const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig);\n        it.indexConfig = JSON.parse(JSON.stringify(it.defaultConfig));\n        return clonedIndexedColumn;\n      }),\n      this.unique,\n      false,\n      this.name\n    );\n  }\n  onOnly(...columns) {\n    return new IndexBuilder(\n      columns.map((it) => {\n        if (is(it, SQL)) {\n          return it;\n        }\n        it = it;\n        const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig);\n        it.indexConfig = it.defaultConfig;\n        return clonedIndexedColumn;\n      }),\n      this.unique,\n      true,\n      this.name\n    );\n  }\n  /**\n   * Specify what index method to use. Choices are `btree`, `hash`, `gist`, `spgist`, `gin`, `brin`, or user-installed access methods like `bloom`. The default method is `btree.\n   *\n   * If you have the `pg_vector` extension installed in your database, you can use the `hnsw` and `ivfflat` options, which are predefined types.\n   *\n   * **You can always specify any string you want in the method, in case Drizzle doesn't have it natively in its types**\n   *\n   * @param method The name of the index method to be used\n   * @param columns\n   * @returns\n   */\n  using(method, ...columns) {\n    return new IndexBuilder(\n      columns.map((it) => {\n        if (is(it, SQL)) {\n          return it;\n        }\n        it = it;\n        const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig);\n        it.indexConfig = JSON.parse(JSON.stringify(it.defaultConfig));\n        return clonedIndexedColumn;\n      }),\n      this.unique,\n      true,\n      this.name,\n      method\n    );\n  }\n}\nclass IndexBuilder {\n  static [entityKind] = \"PgIndexBuilder\";\n  /** @internal */\n  config;\n  constructor(columns, unique, only, name, method = \"btree\") {\n    this.config = {\n      name,\n      columns,\n      unique,\n      only,\n      method\n    };\n  }\n  concurrently() {\n    this.config.concurrently = true;\n    return this;\n  }\n  with(obj) {\n    this.config.with = obj;\n    return this;\n  }\n  where(condition) {\n    this.config.where = condition;\n    return this;\n  }\n  /** @internal */\n  build(table) {\n    return new Index(this.config, table);\n  }\n}\nclass Index {\n  static [entityKind] = \"PgIndex\";\n  config;\n  constructor(config, table) {\n    this.config = { ...config, table };\n  }\n}\nfunction index(name) {\n  return new IndexBuilderOn(false, name);\n}\nfunction uniqueIndex(name) {\n  return new IndexBuilderOn(true, name);\n}\nexport {\n  Index,\n  IndexBuilder,\n  IndexBuilderOn,\n  index,\n  uniqueIndex\n};\n//# sourceMappingURL=indexes.js.map","import { entityKind } from \"../entity.js\";\nclass PgPolicy {\n  constructor(name, config) {\n    this.name = name;\n    if (config) {\n      this.as = config.as;\n      this.for = config.for;\n      this.to = config.to;\n      this.using = config.using;\n      this.withCheck = config.withCheck;\n    }\n  }\n  static [entityKind] = \"PgPolicy\";\n  as;\n  for;\n  to;\n  using;\n  withCheck;\n  /** @internal */\n  _linkedTable;\n  link(table) {\n    this._linkedTable = table;\n    return this;\n  }\n}\nfunction pgPolicy(name, config) {\n  return new PgPolicy(name, config);\n}\nexport {\n  PgPolicy,\n  pgPolicy\n};\n//# sourceMappingURL=policies.js.map","import { entityKind } from \"../entity.js\";\nimport { PgTable } from \"./table.js\";\nfunction primaryKey(...config) {\n  if (config[0].columns) {\n    return new PrimaryKeyBuilder(config[0].columns, config[0].name);\n  }\n  return new PrimaryKeyBuilder(config);\n}\nclass PrimaryKeyBuilder {\n  static [entityKind] = \"PgPrimaryKeyBuilder\";\n  /** @internal */\n  columns;\n  /** @internal */\n  name;\n  constructor(columns, name) {\n    this.columns = columns;\n    this.name = name;\n  }\n  /** @internal */\n  build(table) {\n    return new PrimaryKey(table, this.columns, this.name);\n  }\n}\nclass PrimaryKey {\n  constructor(table, columns, name) {\n    this.table = table;\n    this.columns = columns;\n    this.name = name;\n  }\n  static [entityKind] = \"PgPrimaryKey\";\n  columns;\n  name;\n  getName() {\n    return this.name ?? `${this.table[PgTable.Symbol.Name]}_${this.columns.map((column) => column.name).join(\"_\")}_pk`;\n  }\n}\nexport {\n  PrimaryKey,\n  PrimaryKeyBuilder,\n  primaryKey\n};\n//# sourceMappingURL=primary-keys.js.map","import { entityKind } from \"../entity.js\";\nclass CheckBuilder {\n  constructor(name, value) {\n    this.name = name;\n    this.value = value;\n  }\n  static [entityKind] = \"SQLiteCheckBuilder\";\n  brand;\n  build(table) {\n    return new Check(table, this);\n  }\n}\nclass Check {\n  constructor(table, builder) {\n    this.table = table;\n    this.name = builder.name;\n    this.value = builder.value;\n  }\n  static [entityKind] = \"SQLiteCheck\";\n  name;\n  value;\n}\nfunction check(name, value) {\n  return new CheckBuilder(name, value);\n}\nexport {\n  Check,\n  CheckBuilder,\n  check\n};\n//# sourceMappingURL=checks.js.map","import { entityKind } from \"../entity.js\";\nimport { TableName } from \"../table.utils.js\";\nclass ForeignKeyBuilder {\n  static [entityKind] = \"SQLiteForeignKeyBuilder\";\n  /** @internal */\n  reference;\n  /** @internal */\n  _onUpdate;\n  /** @internal */\n  _onDelete;\n  constructor(config, actions) {\n    this.reference = () => {\n      const { name, columns, foreignColumns } = config();\n      return { name, columns, foreignTable: foreignColumns[0].table, foreignColumns };\n    };\n    if (actions) {\n      this._onUpdate = actions.onUpdate;\n      this._onDelete = actions.onDelete;\n    }\n  }\n  onUpdate(action) {\n    this._onUpdate = action;\n    return this;\n  }\n  onDelete(action) {\n    this._onDelete = action;\n    return this;\n  }\n  /** @internal */\n  build(table) {\n    return new ForeignKey(table, this);\n  }\n}\nclass ForeignKey {\n  constructor(table, builder) {\n    this.table = table;\n    this.reference = builder.reference;\n    this.onUpdate = builder._onUpdate;\n    this.onDelete = builder._onDelete;\n  }\n  static [entityKind] = \"SQLiteForeignKey\";\n  reference;\n  onUpdate;\n  onDelete;\n  getName() {\n    const { name, columns, foreignColumns } = this.reference();\n    const columnNames = columns.map((column) => column.name);\n    const foreignColumnNames = foreignColumns.map((column) => column.name);\n    const chunks = [\n      this.table[TableName],\n      ...columnNames,\n      foreignColumns[0].table[TableName],\n      ...foreignColumnNames\n    ];\n    return name ?? `${chunks.join(\"_\")}_fk`;\n  }\n}\nfunction foreignKey(config) {\n  function mappedConfig() {\n    if (typeof config === \"function\") {\n      const { name, columns, foreignColumns } = config();\n      return {\n        name,\n        columns,\n        foreignColumns\n      };\n    }\n    return config;\n  }\n  return new ForeignKeyBuilder(mappedConfig);\n}\nexport {\n  ForeignKey,\n  ForeignKeyBuilder,\n  foreignKey\n};\n//# sourceMappingURL=foreign-keys.js.map","import { entityKind } from \"../entity.js\";\nimport { TableName } from \"../table.utils.js\";\nfunction uniqueKeyName(table, columns) {\n  return `${table[TableName]}_${columns.join(\"_\")}_unique`;\n}\nfunction unique(name) {\n  return new UniqueOnConstraintBuilder(name);\n}\nclass UniqueConstraintBuilder {\n  constructor(columns, name) {\n    this.name = name;\n    this.columns = columns;\n  }\n  static [entityKind] = \"SQLiteUniqueConstraintBuilder\";\n  /** @internal */\n  columns;\n  /** @internal */\n  build(table) {\n    return new UniqueConstraint(table, this.columns, this.name);\n  }\n}\nclass UniqueOnConstraintBuilder {\n  static [entityKind] = \"SQLiteUniqueOnConstraintBuilder\";\n  /** @internal */\n  name;\n  constructor(name) {\n    this.name = name;\n  }\n  on(...columns) {\n    return new UniqueConstraintBuilder(columns, this.name);\n  }\n}\nclass UniqueConstraint {\n  constructor(table, columns, name) {\n    this.table = table;\n    this.columns = columns;\n    this.name = name ?? uniqueKeyName(this.table, this.columns.map((column) => column.name));\n  }\n  static [entityKind] = \"SQLiteUniqueConstraint\";\n  columns;\n  name;\n  getName() {\n    return this.name;\n  }\n}\nexport {\n  UniqueConstraint,\n  UniqueConstraintBuilder,\n  UniqueOnConstraintBuilder,\n  unique,\n  uniqueKeyName\n};\n//# sourceMappingURL=unique-constraint.js.map","import { ColumnBuilder } from \"../../column-builder.js\";\nimport { Column } from \"../../column.js\";\nimport { entityKind } from \"../../entity.js\";\nimport { ForeignKeyBuilder } from \"../foreign-keys.js\";\nimport { uniqueKeyName } from \"../unique-constraint.js\";\nclass SQLiteColumnBuilder extends ColumnBuilder {\n  static [entityKind] = \"SQLiteColumnBuilder\";\n  foreignKeyConfigs = [];\n  references(ref, actions = {}) {\n    this.foreignKeyConfigs.push({ ref, actions });\n    return this;\n  }\n  unique(name) {\n    this.config.isUnique = true;\n    this.config.uniqueName = name;\n    return this;\n  }\n  generatedAlwaysAs(as, config) {\n    this.config.generated = {\n      as,\n      type: \"always\",\n      mode: config?.mode ?? \"virtual\"\n    };\n    return this;\n  }\n  /** @internal */\n  buildForeignKeys(column, table) {\n    return this.foreignKeyConfigs.map(({ ref, actions }) => {\n      return ((ref2, actions2) => {\n        const builder = new ForeignKeyBuilder(() => {\n          const foreignColumn = ref2();\n          return { columns: [column], foreignColumns: [foreignColumn] };\n        });\n        if (actions2.onUpdate) {\n          builder.onUpdate(actions2.onUpdate);\n        }\n        if (actions2.onDelete) {\n          builder.onDelete(actions2.onDelete);\n        }\n        return builder.build(table);\n      })(ref, actions);\n    });\n  }\n}\nclass SQLiteColumn extends Column {\n  constructor(table, config) {\n    if (!config.uniqueName) {\n      config.uniqueName = uniqueKeyName(table, [config.name]);\n    }\n    super(table, config);\n    this.table = table;\n  }\n  static [entityKind] = \"SQLiteColumn\";\n}\nexport {\n  SQLiteColumn,\n  SQLiteColumnBuilder\n};\n//# sourceMappingURL=common.js.map","import { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig, textDecoder } from \"../../utils.js\";\nimport { SQLiteColumn, SQLiteColumnBuilder } from \"./common.js\";\nclass SQLiteBigIntBuilder extends SQLiteColumnBuilder {\n  static [entityKind] = \"SQLiteBigIntBuilder\";\n  constructor(name) {\n    super(name, \"bigint\", \"SQLiteBigInt\");\n  }\n  /** @internal */\n  build(table) {\n    return new SQLiteBigInt(table, this.config);\n  }\n}\nclass SQLiteBigInt extends SQLiteColumn {\n  static [entityKind] = \"SQLiteBigInt\";\n  getSQLType() {\n    return \"blob\";\n  }\n  mapFromDriverValue(value) {\n    if (typeof Buffer !== \"undefined\" && Buffer.from) {\n      const buf = Buffer.isBuffer(value) ? value : value instanceof ArrayBuffer ? Buffer.from(value) : value.buffer ? Buffer.from(value.buffer, value.byteOffset, value.byteLength) : Buffer.from(value);\n      return BigInt(buf.toString(\"utf8\"));\n    }\n    return BigInt(textDecoder.decode(value));\n  }\n  mapToDriverValue(value) {\n    return Buffer.from(value.toString());\n  }\n}\nclass SQLiteBlobJsonBuilder extends SQLiteColumnBuilder {\n  static [entityKind] = \"SQLiteBlobJsonBuilder\";\n  constructor(name) {\n    super(name, \"json\", \"SQLiteBlobJson\");\n  }\n  /** @internal */\n  build(table) {\n    return new SQLiteBlobJson(\n      table,\n      this.config\n    );\n  }\n}\nclass SQLiteBlobJson extends SQLiteColumn {\n  static [entityKind] = \"SQLiteBlobJson\";\n  getSQLType() {\n    return \"blob\";\n  }\n  mapFromDriverValue(value) {\n    if (typeof Buffer !== \"undefined\" && Buffer.from) {\n      const buf = Buffer.isBuffer(value) ? value : value instanceof ArrayBuffer ? Buffer.from(value) : value.buffer ? Buffer.from(value.buffer, value.byteOffset, value.byteLength) : Buffer.from(value);\n      return JSON.parse(buf.toString(\"utf8\"));\n    }\n    return JSON.parse(textDecoder.decode(value));\n  }\n  mapToDriverValue(value) {\n    return Buffer.from(JSON.stringify(value));\n  }\n}\nclass SQLiteBlobBufferBuilder extends SQLiteColumnBuilder {\n  static [entityKind] = \"SQLiteBlobBufferBuilder\";\n  constructor(name) {\n    super(name, \"buffer\", \"SQLiteBlobBuffer\");\n  }\n  /** @internal */\n  build(table) {\n    return new SQLiteBlobBuffer(table, this.config);\n  }\n}\nclass SQLiteBlobBuffer extends SQLiteColumn {\n  static [entityKind] = \"SQLiteBlobBuffer\";\n  mapFromDriverValue(value) {\n    if (Buffer.isBuffer(value)) {\n      return value;\n    }\n    return Buffer.from(value);\n  }\n  getSQLType() {\n    return \"blob\";\n  }\n}\nfunction blob(a, b) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  if (config?.mode === \"json\") {\n    return new SQLiteBlobJsonBuilder(name);\n  }\n  if (config?.mode === \"bigint\") {\n    return new SQLiteBigIntBuilder(name);\n  }\n  return new SQLiteBlobBufferBuilder(name);\n}\nexport {\n  SQLiteBigInt,\n  SQLiteBigIntBuilder,\n  SQLiteBlobBuffer,\n  SQLiteBlobBufferBuilder,\n  SQLiteBlobJson,\n  SQLiteBlobJsonBuilder,\n  blob\n};\n//# sourceMappingURL=blob.js.map","import { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\nimport { SQLiteColumn, SQLiteColumnBuilder } from \"./common.js\";\nclass SQLiteCustomColumnBuilder extends SQLiteColumnBuilder {\n  static [entityKind] = \"SQLiteCustomColumnBuilder\";\n  constructor(name, fieldConfig, customTypeParams) {\n    super(name, \"custom\", \"SQLiteCustomColumn\");\n    this.config.fieldConfig = fieldConfig;\n    this.config.customTypeParams = customTypeParams;\n  }\n  /** @internal */\n  build(table) {\n    return new SQLiteCustomColumn(\n      table,\n      this.config\n    );\n  }\n}\nclass SQLiteCustomColumn extends SQLiteColumn {\n  static [entityKind] = \"SQLiteCustomColumn\";\n  sqlName;\n  mapTo;\n  mapFrom;\n  constructor(table, config) {\n    super(table, config);\n    this.sqlName = config.customTypeParams.dataType(config.fieldConfig);\n    this.mapTo = config.customTypeParams.toDriver;\n    this.mapFrom = config.customTypeParams.fromDriver;\n  }\n  getSQLType() {\n    return this.sqlName;\n  }\n  mapFromDriverValue(value) {\n    return typeof this.mapFrom === \"function\" ? this.mapFrom(value) : value;\n  }\n  mapToDriverValue(value) {\n    return typeof this.mapTo === \"function\" ? this.mapTo(value) : value;\n  }\n}\nfunction customType(customTypeParams) {\n  return (a, b) => {\n    const { name, config } = getColumnNameAndConfig(a, b);\n    return new SQLiteCustomColumnBuilder(\n      name,\n      config,\n      customTypeParams\n    );\n  };\n}\nexport {\n  SQLiteCustomColumn,\n  SQLiteCustomColumnBuilder,\n  customType\n};\n//# sourceMappingURL=custom.js.map","import { entityKind } from \"../../entity.js\";\nimport { sql } from \"../../sql/sql.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\nimport { SQLiteColumn, SQLiteColumnBuilder } from \"./common.js\";\nclass SQLiteBaseIntegerBuilder extends SQLiteColumnBuilder {\n  static [entityKind] = \"SQLiteBaseIntegerBuilder\";\n  constructor(name, dataType, columnType) {\n    super(name, dataType, columnType);\n    this.config.autoIncrement = false;\n  }\n  primaryKey(config) {\n    if (config?.autoIncrement) {\n      this.config.autoIncrement = true;\n    }\n    this.config.hasDefault = true;\n    return super.primaryKey();\n  }\n}\nclass SQLiteBaseInteger extends SQLiteColumn {\n  static [entityKind] = \"SQLiteBaseInteger\";\n  autoIncrement = this.config.autoIncrement;\n  getSQLType() {\n    return \"integer\";\n  }\n}\nclass SQLiteIntegerBuilder extends SQLiteBaseIntegerBuilder {\n  static [entityKind] = \"SQLiteIntegerBuilder\";\n  constructor(name) {\n    super(name, \"number\", \"SQLiteInteger\");\n  }\n  build(table) {\n    return new SQLiteInteger(\n      table,\n      this.config\n    );\n  }\n}\nclass SQLiteInteger extends SQLiteBaseInteger {\n  static [entityKind] = \"SQLiteInteger\";\n}\nclass SQLiteTimestampBuilder extends SQLiteBaseIntegerBuilder {\n  static [entityKind] = \"SQLiteTimestampBuilder\";\n  constructor(name, mode) {\n    super(name, \"date\", \"SQLiteTimestamp\");\n    this.config.mode = mode;\n  }\n  /**\n   * @deprecated Use `default()` with your own expression instead.\n   *\n   * Adds `DEFAULT (cast((julianday('now') - 2440587.5)*86400000 as integer))` to the column, which is the current epoch timestamp in milliseconds.\n   */\n  defaultNow() {\n    return this.default(sql`(cast((julianday('now') - 2440587.5)*86400000 as integer))`);\n  }\n  build(table) {\n    return new SQLiteTimestamp(\n      table,\n      this.config\n    );\n  }\n}\nclass SQLiteTimestamp extends SQLiteBaseInteger {\n  static [entityKind] = \"SQLiteTimestamp\";\n  mode = this.config.mode;\n  mapFromDriverValue(value) {\n    if (this.config.mode === \"timestamp\") {\n      return new Date(value * 1e3);\n    }\n    return new Date(value);\n  }\n  mapToDriverValue(value) {\n    const unix = value.getTime();\n    if (this.config.mode === \"timestamp\") {\n      return Math.floor(unix / 1e3);\n    }\n    return unix;\n  }\n}\nclass SQLiteBooleanBuilder extends SQLiteBaseIntegerBuilder {\n  static [entityKind] = \"SQLiteBooleanBuilder\";\n  constructor(name, mode) {\n    super(name, \"boolean\", \"SQLiteBoolean\");\n    this.config.mode = mode;\n  }\n  build(table) {\n    return new SQLiteBoolean(\n      table,\n      this.config\n    );\n  }\n}\nclass SQLiteBoolean extends SQLiteBaseInteger {\n  static [entityKind] = \"SQLiteBoolean\";\n  mode = this.config.mode;\n  mapFromDriverValue(value) {\n    return Number(value) === 1;\n  }\n  mapToDriverValue(value) {\n    return value ? 1 : 0;\n  }\n}\nfunction integer(a, b) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  if (config?.mode === \"timestamp\" || config?.mode === \"timestamp_ms\") {\n    return new SQLiteTimestampBuilder(name, config.mode);\n  }\n  if (config?.mode === \"boolean\") {\n    return new SQLiteBooleanBuilder(name, config.mode);\n  }\n  return new SQLiteIntegerBuilder(name);\n}\nconst int = integer;\nexport {\n  SQLiteBaseInteger,\n  SQLiteBaseIntegerBuilder,\n  SQLiteBoolean,\n  SQLiteBooleanBuilder,\n  SQLiteInteger,\n  SQLiteIntegerBuilder,\n  SQLiteTimestamp,\n  SQLiteTimestampBuilder,\n  int,\n  integer\n};\n//# sourceMappingURL=integer.js.map","import { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\nimport { SQLiteColumn, SQLiteColumnBuilder } from \"./common.js\";\nclass SQLiteNumericBuilder extends SQLiteColumnBuilder {\n  static [entityKind] = \"SQLiteNumericBuilder\";\n  constructor(name) {\n    super(name, \"string\", \"SQLiteNumeric\");\n  }\n  /** @internal */\n  build(table) {\n    return new SQLiteNumeric(\n      table,\n      this.config\n    );\n  }\n}\nclass SQLiteNumeric extends SQLiteColumn {\n  static [entityKind] = \"SQLiteNumeric\";\n  mapFromDriverValue(value) {\n    if (typeof value === \"string\") return value;\n    return String(value);\n  }\n  getSQLType() {\n    return \"numeric\";\n  }\n}\nclass SQLiteNumericNumberBuilder extends SQLiteColumnBuilder {\n  static [entityKind] = \"SQLiteNumericNumberBuilder\";\n  constructor(name) {\n    super(name, \"number\", \"SQLiteNumericNumber\");\n  }\n  /** @internal */\n  build(table) {\n    return new SQLiteNumericNumber(\n      table,\n      this.config\n    );\n  }\n}\nclass SQLiteNumericNumber extends SQLiteColumn {\n  static [entityKind] = \"SQLiteNumericNumber\";\n  mapFromDriverValue(value) {\n    if (typeof value === \"number\") return value;\n    return Number(value);\n  }\n  mapToDriverValue = String;\n  getSQLType() {\n    return \"numeric\";\n  }\n}\nclass SQLiteNumericBigIntBuilder extends SQLiteColumnBuilder {\n  static [entityKind] = \"SQLiteNumericBigIntBuilder\";\n  constructor(name) {\n    super(name, \"bigint\", \"SQLiteNumericBigInt\");\n  }\n  /** @internal */\n  build(table) {\n    return new SQLiteNumericBigInt(\n      table,\n      this.config\n    );\n  }\n}\nclass SQLiteNumericBigInt extends SQLiteColumn {\n  static [entityKind] = \"SQLiteNumericBigInt\";\n  mapFromDriverValue = BigInt;\n  mapToDriverValue = String;\n  getSQLType() {\n    return \"numeric\";\n  }\n}\nfunction numeric(a, b) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  const mode = config?.mode;\n  return mode === \"number\" ? new SQLiteNumericNumberBuilder(name) : mode === \"bigint\" ? new SQLiteNumericBigIntBuilder(name) : new SQLiteNumericBuilder(name);\n}\nexport {\n  SQLiteNumeric,\n  SQLiteNumericBigInt,\n  SQLiteNumericBigIntBuilder,\n  SQLiteNumericBuilder,\n  SQLiteNumericNumber,\n  SQLiteNumericNumberBuilder,\n  numeric\n};\n//# sourceMappingURL=numeric.js.map","import { entityKind } from \"../../entity.js\";\nimport { SQLiteColumn, SQLiteColumnBuilder } from \"./common.js\";\nclass SQLiteRealBuilder extends SQLiteColumnBuilder {\n  static [entityKind] = \"SQLiteRealBuilder\";\n  constructor(name) {\n    super(name, \"number\", \"SQLiteReal\");\n  }\n  /** @internal */\n  build(table) {\n    return new SQLiteReal(table, this.config);\n  }\n}\nclass SQLiteReal extends SQLiteColumn {\n  static [entityKind] = \"SQLiteReal\";\n  getSQLType() {\n    return \"real\";\n  }\n}\nfunction real(name) {\n  return new SQLiteRealBuilder(name ?? \"\");\n}\nexport {\n  SQLiteReal,\n  SQLiteRealBuilder,\n  real\n};\n//# sourceMappingURL=real.js.map","import { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\nimport { SQLiteColumn, SQLiteColumnBuilder } from \"./common.js\";\nclass SQLiteTextBuilder extends SQLiteColumnBuilder {\n  static [entityKind] = \"SQLiteTextBuilder\";\n  constructor(name, config) {\n    super(name, \"string\", \"SQLiteText\");\n    this.config.enumValues = config.enum;\n    this.config.length = config.length;\n  }\n  /** @internal */\n  build(table) {\n    return new SQLiteText(\n      table,\n      this.config\n    );\n  }\n}\nclass SQLiteText extends SQLiteColumn {\n  static [entityKind] = \"SQLiteText\";\n  enumValues = this.config.enumValues;\n  length = this.config.length;\n  constructor(table, config) {\n    super(table, config);\n  }\n  getSQLType() {\n    return `text${this.config.length ? `(${this.config.length})` : \"\"}`;\n  }\n}\nclass SQLiteTextJsonBuilder extends SQLiteColumnBuilder {\n  static [entityKind] = \"SQLiteTextJsonBuilder\";\n  constructor(name) {\n    super(name, \"json\", \"SQLiteTextJson\");\n  }\n  /** @internal */\n  build(table) {\n    return new SQLiteTextJson(\n      table,\n      this.config\n    );\n  }\n}\nclass SQLiteTextJson extends SQLiteColumn {\n  static [entityKind] = \"SQLiteTextJson\";\n  getSQLType() {\n    return \"text\";\n  }\n  mapFromDriverValue(value) {\n    return JSON.parse(value);\n  }\n  mapToDriverValue(value) {\n    return JSON.stringify(value);\n  }\n}\nfunction text(a, b = {}) {\n  const { name, config } = getColumnNameAndConfig(a, b);\n  if (config.mode === \"json\") {\n    return new SQLiteTextJsonBuilder(name);\n  }\n  return new SQLiteTextBuilder(name, config);\n}\nexport {\n  SQLiteText,\n  SQLiteTextBuilder,\n  SQLiteTextJson,\n  SQLiteTextJsonBuilder,\n  text\n};\n//# sourceMappingURL=text.js.map","import { blob } from \"./blob.js\";\nimport { customType } from \"./custom.js\";\nimport { integer } from \"./integer.js\";\nimport { numeric } from \"./numeric.js\";\nimport { real } from \"./real.js\";\nimport { text } from \"./text.js\";\nfunction getSQLiteColumnBuilders() {\n  return {\n    blob,\n    customType,\n    integer,\n    numeric,\n    real,\n    text\n  };\n}\nexport {\n  getSQLiteColumnBuilders\n};\n//# sourceMappingURL=all.js.map","import { entityKind } from \"../entity.js\";\nimport { Table } from \"../table.js\";\nimport { getSQLiteColumnBuilders } from \"./columns/all.js\";\nconst InlineForeignKeys = Symbol.for(\"drizzle:SQLiteInlineForeignKeys\");\nclass SQLiteTable extends Table {\n  static [entityKind] = \"SQLiteTable\";\n  /** @internal */\n  static Symbol = Object.assign({}, Table.Symbol, {\n    InlineForeignKeys\n  });\n  /** @internal */\n  [Table.Symbol.Columns];\n  /** @internal */\n  [InlineForeignKeys] = [];\n  /** @internal */\n  [Table.Symbol.ExtraConfigBuilder] = void 0;\n}\nfunction sqliteTableBase(name, columns, extraConfig, schema, baseName = name) {\n  const rawTable = new SQLiteTable(name, schema, baseName);\n  const parsedColumns = typeof columns === \"function\" ? columns(getSQLiteColumnBuilders()) : columns;\n  const builtColumns = Object.fromEntries(\n    Object.entries(parsedColumns).map(([name2, colBuilderBase]) => {\n      const colBuilder = colBuilderBase;\n      colBuilder.setName(name2);\n      const column = colBuilder.build(rawTable);\n      rawTable[InlineForeignKeys].push(...colBuilder.buildForeignKeys(column, rawTable));\n      return [name2, column];\n    })\n  );\n  const table = Object.assign(rawTable, builtColumns);\n  table[Table.Symbol.Columns] = builtColumns;\n  table[Table.Symbol.ExtraConfigColumns] = builtColumns;\n  if (extraConfig) {\n    table[SQLiteTable.Symbol.ExtraConfigBuilder] = extraConfig;\n  }\n  return table;\n}\nconst sqliteTable = (name, columns, extraConfig) => {\n  return sqliteTableBase(name, columns, extraConfig);\n};\nfunction sqliteTableCreator(customizeTableName) {\n  return (name, columns, extraConfig) => {\n    return sqliteTableBase(customizeTableName(name), columns, extraConfig, void 0, name);\n  };\n}\nexport {\n  InlineForeignKeys,\n  SQLiteTable,\n  sqliteTable,\n  sqliteTableCreator\n};\n//# sourceMappingURL=table.js.map","import { entityKind } from \"../entity.js\";\nclass IndexBuilderOn {\n  constructor(name, unique) {\n    this.name = name;\n    this.unique = unique;\n  }\n  static [entityKind] = \"SQLiteIndexBuilderOn\";\n  on(...columns) {\n    return new IndexBuilder(this.name, columns, this.unique);\n  }\n}\nclass IndexBuilder {\n  static [entityKind] = \"SQLiteIndexBuilder\";\n  /** @internal */\n  config;\n  constructor(name, columns, unique) {\n    this.config = {\n      name,\n      columns,\n      unique,\n      where: void 0\n    };\n  }\n  /**\n   * Condition for partial index.\n   */\n  where(condition) {\n    this.config.where = condition;\n    return this;\n  }\n  /** @internal */\n  build(table) {\n    return new Index(this.config, table);\n  }\n}\nclass Index {\n  static [entityKind] = \"SQLiteIndex\";\n  config;\n  constructor(config, table) {\n    this.config = { ...config, table };\n  }\n}\nfunction index(name) {\n  return new IndexBuilderOn(name, false);\n}\nfunction uniqueIndex(name) {\n  return new IndexBuilderOn(name, true);\n}\nexport {\n  Index,\n  IndexBuilder,\n  IndexBuilderOn,\n  index,\n  uniqueIndex\n};\n//# sourceMappingURL=indexes.js.map","import { entityKind } from \"../entity.js\";\nimport { SQLiteTable } from \"./table.js\";\nfunction primaryKey(...config) {\n  if (config[0].columns) {\n    return new PrimaryKeyBuilder(config[0].columns, config[0].name);\n  }\n  return new PrimaryKeyBuilder(config);\n}\nclass PrimaryKeyBuilder {\n  static [entityKind] = \"SQLitePrimaryKeyBuilder\";\n  /** @internal */\n  columns;\n  /** @internal */\n  name;\n  constructor(columns, name) {\n    this.columns = columns;\n    this.name = name;\n  }\n  /** @internal */\n  build(table) {\n    return new PrimaryKey(table, this.columns, this.name);\n  }\n}\nclass PrimaryKey {\n  constructor(table, columns, name) {\n    this.table = table;\n    this.columns = columns;\n    this.name = name;\n  }\n  static [entityKind] = \"SQLitePrimaryKey\";\n  columns;\n  name;\n  getName() {\n    return this.name ?? `${this.table[SQLiteTable.Symbol.Name]}_${this.columns.map((column) => column.name).join(\"_\")}_pk`;\n  }\n}\nexport {\n  PrimaryKey,\n  PrimaryKeyBuilder,\n  primaryKey\n};\n//# sourceMappingURL=primary-keys.js.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\n//#region src/schema/tables/mcp-oauth.ts\n/**\n* Tables backing keystroke as an OAuth 2.1 Authorization Server for the\n* Universal MCP server: dynamically-registered MCP/AI clients, their issued\n* access/refresh tokens, and consent records.\n*\n* NOT to be confused with `oauth_apps` / `oauth_connections`, which model the\n* inverse — keystroke as an OAuth *client* storing our users' connections to\n* third-party providers. These `mcp_oauth_*` tables are the provider side.\n*\n* Wired to Better Auth via the Drizzle adapter (`authSchemaFor`). Better Auth\n* addresses these by its fixed model names (`oauthApplication`,\n* `oauthAccessToken`, `oauthConsent`) and by field name (the JS property keys\n* below); the physical table/column names are ours to choose.\n*\n* Note: access/refresh tokens are stored as opaque plaintext bearer strings\n* (the Better Auth mcp plugin looks them up directly and cannot hash them),\n* consistent with how the `sessions` table stores session tokens. They are\n* short-lived; rely on DB access controls + at-rest encryption.\n*/\nconst mcpOauthClient = pgTable(\"mcp_oauth_client\", {\n\tid: text(\"id\").primaryKey(),\n\tname: text(\"name\").notNull(),\n\ticon: text(\"icon\"),\n\tmetadata: text(\"metadata\"),\n\tclientId: text(\"client_id\").notNull().unique(),\n\tclientSecret: text(\"client_secret\"),\n\tredirectUrls: text(\"redirect_urls\").notNull(),\n\ttype: text(\"type\").notNull(),\n\tdisabled: boolean(\"disabled\").notNull().default(false),\n\tuserId: text(\"user_id\").references(() => users.id, { onDelete: \"cascade\" }),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [index(\"mcp_oauth_client_user_id_idx\").on(table.userId)]);\nconst mcpOauthClientSqlite = sqliteTable(\"mcp_oauth_client\", {\n\tid: text$1(\"id\").primaryKey(),\n\tname: text$1(\"name\").notNull(),\n\ticon: text$1(\"icon\"),\n\tmetadata: text$1(\"metadata\"),\n\tclientId: text$1(\"client_id\").notNull().unique(),\n\tclientSecret: text$1(\"client_secret\"),\n\tredirectUrls: text$1(\"redirect_urls\").notNull(),\n\ttype: text$1(\"type\").notNull(),\n\tdisabled: integer$1(\"disabled\", { mode: \"boolean\" }).notNull().default(false),\n\tuserId: text$1(\"user_id\").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}, (table) => [index$1(\"mcp_oauth_client_user_id_idx\").on(table.userId)]);\nconst mcpOauthAccessToken = pgTable(\"mcp_oauth_access_token\", {\n\tid: text(\"id\").primaryKey(),\n\taccessToken: text(\"access_token\").notNull().unique(),\n\trefreshToken: text(\"refresh_token\").unique(),\n\taccessTokenExpiresAt: timestamp(\"access_token_expires_at\", { withTimezone: true }),\n\trefreshTokenExpiresAt: timestamp(\"refresh_token_expires_at\", { withTimezone: true }),\n\tclientId: text(\"client_id\").notNull(),\n\tuserId: text(\"user_id\").references(() => users.id, { onDelete: \"cascade\" }),\n\tscopes: text(\"scopes\"),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [index(\"mcp_oauth_access_token_client_id_idx\").on(table.clientId), index(\"mcp_oauth_access_token_user_id_idx\").on(table.userId)]);\nconst mcpOauthAccessTokenSqlite = sqliteTable(\"mcp_oauth_access_token\", {\n\tid: text$1(\"id\").primaryKey(),\n\taccessToken: text$1(\"access_token\").notNull().unique(),\n\trefreshToken: text$1(\"refresh_token\").unique(),\n\taccessTokenExpiresAt: integer$1(\"access_token_expires_at\", { mode: \"timestamp_ms\" }),\n\trefreshTokenExpiresAt: integer$1(\"refresh_token_expires_at\", { mode: \"timestamp_ms\" }),\n\tclientId: text$1(\"client_id\").notNull(),\n\tuserId: text$1(\"user_id\").references(() => usersSqlite.id, { onDelete: \"cascade\" }),\n\tscopes: text$1(\"scopes\"),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [index$1(\"mcp_oauth_access_token_client_id_idx\").on(table.clientId), index$1(\"mcp_oauth_access_token_user_id_idx\").on(table.userId)]);\nconst mcpOauthConsent = pgTable(\"mcp_oauth_consent\", {\n\tid: text(\"id\").primaryKey(),\n\tclientId: text(\"client_id\").notNull(),\n\tuserId: text(\"user_id\").notNull().references(() => users.id, { onDelete: \"cascade\" }),\n\tscopes: text(\"scopes\"),\n\tconsentGiven: boolean(\"consent_given\").notNull().default(false),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [index(\"mcp_oauth_consent_client_id_idx\").on(table.clientId), index(\"mcp_oauth_consent_user_id_idx\").on(table.userId)]);\nconst mcpOauthConsentSqlite = sqliteTable(\"mcp_oauth_consent\", {\n\tid: text$1(\"id\").primaryKey(),\n\tclientId: text$1(\"client_id\").notNull(),\n\tuserId: text$1(\"user_id\").notNull().references(() => usersSqlite.id, { onDelete: \"cascade\" }),\n\tscopes: text$1(\"scopes\"),\n\tconsentGiven: integer$1(\"consent_given\", { mode: \"boolean\" }).notNull().default(false),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [index$1(\"mcp_oauth_consent_client_id_idx\").on(table.clientId), index$1(\"mcp_oauth_consent_user_id_idx\").on(table.userId)]);\n//#endregion\nexport { setDatabaseHandle as S, users as _, mcpOauthConsent as a, getDbFromContext as b, authVerificationsSqlite as c, authJwks as d, authJwksSqlite as f, authAccountsSqlite as g, authAccounts as h, mcpOauthClientSqlite as i, authSessions as l, authDeviceCodesSqlite as m, mcpOauthAccessTokenSqlite as n, mcpOauthConsentSqlite as o, authDeviceCodes as p, mcpOauthClient as r, authVerifications as s, mcpOauthAccessToken as t, authSessionsSqlite as u, usersSqlite as v, isDatabaseInitialized as x, getDatabaseHandle as y };\n\n//# sourceMappingURL=mcp-oauth-SRTcHMWZ.mjs.map","","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n    return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getKeyIndexes = exports.hasFlag = exports.exists = exports.list = void 0;\nconst commands_json_1 = __importDefault(require(\"./commands.json\"));\n/**\n * Redis command list\n *\n * All commands are lowercased.\n */\nexports.list = Object.keys(commands_json_1.default);\nconst flags = {};\nexports.list.forEach((commandName) => {\n    flags[commandName] = commands_json_1.default[commandName].flags.reduce(function (flags, flag) {\n        flags[flag] = true;\n        return flags;\n    }, {});\n});\n/**\n * Check if the command exists\n */\nfunction exists(commandName, options) {\n    commandName = (options === null || options === void 0 ? void 0 : options.caseInsensitive)\n        ? String(commandName).toLowerCase()\n        : commandName;\n    return Boolean(commands_json_1.default[commandName]);\n}\nexports.exists = exists;\n/**\n * Check if the command has the flag\n *\n * Some of possible flags: readonly, noscript, loading\n */\nfunction hasFlag(commandName, flag, options) {\n    commandName = (options === null || options === void 0 ? void 0 : options.nameCaseInsensitive)\n        ? String(commandName).toLowerCase()\n        : commandName;\n    if (!flags[commandName]) {\n        throw new Error(\"Unknown command \" + commandName);\n    }\n    return Boolean(flags[commandName][flag]);\n}\nexports.hasFlag = hasFlag;\n/**\n * Get indexes of keys in the command arguments\n *\n * @example\n * ```javascript\n * getKeyIndexes('set', ['key', 'value']) // [0]\n * getKeyIndexes('mget', ['key1', 'key2']) // [0, 1]\n * ```\n */\nfunction getKeyIndexes(commandName, args, options) {\n    commandName = (options === null || options === void 0 ? void 0 : options.nameCaseInsensitive)\n        ? String(commandName).toLowerCase()\n        : commandName;\n    const command = commands_json_1.default[commandName];\n    if (!command) {\n        throw new Error(\"Unknown command \" + commandName);\n    }\n    if (!Array.isArray(args)) {\n        throw new Error(\"Expect args to be an array\");\n    }\n    const keys = [];\n    const parseExternalKey = Boolean(options && options.parseExternalKey);\n    const takeDynamicKeys = (args, startIndex) => {\n        const keys = [];\n        const keyStop = Number(args[startIndex]);\n        for (let i = 0; i < keyStop; i++) {\n            keys.push(i + startIndex + 1);\n        }\n        return keys;\n    };\n    const takeKeyAfterToken = (args, startIndex, token) => {\n        for (let i = startIndex; i < args.length - 1; i += 1) {\n            if (String(args[i]).toLowerCase() === token.toLowerCase()) {\n                return i + 1;\n            }\n        }\n        return null;\n    };\n    switch (commandName) {\n        case \"zunionstore\":\n        case \"zinterstore\":\n        case \"zdiffstore\":\n            keys.push(0, ...takeDynamicKeys(args, 1));\n            break;\n        case \"eval\":\n        case \"evalsha\":\n        case \"eval_ro\":\n        case \"evalsha_ro\":\n        case \"fcall\":\n        case \"fcall_ro\":\n        case \"blmpop\":\n        case \"bzmpop\":\n            keys.push(...takeDynamicKeys(args, 1));\n            break;\n        case \"sintercard\":\n        case \"lmpop\":\n        case \"zunion\":\n        case \"zinter\":\n        case \"zmpop\":\n        case \"zintercard\":\n        case \"zdiff\": {\n            keys.push(...takeDynamicKeys(args, 0));\n            break;\n        }\n        case \"msetex\": {\n            const numKeys = Number(args[0]);\n            for (let i = 0; i < numKeys; i++) {\n                keys.push(1 + i * 2);\n            }\n            break;\n        }\n        case \"georadius\": {\n            keys.push(0);\n            const storeKey = takeKeyAfterToken(args, 5, \"STORE\");\n            if (storeKey)\n                keys.push(storeKey);\n            const distKey = takeKeyAfterToken(args, 5, \"STOREDIST\");\n            if (distKey)\n                keys.push(distKey);\n            break;\n        }\n        case \"georadiusbymember\": {\n            keys.push(0);\n            const storeKey = takeKeyAfterToken(args, 4, \"STORE\");\n            if (storeKey)\n                keys.push(storeKey);\n            const distKey = takeKeyAfterToken(args, 4, \"STOREDIST\");\n            if (distKey)\n                keys.push(distKey);\n            break;\n        }\n        case \"sort\":\n        case \"sort_ro\":\n            keys.push(0);\n            for (let i = 1; i < args.length - 1; i++) {\n                let arg = args[i];\n                if (typeof arg !== \"string\") {\n                    continue;\n                }\n                const directive = arg.toUpperCase();\n                if (directive === \"GET\") {\n                    i += 1;\n                    arg = args[i];\n                    if (arg !== \"#\") {\n                        if (parseExternalKey) {\n                            keys.push([i, getExternalKeyNameLength(arg)]);\n                        }\n                        else {\n                            keys.push(i);\n                        }\n                    }\n                }\n                else if (directive === \"BY\") {\n                    i += 1;\n                    if (parseExternalKey) {\n                        keys.push([i, getExternalKeyNameLength(args[i])]);\n                    }\n                    else {\n                        keys.push(i);\n                    }\n                }\n                else if (directive === \"STORE\") {\n                    i += 1;\n                    keys.push(i);\n                }\n            }\n            break;\n        case \"migrate\":\n            if (args[2] === \"\") {\n                for (let i = 5; i < args.length - 1; i++) {\n                    const arg = args[i];\n                    if (typeof arg === \"string\" && arg.toUpperCase() === \"KEYS\") {\n                        for (let j = i + 1; j < args.length; j++) {\n                            keys.push(j);\n                        }\n                        break;\n                    }\n                }\n            }\n            else {\n                keys.push(2);\n            }\n            break;\n        case \"xreadgroup\":\n        case \"xread\":\n            // Keys are 1st half of the args after STREAMS argument.\n            for (let i = commandName === \"xread\" ? 0 : 3; i < args.length - 1; i++) {\n                if (String(args[i]).toUpperCase() === \"STREAMS\") {\n                    for (let j = i + 1; j <= i + (args.length - 1 - i) / 2; j++) {\n                        keys.push(j);\n                    }\n                    break;\n                }\n            }\n            break;\n        default:\n            // Step has to be at least one in this case, otherwise the command does\n            // not contain a key.\n            if (command.step > 0) {\n                const keyStart = command.keyStart - 1;\n                const keyStop = command.keyStop > 0\n                    ? command.keyStop\n                    : args.length + command.keyStop + 1;\n                for (let i = keyStart; i < keyStop; i += command.step) {\n                    keys.push(i);\n                }\n            }\n            break;\n    }\n    return keys;\n}\nexports.getKeyIndexes = getKeyIndexes;\nfunction getExternalKeyNameLength(key) {\n    if (typeof key !== \"string\") {\n        key = String(key);\n    }\n    const hashPos = key.indexOf(\"->\");\n    return hashPos === -1 ? key.length : hashPos;\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.tryCatch = exports.errorObj = void 0;\n//Try catch is not supported in optimizing\n//compiler, so it is isolated\nexports.errorObj = { e: {} };\nlet tryCatchTarget;\nfunction tryCatcher(err, val) {\n    try {\n        const target = tryCatchTarget;\n        tryCatchTarget = null;\n        return target.apply(this, arguments);\n    }\n    catch (e) {\n        exports.errorObj.e = e;\n        return exports.errorObj;\n    }\n}\nfunction tryCatch(fn) {\n    tryCatchTarget = fn;\n    return tryCatcher;\n}\nexports.tryCatch = tryCatch;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst utils_1 = require(\"./utils\");\nfunction throwLater(e) {\n    setTimeout(function () {\n        throw e;\n    }, 0);\n}\nfunction asCallback(promise, nodeback, options) {\n    if (typeof nodeback === \"function\") {\n        promise.then((val) => {\n            let ret;\n            if (options !== undefined &&\n                Object(options).spread &&\n                Array.isArray(val)) {\n                ret = utils_1.tryCatch(nodeback).apply(undefined, [null].concat(val));\n            }\n            else {\n                ret =\n                    val === undefined\n                        ? utils_1.tryCatch(nodeback)(null)\n                        : utils_1.tryCatch(nodeback)(null, val);\n            }\n            if (ret === utils_1.errorObj) {\n                throwLater(ret.e);\n            }\n        }, (cause) => {\n            if (!cause) {\n                const newReason = new Error(cause + \"\");\n                Object.assign(newReason, { cause });\n                cause = newReason;\n            }\n            const ret = utils_1.tryCatch(nodeback)(cause);\n            if (ret === utils_1.errorObj) {\n                throwLater(ret.e);\n            }\n        });\n    }\n    return promise;\n}\nexports.default = asCallback;\n","'use strict'\n\nconst assert = require('assert')\nconst util = require('util')\n\n// RedisError\n\nfunction RedisError (message) {\n  Object.defineProperty(this, 'message', {\n    value: message || '',\n    configurable: true,\n    writable: true\n  })\n  Error.captureStackTrace(this, this.constructor)\n}\n\nutil.inherits(RedisError, Error)\n\nObject.defineProperty(RedisError.prototype, 'name', {\n  value: 'RedisError',\n  configurable: true,\n  writable: true\n})\n\n// ParserError\n\nfunction ParserError (message, buffer, offset) {\n  assert(buffer)\n  assert.strictEqual(typeof offset, 'number')\n\n  Object.defineProperty(this, 'message', {\n    value: message || '',\n    configurable: true,\n    writable: true\n  })\n\n  const tmp = Error.stackTraceLimit\n  Error.stackTraceLimit = 2\n  Error.captureStackTrace(this, this.constructor)\n  Error.stackTraceLimit = tmp\n  this.offset = offset\n  this.buffer = buffer\n}\n\nutil.inherits(ParserError, RedisError)\n\nObject.defineProperty(ParserError.prototype, 'name', {\n  value: 'ParserError',\n  configurable: true,\n  writable: true\n})\n\n// ReplyError\n\nfunction ReplyError (message) {\n  Object.defineProperty(this, 'message', {\n    value: message || '',\n    configurable: true,\n    writable: true\n  })\n  const tmp = Error.stackTraceLimit\n  Error.stackTraceLimit = 2\n  Error.captureStackTrace(this, this.constructor)\n  Error.stackTraceLimit = tmp\n}\n\nutil.inherits(ReplyError, RedisError)\n\nObject.defineProperty(ReplyError.prototype, 'name', {\n  value: 'ReplyError',\n  configurable: true,\n  writable: true\n})\n\n// AbortError\n\nfunction AbortError (message) {\n  Object.defineProperty(this, 'message', {\n    value: message || '',\n    configurable: true,\n    writable: true\n  })\n  Error.captureStackTrace(this, this.constructor)\n}\n\nutil.inherits(AbortError, RedisError)\n\nObject.defineProperty(AbortError.prototype, 'name', {\n  value: 'AbortError',\n  configurable: true,\n  writable: true\n})\n\n// InterruptError\n\nfunction InterruptError (message) {\n  Object.defineProperty(this, 'message', {\n    value: message || '',\n    configurable: true,\n    writable: true\n  })\n  Error.captureStackTrace(this, this.constructor)\n}\n\nutil.inherits(InterruptError, AbortError)\n\nObject.defineProperty(InterruptError.prototype, 'name', {\n  value: 'InterruptError',\n  configurable: true,\n  writable: true\n})\n\nmodule.exports = {\n  RedisError,\n  ParserError,\n  ReplyError,\n  AbortError,\n  InterruptError\n}\n","'use strict'\n\nconst assert = require('assert')\n\nclass RedisError extends Error {\n  get name () {\n    return this.constructor.name\n  }\n}\n\nclass ParserError extends RedisError {\n  constructor (message, buffer, offset) {\n    assert(buffer)\n    assert.strictEqual(typeof offset, 'number')\n\n    const tmp = Error.stackTraceLimit\n    Error.stackTraceLimit = 2\n    super(message)\n    Error.stackTraceLimit = tmp\n    this.offset = offset\n    this.buffer = buffer\n  }\n\n  get name () {\n    return this.constructor.name\n  }\n}\n\nclass ReplyError extends RedisError {\n  constructor (message) {\n    const tmp = Error.stackTraceLimit\n    Error.stackTraceLimit = 2\n    super(message)\n    Error.stackTraceLimit = tmp\n  }\n  get name () {\n    return this.constructor.name\n  }\n}\n\nclass AbortError extends RedisError {\n  get name () {\n    return this.constructor.name\n  }\n}\n\nclass InterruptError extends AbortError {\n  get name () {\n    return this.constructor.name\n  }\n}\n\nmodule.exports = {\n  RedisError,\n  ParserError,\n  ReplyError,\n  AbortError,\n  InterruptError\n}\n","'use strict'\n\nconst Errors = process.version.charCodeAt(1) < 55 && process.version.charCodeAt(2) === 46\n  ? require('./lib/old') // Node.js < 7\n  : require('./lib/modern')\n\nmodule.exports = Errors\n","/*\n * Copyright 2001-2010 Georges Menie (www.menie.org)\n * Copyright 2010 Salvatore Sanfilippo (adapted to Redis coding style)\n * Copyright 2015 Zihua Li (http://zihua.li) (ported to JavaScript)\n * Copyright 2016 Mike Diarmid (http://github.com/salakar) (re-write for performance, ~700% perf inc)\n * All rights reserved.\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and/or other materials provided with the distribution.\n *     * Neither the name of the University of California, Berkeley nor the\n *       names of its contributors may be used to endorse or promote products\n *       derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n/* CRC16 implementation according to CCITT standards.\n *\n * Note by @antirez: this is actually the XMODEM CRC 16 algorithm, using the\n * following parameters:\n *\n * Name                       : \"XMODEM\", also known as \"ZMODEM\", \"CRC-16/ACORN\"\n * Width                      : 16 bit\n * Poly                       : 1021 (That is actually x^16 + x^12 + x^5 + 1)\n * Initialization             : 0000\n * Reflect Input byte         : False\n * Reflect Output CRC         : False\n * Xor constant to output CRC : 0000\n * Output for \"123456789\"     : 31C3\n */\n\nvar lookup = [\n  0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,\n  0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef,\n  0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6,\n  0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de,\n  0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485,\n  0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d,\n  0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4,\n  0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc,\n  0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823,\n  0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b,\n  0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12,\n  0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a,\n  0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41,\n  0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49,\n  0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70,\n  0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78,\n  0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f,\n  0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067,\n  0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e,\n  0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256,\n  0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d,\n  0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,\n  0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c,\n  0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634,\n  0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab,\n  0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3,\n  0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a,\n  0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92,\n  0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9,\n  0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1,\n  0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8,\n  0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0\n];\n\n/**\n * Convert a string to a UTF8 array - faster than via buffer\n * @param str\n * @returns {Array}\n */\nvar toUTF8Array = function toUTF8Array(str) {\n  var char;\n  var i = 0;\n  var p = 0;\n  var utf8 = [];\n  var len = str.length;\n\n  for (; i < len; i++) {\n    char = str.charCodeAt(i);\n    if (char < 128) {\n      utf8[p++] = char;\n    } else if (char < 2048) {\n      utf8[p++] = (char >> 6) | 192;\n      utf8[p++] = (char & 63) | 128;\n    } else if (\n        ((char & 0xFC00) === 0xD800) && (i + 1) < str.length &&\n        ((str.charCodeAt(i + 1) & 0xFC00) === 0xDC00)) {\n      char = 0x10000 + ((char & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF);\n      utf8[p++] = (char >> 18) | 240;\n      utf8[p++] = ((char >> 12) & 63) | 128;\n      utf8[p++] = ((char >> 6) & 63) | 128;\n      utf8[p++] = (char & 63) | 128;\n    } else {\n      utf8[p++] = (char >> 12) | 224;\n      utf8[p++] = ((char >> 6) & 63) | 128;\n      utf8[p++] = (char & 63) | 128;\n    }\n  }\n\n  return utf8;\n};\n\n/**\n * Convert a string into a redis slot hash.\n * @param str\n * @returns {number}\n */\nvar generate = module.exports = function generate(str) {\n  var char;\n  var i = 0;\n  var start = -1;\n  var result = 0;\n  var resultHash = 0;\n  var utf8 = typeof str === 'string' ? toUTF8Array(str) : str;\n  var len = utf8.length;\n\n  while (i < len) {\n    char = utf8[i++];\n    if (start === -1) {\n      if (char === 0x7B) {\n        start = i;\n      }\n    } else if (char !== 0x7D) {\n      resultHash = lookup[(char ^ (resultHash >> 8)) & 0xFF] ^ (resultHash << 8);\n    } else if (i - 1 !== start) {\n      return resultHash & 0x3FFF;\n    }\n\n    result = lookup[(char ^ (result >> 8)) & 0xFF] ^ (result << 8);\n  }\n\n  return result & 0x3FFF;\n};\n\n/**\n * Convert an array of multiple strings into a redis slot hash.\n * Returns -1 if one of the keys is not for the same slot as the others\n * @param keys\n * @returns {number}\n */\nmodule.exports.generateMulti = function generateMulti(keys) {\n  var i = 1;\n  var len = keys.length;\n  var base = generate(keys[0]);\n\n  while (i < len) {\n    if (generate(keys[i++]) !== base) return -1;\n  }\n\n  return base;\n};\n","\"use strict\";\n/*\n * Derived from `src/compat/object/defaults.ts` in es-toolkit\n * (https://github.com/toss/es-toolkit).\n *\n * Copyright (c) 2024 Viva Republica, Inc\n * Copyright OpenJS Foundation and other contributors\n *\n * Parts of the compatibility layer in `es-toolkit/compat` are derived from\n * Lodash (https://github.com/lodash/lodash) by the OpenJS Foundation\n * (https://openjsf.org/) and Underscore.js by Jeremy Ashkenas, DocumentCloud\n * and Investigative Reporters & Editors (http://underscorejs.org/).\n *\n * This file has been modified from the original source to create a standalone\n * adaptation.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.defaults = void 0;\nconst IS_UNSIGNED_INTEGER = /^(?:0|[1-9]\\d*)$/;\nfunction isNil(value) {\n    return value == null;\n}\nfunction eq(value, other) {\n    return value === other || (Number.isNaN(value) && Number.isNaN(other));\n}\nfunction isLength(value) {\n    return Number.isSafeInteger(value) && value >= 0;\n}\nfunction isArrayLike(value) {\n    return (value != null &&\n        typeof value !== \"function\" &&\n        isLength(value.length));\n}\nfunction isObject(value) {\n    return (value !== null && (typeof value === \"object\" || typeof value === \"function\"));\n}\nfunction isIndex(value, length = Number.MAX_SAFE_INTEGER) {\n    switch (typeof value) {\n        case \"number\":\n            return Number.isInteger(value) && value >= 0 && value < length;\n        case \"symbol\":\n            return false;\n        case \"string\":\n            return IS_UNSIGNED_INTEGER.test(value);\n    }\n}\nfunction isIterateeCall(value, index, object) {\n    if (!isObject(object)) {\n        return false;\n    }\n    if ((typeof index === \"number\" &&\n        isArrayLike(object) &&\n        isIndex(index) &&\n        index < object.length) ||\n        (typeof index === \"string\" && index in object)) {\n        return eq(object[index], value);\n    }\n    return false;\n}\nfunction defaults(object, ...sources) {\n    object = Object(object);\n    const objectProto = Object.prototype;\n    let length = sources.length;\n    const guard = length > 2 ? sources[2] : undefined;\n    if (guard && isIterateeCall(sources[0], sources[1], guard)) {\n        length = 1;\n    }\n    for (let i = 0; i < length; i++) {\n        if (isNil(sources[i])) {\n            continue;\n        }\n        const source = sources[i];\n        for (const key in source) {\n            const value = object[key];\n            if (value === undefined ||\n                (!objectProto.hasOwnProperty.call(object, key) &&\n                    eq(value, objectProto[key]))) {\n                object[key] = source[key];\n            }\n        }\n    }\n    return object;\n}\nexports.defaults = defaults;\n","\"use strict\";\n/*\n * Derived from `src/compat/predicate/isArguments.ts` in es-toolkit\n * (https://github.com/toss/es-toolkit).\n *\n * Copyright (c) 2024 Viva Republica, Inc\n * Copyright OpenJS Foundation and other contributors\n *\n * Parts of the compatibility layer in `es-toolkit/compat` are derived from\n * Lodash (https://github.com/lodash/lodash) by the OpenJS Foundation\n * (https://openjsf.org/) and Underscore.js by Jeremy Ashkenas, DocumentCloud\n * and Investigative Reporters & Editors (http://underscorejs.org/).\n *\n * This file has been modified from the original source to create a standalone\n * adaptation.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.isArguments = void 0;\nfunction getTag(value) {\n    if (value == null) {\n        return value === undefined ? \"[object Undefined]\" : \"[object Null]\";\n    }\n    return Object.prototype.toString.call(value);\n}\nfunction isArguments(value) {\n    return (value !== null &&\n        typeof value === \"object\" &&\n        getTag(value) === \"[object Arguments]\");\n}\nexports.isArguments = isArguments;\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n    if (k2 === undefined) k2 = k;\n    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n    if (k2 === undefined) k2 = k;\n    o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n    for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.noop = void 0;\nfunction noop() { }\nexports.noop = noop;\n__exportStar(require(\"./defaults\"), exports);\n__exportStar(require(\"./isArguments\"), exports);\n","/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n *  - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n  options = options || {};\n  var type = typeof val;\n  if (type === 'string' && val.length > 0) {\n    return parse(val);\n  } else if (type === 'number' && isFinite(val)) {\n    return options.long ? fmtLong(val) : fmtShort(val);\n  }\n  throw new Error(\n    'val is not a non-empty string or a valid number. val=' +\n      JSON.stringify(val)\n  );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n  str = String(str);\n  if (str.length > 100) {\n    return;\n  }\n  var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n    str\n  );\n  if (!match) {\n    return;\n  }\n  var n = parseFloat(match[1]);\n  var type = (match[2] || 'ms').toLowerCase();\n  switch (type) {\n    case 'years':\n    case 'year':\n    case 'yrs':\n    case 'yr':\n    case 'y':\n      return n * y;\n    case 'weeks':\n    case 'week':\n    case 'w':\n      return n * w;\n    case 'days':\n    case 'day':\n    case 'd':\n      return n * d;\n    case 'hours':\n    case 'hour':\n    case 'hrs':\n    case 'hr':\n    case 'h':\n      return n * h;\n    case 'minutes':\n    case 'minute':\n    case 'mins':\n    case 'min':\n    case 'm':\n      return n * m;\n    case 'seconds':\n    case 'second':\n    case 'secs':\n    case 'sec':\n    case 's':\n      return n * s;\n    case 'milliseconds':\n    case 'millisecond':\n    case 'msecs':\n    case 'msec':\n    case 'ms':\n      return n;\n    default:\n      return undefined;\n  }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n  var msAbs = Math.abs(ms);\n  if (msAbs >= d) {\n    return Math.round(ms / d) + 'd';\n  }\n  if (msAbs >= h) {\n    return Math.round(ms / h) + 'h';\n  }\n  if (msAbs >= m) {\n    return Math.round(ms / m) + 'm';\n  }\n  if (msAbs >= s) {\n    return Math.round(ms / s) + 's';\n  }\n  return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n  var msAbs = Math.abs(ms);\n  if (msAbs >= d) {\n    return plural(ms, msAbs, d, 'day');\n  }\n  if (msAbs >= h) {\n    return plural(ms, msAbs, h, 'hour');\n  }\n  if (msAbs >= m) {\n    return plural(ms, msAbs, m, 'minute');\n  }\n  if (msAbs >= s) {\n    return plural(ms, msAbs, s, 'second');\n  }\n  return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n  var isPlural = msAbs >= n * 1.5;\n  return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n","\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\t\tlet namespacesCache;\n\t\tlet enabledCache;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => {\n\t\t\t\tif (enableOverride !== null) {\n\t\t\t\t\treturn enableOverride;\n\t\t\t\t}\n\t\t\t\tif (namespacesCache !== createDebug.namespaces) {\n\t\t\t\t\tnamespacesCache = createDebug.namespaces;\n\t\t\t\t\tenabledCache = createDebug.enabled(namespace);\n\t\t\t\t}\n\n\t\t\t\treturn enabledCache;\n\t\t\t},\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\t\tcreateDebug.namespaces = namespaces;\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '')\n\t\t\t.trim()\n\t\t\t.replace(/\\s+/g, ',')\n\t\t\t.split(',')\n\t\t\t.filter(Boolean);\n\n\t\tfor (const ns of split) {\n\t\t\tif (ns[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(ns.slice(1));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(ns);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Checks if the given string matches a namespace template, honoring\n\t * asterisks as wildcards.\n\t *\n\t * @param {String} search\n\t * @param {String} template\n\t * @return {Boolean}\n\t */\n\tfunction matchesTemplate(search, template) {\n\t\tlet searchIndex = 0;\n\t\tlet templateIndex = 0;\n\t\tlet starIndex = -1;\n\t\tlet matchIndex = 0;\n\n\t\twhile (searchIndex < search.length) {\n\t\t\tif (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) {\n\t\t\t\t// Match character or proceed with wildcard\n\t\t\t\tif (template[templateIndex] === '*') {\n\t\t\t\t\tstarIndex = templateIndex;\n\t\t\t\t\tmatchIndex = searchIndex;\n\t\t\t\t\ttemplateIndex++; // Skip the '*'\n\t\t\t\t} else {\n\t\t\t\t\tsearchIndex++;\n\t\t\t\t\ttemplateIndex++;\n\t\t\t\t}\n\t\t\t} else if (starIndex !== -1) { // eslint-disable-line no-negated-condition\n\t\t\t\t// Backtrack to the last '*' and try to match more characters\n\t\t\t\ttemplateIndex = starIndex + 1;\n\t\t\t\tmatchIndex++;\n\t\t\t\tsearchIndex = matchIndex;\n\t\t\t} else {\n\t\t\t\treturn false; // No match\n\t\t\t}\n\t\t}\n\n\t\t// Handle trailing '*' in template\n\t\twhile (templateIndex < template.length && template[templateIndex] === '*') {\n\t\t\ttemplateIndex++;\n\t\t}\n\n\t\treturn templateIndex === template.length;\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names,\n\t\t\t...createDebug.skips.map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tfor (const skip of createDebug.skips) {\n\t\t\tif (matchesTemplate(name, skip)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (const ns of createDebug.names) {\n\t\t\tif (matchesTemplate(name, ns)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n","/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\tlet m;\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\t// eslint-disable-next-line no-return-assign\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/)) && parseInt(m[1], 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug') || exports.storage.getItem('DEBUG') ;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n","/**\n * Module dependencies.\n */\n\nconst tty = require('tty');\nconst util = require('util');\n\n/**\n * This is the Node.js implementation of `debug()`.\n */\n\nexports.init = init;\nexports.log = log;\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.destroy = util.deprecate(\n\t() => {},\n\t'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'\n);\n\n/**\n * Colors.\n */\n\nexports.colors = [6, 2, 3, 4, 5, 1];\n\ntry {\n\t// Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)\n\t// eslint-disable-next-line import/no-extraneous-dependencies\n\tconst supportsColor = require('supports-color');\n\n\tif (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {\n\t\texports.colors = [\n\t\t\t20,\n\t\t\t21,\n\t\t\t26,\n\t\t\t27,\n\t\t\t32,\n\t\t\t33,\n\t\t\t38,\n\t\t\t39,\n\t\t\t40,\n\t\t\t41,\n\t\t\t42,\n\t\t\t43,\n\t\t\t44,\n\t\t\t45,\n\t\t\t56,\n\t\t\t57,\n\t\t\t62,\n\t\t\t63,\n\t\t\t68,\n\t\t\t69,\n\t\t\t74,\n\t\t\t75,\n\t\t\t76,\n\t\t\t77,\n\t\t\t78,\n\t\t\t79,\n\t\t\t80,\n\t\t\t81,\n\t\t\t92,\n\t\t\t93,\n\t\t\t98,\n\t\t\t99,\n\t\t\t112,\n\t\t\t113,\n\t\t\t128,\n\t\t\t129,\n\t\t\t134,\n\t\t\t135,\n\t\t\t148,\n\t\t\t149,\n\t\t\t160,\n\t\t\t161,\n\t\t\t162,\n\t\t\t163,\n\t\t\t164,\n\t\t\t165,\n\t\t\t166,\n\t\t\t167,\n\t\t\t168,\n\t\t\t169,\n\t\t\t170,\n\t\t\t171,\n\t\t\t172,\n\t\t\t173,\n\t\t\t178,\n\t\t\t179,\n\t\t\t184,\n\t\t\t185,\n\t\t\t196,\n\t\t\t197,\n\t\t\t198,\n\t\t\t199,\n\t\t\t200,\n\t\t\t201,\n\t\t\t202,\n\t\t\t203,\n\t\t\t204,\n\t\t\t205,\n\t\t\t206,\n\t\t\t207,\n\t\t\t208,\n\t\t\t209,\n\t\t\t214,\n\t\t\t215,\n\t\t\t220,\n\t\t\t221\n\t\t];\n\t}\n} catch (error) {\n\t// Swallow - we only care if `supports-color` is available; it doesn't have to be.\n}\n\n/**\n * Build up the default `inspectOpts` object from the environment variables.\n *\n *   $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js\n */\n\nexports.inspectOpts = Object.keys(process.env).filter(key => {\n\treturn /^debug_/i.test(key);\n}).reduce((obj, key) => {\n\t// Camel-case\n\tconst prop = key\n\t\t.substring(6)\n\t\t.toLowerCase()\n\t\t.replace(/_([a-z])/g, (_, k) => {\n\t\t\treturn k.toUpperCase();\n\t\t});\n\n\t// Coerce string value into JS value\n\tlet val = process.env[key];\n\tif (/^(yes|on|true|enabled)$/i.test(val)) {\n\t\tval = true;\n\t} else if (/^(no|off|false|disabled)$/i.test(val)) {\n\t\tval = false;\n\t} else if (val === 'null') {\n\t\tval = null;\n\t} else {\n\t\tval = Number(val);\n\t}\n\n\tobj[prop] = val;\n\treturn obj;\n}, {});\n\n/**\n * Is stdout a TTY? Colored output is enabled when `true`.\n */\n\nfunction useColors() {\n\treturn 'colors' in exports.inspectOpts ?\n\t\tBoolean(exports.inspectOpts.colors) :\n\t\ttty.isatty(process.stderr.fd);\n}\n\n/**\n * Adds ANSI color escape codes if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\tconst {namespace: name, useColors} = this;\n\n\tif (useColors) {\n\t\tconst c = this.color;\n\t\tconst colorCode = '\\u001B[3' + (c < 8 ? c : '8;5;' + c);\n\t\tconst prefix = `  ${colorCode};1m${name} \\u001B[0m`;\n\n\t\targs[0] = prefix + args[0].split('\\n').join('\\n' + prefix);\n\t\targs.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\\u001B[0m');\n\t} else {\n\t\targs[0] = getDate() + name + ' ' + args[0];\n\t}\n}\n\nfunction getDate() {\n\tif (exports.inspectOpts.hideDate) {\n\t\treturn '';\n\t}\n\treturn new Date().toISOString() + ' ';\n}\n\n/**\n * Invokes `util.formatWithOptions()` with the specified arguments and writes to stderr.\n */\n\nfunction log(...args) {\n\treturn process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + '\\n');\n}\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\tif (namespaces) {\n\t\tprocess.env.DEBUG = namespaces;\n\t} else {\n\t\t// If you set a process.env field to null or undefined, it gets cast to the\n\t\t// string 'null' or 'undefined'. Just delete instead.\n\t\tdelete process.env.DEBUG;\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\n\nfunction load() {\n\treturn process.env.DEBUG;\n}\n\n/**\n * Init logic for `debug` instances.\n *\n * Create a new `inspectOpts` object in case `useColors` is set\n * differently for a particular `debug` instance.\n */\n\nfunction init(debug) {\n\tdebug.inspectOpts = {};\n\n\tconst keys = Object.keys(exports.inspectOpts);\n\tfor (let i = 0; i < keys.length; i++) {\n\t\tdebug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %o to `util.inspect()`, all on a single line.\n */\n\nformatters.o = function (v) {\n\tthis.inspectOpts.colors = this.useColors;\n\treturn util.inspect(v, this.inspectOpts)\n\t\t.split('\\n')\n\t\t.map(str => str.trim())\n\t\t.join(' ');\n};\n\n/**\n * Map %O to `util.inspect()`, allowing multiple lines if needed.\n */\n\nformatters.O = function (v) {\n\tthis.inspectOpts.colors = this.useColors;\n\treturn util.inspect(v, this.inspectOpts);\n};\n","/**\n * Detect Electron renderer / nwjs process, which is node, but we should\n * treat as a browser.\n */\n\nif (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {\n\tmodule.exports = require('./browser.js');\n} else {\n\tmodule.exports = require('./node.js');\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.genRedactedString = exports.getStringValue = exports.MAX_ARGUMENT_LENGTH = void 0;\nconst debug_1 = require(\"debug\");\nconst MAX_ARGUMENT_LENGTH = 200;\nexports.MAX_ARGUMENT_LENGTH = MAX_ARGUMENT_LENGTH;\nconst NAMESPACE_PREFIX = \"ioredis\";\n/**\n * helper function that tried to get a string value for\n * arbitrary \"debug\" arg\n */\nfunction getStringValue(v) {\n    if (v === null) {\n        return;\n    }\n    switch (typeof v) {\n        case \"boolean\":\n            return;\n        case \"number\":\n            return;\n        case \"object\":\n            if (Buffer.isBuffer(v)) {\n                return v.toString(\"hex\");\n            }\n            if (Array.isArray(v)) {\n                return v.join(\",\");\n            }\n            try {\n                return JSON.stringify(v);\n            }\n            catch (e) {\n                return;\n            }\n        case \"string\":\n            return v;\n    }\n}\nexports.getStringValue = getStringValue;\n/**\n * helper function that redacts a string representation of a \"debug\" arg\n */\nfunction genRedactedString(str, maxLen) {\n    const { length } = str;\n    return length <= maxLen\n        ? str\n        : str.slice(0, maxLen) + ' ... <REDACTED full-length=\"' + length + '\">';\n}\nexports.genRedactedString = genRedactedString;\n/**\n * a wrapper for the `debug` module, used to generate\n * \"debug functions\" that trim the values in their output\n */\nfunction genDebugFunction(namespace) {\n    const fn = (0, debug_1.default)(`${NAMESPACE_PREFIX}:${namespace}`);\n    function wrappedDebug(...args) {\n        if (!fn.enabled) {\n            return; // no-op\n        }\n        // we skip the first arg because that is the message\n        for (let i = 1; i < args.length; i++) {\n            const str = getStringValue(args[i]);\n            if (typeof str === \"string\" && str.length > MAX_ARGUMENT_LENGTH) {\n                args[i] = genRedactedString(str, MAX_ARGUMENT_LENGTH);\n            }\n        }\n        return fn.apply(null, args);\n    }\n    Object.defineProperties(wrappedDebug, {\n        namespace: {\n            get() {\n                return fn.namespace;\n            },\n        },\n        enabled: {\n            get() {\n                return fn.enabled;\n            },\n        },\n        destroy: {\n            get() {\n                return fn.destroy;\n            },\n        },\n        log: {\n            get() {\n                return fn.log;\n            },\n            set(l) {\n                fn.log = l;\n            },\n        },\n    });\n    return wrappedDebug;\n}\nexports.default = genDebugFunction;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * TLS settings for Redis Cloud. Updated on 2022-08-19.\n */\nconst RedisCloudCA = `-----BEGIN CERTIFICATE-----\nMIIDTzCCAjegAwIBAgIJAKS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CCAQoCggEBAMwldpB5BngiFvXAg7aEyiie/QV2EcWtiHL8\nRgJDx7KKnQRfJMsuS+FggkbhUqsMgUdwbN1k0ev1LKMPgj0MK66X17YUhhB5uzsT\ngHeMCOFJ0mpiLx9e+pZo34knlTifBtc+ycsmWQ1z3rDI6SYOgxXG71uL0gRgykmm\nKPZpO/bLyCiR5Z2KYVc3rHQU3HTgOu5yLy6c+9C7v/U9AOEGM+iCK65TpjoWc4zd\nQQ4gOsC0p6Hpsk+QLjJg6VfLuQSSaGjlOCZgdbKfd/+RFO+uIEn8rUAVSNECMWEZ\nXriX7613t2Saer9fwRPvm2L7DWzgVGkWqQPabumDk3F2xmmFghcCAwEAAaNCMEAw\nDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFI/wS3+o\nLkUkrk1Q+mOai97i3Ru8MA0GCSqGSIb3DQEBCwUAA4IBAQBLQNvAUKr+yAzv95ZU\nRUm7lgAJQayzE4aGKAczymvmdLm6AC2upArT9fHxD4q/c2dKg8dEe3jgr25sbwMp\njjM5RcOO5LlXbKr8EpbsU8Yt5CRsuZRj+9xTaGdWPoO4zzUhw8lo/s7awlOqzJCK\n6fBdRoyV3XpYKBovHd7NADdBj+1EbddTKJd+82cEHhXXipa0095MJ6RMG3NzdvQX\nmcIfeg7jLQitChws/zyrVQ4PkX4268NXSb7hLi18YIvDQVETI53O9zJrlAGomecs\nMx86OyXShkDOOyyGeMlhLxS67ttVb9+E7gUJTb0o2HLO02JQZR7rkpeDMdmztcpH\nWD9f\n-----END CERTIFICATE-----`;\nconst TLSProfiles = {\n    RedisCloudFixed: { ca: RedisCloudCA },\n    RedisCloudFlexible: { ca: RedisCloudCA },\n};\nexports.default = TLSProfiles;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.noop = exports.isArguments = exports.defaults = exports.Debug = exports.getPackageMeta = exports.zipMap = exports.CONNECTION_CLOSED_ERROR_MSG = exports.shuffle = exports.sample = exports.resolveTLSProfile = exports.parseURL = exports.optimizeErrorStack = exports.toArg = exports.convertMapToArray = exports.convertObjectToArray = exports.timeout = exports.packObject = exports.isInt = exports.wrapMultiResult = exports.convertBufferToString = void 0;\nconst fs_1 = require(\"fs\");\nconst path_1 = require(\"path\");\nconst lodash_1 = require(\"./lodash\");\nObject.defineProperty(exports, \"defaults\", { enumerable: true, get: function () { return lodash_1.defaults; } });\nObject.defineProperty(exports, \"isArguments\", { enumerable: true, get: function () { return lodash_1.isArguments; } });\nObject.defineProperty(exports, \"noop\", { enumerable: true, get: function () { return lodash_1.noop; } });\nconst debug_1 = require(\"./debug\");\nexports.Debug = debug_1.default;\nconst TLSProfiles_1 = require(\"../constants/TLSProfiles\");\n/**\n * Convert a buffer to string, supports buffer array\n *\n * @example\n * ```js\n * const input = [Buffer.from('foo'), [Buffer.from('bar')]]\n * const res = convertBufferToString(input, 'utf8')\n * expect(res).to.eql(['foo', ['bar']])\n * ```\n */\nfunction convertBufferToString(value, encoding) {\n    if (value instanceof Buffer) {\n        return value.toString(encoding);\n    }\n    if (Array.isArray(value)) {\n        const length = value.length;\n        const res = Array(length);\n        for (let i = 0; i < length; ++i) {\n            res[i] =\n                value[i] instanceof Buffer && encoding === \"utf8\"\n                    ? value[i].toString()\n                    : convertBufferToString(value[i], encoding);\n        }\n        return res;\n    }\n    return value;\n}\nexports.convertBufferToString = convertBufferToString;\n/**\n * Convert a list of results to node-style\n *\n * @example\n * ```js\n * const input = ['a', 'b', new Error('c'), 'd']\n * const output = exports.wrapMultiResult(input)\n * expect(output).to.eql([[null, 'a'], [null, 'b'], [new Error('c')], [null, 'd'])\n * ```\n */\nfunction wrapMultiResult(arr) {\n    // When using WATCH/EXEC transactions, the EXEC will return\n    // a null instead of an array\n    if (!arr) {\n        return null;\n    }\n    const result = [];\n    const length = arr.length;\n    for (let i = 0; i < length; ++i) {\n        const item = arr[i];\n        if (item instanceof Error) {\n            result.push([item]);\n        }\n        else {\n            result.push([null, item]);\n        }\n    }\n    return result;\n}\nexports.wrapMultiResult = wrapMultiResult;\n/**\n * Detect if the argument is a int\n * @example\n * ```js\n * > isInt('123')\n * true\n * > isInt('123.3')\n * false\n * > isInt('1x')\n * false\n * > isInt(123)\n * true\n * > isInt(true)\n * false\n * ```\n */\nfunction isInt(value) {\n    const x = parseFloat(value);\n    return !isNaN(value) && (x | 0) === x;\n}\nexports.isInt = isInt;\n/**\n * Pack an array to an Object\n *\n * @example\n * ```js\n * > packObject(['a', 'b', 'c', 'd'])\n * { a: 'b', c: 'd' }\n * ```\n */\nfunction packObject(array) {\n    const result = {};\n    const length = array.length;\n    for (let i = 1; i < length; i += 2) {\n        result[array[i - 1]] = array[i];\n    }\n    return result;\n}\nexports.packObject = packObject;\n/**\n * Return a callback with timeout\n */\nfunction timeout(callback, timeout) {\n    let timer = null;\n    const run = function () {\n        if (timer) {\n            clearTimeout(timer);\n            timer = null;\n            callback.apply(this, arguments);\n        }\n    };\n    timer = setTimeout(run, timeout, new Error(\"timeout\"));\n    return run;\n}\nexports.timeout = timeout;\n/**\n * Convert an object to an array\n * @example\n * ```js\n * > convertObjectToArray({ a: '1' })\n * ['a', '1']\n * ```\n */\nfunction convertObjectToArray(obj) {\n    const result = [];\n    const keys = Object.keys(obj); // Object.entries requires node 7+\n    for (let i = 0, l = keys.length; i < l; i++) {\n        result.push(keys[i], obj[keys[i]]);\n    }\n    return result;\n}\nexports.convertObjectToArray = convertObjectToArray;\n/**\n * Convert a map to an array\n * @example\n * ```js\n * > convertMapToArray(new Map([[1, '2']]))\n * [1, '2']\n * ```\n */\nfunction convertMapToArray(map) {\n    const result = [];\n    let pos = 0;\n    map.forEach(function (value, key) {\n        result[pos] = key;\n        result[pos + 1] = value;\n        pos += 2;\n    });\n    return result;\n}\nexports.convertMapToArray = convertMapToArray;\n/**\n * Convert a non-string arg to a string\n */\nfunction toArg(arg) {\n    if (arg === null || typeof arg === \"undefined\") {\n        return \"\";\n    }\n    return String(arg);\n}\nexports.toArg = toArg;\n/**\n * Optimize error stack\n *\n * @param error actually error\n * @param friendlyStack the stack that more meaningful\n * @param filterPath only show stacks with the specified path\n */\nfunction optimizeErrorStack(error, friendlyStack, filterPath) {\n    const stacks = friendlyStack.split(\"\\n\");\n    let lines = \"\";\n    let i;\n    for (i = 1; i < stacks.length; ++i) {\n        if (stacks[i].indexOf(filterPath) === -1) {\n            break;\n        }\n    }\n    for (let j = i; j < stacks.length; ++j) {\n        lines += \"\\n\" + stacks[j];\n    }\n    if (error.stack) {\n        const pos = error.stack.indexOf(\"\\n\");\n        error.stack = error.stack.slice(0, pos) + lines;\n    }\n    return error;\n}\nexports.optimizeErrorStack = optimizeErrorStack;\n/**\n * Parse the redis protocol url\n */\nfunction parseURL(url) {\n    if (isInt(url)) {\n        return { port: url };\n    }\n    // Re-assert string type: isInt's type guard (value is string) incorrectly\n    // narrows url to 'never' in the false branch since url is already string.\n    const rawUrl = url;\n    // Determine if the URL has a known protocol (redis:// or rediss://)\n    const hasProtocol = /^rediss?:\\/\\//i.test(rawUrl);\n    const isProtocolRelative = rawUrl.startsWith(\"//\");\n    // TODO(next major): Consider rejecting protocol-relative Redis URLs early and\n    // requiring explicit redis:// or rediss:// schemes instead. Keep them working\n    // in 5.x for backward compatibility.\n    // Unix socket paths (starting with \"/\") are not valid URLs — handle separately.\n    // Preserve query params (e.g., /tmp/redis.sock?db=2)\n    if (rawUrl[0] === \"/\" && !isProtocolRelative) {\n        const qIdx = rawUrl.indexOf(\"?\");\n        const result = {\n            path: qIdx === -1 ? rawUrl : rawUrl.slice(0, qIdx),\n        };\n        if (qIdx !== -1) {\n            const options = {};\n            const params = new URLSearchParams(rawUrl.slice(qIdx + 1));\n            params.forEach((value, key) => {\n                options[key] = parseURLQueryItem(key, value);\n            });\n            (0, lodash_1.defaults)(result, options);\n        }\n        return result;\n    }\n    let parsed;\n    if (hasProtocol) {\n        parsed = new URL(rawUrl);\n    }\n    else if (isProtocolRelative) {\n        parsed = new URL(\"redis:\" + rawUrl);\n    }\n    else {\n        // Prepend a dummy protocol so new URL() can parse \"host:port?query\" correctly\n        parsed = new URL(\"redis://\" + rawUrl);\n    }\n    // Convert searchParams to a plain object (equivalent to url.parse(url, true).query)\n    const options = {};\n    parsed.searchParams.forEach((value, key) => {\n        options[key] = parseURLQueryItem(key, value);\n    });\n    const result = {};\n    // Extract auth — WHATWG URL percent-encodes special chars, so decode them.\n    // Check both username AND password: redis://:password@host has empty username but valid password.\n    if (parsed.username || parsed.password) {\n        result.username = decodeURIComponent(parsed.username);\n        result.password = decodeURIComponent(parsed.password);\n    }\n    if (parsed.pathname && parsed.pathname !== \"/\") {\n        if (hasProtocol || isProtocolRelative) {\n            // For redis://, rediss://, and protocol-relative URLs, the path after /\n            // is the db number\n            if (parsed.pathname.length > 1) {\n                result.db = parsed.pathname.slice(1);\n            }\n        }\n        else {\n            result.path = parsed.pathname;\n        }\n    }\n    if (parsed.hostname) {\n        // WHATWG URL keeps brackets around IPv6 addresses (e.g., \"[::1]\").\n        // Strip them to match the old url.parse() behavior.\n        result.host = parsed.hostname.replace(/^\\[|\\]$/g, \"\");\n    }\n    if (parsed.port) {\n        result.port = parsed.port;\n    }\n    (0, lodash_1.defaults)(result, options);\n    return result;\n}\nexports.parseURL = parseURL;\nfunction parseURLQueryItem(key, value) {\n    if (key === \"family\") {\n        const intFamily = Number.parseInt(value, 10);\n        if (!Number.isNaN(intFamily)) {\n            return intFamily;\n        }\n    }\n    return value;\n}\n/**\n * Resolve TLS profile shortcut in connection options\n */\nfunction resolveTLSProfile(options) {\n    let tls = options === null || options === void 0 ? void 0 : options.tls;\n    if (typeof tls === \"string\")\n        tls = { profile: tls };\n    const profile = TLSProfiles_1.default[tls === null || tls === void 0 ? void 0 : tls.profile];\n    if (profile) {\n        tls = Object.assign({}, profile, tls);\n        delete tls.profile;\n        options = Object.assign({}, options, { tls });\n    }\n    return options;\n}\nexports.resolveTLSProfile = resolveTLSProfile;\n/**\n * Get a random element from `array`\n */\nfunction sample(array, from = 0) {\n    const length = array.length;\n    if (from >= length) {\n        return null;\n    }\n    return array[from + Math.floor(Math.random() * (length - from))];\n}\nexports.sample = sample;\n/**\n * Shuffle the array using the Fisher-Yates Shuffle.\n * This method will mutate the original array.\n */\nfunction shuffle(array) {\n    let counter = array.length;\n    // While there are elements in the array\n    while (counter > 0) {\n        // Pick a random index\n        const index = Math.floor(Math.random() * counter);\n        // Decrease counter by 1\n        counter--;\n        // And swap the last element with it\n        [array[counter], array[index]] = [array[index], array[counter]];\n    }\n    return array;\n}\nexports.shuffle = shuffle;\n/**\n * Error message for connection being disconnected\n */\nexports.CONNECTION_CLOSED_ERROR_MSG = \"Connection is closed.\";\nfunction zipMap(keys, values) {\n    const map = new Map();\n    keys.forEach((key, index) => {\n        map.set(key, values[index]);\n    });\n    return map;\n}\nexports.zipMap = zipMap;\n/**\n * Memoized package metadata to avoid repeated file system reads.\n *\n * @internal\n */\nlet cachedPackageMeta = null;\n/**\n * Retrieves cached package metadata from package.json.\n *\n * @internal\n * @returns {Promise<{version: string} | null>} Package metadata or null if unavailable\n */\nasync function getPackageMeta() {\n    if (cachedPackageMeta) {\n        return cachedPackageMeta;\n    }\n    try {\n        const filePath = (0, path_1.resolve)(__dirname, \"..\", \"..\", \"package.json\");\n        const data = await fs_1.promises.readFile(filePath, \"utf8\");\n        const parsed = JSON.parse(data);\n        cachedPackageMeta = {\n            version: parsed.version,\n        };\n        return cachedPackageMeta;\n    }\n    catch (err) {\n        cachedPackageMeta = {\n            version: \"error-fetching-version\",\n        };\n        return cachedPackageMeta;\n    }\n}\nexports.getPackageMeta = getPackageMeta;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.parseBlockOption = exports.parseSecondsArgument = void 0;\n/**\n * Parses a command parameter to a number.\n * @param arg - The command parameter to parse (number, string, or Buffer)\n * @returns The parsed number, or undefined if parsing fails or arg is undefined\n */\nconst parseNumberArgument = (arg) => {\n    if (typeof arg === \"number\") {\n        return arg;\n    }\n    if (Buffer.isBuffer(arg)) {\n        return parseNumberArgument(arg.toString());\n    }\n    if (typeof arg === \"string\") {\n        const value = Number(arg);\n        return Number.isFinite(value) ? value : undefined;\n    }\n    return undefined;\n};\n/**\n * Parses a command parameter to a string.\n * @param arg - The command parameter to parse (string or Buffer)\n * @returns The parsed string, or undefined if arg is not a string/Buffer or is undefined\n */\nconst parseStringArgument = (arg) => {\n    if (typeof arg === \"string\") {\n        return arg;\n    }\n    if (Buffer.isBuffer(arg)) {\n        return arg.toString();\n    }\n    return undefined;\n};\n/**\n * Parses a command parameter as seconds and converts to milliseconds.\n * @param arg - The command parameter representing seconds\n * @returns The value in milliseconds, 0 if value is <= 0, or undefined if parsing fails\n */\nconst parseSecondsArgument = (arg) => {\n    const value = parseNumberArgument(arg);\n    if (value === undefined) {\n        return undefined;\n    }\n    if (value <= 0) {\n        return 0;\n    }\n    return value * 1000;\n};\nexports.parseSecondsArgument = parseSecondsArgument;\n/**\n * Parses the BLOCK option from Redis command arguments (e.g., XREAD, XREADGROUP).\n * @param args - Array of command parameters to search for the BLOCK option\n * @returns The block duration in milliseconds, 0 if duration is <= 0,\n *          null if BLOCK option is not found, or undefined if BLOCK is found but duration is invalid\n */\nconst parseBlockOption = (args) => {\n    for (let i = 0; i < args.length; i++) {\n        const token = parseStringArgument(args[i]);\n        if (token && token.toLowerCase() === \"block\") {\n            const duration = parseNumberArgument(args[i + 1]);\n            if (duration === undefined) {\n                return undefined;\n            }\n            if (duration <= 0) {\n                return 0;\n            }\n            return duration;\n        }\n    }\n    return null;\n};\nexports.parseBlockOption = parseBlockOption;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst commands_1 = require(\"@ioredis/commands\");\nconst calculateSlot = require(\"cluster-key-slot\");\nconst standard_as_callback_1 = require(\"standard-as-callback\");\nconst utils_1 = require(\"./utils\");\nconst argumentParsers_1 = require(\"./utils/argumentParsers\");\n/**\n * Command instance\n *\n * It's rare that you need to create a Command instance yourself.\n *\n * ```js\n * var infoCommand = new Command('info', null, function (err, result) {\n *   console.log('result', result);\n * });\n *\n * redis.sendCommand(infoCommand);\n *\n * // When no callback provided, Command instance will have a `promise` property,\n * // which will resolve/reject with the result of the command.\n * var getCommand = new Command('get', ['foo']);\n * getCommand.promise.then(function (result) {\n *   console.log('result', result);\n * });\n * ```\n */\nclass Command {\n    /**\n     * Creates an instance of Command.\n     * @param name Command name\n     * @param args An array of command arguments\n     * @param options\n     * @param callback The callback that handles the response.\n     * If omit, the response will be handled via Promise\n     */\n    constructor(name, args = [], options = {}, callback) {\n        this.name = name;\n        this.inTransaction = false;\n        this.isTraced = false;\n        this.isResolved = false;\n        this.transformed = false;\n        this.replyEncoding = options.replyEncoding;\n        this.errorStack = options.errorStack;\n        this.args = args.flat();\n        this.callback = callback;\n        this.initPromise();\n        if (options.keyPrefix) {\n            // @ts-expect-error\n            const isBufferKeyPrefix = options.keyPrefix instanceof Buffer;\n            // @ts-expect-error\n            let keyPrefixBuffer = isBufferKeyPrefix\n                ? options.keyPrefix\n                : null;\n            this._iterateKeys((key) => {\n                if (key instanceof Buffer) {\n                    if (keyPrefixBuffer === null) {\n                        keyPrefixBuffer = Buffer.from(options.keyPrefix);\n                    }\n                    return Buffer.concat([keyPrefixBuffer, key]);\n                }\n                else if (isBufferKeyPrefix) {\n                    // @ts-expect-error\n                    return Buffer.concat([options.keyPrefix, Buffer.from(String(key))]);\n                }\n                return options.keyPrefix + key;\n            });\n        }\n        if (options.readOnly) {\n            this.isReadOnly = true;\n        }\n    }\n    /**\n     * Check whether the command has the flag\n     */\n    static checkFlag(flagName, commandName) {\n        commandName = commandName.toLowerCase();\n        return !!this.getFlagMap()[flagName][commandName];\n    }\n    static setArgumentTransformer(name, func) {\n        this._transformer.argument[name] = func;\n    }\n    static setReplyTransformer(name, func) {\n        this._transformer.reply[name] = func;\n    }\n    static getFlagMap() {\n        if (!this.flagMap) {\n            this.flagMap = Object.keys(Command.FLAGS).reduce((map, flagName) => {\n                map[flagName] = {};\n                Command.FLAGS[flagName].forEach((commandName) => {\n                    map[flagName][commandName] = true;\n                });\n                return map;\n            }, {});\n        }\n        return this.flagMap;\n    }\n    getSlot() {\n        if (typeof this.slot === \"undefined\") {\n            const key = this.getKeys()[0];\n            this.slot = key == null ? null : calculateSlot(key);\n        }\n        return this.slot;\n    }\n    getKeys() {\n        return this._iterateKeys();\n    }\n    /**\n     * Convert command to writable buffer or string\n     */\n    toWritable(_socket) {\n        let result;\n        const commandStr = \"*\" +\n            (this.args.length + 1) +\n            \"\\r\\n$\" +\n            Buffer.byteLength(this.name) +\n            \"\\r\\n\" +\n            this.name +\n            \"\\r\\n\";\n        if (this.bufferMode) {\n            const buffers = new MixedBuffers();\n            buffers.push(commandStr);\n            for (let i = 0; i < this.args.length; ++i) {\n                const arg = this.args[i];\n                if (arg instanceof Buffer) {\n                    if (arg.length === 0) {\n                        buffers.push(\"$0\\r\\n\\r\\n\");\n                    }\n                    else {\n                        buffers.push(\"$\" + arg.length + \"\\r\\n\");\n                        buffers.push(arg);\n                        buffers.push(\"\\r\\n\");\n                    }\n                }\n                else {\n                    buffers.push(\"$\" +\n                        Buffer.byteLength(arg) +\n                        \"\\r\\n\" +\n                        arg +\n                        \"\\r\\n\");\n                }\n            }\n            result = buffers.toBuffer();\n        }\n        else {\n            result = commandStr;\n            for (let i = 0; i < this.args.length; ++i) {\n                const arg = this.args[i];\n                result +=\n                    \"$\" +\n                        Buffer.byteLength(arg) +\n                        \"\\r\\n\" +\n                        arg +\n                        \"\\r\\n\";\n            }\n        }\n        return result;\n    }\n    stringifyArguments() {\n        for (let i = 0; i < this.args.length; ++i) {\n            const arg = this.args[i];\n            if (typeof arg === \"string\") {\n                // buffers and strings don't need any transformation\n            }\n            else if (arg instanceof Buffer) {\n                this.bufferMode = true;\n            }\n            else {\n                this.args[i] = (0, utils_1.toArg)(arg);\n            }\n        }\n    }\n    /**\n     * Convert buffer/buffer[] to string/string[],\n     * and apply reply transformer.\n     */\n    transformReply(result) {\n        if (this.replyEncoding) {\n            result = (0, utils_1.convertBufferToString)(result, this.replyEncoding);\n        }\n        const transformer = Command._transformer.reply[this.name];\n        if (transformer) {\n            result = transformer(result);\n        }\n        return result;\n    }\n    /**\n     * Set the wait time before terminating the attempt to execute a command\n     * and generating an error.\n     */\n    setTimeout(ms) {\n        if (!this._commandTimeoutTimer) {\n            this._commandTimeoutTimer = setTimeout(() => {\n                if (!this.isResolved) {\n                    this.reject(new Error(\"Command timed out\"));\n                }\n            }, ms);\n        }\n    }\n    /**\n     * Set a timeout for blocking commands.\n     * When the timeout expires, the command resolves with null (matching Redis behavior).\n     * This handles the case of undetectable network failures (e.g., docker network disconnect)\n     * where the TCP connection becomes a zombie and no close event fires.\n     */\n    setBlockingTimeout(ms) {\n        if (ms <= 0) {\n            return;\n        }\n        // Clear existing timer if any (can happen when command moves from offline to command queue)\n        if (this._blockingTimeoutTimer) {\n            clearTimeout(this._blockingTimeoutTimer);\n            this._blockingTimeoutTimer = undefined;\n        }\n        const now = Date.now();\n        // First call: establish absolute deadline\n        if (this._blockingDeadline === undefined) {\n            this._blockingDeadline = now + ms;\n        }\n        // Check if we've already exceeded the deadline\n        const remaining = this._blockingDeadline - now;\n        if (remaining <= 0) {\n            // Resolve with null to indicate timeout (same as Redis behavior)\n            this.resolve(null);\n            return;\n        }\n        this._blockingTimeoutTimer = setTimeout(() => {\n            if (this.isResolved) {\n                this._blockingTimeoutTimer = undefined;\n                return;\n            }\n            this._blockingTimeoutTimer = undefined;\n            // Timeout expired - resolve with null (same as Redis behavior when blocking command times out)\n            this.resolve(null);\n        }, remaining);\n    }\n    /**\n     * Extract the blocking timeout from the command arguments.\n     *\n     * @returns The timeout in seconds, null for indefinite blocking (timeout of 0),\n     *          or undefined if this is not a blocking command\n     */\n    extractBlockingTimeout() {\n        const args = this.args;\n        if (!args || args.length === 0) {\n            return undefined;\n        }\n        const name = this.name.toLowerCase();\n        if (Command.checkFlag(\"LAST_ARG_TIMEOUT_COMMANDS\", name)) {\n            return (0, argumentParsers_1.parseSecondsArgument)(args[args.length - 1]);\n        }\n        if (Command.checkFlag(\"FIRST_ARG_TIMEOUT_COMMANDS\", name)) {\n            return (0, argumentParsers_1.parseSecondsArgument)(args[0]);\n        }\n        if (Command.checkFlag(\"BLOCK_OPTION_COMMANDS\", name)) {\n            return (0, argumentParsers_1.parseBlockOption)(args);\n        }\n        return undefined;\n    }\n    /**\n     * Clear the command and blocking timers\n     */\n    _clearTimers() {\n        const existingTimer = this._commandTimeoutTimer;\n        if (existingTimer) {\n            clearTimeout(existingTimer);\n            delete this._commandTimeoutTimer;\n        }\n        const blockingTimer = this._blockingTimeoutTimer;\n        if (blockingTimer) {\n            clearTimeout(blockingTimer);\n            delete this._blockingTimeoutTimer;\n        }\n    }\n    initPromise() {\n        const promise = new Promise((resolve, reject) => {\n            if (!this.transformed) {\n                this.transformed = true;\n                const transformer = Command._transformer.argument[this.name];\n                if (transformer) {\n                    this.args = transformer(this.args);\n                }\n                this.stringifyArguments();\n            }\n            this.resolve = this._convertValue(resolve);\n            this.reject = (err) => {\n                this._clearTimers();\n                if (this.errorStack) {\n                    reject((0, utils_1.optimizeErrorStack)(err, this.errorStack.stack, __dirname));\n                }\n                else {\n                    reject(err);\n                }\n            };\n        });\n        this.promise = (0, standard_as_callback_1.default)(promise, this.callback);\n    }\n    /**\n     * Iterate through the command arguments that are considered keys.\n     */\n    _iterateKeys(transform = (key) => key) {\n        if (typeof this.keys === \"undefined\") {\n            this.keys = [];\n            if ((0, commands_1.exists)(this.name, { caseInsensitive: true })) {\n                // @ts-expect-error\n                const keyIndexes = (0, commands_1.getKeyIndexes)(this.name, this.args, {\n                    nameCaseInsensitive: true,\n                });\n                for (const index of keyIndexes) {\n                    this.args[index] = transform(this.args[index]);\n                    this.keys.push(this.args[index]);\n                }\n            }\n        }\n        return this.keys;\n    }\n    /**\n     * Convert the value from buffer to the target encoding.\n     */\n    _convertValue(resolve) {\n        return (value) => {\n            try {\n                this._clearTimers();\n                resolve(this.transformReply(value));\n                this.isResolved = true;\n            }\n            catch (err) {\n                this.reject(err);\n            }\n            return this.promise;\n        };\n    }\n}\nexports.default = Command;\nCommand.FLAGS = {\n    VALID_IN_SUBSCRIBER_MODE: [\n        \"subscribe\",\n        \"psubscribe\",\n        \"unsubscribe\",\n        \"punsubscribe\",\n        \"ssubscribe\",\n        \"sunsubscribe\",\n        \"ping\",\n        \"quit\",\n    ],\n    VALID_IN_MONITOR_MODE: [\"monitor\", \"auth\"],\n    ENTER_SUBSCRIBER_MODE: [\"subscribe\", \"psubscribe\", \"ssubscribe\"],\n    EXIT_SUBSCRIBER_MODE: [\"unsubscribe\", \"punsubscribe\", \"sunsubscribe\"],\n    WILL_DISCONNECT: [\"quit\"],\n    HANDSHAKE_COMMANDS: [\"auth\", \"select\", \"client\", \"readonly\", \"info\"],\n    IGNORE_RECONNECT_ON_ERROR: [\"client\"],\n    BLOCKING_COMMANDS: [\n        \"blpop\",\n        \"brpop\",\n        \"brpoplpush\",\n        \"blmove\",\n        \"bzpopmin\",\n        \"bzpopmax\",\n        \"bzmpop\",\n        \"blmpop\",\n        \"xread\",\n        \"xreadgroup\",\n    ],\n    LAST_ARG_TIMEOUT_COMMANDS: [\n        \"blpop\",\n        \"brpop\",\n        \"brpoplpush\",\n        \"blmove\",\n        \"bzpopmin\",\n        \"bzpopmax\",\n    ],\n    FIRST_ARG_TIMEOUT_COMMANDS: [\"bzmpop\", \"blmpop\"],\n    BLOCK_OPTION_COMMANDS: [\"xread\", \"xreadgroup\"],\n};\nCommand._transformer = {\n    argument: {},\n    reply: {},\n};\nconst msetArgumentTransformer = function (args) {\n    if (args.length === 1) {\n        if (args[0] instanceof Map) {\n            return (0, utils_1.convertMapToArray)(args[0]);\n        }\n        if (typeof args[0] === \"object\" && args[0] !== null) {\n            return (0, utils_1.convertObjectToArray)(args[0]);\n        }\n    }\n    return args;\n};\nconst hsetArgumentTransformer = function (args) {\n    if (args.length === 2) {\n        if (args[1] instanceof Map) {\n            return [args[0]].concat((0, utils_1.convertMapToArray)(args[1]));\n        }\n        if (typeof args[1] === \"object\" && args[1] !== null) {\n            return [args[0]].concat((0, utils_1.convertObjectToArray)(args[1]));\n        }\n    }\n    return args;\n};\nCommand.setArgumentTransformer(\"mset\", msetArgumentTransformer);\nCommand.setArgumentTransformer(\"msetnx\", msetArgumentTransformer);\nCommand.setArgumentTransformer(\"hset\", hsetArgumentTransformer);\nCommand.setArgumentTransformer(\"hmset\", hsetArgumentTransformer);\nCommand.setReplyTransformer(\"hgetall\", function (result) {\n    if (Array.isArray(result)) {\n        const obj = {};\n        for (let i = 0; i < result.length; i += 2) {\n            const key = result[i];\n            const value = result[i + 1];\n            if (key in obj) {\n                // can only be truthy if the property is special somehow, like '__proto__' or 'constructor'\n                // https://github.com/luin/ioredis/issues/1267\n                Object.defineProperty(obj, key, {\n                    value,\n                    configurable: true,\n                    enumerable: true,\n                    writable: true,\n                });\n            }\n            else {\n                obj[key] = value;\n            }\n        }\n        return obj;\n    }\n    return result;\n});\nclass MixedBuffers {\n    constructor() {\n        this.length = 0;\n        this.items = [];\n    }\n    push(x) {\n        this.length += Buffer.byteLength(x);\n        this.items.push(x);\n    }\n    toBuffer() {\n        const result = Buffer.allocUnsafe(this.length);\n        let offset = 0;\n        for (const item of this.items) {\n            const length = Buffer.byteLength(item);\n            Buffer.isBuffer(item)\n                ? item.copy(result, offset)\n                : result.write(item, offset, length);\n            offset += length;\n        }\n        return result;\n    }\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst redis_errors_1 = require(\"redis-errors\");\nclass ClusterAllFailedError extends redis_errors_1.RedisError {\n    constructor(message, lastNodeError) {\n        super(message);\n        this.lastNodeError = lastNodeError;\n        Error.captureStackTrace(this, this.constructor);\n    }\n    get name() {\n        return this.constructor.name;\n    }\n}\nexports.default = ClusterAllFailedError;\nClusterAllFailedError.defaultMessage = \"Failed to refresh slots cache.\";\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst stream_1 = require(\"stream\");\n/**\n * Convenient class to convert the process of scanning keys to a readable stream.\n */\nclass ScanStream extends stream_1.Readable {\n    constructor(opt) {\n        super(opt);\n        this.opt = opt;\n        this._redisCursor = \"0\";\n        this._redisDrained = false;\n    }\n    _read() {\n        if (this._redisDrained) {\n            this.push(null);\n            return;\n        }\n        const args = [this._redisCursor];\n        if (this.opt.key) {\n            args.unshift(this.opt.key);\n        }\n        if (this.opt.match) {\n            args.push(\"MATCH\", this.opt.match);\n        }\n        if (this.opt.type) {\n            args.push(\"TYPE\", this.opt.type);\n        }\n        if (this.opt.count) {\n            args.push(\"COUNT\", String(this.opt.count));\n        }\n        if (this.opt.noValues) {\n            args.push(\"NOVALUES\");\n        }\n        this.opt.redis[this.opt.command](args, (err, res) => {\n            if (err) {\n                this.emit(\"error\", err);\n                return;\n            }\n            this._redisCursor = res[0] instanceof Buffer ? res[0].toString() : res[0];\n            if (this._redisCursor === \"0\") {\n                this._redisDrained = true;\n            }\n            this.push(res[1]);\n        });\n    }\n    close() {\n        this._redisDrained = true;\n    }\n}\nexports.default = ScanStream;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.executeWithAutoPipelining = exports.getFirstValueInFlattenedArray = exports.shouldUseAutoPipelining = exports.notAllowedAutoPipelineCommands = exports.kCallbacks = exports.kExec = void 0;\nconst lodash_1 = require(\"./utils/lodash\");\nconst calculateSlot = require(\"cluster-key-slot\");\nconst standard_as_callback_1 = require(\"standard-as-callback\");\nconst commands_1 = require(\"@ioredis/commands\");\nexports.kExec = Symbol(\"exec\");\nexports.kCallbacks = Symbol(\"callbacks\");\nexports.notAllowedAutoPipelineCommands = [\n    \"auth\",\n    \"info\",\n    \"script\",\n    \"quit\",\n    \"cluster\",\n    \"pipeline\",\n    \"multi\",\n    \"subscribe\",\n    \"psubscribe\",\n    \"unsubscribe\",\n    \"unpsubscribe\",\n    \"select\",\n    \"client\",\n];\nfunction executeAutoPipeline(client, slotKey) {\n    /*\n      If a pipeline is already executing, keep queueing up commands\n      since ioredis won't serve two pipelines at the same time\n    */\n    if (client._runningAutoPipelines.has(slotKey)) {\n        return;\n    }\n    if (!client._autoPipelines.has(slotKey)) {\n        /*\n          Rare edge case. Somehow, something has deleted this running autopipeline in an immediate\n          call to executeAutoPipeline.\n         \n          Maybe the callback in the pipeline.exec is sometimes called in the same tick,\n          e.g. if redis is disconnected?\n        */\n        return;\n    }\n    client._runningAutoPipelines.add(slotKey);\n    // Get the pipeline and immediately delete it so that new commands are queued on a new pipeline\n    const pipeline = client._autoPipelines.get(slotKey);\n    client._autoPipelines.delete(slotKey);\n    const callbacks = pipeline[exports.kCallbacks];\n    // Stop keeping a reference to callbacks immediately after the callbacks stop being used.\n    // This allows the GC to reclaim objects referenced by callbacks, especially with 16384 slots\n    // in Redis.Cluster\n    pipeline[exports.kCallbacks] = null;\n    // Perform the call\n    pipeline.exec(function (err, results) {\n        client._runningAutoPipelines.delete(slotKey);\n        /*\n          Invoke all callback in nextTick so the stack is cleared\n          and callbacks can throw errors without affecting other callbacks.\n        */\n        if (err) {\n            for (let i = 0; i < callbacks.length; i++) {\n                process.nextTick(callbacks[i], err);\n            }\n        }\n        else {\n            for (let i = 0; i < callbacks.length; i++) {\n                process.nextTick(callbacks[i], ...results[i]);\n            }\n        }\n        // If there is another pipeline on the same node, immediately execute it without waiting for nextTick\n        if (client._autoPipelines.has(slotKey)) {\n            executeAutoPipeline(client, slotKey);\n        }\n    });\n}\nfunction shouldUseAutoPipelining(client, functionName, commandName) {\n    return (functionName &&\n        client.options.enableAutoPipelining &&\n        !client.isPipeline &&\n        !exports.notAllowedAutoPipelineCommands.includes(commandName) &&\n        !client.options.autoPipeliningIgnoredCommands.includes(commandName));\n}\nexports.shouldUseAutoPipelining = shouldUseAutoPipelining;\nfunction getFirstValueInFlattenedArray(args) {\n    for (let i = 0; i < args.length; i++) {\n        const arg = args[i];\n        if (typeof arg === \"string\") {\n            return arg;\n        }\n        else if (Array.isArray(arg) || (0, lodash_1.isArguments)(arg)) {\n            if (arg.length === 0) {\n                continue;\n            }\n            return arg[0];\n        }\n        const flattened = [arg].flat();\n        if (flattened.length > 0) {\n            return flattened[0];\n        }\n    }\n    return undefined;\n}\nexports.getFirstValueInFlattenedArray = getFirstValueInFlattenedArray;\nfunction getFirstKeyForCommand(commandName, args) {\n    if ((0, commands_1.exists)(commandName, { caseInsensitive: true })) {\n        const flattenedArgs = args.flat();\n        const keyIndexes = (0, commands_1.getKeyIndexes)(commandName, flattenedArgs, {\n            nameCaseInsensitive: true,\n        });\n        if (keyIndexes.length) {\n            return flattenedArgs[keyIndexes[0]];\n        }\n    }\n    return getFirstValueInFlattenedArray(args);\n}\nfunction executeWithAutoPipelining(client, functionName, commandName, args, callback) {\n    // On cluster mode let's wait for slots to be available\n    if (client.isCluster && !client.slots.length) {\n        if (client.status === \"wait\")\n            client.connect().catch(lodash_1.noop);\n        return (0, standard_as_callback_1.default)(new Promise(function (resolve, reject) {\n            client.delayUntilReady((err) => {\n                if (err) {\n                    reject(err);\n                    return;\n                }\n                executeWithAutoPipelining(client, functionName, commandName, args, null).then(resolve, reject);\n            });\n        }), callback);\n    }\n    // If we have slot information, we can improve routing by grouping slots served by the same subset of nodes\n    const prefix = client.options.keyPrefix || \"\";\n    let slotKey = client.isCluster\n        ? client.slots[calculateSlot(`${prefix}${getFirstKeyForCommand(commandName, args)}`)].join(\",\")\n        : \"main\";\n    // When scaleReads is enabled, separate read and write commands into different pipelines\n    // so they can be routed to replicas and masters respectively\n    if (client.isCluster && client.options.scaleReads !== \"master\") {\n        const isReadOnly = (0, commands_1.exists)(commandName) && (0, commands_1.hasFlag)(commandName, \"readonly\");\n        slotKey += isReadOnly ? \":read\" : \":write\";\n    }\n    if (!client._autoPipelines.has(slotKey)) {\n        const pipeline = client.pipeline();\n        pipeline[exports.kExec] = false;\n        pipeline[exports.kCallbacks] = [];\n        client._autoPipelines.set(slotKey, pipeline);\n    }\n    const pipeline = client._autoPipelines.get(slotKey);\n    /*\n      Mark the pipeline as scheduled.\n      The symbol will make sure that the pipeline is only scheduled once per tick.\n      New commands are appended to an already scheduled pipeline.\n    */\n    if (!pipeline[exports.kExec]) {\n        pipeline[exports.kExec] = true;\n        /*\n          Deferring with setImmediate so we have a chance to capture multiple\n          commands that can be scheduled by I/O events already in the event loop queue.\n        */\n        setImmediate(executeAutoPipeline, client, slotKey);\n    }\n    // Create the promise which will execute the command in the pipeline.\n    const autoPipelinePromise = new Promise(function (resolve, reject) {\n        pipeline[exports.kCallbacks].push(function (err, value) {\n            if (err) {\n                reject(err);\n                return;\n            }\n            resolve(value);\n        });\n        if (functionName === \"call\") {\n            args.unshift(commandName);\n        }\n        pipeline[functionName](...args);\n    });\n    return (0, standard_as_callback_1.default)(autoPipelinePromise, callback);\n}\nexports.executeWithAutoPipelining = executeWithAutoPipelining;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst crypto_1 = require(\"crypto\");\nconst Command_1 = require(\"./Command\");\nconst standard_as_callback_1 = require(\"standard-as-callback\");\nclass Script {\n    constructor(lua, numberOfKeys = null, keyPrefix = \"\", readOnly = false) {\n        this.lua = lua;\n        this.numberOfKeys = numberOfKeys;\n        this.keyPrefix = keyPrefix;\n        this.readOnly = readOnly;\n        this.sha = (0, crypto_1.createHash)(\"sha1\").update(lua).digest(\"hex\");\n        const sha = this.sha;\n        const socketHasScriptLoaded = new WeakSet();\n        this.Command = class CustomScriptCommand extends Command_1.default {\n            toWritable(socket) {\n                const origReject = this.reject;\n                this.reject = (err) => {\n                    if (err.message.indexOf(\"NOSCRIPT\") !== -1) {\n                        socketHasScriptLoaded.delete(socket);\n                    }\n                    origReject.call(this, err);\n                };\n                if (!socketHasScriptLoaded.has(socket)) {\n                    socketHasScriptLoaded.add(socket);\n                    this.name = \"eval\";\n                    this.args[0] = lua;\n                }\n                else if (this.name === \"eval\") {\n                    this.name = \"evalsha\";\n                    this.args[0] = sha;\n                }\n                return super.toWritable(socket);\n            }\n        };\n    }\n    execute(container, args, options, callback) {\n        if (typeof this.numberOfKeys === \"number\") {\n            args.unshift(this.numberOfKeys);\n        }\n        if (this.keyPrefix) {\n            options.keyPrefix = this.keyPrefix;\n        }\n        if (this.readOnly) {\n            options.readOnly = true;\n        }\n        const evalsha = new this.Command(\"evalsha\", [this.sha, ...args], options);\n        evalsha.promise = evalsha.promise.catch((err) => {\n            if (err.message.indexOf(\"NOSCRIPT\") === -1) {\n                throw err;\n            }\n            // Resend the same custom evalsha command that gets transformed\n            // to an eval in case it's not loaded yet on the connection.\n            const resend = new this.Command(\"evalsha\", [this.sha, ...args], options);\n            const client = container.isPipeline ? container.redis : container;\n            return client.sendCommand(resend);\n        });\n        (0, standard_as_callback_1.default)(evalsha.promise, callback);\n        return container.sendCommand(evalsha);\n    }\n}\nexports.default = Script;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst commands_1 = require(\"@ioredis/commands\");\nconst autoPipelining_1 = require(\"../autoPipelining\");\nconst Command_1 = require(\"../Command\");\nconst Script_1 = require(\"../Script\");\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nclass Commander {\n    constructor() {\n        this.options = {};\n        /**\n         * @ignore\n         */\n        this.scriptsSet = {};\n        /**\n         * @ignore\n         */\n        this.addedBuiltinSet = new Set();\n    }\n    /**\n     * Return supported builtin commands\n     */\n    getBuiltinCommands() {\n        return commands.slice(0);\n    }\n    /**\n     * Create a builtin command\n     */\n    createBuiltinCommand(commandName) {\n        return {\n            string: generateFunction(null, commandName, \"utf8\"),\n            buffer: generateFunction(null, commandName, null),\n        };\n    }\n    /**\n     * Create add builtin command\n     */\n    addBuiltinCommand(commandName) {\n        this.addedBuiltinSet.add(commandName);\n        this[commandName] = generateFunction(commandName, commandName, \"utf8\");\n        this[commandName + \"Buffer\"] = generateFunction(commandName + \"Buffer\", commandName, null);\n    }\n    /**\n     * Define a custom command using lua script\n     */\n    defineCommand(name, definition) {\n        const script = new Script_1.default(definition.lua, definition.numberOfKeys, this.options.keyPrefix, definition.readOnly);\n        this.scriptsSet[name] = script;\n        this[name] = generateScriptingFunction(name, name, script, \"utf8\");\n        this[name + \"Buffer\"] = generateScriptingFunction(name + \"Buffer\", name, script, null);\n    }\n    /**\n     * @ignore\n     */\n    sendCommand(command, stream, node) {\n        throw new Error('\"sendCommand\" is not implemented');\n    }\n}\nconst commands = commands_1.list.filter((command) => command !== \"monitor\");\ncommands.push(\"sentinel\");\ncommands.forEach(function (commandName) {\n    Commander.prototype[commandName] = generateFunction(commandName, commandName, \"utf8\");\n    Commander.prototype[commandName + \"Buffer\"] = generateFunction(commandName + \"Buffer\", commandName, null);\n});\nCommander.prototype.call = generateFunction(\"call\", \"utf8\");\nCommander.prototype.callBuffer = generateFunction(\"callBuffer\", null);\n// @ts-expect-error\nCommander.prototype.send_command = Commander.prototype.call;\nfunction generateFunction(functionName, _commandName, _encoding) {\n    if (typeof _encoding === \"undefined\") {\n        _encoding = _commandName;\n        _commandName = null;\n    }\n    return function (...args) {\n        const commandName = (_commandName || args.shift());\n        let callback = args[args.length - 1];\n        if (typeof callback === \"function\") {\n            args.pop();\n        }\n        else {\n            callback = undefined;\n        }\n        const options = {\n            errorStack: this.options.showFriendlyErrorStack ? new Error() : undefined,\n            keyPrefix: this.options.keyPrefix,\n            replyEncoding: _encoding,\n        };\n        // No auto pipeline, use regular command sending\n        if (!(0, autoPipelining_1.shouldUseAutoPipelining)(this, functionName, commandName)) {\n            return this.sendCommand(\n            // @ts-expect-error\n            new Command_1.default(commandName, args, options, callback));\n        }\n        // Create a new pipeline and make sure it's scheduled\n        return (0, autoPipelining_1.executeWithAutoPipelining)(this, functionName, commandName, \n        // @ts-expect-error\n        args, callback);\n    };\n}\nfunction generateScriptingFunction(functionName, commandName, script, encoding) {\n    return function (...args) {\n        const callback = typeof args[args.length - 1] === \"function\" ? args.pop() : undefined;\n        const options = {\n            replyEncoding: encoding,\n        };\n        if (this.options.showFriendlyErrorStack) {\n            options.errorStack = new Error();\n        }\n        // No auto pipeline, use regular command sending\n        if (!(0, autoPipelining_1.shouldUseAutoPipelining)(this, functionName, commandName)) {\n            return script.execute(this, args, options, callback);\n        }\n        // Create a new pipeline and make sure it's scheduled\n        return (0, autoPipelining_1.executeWithAutoPipelining)(this, functionName, commandName, args, callback);\n    };\n}\nexports.default = Commander;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst calculateSlot = require(\"cluster-key-slot\");\nconst commands_1 = require(\"@ioredis/commands\");\nconst standard_as_callback_1 = require(\"standard-as-callback\");\nconst util_1 = require(\"util\");\nconst Command_1 = require(\"./Command\");\nconst buffer_1 = require(\"buffer\");\nconst utils_1 = require(\"./utils\");\nconst Commander_1 = require(\"./utils/Commander\");\n/*\n  This function derives from the cluster-key-slot implementation.\n  Instead of checking that all keys have the same slot, it checks that all slots are served by the same set of nodes.\n  If this is satisfied, it returns the first key's slot.\n*/\nfunction generateMultiWithNodes(redis, keys) {\n    const slot = calculateSlot(keys[0]);\n    const target = redis._groupsBySlot[slot];\n    for (let i = 1; i < keys.length; i++) {\n        if (redis._groupsBySlot[calculateSlot(keys[i])] !== target) {\n            return -1;\n        }\n    }\n    return slot;\n}\nclass Pipeline extends Commander_1.default {\n    constructor(redis) {\n        super();\n        this.redis = redis;\n        this.isPipeline = true;\n        this.replyPending = 0;\n        this._queue = [];\n        this._result = [];\n        this._transactions = 0;\n        this._shaToScript = {};\n        this.isCluster =\n            this.redis.constructor.name === \"Cluster\" || this.redis.isCluster;\n        this.options = redis.options;\n        Object.keys(redis.scriptsSet).forEach((name) => {\n            const script = redis.scriptsSet[name];\n            this._shaToScript[script.sha] = script;\n            this[name] = redis[name];\n            this[name + \"Buffer\"] = redis[name + \"Buffer\"];\n        });\n        redis.addedBuiltinSet.forEach((name) => {\n            this[name] = redis[name];\n            this[name + \"Buffer\"] = redis[name + \"Buffer\"];\n        });\n        this.promise = new Promise((resolve, reject) => {\n            this.resolve = resolve;\n            this.reject = reject;\n        });\n        const _this = this;\n        Object.defineProperty(this, \"length\", {\n            get: function () {\n                return _this._queue.length;\n            },\n        });\n    }\n    fillResult(value, position) {\n        if (this._queue[position].name === \"exec\" && Array.isArray(value[1])) {\n            const execLength = value[1].length;\n            for (let i = 0; i < execLength; i++) {\n                if (value[1][i] instanceof Error) {\n                    continue;\n                }\n                const cmd = this._queue[position - (execLength - i)];\n                try {\n                    value[1][i] = cmd.transformReply(value[1][i]);\n                }\n                catch (err) {\n                    value[1][i] = err;\n                }\n            }\n        }\n        this._result[position] = value;\n        if (--this.replyPending) {\n            return;\n        }\n        if (this.isCluster) {\n            let retriable = true;\n            let commonError;\n            for (let i = 0; i < this._result.length; ++i) {\n                const error = this._result[i][0];\n                const command = this._queue[i];\n                if (error) {\n                    if (command.name === \"exec\" &&\n                        error.message ===\n                            \"EXECABORT Transaction discarded because of previous errors.\") {\n                        continue;\n                    }\n                    if (!commonError) {\n                        commonError = {\n                            name: error.name,\n                            message: error.message,\n                        };\n                    }\n                    else if (commonError.name !== error.name ||\n                        commonError.message !== error.message) {\n                        retriable = false;\n                        break;\n                    }\n                }\n                else if (!command.inTransaction) {\n                    const isReadOnly = (0, commands_1.exists)(command.name, { caseInsensitive: true }) &&\n                        (0, commands_1.hasFlag)(command.name, \"readonly\", { nameCaseInsensitive: true });\n                    if (!isReadOnly) {\n                        retriable = false;\n                        break;\n                    }\n                }\n            }\n            if (commonError && retriable) {\n                const _this = this;\n                const errv = commonError.message.split(\" \");\n                const queue = this._queue;\n                let inTransaction = false;\n                this._queue = [];\n                for (let i = 0; i < queue.length; ++i) {\n                    if (errv[0] === \"ASK\" &&\n                        !inTransaction &&\n                        queue[i].name !== \"asking\" &&\n                        (!queue[i - 1] || queue[i - 1].name !== \"asking\")) {\n                        const asking = new Command_1.default(\"asking\");\n                        asking.ignore = true;\n                        this.sendCommand(asking);\n                    }\n                    queue[i].initPromise();\n                    this.sendCommand(queue[i]);\n                    inTransaction = queue[i].inTransaction;\n                }\n                let matched = true;\n                if (typeof this.leftRedirections === \"undefined\") {\n                    this.leftRedirections = {};\n                }\n                const exec = function () {\n                    _this.exec();\n                };\n                const cluster = this.redis;\n                cluster.handleError(commonError, this.leftRedirections, {\n                    moved: function (_slot, key) {\n                        _this.preferKey = key;\n                        if (cluster.slots[errv[1]]) {\n                            if (cluster.slots[errv[1]][0] !== key) {\n                                cluster.slots[errv[1]] = [key];\n                            }\n                        }\n                        else {\n                            cluster.slots[errv[1]] = [key];\n                        }\n                        cluster._groupsBySlot[errv[1]] =\n                            cluster._groupsIds[cluster.slots[errv[1]].join(\";\")];\n                        cluster.refreshSlotsCache();\n                        _this.exec();\n                    },\n                    ask: function (_slot, key) {\n                        _this.preferKey = key;\n                        _this.exec();\n                    },\n                    tryagain: exec,\n                    clusterDown: exec,\n                    connectionClosed: exec,\n                    maxRedirections: () => {\n                        matched = false;\n                    },\n                    defaults: () => {\n                        matched = false;\n                    },\n                });\n                if (matched) {\n                    return;\n                }\n            }\n        }\n        let ignoredCount = 0;\n        for (let i = 0; i < this._queue.length - ignoredCount; ++i) {\n            if (this._queue[i + ignoredCount].ignore) {\n                ignoredCount += 1;\n            }\n            this._result[i] = this._result[i + ignoredCount];\n        }\n        this.resolve(this._result.slice(0, this._result.length - ignoredCount));\n    }\n    sendCommand(command) {\n        if (this._transactions > 0) {\n            command.inTransaction = true;\n        }\n        const position = this._queue.length;\n        command.pipelineIndex = position;\n        command.promise\n            .then((result) => {\n            this.fillResult([null, result], position);\n        })\n            .catch((error) => {\n            this.fillResult([error], position);\n        });\n        this._queue.push(command);\n        return this;\n    }\n    addBatch(commands) {\n        let command, commandName, args;\n        for (let i = 0; i < commands.length; ++i) {\n            command = commands[i];\n            commandName = command[0];\n            args = command.slice(1);\n            this[commandName].apply(this, args);\n        }\n        return this;\n    }\n}\nexports.default = Pipeline;\n// @ts-expect-error\nconst multi = Pipeline.prototype.multi;\n// @ts-expect-error\nPipeline.prototype.multi = function () {\n    this._transactions += 1;\n    return multi.apply(this, arguments);\n};\n// @ts-expect-error\nconst execBuffer = Pipeline.prototype.execBuffer;\n// @ts-expect-error\nPipeline.prototype.execBuffer = (0, util_1.deprecate)(function () {\n    if (this._transactions > 0) {\n        this._transactions -= 1;\n    }\n    return execBuffer.apply(this, arguments);\n}, \"Pipeline#execBuffer: Use Pipeline#exec instead\");\n// NOTE: To avoid an unhandled promise rejection, this will unconditionally always return this.promise,\n// which always has the rejection handled by standard-as-callback\n// adding the provided rejection callback.\n//\n// If a different promise instance were returned, that promise would cause its own unhandled promise rejection\n// errors, even if that promise unconditionally resolved to **the resolved value of** this.promise.\nPipeline.prototype.exec = function (callback) {\n    // Wait for the cluster to be connected, since we need nodes information before continuing\n    if (this.isCluster && !this.redis.slots.length) {\n        if (this.redis.status === \"wait\")\n            this.redis.connect().catch(utils_1.noop);\n        if (callback && !this.nodeifiedPromise) {\n            this.nodeifiedPromise = true;\n            (0, standard_as_callback_1.default)(this.promise, callback);\n        }\n        this.redis.delayUntilReady((err) => {\n            if (err) {\n                this.reject(err);\n                return;\n            }\n            this.exec(callback);\n        });\n        return this.promise;\n    }\n    if (this._transactions > 0) {\n        this._transactions -= 1;\n        return execBuffer.apply(this, arguments);\n    }\n    if (!this.nodeifiedPromise) {\n        this.nodeifiedPromise = true;\n        (0, standard_as_callback_1.default)(this.promise, callback);\n    }\n    if (!this._queue.length) {\n        this.resolve([]);\n    }\n    let pipelineSlot;\n    if (this.isCluster) {\n        // List of the first key for each command\n        const sampleKeys = [];\n        for (let i = 0; i < this._queue.length; i++) {\n            const keys = this._queue[i].getKeys();\n            if (keys.length) {\n                sampleKeys.push(keys[0]);\n            }\n            // For each command, check that the keys belong to the same slot\n            if (keys.length && calculateSlot.generateMulti(keys) < 0) {\n                this.reject(new Error(\"All the keys in a pipeline command should belong to the same slot\"));\n                return this.promise;\n            }\n        }\n        if (sampleKeys.length) {\n            pipelineSlot = generateMultiWithNodes(this.redis, sampleKeys);\n            if (pipelineSlot < 0) {\n                this.reject(new Error(\"All keys in the pipeline should belong to the same slots allocation group\"));\n                return this.promise;\n            }\n        }\n        else {\n            // Send the pipeline to a random node\n            pipelineSlot = (Math.random() * 16384) | 0;\n        }\n    }\n    const _this = this;\n    execPipeline();\n    return this.promise;\n    function execPipeline() {\n        let writePending = (_this.replyPending = _this._queue.length);\n        let node;\n        if (_this.isCluster) {\n            node = {\n                slot: pipelineSlot,\n                redis: _this.redis.connectionPool.nodes.all[_this.preferKey],\n            };\n        }\n        let data = \"\";\n        let buffers;\n        const stream = {\n            isPipeline: true,\n            destination: _this.isCluster ? node : { redis: _this.redis },\n            write(writable) {\n                if (typeof writable !== \"string\") {\n                    if (!buffers) {\n                        buffers = [];\n                    }\n                    if (data) {\n                        buffers.push(Buffer.from(data, \"utf8\"));\n                        data = \"\";\n                    }\n                    buffers.push(writable);\n                }\n                else {\n                    if (data.length + writable.length >= buffer_1.constants.MAX_STRING_LENGTH) {\n                        if (!buffers) {\n                            buffers = [];\n                        }\n                        if (data) {\n                            buffers.push(Buffer.from(data, \"utf8\"));\n                            data = \"\";\n                        }\n                    }\n                    data += writable;\n                }\n                if (!--writePending) {\n                    if (buffers) {\n                        if (data) {\n                            buffers.push(Buffer.from(data, \"utf8\"));\n                        }\n                        stream.destination.redis.stream.write(Buffer.concat(buffers));\n                    }\n                    else {\n                        stream.destination.redis.stream.write(data);\n                    }\n                    // Reset writePending for resending\n                    writePending = _this._queue.length;\n                    data = \"\";\n                    buffers = undefined;\n                }\n            },\n        };\n        for (let i = 0; i < _this._queue.length; ++i) {\n            _this.redis.sendCommand(_this._queue[i], stream, node);\n        }\n        return _this.promise;\n    }\n};\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.traceConnect = exports.traceBatch = exports.traceCommand = exports.sanitizeArgs = void 0;\n// Argument sanitization rules adapted from @opentelemetry/redis-common (Apache 2.0).\n// https://github.com/open-telemetry/opentelemetry-js-contrib/blob/main/packages/redis-common/src/index.ts\n//\n// Each entry specifies how many positional args (after the command name) are safe\n// to emit. -1 means all args are safe (read-only/structural commands).\n// Unlisted commands default to 0 (all args redacted) for safe-by-default behavior,\n// which covers AUTH, HELLO, and unknown/custom commands.\nconst SERIALIZATION_SUBSETS = [\n    { regex: /^ECHO/i, args: 0 },\n    {\n        regex: /^(LPUSH|MSET|PFA|PUBLISH|RPUSH|SADD|SET|SPUBLISH|XADD|ZADD)/i,\n        args: 1,\n    },\n    { regex: /^(HSET|HMSET|LSET|LINSERT)/i, args: 2 },\n    {\n        regex: /^(ACL|BIT|B[LRZ]|CLIENT|CLUSTER|CONFIG|COMMAND|DECR|DEL|EVAL|EX|FUNCTION|GEO|GET|HINCR|HMGET|HSCAN|INCR|L[TRLM]|MEMORY|P[EFISTU]|RPOP|S[CDIMORSU]|XACK|X[CDGILPRT]|Z[CDILMPRS])/i,\n        args: -1,\n    },\n];\nfunction sanitizeArgs(commandName, args) {\n    let allowedArgCount = 0;\n    for (const subset of SERIALIZATION_SUBSETS) {\n        if (subset.regex.test(commandName)) {\n            allowedArgCount = subset.args;\n            break;\n        }\n    }\n    if (allowedArgCount === -1) {\n        return args.map((a) => String(a));\n    }\n    const result = [];\n    for (let i = 0; i < args.length; i++) {\n        if (i < allowedArgCount) {\n            result.push(String(args[i]));\n        }\n        else {\n            result.push(\"?\");\n        }\n    }\n    return result;\n}\nexports.sanitizeArgs = sanitizeArgs;\n// Load diagnostics_channel with Node 18 compatibility\nconst dc = (() => {\n    try {\n        return \"getBuiltinModule\" in process\n            ? process.getBuiltinModule(\"node:diagnostics_channel\")\n            : require(\"node:diagnostics_channel\");\n    }\n    catch {\n        return undefined;\n    }\n})();\nconst hasTracingChannel = dc && typeof dc.tracingChannel === \"function\";\nconst commandChannel = hasTracingChannel\n    ? dc.tracingChannel(\"ioredis:command\")\n    : undefined;\nconst batchChannel = hasTracingChannel\n    ? dc.tracingChannel(\"ioredis:batch\")\n    : undefined;\nconst connectChannel = hasTracingChannel\n    ? dc.tracingChannel(\"ioredis:connect\")\n    : undefined;\nfunction shouldTrace(channel) {\n    return !!channel && channel.hasSubscribers !== false;\n}\nconst noop = () => { };\nfunction traceCommand(fn, contextFactory) {\n    if (!shouldTrace(commandChannel))\n        return fn();\n    // tracePromise returns a wrapper promise that re-rejects on error.\n    // Silence the wrapper to prevent unhandled rejections when callers\n    // (e.g. Pipeline) discard the return value. Callers that await this\n    // promise still see the rejection through their own .then() chain.\n    const traced = commandChannel.tracePromise(fn, contextFactory());\n    traced.catch(noop);\n    return traced;\n}\nexports.traceCommand = traceCommand;\nfunction traceBatch(fn, contextFactory) {\n    if (!shouldTrace(batchChannel))\n        return fn();\n    const traced = batchChannel.tracePromise(fn, contextFactory());\n    traced.catch(noop);\n    return traced;\n}\nexports.traceBatch = traceBatch;\nfunction traceConnect(fn, contextFactory) {\n    if (!shouldTrace(connectChannel))\n        return fn();\n    return connectChannel.tracePromise(fn, contextFactory());\n}\nexports.traceConnect = traceConnect;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.addTransactionSupport = void 0;\nconst utils_1 = require(\"./utils\");\nconst standard_as_callback_1 = require(\"standard-as-callback\");\nconst Pipeline_1 = require(\"./Pipeline\");\nconst tracing_1 = require(\"./tracing\");\nfunction addTransactionSupport(redis) {\n    redis.pipeline = function (commands) {\n        const pipeline = new Pipeline_1.default(this);\n        if (Array.isArray(commands)) {\n            pipeline.addBatch(commands);\n        }\n        return pipeline;\n    };\n    const { multi } = redis;\n    redis.multi = function (commands, options) {\n        if (typeof options === \"undefined\" && !Array.isArray(commands)) {\n            options = commands;\n            commands = null;\n        }\n        if (options && options.pipeline === false) {\n            return multi.call(this);\n        }\n        const pipeline = new Pipeline_1.default(this);\n        // @ts-expect-error\n        pipeline.multi();\n        if (Array.isArray(commands)) {\n            pipeline.addBatch(commands);\n        }\n        const exec = pipeline.exec;\n        pipeline.exec = function (callback) {\n            // Wait for the cluster to be connected, since we need nodes information before continuing\n            if (this.isCluster && !this.redis.slots.length) {\n                if (this.redis.status === \"wait\")\n                    this.redis.connect().catch(utils_1.noop);\n                return (0, standard_as_callback_1.default)(new Promise((resolve, reject) => {\n                    this.redis.delayUntilReady((err) => {\n                        if (err) {\n                            reject(err);\n                            return;\n                        }\n                        this.exec(pipeline).then(resolve, reject);\n                    });\n                }), callback);\n            }\n            if (this._transactions > 0) {\n                exec.call(pipeline);\n            }\n            // Returns directly when the pipeline\n            // has been called multiple times (retries).\n            if (this.nodeifiedPromise) {\n                return exec.call(pipeline);\n            }\n            // Count only user commands (exclude MULTI/EXEC wrappers).\n            const batchSize = Math.max(pipeline.length - 2, 0);\n            const execAndUnwrap = () => exec.call(pipeline).then(function (result) {\n                const execResult = result[result.length - 1];\n                if (typeof execResult === \"undefined\") {\n                    throw new Error(\"Pipeline cannot be used to send any commands when the `exec()` has been called on it.\");\n                }\n                if (execResult[0]) {\n                    execResult[0].previousErrors = [];\n                    for (let i = 0; i < result.length - 1; ++i) {\n                        if (result[i][0]) {\n                            execResult[0].previousErrors.push(result[i][0]);\n                        }\n                    }\n                    throw execResult[0];\n                }\n                return (0, utils_1.wrapMultiResult)(execResult[1]);\n            });\n            // Trace MULTI as a single batch operation on ioredis:batch.\n            const promise = \"_buildBatchContext\" in this.redis\n                ? (0, tracing_1.traceBatch)(execAndUnwrap, () => this.redis._buildBatchContext(batchSize))\n                : execAndUnwrap();\n            return (0, standard_as_callback_1.default)(promise, callback);\n        };\n        // @ts-expect-error\n        const { execBuffer } = pipeline;\n        // @ts-expect-error\n        pipeline.execBuffer = function (callback) {\n            if (this._transactions > 0) {\n                execBuffer.call(pipeline);\n            }\n            return pipeline.exec(callback);\n        };\n        return pipeline;\n    };\n    const { exec } = redis;\n    redis.exec = function (callback) {\n        return (0, standard_as_callback_1.default)(exec.call(this).then(function (results) {\n            if (Array.isArray(results)) {\n                results = (0, utils_1.wrapMultiResult)(results);\n            }\n            return results;\n        }), callback);\n    };\n}\nexports.addTransactionSupport = addTransactionSupport;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nfunction applyMixin(derivedConstructor, mixinConstructor) {\n    Object.getOwnPropertyNames(mixinConstructor.prototype).forEach((name) => {\n        Object.defineProperty(derivedConstructor.prototype, name, Object.getOwnPropertyDescriptor(mixinConstructor.prototype, name));\n    });\n}\nexports.default = applyMixin;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DEFAULT_CLUSTER_OPTIONS = void 0;\nconst dns_1 = require(\"dns\");\nexports.DEFAULT_CLUSTER_OPTIONS = {\n    clusterRetryStrategy: (times) => Math.min(100 + times * 2, 2000),\n    clusterNodeRetryStrategy: null,\n    enableOfflineQueue: true,\n    enableReadyCheck: true,\n    scaleReads: \"master\",\n    maxRedirections: 16,\n    retryDelayOnMoved: 0,\n    retryDelayOnFailover: 100,\n    retryDelayOnClusterDown: 100,\n    retryDelayOnTryAgain: 100,\n    slotsRefreshTimeout: 1000,\n    useSRVRecords: false,\n    resolveSrv: dns_1.resolveSrv,\n    dnsLookup: dns_1.lookup,\n    enableAutoPipelining: false,\n    autoPipeliningIgnoredCommands: [],\n    shardedSubscribers: false,\n};\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getConnectionName = exports.weightSrvRecords = exports.groupSrvRecords = exports.getUniqueHostnamesFromOptions = exports.normalizeNodeOptions = exports.nodeKeyToRedisOptions = exports.getNodeKey = void 0;\nconst utils_1 = require(\"../utils\");\nconst net_1 = require(\"net\");\nfunction getNodeKey(node) {\n    node.port = node.port || 6379;\n    node.host = node.host || \"127.0.0.1\";\n    return node.host + \":\" + node.port;\n}\nexports.getNodeKey = getNodeKey;\nfunction nodeKeyToRedisOptions(nodeKey) {\n    const portIndex = nodeKey.lastIndexOf(\":\");\n    if (portIndex === -1) {\n        throw new Error(`Invalid node key ${nodeKey}`);\n    }\n    return {\n        host: nodeKey.slice(0, portIndex),\n        port: Number(nodeKey.slice(portIndex + 1)),\n    };\n}\nexports.nodeKeyToRedisOptions = nodeKeyToRedisOptions;\nfunction normalizeNodeOptions(nodes) {\n    return nodes.map((node) => {\n        const options = {};\n        if (typeof node === \"object\") {\n            Object.assign(options, node);\n        }\n        else if (typeof node === \"string\") {\n            Object.assign(options, (0, utils_1.parseURL)(node));\n        }\n        else if (typeof node === \"number\") {\n            options.port = node;\n        }\n        else {\n            throw new Error(\"Invalid argument \" + node);\n        }\n        if (typeof options.port === \"string\") {\n            options.port = parseInt(options.port, 10);\n        }\n        // Cluster mode only support db 0\n        delete options.db;\n        if (!options.port) {\n            options.port = 6379;\n        }\n        if (!options.host) {\n            options.host = \"127.0.0.1\";\n        }\n        return (0, utils_1.resolveTLSProfile)(options);\n    });\n}\nexports.normalizeNodeOptions = normalizeNodeOptions;\nfunction getUniqueHostnamesFromOptions(nodes) {\n    const uniqueHostsMap = {};\n    nodes.forEach((node) => {\n        uniqueHostsMap[node.host] = true;\n    });\n    return Object.keys(uniqueHostsMap).filter((host) => !(0, net_1.isIP)(host));\n}\nexports.getUniqueHostnamesFromOptions = getUniqueHostnamesFromOptions;\nfunction groupSrvRecords(records) {\n    const recordsByPriority = {};\n    for (const record of records) {\n        if (!recordsByPriority.hasOwnProperty(record.priority)) {\n            recordsByPriority[record.priority] = {\n                totalWeight: record.weight,\n                records: [record],\n            };\n        }\n        else {\n            recordsByPriority[record.priority].totalWeight += record.weight;\n            recordsByPriority[record.priority].records.push(record);\n        }\n    }\n    return recordsByPriority;\n}\nexports.groupSrvRecords = groupSrvRecords;\nfunction weightSrvRecords(recordsGroup) {\n    if (recordsGroup.records.length === 1) {\n        recordsGroup.totalWeight = 0;\n        return recordsGroup.records.shift();\n    }\n    // + `recordsGroup.records.length` to support `weight` 0\n    const random = Math.floor(Math.random() * (recordsGroup.totalWeight + recordsGroup.records.length));\n    let total = 0;\n    for (const [i, record] of recordsGroup.records.entries()) {\n        total += 1 + record.weight;\n        if (total > random) {\n            recordsGroup.totalWeight -= record.weight;\n            recordsGroup.records.splice(i, 1);\n            return record;\n        }\n    }\n}\nexports.weightSrvRecords = weightSrvRecords;\nfunction getConnectionName(component, nodeConnectionName) {\n    const prefix = `ioredis-cluster(${component})`;\n    return nodeConnectionName ? `${prefix}:${nodeConnectionName}` : prefix;\n}\nexports.getConnectionName = getConnectionName;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst util_1 = require(\"./util\");\nconst utils_1 = require(\"../utils\");\nconst Redis_1 = require(\"../Redis\");\nconst debug = (0, utils_1.Debug)(\"cluster:subscriber\");\nclass ClusterSubscriber {\n    constructor(connectionPool, emitter, isSharded = false) {\n        this.connectionPool = connectionPool;\n        this.emitter = emitter;\n        this.isSharded = isSharded;\n        this.started = false;\n        //There is only one connection for the entire pool\n        this.subscriber = null;\n        //The slot range for which this subscriber is responsible\n        this.slotRange = [];\n        this.onSubscriberEnd = () => {\n            if (!this.started) {\n                debug(\"subscriber has disconnected, but ClusterSubscriber is not started, so not reconnecting.\");\n                return;\n            }\n            // If the subscriber closes whilst it's still the active connection,\n            // we might as well try to connecting to a new node if possible to\n            // minimise the number of missed publishes.\n            debug(\"subscriber has disconnected, selecting a new one...\");\n            this.selectSubscriber();\n        };\n        // If the current node we're using as the subscriber disappears\n        // from the node pool for some reason, we will select a new one\n        // to connect to.\n        // Note that this event is only triggered if the connection to\n        // the node has been used; cluster subscriptions are setup with\n        // lazyConnect = true. It's possible for the subscriber node to\n        // disappear without this method being called!\n        // See https://github.com/luin/ioredis/pull/1589\n        this.connectionPool.on(\"-node\", (_, key) => {\n            if (!this.started || !this.subscriber) {\n                return;\n            }\n            if ((0, util_1.getNodeKey)(this.subscriber.options) === key) {\n                debug(\"subscriber has left, selecting a new one...\");\n                this.selectSubscriber();\n            }\n        });\n        this.connectionPool.on(\"+node\", () => {\n            if (!this.started || this.subscriber) {\n                return;\n            }\n            debug(\"a new node is discovered and there is no subscriber, selecting a new one...\");\n            this.selectSubscriber();\n        });\n    }\n    getInstance() {\n        return this.subscriber;\n    }\n    /**\n     * Associate this subscriber to a specific slot range.\n     *\n     * Returns the range or an empty array if the slot range couldn't be associated.\n     *\n     * BTW: This is more for debugging and testing purposes.\n     *\n     * @param range\n     */\n    associateSlotRange(range) {\n        if (this.isSharded) {\n            this.slotRange = range;\n        }\n        return this.slotRange;\n    }\n    start() {\n        this.started = true;\n        this.selectSubscriber();\n        debug(\"started\");\n    }\n    stop() {\n        this.started = false;\n        if (this.subscriber) {\n            this.subscriber.disconnect();\n            this.subscriber = null;\n        }\n    }\n    isStarted() {\n        return this.started;\n    }\n    selectSubscriber() {\n        const lastActiveSubscriber = this.lastActiveSubscriber;\n        // Disconnect the previous subscriber even if there\n        // will not be a new one.\n        if (lastActiveSubscriber) {\n            lastActiveSubscriber.off(\"end\", this.onSubscriberEnd);\n            lastActiveSubscriber.disconnect();\n        }\n        if (this.subscriber) {\n            this.subscriber.off(\"end\", this.onSubscriberEnd);\n            this.subscriber.disconnect();\n        }\n        const sampleNode = (0, utils_1.sample)(this.connectionPool.getNodes());\n        if (!sampleNode) {\n            debug(\"selecting subscriber failed since there is no node discovered in the cluster yet\");\n            this.subscriber = null;\n            return;\n        }\n        const { options } = sampleNode;\n        debug(\"selected a subscriber %s:%s\", options.host, options.port);\n        /*\n         * Create a specialized Redis connection for the subscription.\n         * Note that auto reconnection is enabled here.\n         *\n         * `enableReadyCheck` is also enabled because although subscription is allowed\n         * while redis is loading data from the disk, we can check if the password\n         * provided for the subscriber is correct, and if not, the current subscriber\n         * will be disconnected and a new subscriber will be selected.\n         */\n        let connectionPrefix = \"subscriber\";\n        if (this.isSharded)\n            connectionPrefix = \"ssubscriber\";\n        this.subscriber = new Redis_1.default({\n            port: options.port,\n            host: options.host,\n            username: options.username,\n            password: options.password,\n            enableReadyCheck: true,\n            connectionName: (0, util_1.getConnectionName)(connectionPrefix, options.connectionName),\n            lazyConnect: true,\n            tls: options.tls,\n            // Don't try to reconnect the subscriber connection. If the connection fails\n            // we will get an end event (handled below), at which point we'll pick a new\n            // node from the pool and try to connect to that as the subscriber connection.\n            retryStrategy: null,\n        });\n        // Ignore the errors since they're handled in the connection pool.\n        this.subscriber.on(\"error\", utils_1.noop);\n        this.subscriber.on(\"moved\", () => {\n            this.emitter.emit(\"forceRefresh\");\n        });\n        // The node we lost connection to may not come back up in a\n        // reasonable amount of time (e.g. a slave that's taken down\n        // for maintainence), we could potentially miss many published\n        // messages so we should reconnect as quickly as possible, to\n        // a different node if needed.\n        this.subscriber.once(\"end\", this.onSubscriberEnd);\n        // Re-subscribe previous channels\n        const previousChannels = { subscribe: [], psubscribe: [], ssubscribe: [] };\n        if (lastActiveSubscriber) {\n            const condition = lastActiveSubscriber.condition || lastActiveSubscriber.prevCondition;\n            if (condition && condition.subscriber) {\n                previousChannels.subscribe = condition.subscriber.channels(\"subscribe\");\n                previousChannels.psubscribe =\n                    condition.subscriber.channels(\"psubscribe\");\n                previousChannels.ssubscribe =\n                    condition.subscriber.channels(\"ssubscribe\");\n            }\n        }\n        if (previousChannels.subscribe.length ||\n            previousChannels.psubscribe.length ||\n            previousChannels.ssubscribe.length) {\n            let pending = 0;\n            for (const type of [\"subscribe\", \"psubscribe\", \"ssubscribe\"]) {\n                const channels = previousChannels[type];\n                if (channels.length == 0) {\n                    continue;\n                }\n                debug(\"%s %d channels\", type, channels.length);\n                if (type === \"ssubscribe\") {\n                    for (const channel of channels) {\n                        pending += 1;\n                        this.subscriber[type](channel)\n                            .then(() => {\n                            if (!--pending) {\n                                this.lastActiveSubscriber = this.subscriber;\n                            }\n                        })\n                            .catch(() => {\n                            // TODO: should probably disconnect the subscriber and try again.\n                            debug(\"failed to ssubscribe to channel: %s\", channel);\n                        });\n                    }\n                }\n                else {\n                    pending += 1;\n                    this.subscriber[type](channels)\n                        .then(() => {\n                        if (!--pending) {\n                            this.lastActiveSubscriber = this.subscriber;\n                        }\n                    })\n                        .catch(() => {\n                        // TODO: should probably disconnect the subscriber and try again.\n                        debug(\"failed to %s %d channels\", type, channels.length);\n                    });\n                }\n            }\n        }\n        else {\n            this.lastActiveSubscriber = this.subscriber;\n        }\n        for (const event of [\n            \"message\",\n            \"messageBuffer\",\n        ]) {\n            this.subscriber.on(event, (arg1, arg2) => {\n                this.emitter.emit(event, arg1, arg2);\n            });\n        }\n        for (const event of [\"pmessage\", \"pmessageBuffer\"]) {\n            this.subscriber.on(event, (arg1, arg2, arg3) => {\n                this.emitter.emit(event, arg1, arg2, arg3);\n            });\n        }\n        if (this.isSharded == true) {\n            for (const event of [\n                \"smessage\",\n                \"smessageBuffer\",\n            ]) {\n                this.subscriber.on(event, (arg1, arg2) => {\n                    this.emitter.emit(event, arg1, arg2);\n                });\n            }\n        }\n    }\n}\nexports.default = ClusterSubscriber;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst events_1 = require(\"events\");\nconst utils_1 = require(\"../utils\");\nconst util_1 = require(\"./util\");\nconst Redis_1 = require(\"../Redis\");\nconst debug = (0, utils_1.Debug)(\"cluster:connectionPool\");\nclass ConnectionPool extends events_1.EventEmitter {\n    constructor(redisOptions, clusterNodeRetryStrategy = null) {\n        super();\n        this.redisOptions = redisOptions;\n        this.clusterNodeRetryStrategy = clusterNodeRetryStrategy;\n        // master + slave = all\n        this.nodes = {\n            all: {},\n            master: {},\n            slave: {},\n        };\n        this.specifiedOptions = {};\n    }\n    getNodes(role = \"all\") {\n        const nodes = this.nodes[role];\n        return Object.keys(nodes).map((key) => nodes[key]);\n    }\n    getInstanceByKey(key) {\n        return this.nodes.all[key];\n    }\n    getSampleInstance(role) {\n        const keys = Object.keys(this.nodes[role]);\n        const sampleKey = (0, utils_1.sample)(keys);\n        return this.nodes[role][sampleKey];\n    }\n    /**\n     * Add a master node to the pool\n     * @param node\n     */\n    addMasterNode(node) {\n        const key = (0, util_1.getNodeKey)(node.options);\n        const redis = this.createRedisFromOptions(node, node.options.readOnly);\n        //Master nodes aren't read-only\n        if (!node.options.readOnly) {\n            this.nodes.all[key] = redis;\n            this.nodes.master[key] = redis;\n            return true;\n        }\n        return false;\n    }\n    /**\n     * Creates a Redis connection instance from the node options\n     * @param node\n     * @param readOnly\n     */\n    createRedisFromOptions(node, readOnly) {\n        const redis = new Redis_1.default((0, utils_1.defaults)({\n            // By default, never try to reconnect when a node is lost,\n            // instead, waiting for a `MOVED` error and fetching slots again.\n            // When `clusterNodeRetryStrategy` is set, use it to allow\n            // reconnection (e.g. for replica nodes that restart without\n            // any slot changes).\n            retryStrategy: typeof this.clusterNodeRetryStrategy === \"function\"\n                ? this.clusterNodeRetryStrategy\n                : null,\n            // Offline queue should be enabled so that\n            // we don't need to wait for the `ready` event\n            // before sending commands to the node.\n            enableOfflineQueue: true,\n            readOnly: readOnly,\n        }, node, this.redisOptions, { lazyConnect: true }));\n        return redis;\n    }\n    /**\n     * Find or create a connection to the node\n     */\n    findOrCreate(node, readOnly = false) {\n        const key = (0, util_1.getNodeKey)(node);\n        readOnly = Boolean(readOnly);\n        if (this.specifiedOptions[key]) {\n            Object.assign(node, this.specifiedOptions[key]);\n        }\n        else {\n            this.specifiedOptions[key] = node;\n        }\n        let redis;\n        if (this.nodes.all[key]) {\n            redis = this.nodes.all[key];\n            if (redis.options.readOnly !== readOnly) {\n                redis.options.readOnly = readOnly;\n                debug(\"Change role of %s to %s\", key, readOnly ? \"slave\" : \"master\");\n                redis[readOnly ? \"readonly\" : \"readwrite\"]().catch(utils_1.noop);\n                if (readOnly) {\n                    delete this.nodes.master[key];\n                    this.nodes.slave[key] = redis;\n                }\n                else {\n                    delete this.nodes.slave[key];\n                    this.nodes.master[key] = redis;\n                }\n            }\n        }\n        else {\n            debug(\"Connecting to %s as %s\", key, readOnly ? \"slave\" : \"master\");\n            redis = this.createRedisFromOptions(node, readOnly);\n            this.nodes.all[key] = redis;\n            this.nodes[readOnly ? \"slave\" : \"master\"][key] = redis;\n            redis.once(\"end\", () => {\n                this.removeNode(key);\n                this.emit(\"-node\", redis, key);\n                if (!Object.keys(this.nodes.all).length) {\n                    this.emit(\"drain\");\n                }\n            });\n            this.emit(\"+node\", redis, key);\n            redis.on(\"error\", (error) => {\n                this.emit(\"nodeError\", error, key);\n            });\n        }\n        return redis;\n    }\n    /**\n     * Reset the pool with a set of nodes.\n     * The old node will be removed.\n     */\n    reset(nodes) {\n        debug(\"Reset with %O\", nodes);\n        const newNodes = {};\n        nodes.forEach((node) => {\n            const key = (0, util_1.getNodeKey)(node);\n            // Don't override the existing (master) node\n            // when the current one is slave.\n            if (!(node.readOnly && newNodes[key])) {\n                newNodes[key] = node;\n            }\n        });\n        Object.keys(this.nodes.all).forEach((key) => {\n            if (!newNodes[key]) {\n                debug(\"Disconnect %s because the node does not hold any slot\", key);\n                this.nodes.all[key].disconnect();\n                this.removeNode(key);\n            }\n        });\n        Object.keys(newNodes).forEach((key) => {\n            const node = newNodes[key];\n            this.findOrCreate(node, node.readOnly);\n        });\n    }\n    /**\n     * Remove a node from the pool.\n     */\n    removeNode(key) {\n        const { nodes } = this;\n        if (nodes.all[key]) {\n            debug(\"Remove %s from the pool\", key);\n            delete nodes.all[key];\n        }\n        delete nodes.master[key];\n        delete nodes.slave[key];\n    }\n}\nexports.default = ConnectionPool;\n","'use strict';\n\n/**\n * Custom implementation of a double ended queue.\n */\nfunction Denque(array, options) {\n  var options = options || {};\n  this._capacity = options.capacity;\n\n  this._head = 0;\n  this._tail = 0;\n\n  if (Array.isArray(array)) {\n    this._fromArray(array);\n  } else {\n    this._capacityMask = 0x3;\n    this._list = new Array(4);\n  }\n}\n\n/**\n * --------------\n *  PUBLIC API\n * -------------\n */\n\n/**\n * Returns the item at the specified index from the list.\n * 0 is the first element, 1 is the second, and so on...\n * Elements at negative values are that many from the end: -1 is one before the end\n * (the last element), -2 is two before the end (one before last), etc.\n * @param index\n * @returns {*}\n */\nDenque.prototype.peekAt = function peekAt(index) {\n  var i = index;\n  // expect a number or return undefined\n  if ((i !== (i | 0))) {\n    return void 0;\n  }\n  var len = this.size();\n  if (i >= len || i < -len) return undefined;\n  if (i < 0) i += len;\n  i = (this._head + i) & this._capacityMask;\n  return this._list[i];\n};\n\n/**\n * Alias for peekAt()\n * @param i\n * @returns {*}\n */\nDenque.prototype.get = function get(i) {\n  return this.peekAt(i);\n};\n\n/**\n * Returns the first item in the list without removing it.\n * @returns {*}\n */\nDenque.prototype.peek = function peek() {\n  if (this._head === this._tail) return undefined;\n  return this._list[this._head];\n};\n\n/**\n * Alias for peek()\n * @returns {*}\n */\nDenque.prototype.peekFront = function peekFront() {\n  return this.peek();\n};\n\n/**\n * Returns the item that is at the back of the queue without removing it.\n * Uses peekAt(-1)\n */\nDenque.prototype.peekBack = function peekBack() {\n  return this.peekAt(-1);\n};\n\n/**\n * Returns the current length of the queue\n * @return {Number}\n */\nObject.defineProperty(Denque.prototype, 'length', {\n  get: function length() {\n    return this.size();\n  }\n});\n\n/**\n * Return the number of items on the list, or 0 if empty.\n * @returns {number}\n */\nDenque.prototype.size = function size() {\n  if (this._head === this._tail) return 0;\n  if (this._head < this._tail) return this._tail - this._head;\n  else return this._capacityMask + 1 - (this._head - this._tail);\n};\n\n/**\n * Add an item at the beginning of the list.\n * @param item\n */\nDenque.prototype.unshift = function unshift(item) {\n  if (arguments.length === 0) return this.size();\n  var len = this._list.length;\n  this._head = (this._head - 1 + len) & this._capacityMask;\n  this._list[this._head] = item;\n  if (this._tail === this._head) this._growArray();\n  if (this._capacity && this.size() > this._capacity) this.pop();\n  if (this._head < this._tail) return this._tail - this._head;\n  else return this._capacityMask + 1 - (this._head - this._tail);\n};\n\n/**\n * Remove and return the first item on the list,\n * Returns undefined if the list is empty.\n * @returns {*}\n */\nDenque.prototype.shift = function shift() {\n  var head = this._head;\n  if (head === this._tail) return undefined;\n  var item = this._list[head];\n  this._list[head] = undefined;\n  this._head = (head + 1) & this._capacityMask;\n  if (head < 2 && this._tail > 10000 && this._tail <= this._list.length >>> 2) this._shrinkArray();\n  return item;\n};\n\n/**\n * Add an item to the bottom of the list.\n * @param item\n */\nDenque.prototype.push = function push(item) {\n  if (arguments.length === 0) return this.size();\n  var tail = this._tail;\n  this._list[tail] = item;\n  this._tail = (tail + 1) & this._capacityMask;\n  if (this._tail === this._head) {\n    this._growArray();\n  }\n  if (this._capacity && this.size() > this._capacity) {\n    this.shift();\n  }\n  if (this._head < this._tail) return this._tail - this._head;\n  else return this._capacityMask + 1 - (this._head - this._tail);\n};\n\n/**\n * Remove and return the last item on the list.\n * Returns undefined if the list is empty.\n * @returns {*}\n */\nDenque.prototype.pop = function pop() {\n  var tail = this._tail;\n  if (tail === this._head) return undefined;\n  var len = this._list.length;\n  this._tail = (tail - 1 + len) & this._capacityMask;\n  var item = this._list[this._tail];\n  this._list[this._tail] = undefined;\n  if (this._head < 2 && tail > 10000 && tail <= len >>> 2) this._shrinkArray();\n  return item;\n};\n\n/**\n * Remove and return the item at the specified index from the list.\n * Returns undefined if the list is empty.\n * @param index\n * @returns {*}\n */\nDenque.prototype.removeOne = function removeOne(index) {\n  var i = index;\n  // expect a number or return undefined\n  if ((i !== (i | 0))) {\n    return void 0;\n  }\n  if (this._head === this._tail) return void 0;\n  var size = this.size();\n  var len = this._list.length;\n  if (i >= size || i < -size) return void 0;\n  if (i < 0) i += size;\n  i = (this._head + i) & this._capacityMask;\n  var item = this._list[i];\n  var k;\n  if (index < size / 2) {\n    for (k = index; k > 0; k--) {\n      this._list[i] = this._list[i = (i - 1 + len) & this._capacityMask];\n    }\n    this._list[i] = void 0;\n    this._head = (this._head + 1 + len) & this._capacityMask;\n  } else {\n    for (k = size - 1 - index; k > 0; k--) {\n      this._list[i] = this._list[i = (i + 1 + len) & this._capacityMask];\n    }\n    this._list[i] = void 0;\n    this._tail = (this._tail - 1 + len) & this._capacityMask;\n  }\n  return item;\n};\n\n/**\n * Remove number of items from the specified index from the list.\n * Returns array of removed items.\n * Returns undefined if the list is empty.\n * @param index\n * @param count\n * @returns {array}\n */\nDenque.prototype.remove = function remove(index, count) {\n  var i = index;\n  var removed;\n  var del_count = count;\n  // expect a number or return undefined\n  if ((i !== (i | 0))) {\n    return void 0;\n  }\n  if (this._head === this._tail) return void 0;\n  var size = this.size();\n  var len = this._list.length;\n  if (i >= size || i < -size || count < 1) return void 0;\n  if (i < 0) i += size;\n  if (count === 1 || !count) {\n    removed = new Array(1);\n    removed[0] = this.removeOne(i);\n    return removed;\n  }\n  if (i === 0 && i + count >= size) {\n    removed = this.toArray();\n    this.clear();\n    return removed;\n  }\n  if (i + count > size) count = size - i;\n  var k;\n  removed = new Array(count);\n  for (k = 0; k < count; k++) {\n    removed[k] = this._list[(this._head + i + k) & this._capacityMask];\n  }\n  i = (this._head + i) & this._capacityMask;\n  if (index + count === size) {\n    this._tail = (this._tail - count + len) & this._capacityMask;\n    for (k = count; k > 0; k--) {\n      this._list[i = (i + 1 + len) & this._capacityMask] = void 0;\n    }\n    return removed;\n  }\n  if (index === 0) {\n    this._head = (this._head + count + len) & this._capacityMask;\n    for (k = count - 1; k > 0; k--) {\n      this._list[i = (i + 1 + len) & this._capacityMask] = void 0;\n    }\n    return removed;\n  }\n  if (i < size / 2) {\n    this._head = (this._head + index + count + len) & this._capacityMask;\n    for (k = index; k > 0; k--) {\n      this.unshift(this._list[i = (i - 1 + len) & this._capacityMask]);\n    }\n    i = (this._head - 1 + len) & this._capacityMask;\n    while (del_count > 0) {\n      this._list[i = (i - 1 + len) & this._capacityMask] = void 0;\n      del_count--;\n    }\n    if (index < 0) this._tail = i;\n  } else {\n    this._tail = i;\n    i = (i + count + len) & this._capacityMask;\n    for (k = size - (count + index); k > 0; k--) {\n      this.push(this._list[i++]);\n    }\n    i = this._tail;\n    while (del_count > 0) {\n      this._list[i = (i + 1 + len) & this._capacityMask] = void 0;\n      del_count--;\n    }\n  }\n  if (this._head < 2 && this._tail > 10000 && this._tail <= len >>> 2) this._shrinkArray();\n  return removed;\n};\n\n/**\n * Native splice implementation.\n * Remove number of items from the specified index from the list and/or add new elements.\n * Returns array of removed items or empty array if count == 0.\n * Returns undefined if the list is empty.\n *\n * @param index\n * @param count\n * @param {...*} [elements]\n * @returns {array}\n */\nDenque.prototype.splice = function splice(index, count) {\n  var i = index;\n  // expect a number or return undefined\n  if ((i !== (i | 0))) {\n    return void 0;\n  }\n  var size = this.size();\n  if (i < 0) i += size;\n  if (i > size) return void 0;\n  if (arguments.length > 2) {\n    var k;\n    var temp;\n    var removed;\n    var arg_len = arguments.length;\n    var len = this._list.length;\n    var arguments_index = 2;\n    if (!size || i < size / 2) {\n      temp = new Array(i);\n      for (k = 0; k < i; k++) {\n        temp[k] = this._list[(this._head + k) & this._capacityMask];\n      }\n      if (count === 0) {\n        removed = [];\n        if (i > 0) {\n          this._head = (this._head + i + len) & this._capacityMask;\n        }\n      } else {\n        removed = this.remove(i, count);\n        this._head = (this._head + i + len) & this._capacityMask;\n      }\n      while (arg_len > arguments_index) {\n        this.unshift(arguments[--arg_len]);\n      }\n      for (k = i; k > 0; k--) {\n        this.unshift(temp[k - 1]);\n      }\n    } else {\n      temp = new Array(size - (i + count));\n      var leng = temp.length;\n      for (k = 0; k < leng; k++) {\n        temp[k] = this._list[(this._head + i + count + k) & this._capacityMask];\n      }\n      if (count === 0) {\n        removed = [];\n        if (i != size) {\n          this._tail = (this._head + i + len) & this._capacityMask;\n        }\n      } else {\n        removed = this.remove(i, count);\n        this._tail = (this._tail - leng + len) & this._capacityMask;\n      }\n      while (arguments_index < arg_len) {\n        this.push(arguments[arguments_index++]);\n      }\n      for (k = 0; k < leng; k++) {\n        this.push(temp[k]);\n      }\n    }\n    return removed;\n  } else {\n    return this.remove(i, count);\n  }\n};\n\n/**\n * Soft clear - does not reset capacity.\n */\nDenque.prototype.clear = function clear() {\n  this._list = new Array(this._list.length);\n  this._head = 0;\n  this._tail = 0;\n};\n\n/**\n * Returns true or false whether the list is empty.\n * @returns {boolean}\n */\nDenque.prototype.isEmpty = function isEmpty() {\n  return this._head === this._tail;\n};\n\n/**\n * Returns an array of all queue items.\n * @returns {Array}\n */\nDenque.prototype.toArray = function toArray() {\n  return this._copyArray(false);\n};\n\n/**\n * -------------\n *   INTERNALS\n * -------------\n */\n\n/**\n * Fills the queue with items from an array\n * For use in the constructor\n * @param array\n * @private\n */\nDenque.prototype._fromArray = function _fromArray(array) {\n  var length = array.length;\n  var capacity = this._nextPowerOf2(length);\n\n  this._list = new Array(capacity);\n  this._capacityMask = capacity - 1;\n  this._tail = length;\n\n  for (var i = 0; i < length; i++) this._list[i] = array[i];\n};\n\n/**\n *\n * @param fullCopy\n * @param size Initialize the array with a specific size. Will default to the current list size\n * @returns {Array}\n * @private\n */\nDenque.prototype._copyArray = function _copyArray(fullCopy, size) {\n  var src = this._list;\n  var capacity = src.length;\n  var length = this.length;\n  size = size | length;\n\n  // No prealloc requested and the buffer is contiguous\n  if (size == length && this._head < this._tail) {\n    // Simply do a fast slice copy\n    return this._list.slice(this._head, this._tail);\n  }\n\n  var dest = new Array(size);\n\n  var k = 0;\n  var i;\n  if (fullCopy || this._head > this._tail) {\n    for (i = this._head; i < capacity; i++) dest[k++] = src[i];\n    for (i = 0; i < this._tail; i++) dest[k++] = src[i];\n  } else {\n    for (i = this._head; i < this._tail; i++) dest[k++] = src[i];\n  }\n\n  return dest;\n}\n\n/**\n * Grows the internal list array.\n * @private\n */\nDenque.prototype._growArray = function _growArray() {\n  if (this._head != 0) {\n    // double array size and copy existing data, head to end, then beginning to tail.\n    var newList = this._copyArray(true, this._list.length << 1);\n\n    this._tail = this._list.length;\n    this._head = 0;\n\n    this._list = newList;\n  } else {\n    this._tail = this._list.length;\n    this._list.length <<= 1;\n  }\n\n  this._capacityMask = (this._capacityMask << 1) | 1;\n};\n\n/**\n * Shrinks the internal list array.\n * @private\n */\nDenque.prototype._shrinkArray = function _shrinkArray() {\n  this._list.length >>>= 1;\n  this._capacityMask >>>= 1;\n};\n\n/**\n * Find the next power of 2, at least 4\n * @private\n * @param {number} num \n * @returns {number}\n */\nDenque.prototype._nextPowerOf2 = function _nextPowerOf2(num) {\n  var log2 = Math.log(num) / Math.log(2);\n  var nextPow2 = 1 << (log2 + 1);\n\n  return Math.max(nextPow2, 4);\n}\n\nmodule.exports = Denque;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst utils_1 = require(\"../utils\");\nconst Deque = require(\"denque\");\nconst debug = (0, utils_1.Debug)(\"delayqueue\");\n/**\n * Queue that runs items after specified duration\n */\nclass DelayQueue {\n    constructor() {\n        this.queues = {};\n        this.timeouts = {};\n    }\n    /**\n     * Add a new item to the queue\n     *\n     * @param bucket bucket name\n     * @param item function that will run later\n     * @param options\n     */\n    push(bucket, item, options) {\n        const callback = options.callback || process.nextTick;\n        if (!this.queues[bucket]) {\n            this.queues[bucket] = new Deque();\n        }\n        const queue = this.queues[bucket];\n        queue.push(item);\n        if (!this.timeouts[bucket]) {\n            this.timeouts[bucket] = setTimeout(() => {\n                callback(() => {\n                    this.timeouts[bucket] = null;\n                    this.execute(bucket);\n                });\n            }, options.timeout);\n        }\n    }\n    execute(bucket) {\n        const queue = this.queues[bucket];\n        if (!queue) {\n            return;\n        }\n        const { length } = queue;\n        if (!length) {\n            return;\n        }\n        debug(\"send %d commands in %s queue\", length, bucket);\n        this.queues[bucket] = null;\n        while (queue.length > 0) {\n            queue.shift()();\n        }\n    }\n}\nexports.default = DelayQueue;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst util_1 = require(\"./util\");\nconst utils_1 = require(\"../utils\");\nconst Redis_1 = require(\"../Redis\");\nconst debug = (0, utils_1.Debug)(\"cluster:subscriberGroup:shardedSubscriber\");\nconst SubscriberStatus = {\n    IDLE: \"idle\",\n    STARTING: \"starting\",\n    CONNECTED: \"connected\",\n    STOPPING: \"stopping\",\n    ENDED: \"ended\",\n};\nconst ALLOWED_STATUS_UPDATES = {\n    [SubscriberStatus.IDLE]: [\n        SubscriberStatus.STARTING,\n        SubscriberStatus.STOPPING,\n        SubscriberStatus.ENDED,\n    ],\n    [SubscriberStatus.STARTING]: [\n        SubscriberStatus.CONNECTED,\n        SubscriberStatus.STOPPING,\n        SubscriberStatus.ENDED,\n    ],\n    [SubscriberStatus.CONNECTED]: [\n        SubscriberStatus.STOPPING,\n        SubscriberStatus.ENDED,\n    ],\n    [SubscriberStatus.STOPPING]: [SubscriberStatus.ENDED],\n    [SubscriberStatus.ENDED]: [],\n};\nclass ShardedSubscriber {\n    constructor(emitter, options, redisOptions) {\n        var _a;\n        this.emitter = emitter;\n        this.status = SubscriberStatus.IDLE;\n        this.instance = null;\n        this.connectPromise = null;\n        // Store listener references for cleanup\n        this.messageListeners = new Map();\n        this.onEnd = () => {\n            this.updateStatus(SubscriberStatus.ENDED);\n            this.emitter.emit(\"-node\", this.instance, this.nodeKey);\n        };\n        this.onError = (error) => {\n            this.emitter.emit(\"nodeError\", error, this.nodeKey);\n        };\n        this.onMoved = () => {\n            this.emitter.emit(\"moved\");\n        };\n        this.instance = new Redis_1.default((0, utils_1.defaults)({\n            enableReadyCheck: false,\n            enableOfflineQueue: true,\n            connectionName: (0, util_1.getConnectionName)(\"ssubscriber\", options.connectionName),\n            /**\n             * Disable auto reconnection for subscribers.\n             * The ClusterSubscriberGroup will handle the reconnection.\n             */\n            retryStrategy: null,\n            lazyConnect: true,\n        }, options, redisOptions));\n        this.lazyConnect = (_a = redisOptions === null || redisOptions === void 0 ? void 0 : redisOptions.lazyConnect) !== null && _a !== void 0 ? _a : true;\n        this.nodeKey = (0, util_1.getNodeKey)(options);\n        // Register listeners\n        this.instance.on(\"end\", this.onEnd);\n        this.instance.on(\"error\", this.onError);\n        this.instance.on(\"moved\", this.onMoved);\n        for (const event of [\"smessage\", \"smessageBuffer\"]) {\n            const listener = (...args) => {\n                this.emitter.emit(event, ...args);\n            };\n            this.messageListeners.set(event, listener);\n            this.instance.on(event, listener);\n        }\n    }\n    async start() {\n        if (this.connectPromise) {\n            return this.connectPromise;\n        }\n        if (this.status === SubscriberStatus.STARTING ||\n            this.status === SubscriberStatus.CONNECTED) {\n            return;\n        }\n        if (this.status === SubscriberStatus.ENDED || !this.instance) {\n            throw new Error(`Sharded subscriber ${this.nodeKey} cannot be restarted once ended.`);\n        }\n        this.updateStatus(SubscriberStatus.STARTING);\n        this.connectPromise = this.instance.connect();\n        try {\n            await this.connectPromise;\n            this.updateStatus(SubscriberStatus.CONNECTED);\n        }\n        catch (err) {\n            this.updateStatus(SubscriberStatus.ENDED);\n            throw err;\n        }\n        finally {\n            this.connectPromise = null;\n        }\n    }\n    stop() {\n        this.updateStatus(SubscriberStatus.STOPPING);\n        if (this.instance) {\n            this.instance.disconnect();\n            this.instance.removeAllListeners();\n            this.messageListeners.clear();\n            this.instance = null;\n        }\n        this.updateStatus(SubscriberStatus.ENDED);\n        debug(\"stopped %s\", this.nodeKey);\n    }\n    isStarted() {\n        return [\n            SubscriberStatus.CONNECTED,\n            SubscriberStatus.STARTING,\n        ].includes(this.status);\n    }\n    get subscriberStatus() {\n        return this.status;\n    }\n    isHealthy() {\n        return ((this.status === SubscriberStatus.IDLE ||\n            this.status === SubscriberStatus.CONNECTED ||\n            this.status === SubscriberStatus.STARTING) &&\n            this.instance !== null);\n    }\n    getInstance() {\n        return this.instance;\n    }\n    getNodeKey() {\n        return this.nodeKey;\n    }\n    isLazyConnect() {\n        return this.lazyConnect;\n    }\n    updateStatus(nextStatus) {\n        if (this.status === nextStatus) {\n            return;\n        }\n        if (!ALLOWED_STATUS_UPDATES[this.status].includes(nextStatus)) {\n            debug(\"Invalid status transition for %s: %s -> %s\", this.nodeKey, this.status, nextStatus);\n            return;\n        }\n        this.status = nextStatus;\n    }\n}\nexports.default = ShardedSubscriber;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst utils_1 = require(\"../utils\");\nconst util_1 = require(\"./util\");\nconst calculateSlot = require(\"cluster-key-slot\");\nconst ShardedSubscriber_1 = require(\"./ShardedSubscriber\");\nconst debug = (0, utils_1.Debug)(\"cluster:subscriberGroup\");\n/**\n * Redis distinguishes between \"normal\" and sharded PubSub. When using the normal PubSub feature,\n * exactly one subscriber exists per cluster instance because the Redis cluster bus forwards\n * messages between shards. Sharded PubSub removes this limitation by making each shard\n * responsible for its own messages.\n *\n * This class coordinates one ShardedSubscriber per master node in the cluster, providing\n * sharded PubSub support while keeping the public API backward compatible.\n */\nclass ClusterSubscriberGroup {\n    /**\n     * Register callbacks\n     *\n     * @param cluster\n     */\n    constructor(subscriberGroupEmitter, options) {\n        this.subscriberGroupEmitter = subscriberGroupEmitter;\n        this.options = options;\n        this.shardedSubscribers = new Map();\n        this.clusterSlots = [];\n        // Simple [min, max] slot ranges aren't enough because you can migrate single slots\n        this.subscriberToSlotsIndex = new Map();\n        this.channels = new Map();\n        this.failedAttemptsByNode = new Map();\n        // Only latest pending reset kept; throttled by refreshSlotsCache's isRefreshing + backoff delay\n        this.isResetting = false;\n        this.pendingReset = null;\n        /**\n         * Handles failed subscriber connections by emitting an event to refresh the slots cache\n         * after a backoff period.\n         *\n         * @param error\n         * @param nodeKey\n         */\n        this.handleSubscriberConnectFailed = (error, nodeKey) => {\n            const currentAttempts = this.failedAttemptsByNode.get(nodeKey) || 0;\n            const failedAttempts = currentAttempts + 1;\n            this.failedAttemptsByNode.set(nodeKey, failedAttempts);\n            const attempts = Math.min(failedAttempts, ClusterSubscriberGroup.MAX_RETRY_ATTEMPTS);\n            const backoff = Math.min(ClusterSubscriberGroup.BASE_BACKOFF_MS * 2 ** attempts, ClusterSubscriberGroup.MAX_BACKOFF_MS);\n            const jitter = Math.floor((Math.random() - 0.5) * (backoff * 0.5));\n            const delay = Math.max(0, backoff + jitter);\n            debug(\"Failed to connect subscriber for %s. Refreshing slots in %dms\", nodeKey, delay);\n            this.subscriberGroupEmitter.emit(\"subscriberConnectFailed\", {\n                delay,\n                error,\n            });\n        };\n        /**\n         * Handles successful subscriber connections by resetting the failed attempts counter.\n         *\n         * @param nodeKey\n         */\n        this.handleSubscriberConnectSucceeded = (nodeKey) => {\n            this.failedAttemptsByNode.delete(nodeKey);\n        };\n    }\n    /**\n     * Get the responsible subscriber.\n     *\n     * @param slot\n     */\n    getResponsibleSubscriber(slot) {\n        const nodeKey = this.clusterSlots[slot][0];\n        const sub = this.shardedSubscribers.get(nodeKey);\n        if (sub && sub.subscriberStatus === \"idle\") {\n            sub\n                .start()\n                .then(() => {\n                this.handleSubscriberConnectSucceeded(sub.getNodeKey());\n            })\n                .catch((err) => {\n                this.handleSubscriberConnectFailed(err, sub.getNodeKey());\n            });\n        }\n        return sub;\n    }\n    /**\n     * Adds a channel for which this subscriber group is responsible\n     *\n     * @param channels\n     */\n    addChannels(channels) {\n        const slot = calculateSlot(channels[0]);\n        // Check if the all channels belong to the same slot and otherwise reject the operation\n        for (const c of channels) {\n            if (calculateSlot(c) !== slot) {\n                return -1;\n            }\n        }\n        const currChannels = this.channels.get(slot);\n        if (!currChannels) {\n            this.channels.set(slot, channels);\n        }\n        else {\n            this.channels.set(slot, currChannels.concat(channels));\n        }\n        return Array.from(this.channels.values()).reduce((sum, array) => sum + array.length, 0);\n    }\n    /**\n     * Removes channels for which the subscriber group is responsible by optionally unsubscribing\n     * @param channels\n     */\n    removeChannels(channels) {\n        const slot = calculateSlot(channels[0]);\n        // Check if the all channels belong to the same slot and otherwise reject the operation\n        for (const c of channels) {\n            if (calculateSlot(c) !== slot) {\n                return -1;\n            }\n        }\n        const slotChannels = this.channels.get(slot);\n        if (slotChannels) {\n            const updatedChannels = slotChannels.filter((c) => !channels.includes(c));\n            this.channels.set(slot, updatedChannels);\n        }\n        return Array.from(this.channels.values()).reduce((sum, array) => sum + array.length, 0);\n    }\n    /**\n     * Disconnect all subscribers and clear some of the internal state.\n     */\n    stop() {\n        for (const s of this.shardedSubscribers.values()) {\n            s.stop();\n        }\n        // Clear subscriber instances and pending operations.\n        // Channels are preserved for resubscription on reconnect.\n        this.pendingReset = null;\n        this.shardedSubscribers.clear();\n        this.subscriberToSlotsIndex.clear();\n    }\n    /**\n     * Start all not yet started subscribers\n     */\n    start() {\n        const startPromises = [];\n        for (const s of this.shardedSubscribers.values()) {\n            if (this.shouldStartSubscriber(s)) {\n                startPromises.push(s\n                    .start()\n                    .then(() => {\n                    this.handleSubscriberConnectSucceeded(s.getNodeKey());\n                })\n                    .catch((err) => {\n                    this.handleSubscriberConnectFailed(err, s.getNodeKey());\n                }));\n                this.subscriberGroupEmitter.emit(\"+subscriber\");\n            }\n        }\n        return Promise.all(startPromises);\n    }\n    /**\n     * Resets the subscriber group by disconnecting all subscribers that are no longer needed and connecting new ones.\n     */\n    async reset(clusterSlots, clusterNodes) {\n        if (this.isResetting) {\n            this.pendingReset = { slots: clusterSlots, nodes: clusterNodes };\n            return;\n        }\n        this.isResetting = true;\n        try {\n            const hasTopologyChanged = this._refreshSlots(clusterSlots);\n            const hasFailedSubscribers = this.hasUnhealthySubscribers();\n            if (!hasTopologyChanged && !hasFailedSubscribers) {\n                debug(\"No topology change detected or failed subscribers. Skipping reset.\");\n                return;\n            }\n            // For each of the sharded subscribers\n            for (const [nodeKey, shardedSubscriber] of this.shardedSubscribers) {\n                if (\n                // If the subscriber is still responsible for a slot range and is healthy then keep it\n                this.subscriberToSlotsIndex.has(nodeKey) &&\n                    shardedSubscriber.isHealthy()) {\n                    debug(\"Skipping deleting subscriber for %s\", nodeKey);\n                    continue;\n                }\n                debug(\"Removing subscriber for %s\", nodeKey);\n                // Otherwise stop the subscriber and remove it\n                shardedSubscriber.stop();\n                this.shardedSubscribers.delete(nodeKey);\n                this.subscriberGroupEmitter.emit(\"-subscriber\");\n            }\n            const startPromises = [];\n            // For each node in slots cache\n            for (const [nodeKey, _] of this.subscriberToSlotsIndex) {\n                const existingSubscriber = this.shardedSubscribers.get(nodeKey);\n                // If we already have a subscriber for this node, only ensure it is healthy\n                // when it now owns slots with active channel subscriptions.\n                if (existingSubscriber && existingSubscriber.isHealthy()) {\n                    debug(\"Skipping creating new subscriber for %s\", nodeKey);\n                    if (!existingSubscriber.isStarted() &&\n                        this.shouldStartSubscriber(existingSubscriber)) {\n                        startPromises.push(existingSubscriber\n                            .start()\n                            .then(() => {\n                            this.handleSubscriberConnectSucceeded(nodeKey);\n                        })\n                            .catch((error) => {\n                            this.handleSubscriberConnectFailed(error, nodeKey);\n                        }));\n                    }\n                    continue;\n                }\n                // If we have an existing subscriber but it is not healthy, stop it\n                if (existingSubscriber && !existingSubscriber.isHealthy()) {\n                    debug(\"Replacing subscriber for %s\", nodeKey);\n                    existingSubscriber.stop();\n                    this.shardedSubscribers.delete(nodeKey);\n                    this.subscriberGroupEmitter.emit(\"-subscriber\");\n                }\n                debug(\"Creating new subscriber for %s\", nodeKey);\n                // Otherwise create a new subscriber\n                const redis = clusterNodes.find((node) => {\n                    return (0, util_1.getNodeKey)(node.options) === nodeKey;\n                });\n                if (!redis) {\n                    debug(\"Failed to find node for key %s\", nodeKey);\n                    continue;\n                }\n                const sub = new ShardedSubscriber_1.default(this.subscriberGroupEmitter, redis.options, this.options.redisOptions);\n                this.shardedSubscribers.set(nodeKey, sub);\n                if (this.shouldStartSubscriber(sub)) {\n                    startPromises.push(sub\n                        .start()\n                        .then(() => {\n                        this.handleSubscriberConnectSucceeded(nodeKey);\n                    })\n                        .catch((error) => {\n                        this.handleSubscriberConnectFailed(error, nodeKey);\n                    }));\n                }\n                this.subscriberGroupEmitter.emit(\"+subscriber\");\n            }\n            // It's vital to await the start promises before resubscribing\n            // Otherwise we might try to resubscribe to a subscriber that is not yet connected\n            // This can cause a race condition\n            await Promise.all(startPromises);\n            this._resubscribe();\n            this.subscriberGroupEmitter.emit(\"subscribersReady\");\n        }\n        finally {\n            this.isResetting = false;\n            if (this.pendingReset) {\n                const { slots, nodes } = this.pendingReset;\n                this.pendingReset = null;\n                await this.reset(slots, nodes);\n            }\n        }\n    }\n    /**\n     * Refreshes the subscriber-related slot ranges\n     *\n     * Returns false if no refresh was needed\n     *\n     * @param targetSlots\n     */\n    _refreshSlots(targetSlots) {\n        //If there was an actual change, then reassign the slot ranges\n        // Also rebuild if subscriberToSlotsIndex is empty (e.g., after stop() was called)\n        if (this._slotsAreEqual(targetSlots) && this.subscriberToSlotsIndex.size > 0) {\n            debug(\"Nothing to refresh because the new cluster map is equal to the previous one.\");\n            return false;\n        }\n        debug(\"Refreshing the slots of the subscriber group.\");\n        //Rebuild the slots index\n        this.subscriberToSlotsIndex = new Map();\n        for (let slot = 0; slot < targetSlots.length; slot++) {\n            const node = targetSlots[slot][0];\n            if (!this.subscriberToSlotsIndex.has(node)) {\n                this.subscriberToSlotsIndex.set(node, []);\n            }\n            this.subscriberToSlotsIndex.get(node).push(Number(slot));\n        }\n        //Update the cached slots map\n        this.clusterSlots = JSON.parse(JSON.stringify(targetSlots));\n        return true;\n    }\n    /**\n     * Resubscribes to the previous channels\n     *\n     * @private\n     */\n    _resubscribe() {\n        if (this.shardedSubscribers) {\n            this.shardedSubscribers.forEach((s, nodeKey) => {\n                const subscriberSlots = this.subscriberToSlotsIndex.get(nodeKey);\n                if (subscriberSlots) {\n                    //Resubscribe on the underlying connection\n                    subscriberSlots.forEach((ss) => {\n                        //Might return null if being disconnected\n                        const redis = s.getInstance();\n                        const channels = this.channels.get(ss);\n                        if (channels && channels.length > 0) {\n                            if (!redis || redis.status === \"end\") {\n                                return;\n                            }\n                            if (redis.status === \"ready\") {\n                                redis.ssubscribe(...channels).catch((err) => {\n                                    // TODO: Should we emit an error event here?\n                                    debug(\"Failed to ssubscribe on node %s: %s\", nodeKey, err);\n                                });\n                            }\n                            else {\n                                redis.once(\"ready\", () => {\n                                    redis.ssubscribe(...channels).catch((err) => {\n                                        // TODO: Should we emit an error event here?\n                                        debug(\"Failed to ssubscribe on node %s: %s\", nodeKey, err);\n                                    });\n                                });\n                            }\n                        }\n                    });\n                }\n            });\n        }\n    }\n    /**\n     * Deep equality of the cluster slots objects\n     *\n     * @param other\n     * @private\n     */\n    _slotsAreEqual(other) {\n        if (this.clusterSlots === undefined) {\n            return false;\n        }\n        else {\n            return JSON.stringify(this.clusterSlots) === JSON.stringify(other);\n        }\n    }\n    /**\n     * Checks if any subscribers are in an unhealthy state.\n     *\n     * A subscriber is considered unhealthy if:\n     * - It exists but is not started (failed/disconnected)\n     * - It's missing entirely for a node that should have one\n     *\n     * @returns true if any subscribers need to be recreated\n     */\n    hasUnhealthySubscribers() {\n        const hasFailedSubscribers = Array.from(this.shardedSubscribers.values()).some((sub) => !sub.isHealthy());\n        const hasMissingSubscribers = Array.from(this.subscriberToSlotsIndex.keys()).some((nodeKey) => !this.shardedSubscribers.has(nodeKey));\n        return hasFailedSubscribers || hasMissingSubscribers;\n    }\n    shouldStartSubscriber(sub) {\n        if (sub.isStarted()) {\n            return false;\n        }\n        if (!sub.isLazyConnect()) {\n            return true;\n        }\n        const subscriberSlots = this.subscriberToSlotsIndex.get(sub.getNodeKey());\n        if (!subscriberSlots) {\n            return false;\n        }\n        return subscriberSlots.some((slot) => {\n            const channels = this.channels.get(slot);\n            return Boolean(channels && channels.length > 0);\n        });\n    }\n}\nexports.default = ClusterSubscriberGroup;\n// Retry strategy\nClusterSubscriberGroup.MAX_RETRY_ATTEMPTS = 10;\nClusterSubscriberGroup.MAX_BACKOFF_MS = 2000;\nClusterSubscriberGroup.BASE_BACKOFF_MS = 100;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst commands_1 = require(\"@ioredis/commands\");\nconst events_1 = require(\"events\");\nconst redis_errors_1 = require(\"redis-errors\");\nconst standard_as_callback_1 = require(\"standard-as-callback\");\nconst Command_1 = require(\"../Command\");\nconst ClusterAllFailedError_1 = require(\"../errors/ClusterAllFailedError\");\nconst Redis_1 = require(\"../Redis\");\nconst ScanStream_1 = require(\"../ScanStream\");\nconst transaction_1 = require(\"../transaction\");\nconst utils_1 = require(\"../utils\");\nconst applyMixin_1 = require(\"../utils/applyMixin\");\nconst Commander_1 = require(\"../utils/Commander\");\nconst ClusterOptions_1 = require(\"./ClusterOptions\");\nconst ClusterSubscriber_1 = require(\"./ClusterSubscriber\");\nconst ConnectionPool_1 = require(\"./ConnectionPool\");\nconst DelayQueue_1 = require(\"./DelayQueue\");\nconst util_1 = require(\"./util\");\nconst Deque = require(\"denque\");\nconst ClusterSubscriberGroup_1 = require(\"./ClusterSubscriberGroup\");\nconst debug = (0, utils_1.Debug)(\"cluster\");\nconst REJECT_OVERWRITTEN_COMMANDS = new WeakSet();\n/**\n * Client for the official Redis Cluster\n */\nclass Cluster extends Commander_1.default {\n    /**\n     * Creates an instance of Cluster.\n     */\n    //TODO: Add an option that enables or disables sharded PubSub\n    constructor(startupNodes, options = {}) {\n        var _a;\n        super();\n        this.slots = [];\n        /**\n         * @ignore\n         */\n        this._groupsIds = {};\n        /**\n         * @ignore\n         */\n        this._groupsBySlot = Array(16384);\n        /**\n         * @ignore\n         */\n        this.isCluster = true;\n        this.retryAttempts = 0;\n        this.delayQueue = new DelayQueue_1.default();\n        this.offlineQueue = new Deque();\n        this.isRefreshing = false;\n        this._refreshSlotsCacheCallbacks = [];\n        this._autoPipelines = new Map();\n        this._runningAutoPipelines = new Set();\n        this._readyDelayedCallbacks = [];\n        /**\n         * Every time Cluster#connect() is called, this value will be\n         * auto-incrementing. The purpose of this value is used for\n         * discarding previous connect attampts when creating a new\n         * connection.\n         */\n        this.connectionEpoch = 0;\n        events_1.EventEmitter.call(this);\n        this.startupNodes = startupNodes;\n        this.options = (0, utils_1.defaults)({}, options, ClusterOptions_1.DEFAULT_CLUSTER_OPTIONS, this.options);\n        if (this.options.shardedSubscribers) {\n            this.createShardedSubscriberGroup();\n        }\n        if (this.options.redisOptions &&\n            this.options.redisOptions.keyPrefix &&\n            !this.options.keyPrefix) {\n            this.options.keyPrefix = this.options.redisOptions.keyPrefix;\n        }\n        // validate options\n        if (typeof this.options.scaleReads !== \"function\" &&\n            [\"all\", \"master\", \"slave\"].indexOf(this.options.scaleReads) === -1) {\n            throw new Error('Invalid option scaleReads \"' +\n                this.options.scaleReads +\n                '\". Expected \"all\", \"master\", \"slave\" or a custom function');\n        }\n        this.connectionPool = new ConnectionPool_1.default((_a = this.options.redisOptions) !== null && _a !== void 0 ? _a : {}, this.options.clusterNodeRetryStrategy);\n        this.connectionPool.on(\"-node\", (redis, key) => {\n            this.emit(\"-node\", redis);\n        });\n        this.connectionPool.on(\"+node\", (redis) => {\n            this.emit(\"+node\", redis);\n        });\n        this.connectionPool.on(\"drain\", () => {\n            this.setStatus(\"close\");\n        });\n        this.connectionPool.on(\"nodeError\", (error, key) => {\n            this.emit(\"node error\", error, key);\n        });\n        this.subscriber = new ClusterSubscriber_1.default(this.connectionPool, this);\n        if (this.options.scripts) {\n            Object.entries(this.options.scripts).forEach(([name, definition]) => {\n                this.defineCommand(name, definition);\n            });\n        }\n        if (this.options.lazyConnect) {\n            this.setStatus(\"wait\");\n        }\n        else {\n            this.connect().catch((err) => {\n                debug(\"connecting failed: %s\", err);\n            });\n        }\n    }\n    /**\n     * Connect to a cluster\n     */\n    connect() {\n        return new Promise((resolve, reject) => {\n            if (this.status === \"connecting\" ||\n                this.status === \"connect\" ||\n                this.status === \"ready\") {\n                reject(new Error(\"Redis is already connecting/connected\"));\n                return;\n            }\n            const epoch = ++this.connectionEpoch;\n            this.setStatus(\"connecting\");\n            this.resolveStartupNodeHostnames()\n                .then((nodes) => {\n                if (this.connectionEpoch !== epoch) {\n                    debug(\"discard connecting after resolving startup nodes because epoch not match: %d != %d\", epoch, this.connectionEpoch);\n                    reject(new redis_errors_1.RedisError(\"Connection is discarded because a new connection is made\"));\n                    return;\n                }\n                if (this.status !== \"connecting\") {\n                    debug(\"discard connecting after resolving startup nodes because the status changed to %s\", this.status);\n                    reject(new redis_errors_1.RedisError(\"Connection is aborted\"));\n                    return;\n                }\n                this.connectionPool.reset(nodes);\n                if (this.options.shardedSubscribers) {\n                    this.shardedSubscribers\n                        .reset(this.slots, this.connectionPool.getNodes(\"all\"))\n                        .catch((err) => {\n                        // TODO should we emit an error event here?\n                        debug(\"Error while starting subscribers: %s\", err);\n                    });\n                }\n                const readyHandler = () => {\n                    this.setStatus(\"ready\");\n                    this.retryAttempts = 0;\n                    this.executeOfflineCommands();\n                    this.resetNodesRefreshInterval();\n                    resolve();\n                };\n                let closeListener = undefined;\n                const refreshListener = () => {\n                    this.invokeReadyDelayedCallbacks(undefined);\n                    this.removeListener(\"close\", closeListener);\n                    this.manuallyClosing = false;\n                    this.setStatus(\"connect\");\n                    if (this.options.enableReadyCheck) {\n                        this.readyCheck((err, fail) => {\n                            if (err || fail) {\n                                debug(\"Ready check failed (%s). Reconnecting...\", err || fail);\n                                if (this.status === \"connect\") {\n                                    this.disconnect(true);\n                                }\n                            }\n                            else {\n                                readyHandler();\n                            }\n                        });\n                    }\n                    else {\n                        readyHandler();\n                    }\n                };\n                closeListener = () => {\n                    const error = new Error(\"None of startup nodes is available\");\n                    this.removeListener(\"refresh\", refreshListener);\n                    this.invokeReadyDelayedCallbacks(error);\n                    reject(error);\n                };\n                this.once(\"refresh\", refreshListener);\n                this.once(\"close\", closeListener);\n                this.once(\"close\", this.handleCloseEvent.bind(this));\n                this.refreshSlotsCache((err) => {\n                    if (err && err.message === ClusterAllFailedError_1.default.defaultMessage) {\n                        Redis_1.default.prototype.silentEmit.call(this, \"error\", err);\n                        this.connectionPool.reset([]);\n                    }\n                });\n                this.subscriber.start();\n                if (this.options.shardedSubscribers) {\n                    this.shardedSubscribers.start().catch((err) => {\n                        // TODO should we emit an error event here?\n                        debug(\"Error while starting subscribers: %s\", err);\n                    });\n                }\n            })\n                .catch((err) => {\n                this.setStatus(\"close\");\n                this.handleCloseEvent(err);\n                this.invokeReadyDelayedCallbacks(err);\n                reject(err);\n            });\n        });\n    }\n    /**\n     * Disconnect from every node in the cluster.\n     */\n    disconnect(reconnect = false) {\n        const status = this.status;\n        this.setStatus(\"disconnecting\");\n        if (!reconnect) {\n            this.manuallyClosing = true;\n        }\n        if (this.reconnectTimeout && !reconnect) {\n            clearTimeout(this.reconnectTimeout);\n            this.reconnectTimeout = null;\n            debug(\"Canceled reconnecting attempts\");\n        }\n        this.clearNodesRefreshInterval();\n        this.subscriber.stop();\n        if (this.options.shardedSubscribers) {\n            this.shardedSubscribers.stop();\n        }\n        if (status === \"wait\") {\n            this.setStatus(\"close\");\n            this.handleCloseEvent();\n        }\n        else {\n            this.connectionPool.reset([]);\n        }\n    }\n    /**\n     * Quit the cluster gracefully.\n     */\n    quit(callback) {\n        const status = this.status;\n        this.setStatus(\"disconnecting\");\n        this.manuallyClosing = true;\n        if (this.reconnectTimeout) {\n            clearTimeout(this.reconnectTimeout);\n            this.reconnectTimeout = null;\n        }\n        this.clearNodesRefreshInterval();\n        this.subscriber.stop();\n        if (this.options.shardedSubscribers) {\n            this.shardedSubscribers.stop();\n        }\n        if (status === \"wait\") {\n            const ret = (0, standard_as_callback_1.default)(Promise.resolve(\"OK\"), callback);\n            // use setImmediate to make sure \"close\" event\n            // being emitted after quit() is returned\n            setImmediate(function () {\n                this.setStatus(\"close\");\n                this.handleCloseEvent();\n            }.bind(this));\n            return ret;\n        }\n        return (0, standard_as_callback_1.default)(Promise.all(this.nodes().map((node) => node.quit().catch((err) => {\n            // Ignore the error caused by disconnecting since\n            // we're disconnecting...\n            if (err.message === utils_1.CONNECTION_CLOSED_ERROR_MSG) {\n                return \"OK\";\n            }\n            throw err;\n        }))).then(() => \"OK\"), callback);\n    }\n    /**\n     * Create a new instance with the same startup nodes and options as the current one.\n     *\n     * @example\n     * ```js\n     * var cluster = new Redis.Cluster([{ host: \"127.0.0.1\", port: \"30001\" }]);\n     * var anotherCluster = cluster.duplicate();\n     * ```\n     */\n    duplicate(overrideStartupNodes = [], overrideOptions = {}) {\n        const startupNodes = overrideStartupNodes.length > 0\n            ? overrideStartupNodes\n            : this.startupNodes.slice(0);\n        const options = Object.assign({}, this.options, overrideOptions);\n        return new Cluster(startupNodes, options);\n    }\n    /**\n     * Get nodes with the specified role\n     */\n    nodes(role = \"all\") {\n        if (role !== \"all\" && role !== \"master\" && role !== \"slave\") {\n            throw new Error('Invalid role \"' + role + '\". Expected \"all\", \"master\" or \"slave\"');\n        }\n        return this.connectionPool.getNodes(role);\n    }\n    /**\n     * This is needed in order not to install a listener for each auto pipeline\n     *\n     * @ignore\n     */\n    delayUntilReady(callback) {\n        this._readyDelayedCallbacks.push(callback);\n    }\n    /**\n     * Get the number of commands queued in automatic pipelines.\n     *\n     * This is not available (and returns 0) until the cluster is connected and slots information have been received.\n     */\n    get autoPipelineQueueSize() {\n        let queued = 0;\n        for (const pipeline of this._autoPipelines.values()) {\n            queued += pipeline.length;\n        }\n        return queued;\n    }\n    /**\n     * Refresh the slot cache\n     *\n     * @ignore\n     */\n    refreshSlotsCache(callback) {\n        if (callback) {\n            this._refreshSlotsCacheCallbacks.push(callback);\n        }\n        if (this.isRefreshing) {\n            return;\n        }\n        this.isRefreshing = true;\n        const _this = this;\n        const wrapper = (error) => {\n            this.isRefreshing = false;\n            for (const callback of this._refreshSlotsCacheCallbacks) {\n                callback(error);\n            }\n            this._refreshSlotsCacheCallbacks = [];\n        };\n        const nodes = (0, utils_1.shuffle)(this.connectionPool.getNodes());\n        let lastNodeError = null;\n        function tryNode(index) {\n            if (index === nodes.length) {\n                const error = new ClusterAllFailedError_1.default(ClusterAllFailedError_1.default.defaultMessage, lastNodeError);\n                return wrapper(error);\n            }\n            const node = nodes[index];\n            const key = `${node.options.host}:${node.options.port}`;\n            debug(\"getting slot cache from %s\", key);\n            _this.getInfoFromNode(node, function (err) {\n                switch (_this.status) {\n                    case \"close\":\n                    case \"end\":\n                        return wrapper(new Error(\"Cluster is disconnected.\"));\n                    case \"disconnecting\":\n                        return wrapper(new Error(\"Cluster is disconnecting.\"));\n                }\n                if (err) {\n                    _this.emit(\"node error\", err, key);\n                    lastNodeError = err;\n                    tryNode(index + 1);\n                }\n                else {\n                    _this.emit(\"refresh\");\n                    wrapper();\n                }\n            });\n        }\n        tryNode(0);\n    }\n    /**\n     * @ignore\n     */\n    sendCommand(command, stream, node) {\n        if (this.status === \"wait\") {\n            this.connect().catch(utils_1.noop);\n        }\n        if (this.status === \"end\") {\n            command.reject(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG));\n            return command.promise;\n        }\n        let to = this.options.scaleReads;\n        if (to !== \"master\") {\n            const isCommandReadOnly = command.isReadOnly ||\n                ((0, commands_1.exists)(command.name) && (0, commands_1.hasFlag)(command.name, \"readonly\"));\n            if (!isCommandReadOnly) {\n                to = \"master\";\n            }\n        }\n        let targetSlot = node ? node.slot : command.getSlot();\n        const ttl = {};\n        const _this = this;\n        if (!node && !REJECT_OVERWRITTEN_COMMANDS.has(command)) {\n            REJECT_OVERWRITTEN_COMMANDS.add(command);\n            const reject = command.reject;\n            command.reject = function (err) {\n                const partialTry = tryConnection.bind(null, true);\n                _this.handleError(err, ttl, {\n                    moved: function (slot, key) {\n                        debug(\"command %s is moved to %s\", command.name, key);\n                        targetSlot = Number(slot);\n                        if (_this.slots[slot]) {\n                            _this.slots[slot][0] = key;\n                        }\n                        else {\n                            _this.slots[slot] = [key];\n                        }\n                        _this._groupsBySlot[slot] =\n                            _this._groupsIds[_this.slots[slot].join(\";\")];\n                        _this.connectionPool.findOrCreate(_this.natMapper(key));\n                        tryConnection();\n                        debug(\"refreshing slot caches... (triggered by MOVED error)\");\n                        _this.refreshSlotsCache();\n                    },\n                    ask: function (slot, key) {\n                        debug(\"command %s is required to ask %s:%s\", command.name, key);\n                        const mapped = _this.natMapper(key);\n                        _this.connectionPool.findOrCreate(mapped);\n                        tryConnection(false, `${mapped.host}:${mapped.port}`);\n                    },\n                    tryagain: partialTry,\n                    clusterDown: partialTry,\n                    connectionClosed: partialTry,\n                    maxRedirections: function (redirectionError) {\n                        reject.call(command, redirectionError);\n                    },\n                    defaults: function () {\n                        reject.call(command, err);\n                    },\n                });\n            };\n        }\n        tryConnection();\n        function tryConnection(random, asking) {\n            if (_this.status === \"end\") {\n                command.reject(new redis_errors_1.AbortError(\"Cluster is ended.\"));\n                return;\n            }\n            let redis;\n            if (_this.status === \"ready\" || command.name === \"cluster\") {\n                if (node && node.redis) {\n                    redis = node.redis;\n                }\n                else if (Command_1.default.checkFlag(\"ENTER_SUBSCRIBER_MODE\", command.name) ||\n                    Command_1.default.checkFlag(\"EXIT_SUBSCRIBER_MODE\", command.name)) {\n                    if (_this.options.shardedSubscribers &&\n                        (command.name == \"ssubscribe\" || command.name == \"sunsubscribe\")) {\n                        const sub = _this.shardedSubscribers.getResponsibleSubscriber(targetSlot);\n                        if (!sub) {\n                            command.reject(new redis_errors_1.AbortError(`No sharded subscriber for slot: ${targetSlot}`));\n                            return;\n                        }\n                        let status = -1;\n                        if (command.name == \"ssubscribe\") {\n                            status = _this.shardedSubscribers.addChannels(command.getKeys());\n                        }\n                        if (command.name == \"sunsubscribe\") {\n                            status = _this.shardedSubscribers.removeChannels(command.getKeys());\n                        }\n                        if (status !== -1) {\n                            redis = sub.getInstance();\n                        }\n                        else {\n                            command.reject(new redis_errors_1.AbortError(\"Possible CROSSSLOT error: All channels must hash to the same slot\"));\n                        }\n                    }\n                    else {\n                        redis = _this.subscriber.getInstance();\n                    }\n                    if (!redis) {\n                        command.reject(new redis_errors_1.AbortError(\"No subscriber for the cluster\"));\n                        return;\n                    }\n                }\n                else {\n                    if (!random) {\n                        if (typeof targetSlot === \"number\" && _this.slots[targetSlot]) {\n                            const nodeKeys = _this.slots[targetSlot];\n                            if (typeof to === \"function\") {\n                                const nodes = nodeKeys.map(function (key) {\n                                    return _this.connectionPool.getInstanceByKey(key);\n                                });\n                                redis = to(nodes, command);\n                                if (Array.isArray(redis)) {\n                                    redis = (0, utils_1.sample)(redis);\n                                }\n                                if (!redis) {\n                                    redis = nodes[0];\n                                }\n                            }\n                            else {\n                                let key;\n                                if (to === \"all\") {\n                                    key = (0, utils_1.sample)(nodeKeys);\n                                }\n                                else if (to === \"slave\" && nodeKeys.length > 1) {\n                                    key = (0, utils_1.sample)(nodeKeys, 1);\n                                }\n                                else {\n                                    key = nodeKeys[0];\n                                }\n                                redis = _this.connectionPool.getInstanceByKey(key);\n                            }\n                        }\n                        if (asking) {\n                            redis = _this.connectionPool.getInstanceByKey(asking);\n                            redis.asking();\n                        }\n                    }\n                    if (!redis) {\n                        redis =\n                            (typeof to === \"function\"\n                                ? null\n                                : _this.connectionPool.getSampleInstance(to)) ||\n                                _this.connectionPool.getSampleInstance(\"all\");\n                    }\n                    if (redis &&\n                        !_this.options.enableOfflineQueue &&\n                        redis.status !== \"ready\" &&\n                        redis.status !== \"wait\") {\n                        command.reject(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG));\n                        return;\n                    }\n                }\n                if (node && !node.redis) {\n                    node.redis = redis;\n                }\n            }\n            if (!redis && _this.options.enableOfflineQueue) {\n                _this.offlineQueue.push({\n                    command: command,\n                    stream: stream,\n                    node: node,\n                });\n                return;\n            }\n            if (!redis) {\n                command.reject(new Error(\"Cluster isn't ready and enableOfflineQueue options is false\"));\n                return;\n            }\n            redis.sendCommand(command, stream);\n        }\n        return command.promise;\n    }\n    sscanStream(key, options) {\n        return this.createScanStream(\"sscan\", { key, options });\n    }\n    sscanBufferStream(key, options) {\n        return this.createScanStream(\"sscanBuffer\", { key, options });\n    }\n    hscanStream(key, options) {\n        return this.createScanStream(\"hscan\", { key, options });\n    }\n    hscanBufferStream(key, options) {\n        return this.createScanStream(\"hscanBuffer\", { key, options });\n    }\n    zscanStream(key, options) {\n        return this.createScanStream(\"zscan\", { key, options });\n    }\n    zscanBufferStream(key, options) {\n        return this.createScanStream(\"zscanBuffer\", { key, options });\n    }\n    /**\n     * @ignore\n     */\n    handleError(error, ttl, handlers) {\n        if (typeof ttl.value === \"undefined\") {\n            ttl.value = this.options.maxRedirections;\n        }\n        else {\n            ttl.value -= 1;\n        }\n        if (ttl.value <= 0) {\n            handlers.maxRedirections(new Error(\"Too many Cluster redirections. Last error: \" + error));\n            return;\n        }\n        const errv = error.message.split(\" \");\n        if (errv[0] === \"MOVED\") {\n            const timeout = this.options.retryDelayOnMoved;\n            if (timeout && typeof timeout === \"number\") {\n                this.delayQueue.push(\"moved\", handlers.moved.bind(null, errv[1], errv[2]), { timeout });\n            }\n            else {\n                handlers.moved(errv[1], errv[2]);\n            }\n        }\n        else if (errv[0] === \"ASK\") {\n            handlers.ask(errv[1], errv[2]);\n        }\n        else if (errv[0] === \"TRYAGAIN\") {\n            this.delayQueue.push(\"tryagain\", handlers.tryagain, {\n                timeout: this.options.retryDelayOnTryAgain,\n            });\n        }\n        else if (errv[0] === \"CLUSTERDOWN\" &&\n            this.options.retryDelayOnClusterDown > 0) {\n            this.delayQueue.push(\"clusterdown\", handlers.connectionClosed, {\n                timeout: this.options.retryDelayOnClusterDown,\n                callback: this.refreshSlotsCache.bind(this),\n            });\n        }\n        else if (error.message === utils_1.CONNECTION_CLOSED_ERROR_MSG &&\n            this.options.retryDelayOnFailover > 0 &&\n            this.status === \"ready\") {\n            this.delayQueue.push(\"failover\", handlers.connectionClosed, {\n                timeout: this.options.retryDelayOnFailover,\n                callback: this.refreshSlotsCache.bind(this),\n            });\n        }\n        else {\n            handlers.defaults();\n        }\n    }\n    resetOfflineQueue() {\n        this.offlineQueue = new Deque();\n    }\n    clearNodesRefreshInterval() {\n        if (this.slotsTimer) {\n            clearTimeout(this.slotsTimer);\n            this.slotsTimer = null;\n        }\n    }\n    resetNodesRefreshInterval() {\n        if (this.slotsTimer || !this.options.slotsRefreshInterval) {\n            return;\n        }\n        const nextRound = () => {\n            this.slotsTimer = setTimeout(() => {\n                debug('refreshing slot caches... (triggered by \"slotsRefreshInterval\" option)');\n                this.refreshSlotsCache(() => {\n                    nextRound();\n                });\n            }, this.options.slotsRefreshInterval);\n        };\n        nextRound();\n    }\n    /**\n     * Change cluster instance's status\n     */\n    setStatus(status) {\n        debug(\"status: %s -> %s\", this.status || \"[empty]\", status);\n        this.status = status;\n        process.nextTick(() => {\n            this.emit(status);\n        });\n    }\n    /**\n     * Called when closed to check whether a reconnection should be made\n     */\n    handleCloseEvent(reason) {\n        var _a;\n        if (reason) {\n            debug(\"closed because %s\", reason);\n        }\n        let retryDelay;\n        if (!this.manuallyClosing &&\n            typeof this.options.clusterRetryStrategy === \"function\") {\n            retryDelay = this.options.clusterRetryStrategy.call(this, ++this.retryAttempts, reason);\n        }\n        if (typeof retryDelay === \"number\") {\n            this.setStatus(\"reconnecting\");\n            this.reconnectTimeout = setTimeout(() => {\n                this.reconnectTimeout = null;\n                debug(\"Cluster is disconnected. Retrying after %dms\", retryDelay);\n                this.connect().catch(function (err) {\n                    debug(\"Got error %s when reconnecting. Ignoring...\", err);\n                });\n            }, retryDelay);\n        }\n        else {\n            if (this.options.shardedSubscribers) {\n                (_a = this.subscriberGroupEmitter) === null || _a === void 0 ? void 0 : _a.removeAllListeners();\n            }\n            this.setStatus(\"end\");\n            this.flushQueue(new Error(\"None of startup nodes is available\"));\n        }\n    }\n    /**\n     * Flush offline queue with error.\n     */\n    flushQueue(error) {\n        let item;\n        while ((item = this.offlineQueue.shift())) {\n            item.command.reject(error);\n        }\n    }\n    executeOfflineCommands() {\n        if (this.offlineQueue.length) {\n            debug(\"send %d commands in offline queue\", this.offlineQueue.length);\n            const offlineQueue = this.offlineQueue;\n            this.resetOfflineQueue();\n            let item;\n            while ((item = offlineQueue.shift())) {\n                this.sendCommand(item.command, item.stream, item.node);\n            }\n        }\n    }\n    natMapper(nodeKey) {\n        const key = typeof nodeKey === \"string\"\n            ? nodeKey\n            : `${nodeKey.host}:${nodeKey.port}`;\n        let mapped = null;\n        if (this.options.natMap && typeof this.options.natMap === \"function\") {\n            mapped = this.options.natMap(key);\n        }\n        else if (this.options.natMap && typeof this.options.natMap === \"object\") {\n            mapped = this.options.natMap[key];\n        }\n        if (mapped) {\n            debug(\"NAT mapping %s -> %O\", key, mapped);\n            return Object.assign({}, mapped);\n        }\n        return typeof nodeKey === \"string\"\n            ? (0, util_1.nodeKeyToRedisOptions)(nodeKey)\n            : nodeKey;\n    }\n    getInfoFromNode(redis, callback) {\n        if (!redis) {\n            return callback(new Error(\"Node is disconnected\"));\n        }\n        // Use a duplication of the connection to avoid\n        // timeouts when the connection is in the blocking\n        // mode (e.g. waiting for BLPOP).\n        const duplicatedConnection = redis.duplicate({\n            enableOfflineQueue: true,\n            enableReadyCheck: false,\n            retryStrategy: null,\n            connectionName: (0, util_1.getConnectionName)(\"refresher\", this.options.redisOptions && this.options.redisOptions.connectionName),\n        });\n        // Ignore error events since we will handle\n        // exceptions for the CLUSTER SLOTS command.\n        duplicatedConnection.on(\"error\", utils_1.noop);\n        duplicatedConnection.cluster(\"SLOTS\", (0, utils_1.timeout)((err, result) => {\n            duplicatedConnection.disconnect();\n            if (err) {\n                debug(\"error encountered running CLUSTER.SLOTS: %s\", err);\n                return callback(err);\n            }\n            if (this.status === \"disconnecting\" ||\n                this.status === \"close\" ||\n                this.status === \"end\") {\n                debug(\"ignore CLUSTER.SLOTS results (count: %d) since cluster status is %s\", result.length, this.status);\n                callback();\n                return;\n            }\n            const nodes = [];\n            debug(\"cluster slots result count: %d\", result.length);\n            for (let i = 0; i < result.length; ++i) {\n                const items = result[i];\n                const slotRangeStart = items[0];\n                const slotRangeEnd = items[1];\n                const keys = [];\n                for (let j = 2; j < items.length; j++) {\n                    if (!items[j][0]) {\n                        continue;\n                    }\n                    const node = this.natMapper({\n                        host: items[j][0],\n                        port: items[j][1],\n                    });\n                    node.readOnly = j !== 2;\n                    nodes.push(node);\n                    keys.push(node.host + \":\" + node.port);\n                }\n                debug(\"cluster slots result [%d]: slots %d~%d served by %s\", i, slotRangeStart, slotRangeEnd, keys);\n                for (let slot = slotRangeStart; slot <= slotRangeEnd; slot++) {\n                    this.slots[slot] = keys;\n                }\n            }\n            // Assign to each node keys a numeric value to make autopipeline comparison faster.\n            this._groupsIds = Object.create(null);\n            let j = 0;\n            for (let i = 0; i < 16384; i++) {\n                const target = (this.slots[i] || []).join(\";\");\n                if (!target.length) {\n                    this._groupsBySlot[i] = undefined;\n                    continue;\n                }\n                if (!this._groupsIds[target]) {\n                    this._groupsIds[target] = ++j;\n                }\n                this._groupsBySlot[i] = this._groupsIds[target];\n            }\n            this.connectionPool.reset(nodes);\n            if (this.options.shardedSubscribers) {\n                this.shardedSubscribers\n                    .reset(this.slots, this.connectionPool.getNodes(\"all\"))\n                    .catch((err) => {\n                    // TODO should we emit an error event here?\n                    debug(\"Error while starting subscribers: %s\", err);\n                });\n            }\n            callback();\n        }, this.options.slotsRefreshTimeout));\n    }\n    invokeReadyDelayedCallbacks(err) {\n        for (const c of this._readyDelayedCallbacks) {\n            process.nextTick(c, err);\n        }\n        this._readyDelayedCallbacks = [];\n    }\n    /**\n     * Check whether Cluster is able to process commands\n     */\n    readyCheck(callback) {\n        this.cluster(\"INFO\", (err, res) => {\n            if (err) {\n                return callback(err);\n            }\n            if (typeof res !== \"string\") {\n                return callback();\n            }\n            let state;\n            const lines = res.split(\"\\r\\n\");\n            for (let i = 0; i < lines.length; ++i) {\n                const parts = lines[i].split(\":\");\n                if (parts[0] === \"cluster_state\") {\n                    state = parts[1];\n                    break;\n                }\n            }\n            if (state === \"fail\") {\n                debug(\"cluster state not ok (%s)\", state);\n                callback(null, state);\n            }\n            else {\n                callback();\n            }\n        });\n    }\n    resolveSrv(hostname) {\n        return new Promise((resolve, reject) => {\n            this.options.resolveSrv(hostname, (err, records) => {\n                if (err) {\n                    return reject(err);\n                }\n                const self = this, groupedRecords = (0, util_1.groupSrvRecords)(records), sortedKeys = Object.keys(groupedRecords).sort((a, b) => parseInt(a) - parseInt(b));\n                function tryFirstOne(err) {\n                    if (!sortedKeys.length) {\n                        return reject(err);\n                    }\n                    const key = sortedKeys[0], group = groupedRecords[key], record = (0, util_1.weightSrvRecords)(group);\n                    if (!group.records.length) {\n                        sortedKeys.shift();\n                    }\n                    self.dnsLookup(record.name).then((host) => resolve({\n                        host,\n                        port: record.port,\n                    }), tryFirstOne);\n                }\n                tryFirstOne();\n            });\n        });\n    }\n    dnsLookup(hostname) {\n        return new Promise((resolve, reject) => {\n            this.options.dnsLookup(hostname, (err, address) => {\n                if (err) {\n                    debug(\"failed to resolve hostname %s to IP: %s\", hostname, err.message);\n                    reject(err);\n                }\n                else {\n                    debug(\"resolved hostname %s to IP %s\", hostname, address);\n                    resolve(address);\n                }\n            });\n        });\n    }\n    /**\n     * Normalize startup nodes, and resolving hostnames to IPs.\n     *\n     * This process happens every time when #connect() is called since\n     * #startupNodes and DNS records may chanage.\n     */\n    async resolveStartupNodeHostnames() {\n        if (!Array.isArray(this.startupNodes) || this.startupNodes.length === 0) {\n            throw new Error(\"`startupNodes` should contain at least one node.\");\n        }\n        const startupNodes = (0, util_1.normalizeNodeOptions)(this.startupNodes);\n        const hostnames = (0, util_1.getUniqueHostnamesFromOptions)(startupNodes);\n        if (hostnames.length === 0) {\n            return startupNodes;\n        }\n        const configs = await Promise.all(hostnames.map((this.options.useSRVRecords ? this.resolveSrv : this.dnsLookup).bind(this)));\n        const hostnameToConfig = (0, utils_1.zipMap)(hostnames, configs);\n        return startupNodes.map((node) => {\n            const config = hostnameToConfig.get(node.host);\n            if (!config) {\n                return node;\n            }\n            if (this.options.useSRVRecords) {\n                return Object.assign({}, node, config);\n            }\n            return Object.assign({}, node, { host: config });\n        });\n    }\n    createScanStream(command, { key, options = {} }) {\n        return new ScanStream_1.default({\n            objectMode: true,\n            key: key,\n            redis: this,\n            command: command,\n            ...options,\n        });\n    }\n    createShardedSubscriberGroup() {\n        this.subscriberGroupEmitter = new events_1.EventEmitter();\n        this.shardedSubscribers = new ClusterSubscriberGroup_1.default(this.subscriberGroupEmitter, this.options);\n        // Error handler used only for sharded-subscriber-triggered slots cache refreshes.\n        // Normal (non-subscriber) connections are created with lazyConnect: true and can\n        // become zombied. For sharded subscribers, a ClusterAllFailedError means\n        // we have lost all nodes from the subscriber perspective and must tear down.\n        const refreshSlotsCacheCallback = (err) => {\n            // Disconnect only when refreshing the slots cache fails with ClusterAllFailedError\n            if (err instanceof ClusterAllFailedError_1.default) {\n                this.disconnect(true);\n            }\n        };\n        this.subscriberGroupEmitter.on(\"-node\", (redis, nodeKey) => {\n            this.emit(\"-node\", redis, nodeKey);\n            this.refreshSlotsCache(refreshSlotsCacheCallback);\n        });\n        this.subscriberGroupEmitter.on(\"subscriberConnectFailed\", ({ delay, error }) => {\n            this.emit(\"error\", error);\n            setTimeout(() => {\n                this.refreshSlotsCache(refreshSlotsCacheCallback);\n            }, delay);\n        });\n        this.subscriberGroupEmitter.on(\"moved\", () => {\n            this.refreshSlotsCache(refreshSlotsCacheCallback);\n        });\n        this.subscriberGroupEmitter.on(\"-subscriber\", () => {\n            this.emit(\"-subscriber\");\n        });\n        this.subscriberGroupEmitter.on(\"+subscriber\", () => {\n            this.emit(\"+subscriber\");\n        });\n        this.subscriberGroupEmitter.on(\"nodeError\", (error, nodeKey) => {\n            this.emit(\"nodeError\", error, nodeKey);\n        });\n        this.subscriberGroupEmitter.on(\"subscribersReady\", () => {\n            this.emit(\"subscribersReady\");\n        });\n        for (const event of [\"smessage\", \"smessageBuffer\"]) {\n            this.subscriberGroupEmitter.on(event, (arg1, arg2, arg3) => {\n                this.emit(event, arg1, arg2, arg3);\n            });\n        }\n    }\n}\n(0, applyMixin_1.default)(Cluster, events_1.EventEmitter);\n(0, transaction_1.addTransactionSupport)(Cluster.prototype);\nexports.default = Cluster;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst utils_1 = require(\"../utils\");\nconst debug = (0, utils_1.Debug)(\"AbstractConnector\");\nclass AbstractConnector {\n    constructor(disconnectTimeout) {\n        this.connecting = false;\n        this.disconnectTimeout = disconnectTimeout;\n    }\n    check(info) {\n        return true;\n    }\n    disconnect() {\n        this.connecting = false;\n        if (this.stream) {\n            const stream = this.stream; // Make sure callbacks refer to the same instance\n            const timeout = setTimeout(() => {\n                debug(\"stream %s:%s still open, destroying it\", stream.remoteAddress, stream.remotePort);\n                stream.destroy();\n            }, this.disconnectTimeout);\n            stream.on(\"close\", () => clearTimeout(timeout));\n            stream.end();\n        }\n    }\n}\nexports.default = AbstractConnector;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst net_1 = require(\"net\");\nconst tls_1 = require(\"tls\");\nconst utils_1 = require(\"../utils\");\nconst AbstractConnector_1 = require(\"./AbstractConnector\");\nclass StandaloneConnector extends AbstractConnector_1.default {\n    constructor(options) {\n        super(options.disconnectTimeout);\n        this.options = options;\n    }\n    connect(_) {\n        const { options } = this;\n        this.connecting = true;\n        let connectionOptions;\n        if (\"path\" in options && options.path) {\n            connectionOptions = {\n                path: options.path,\n            };\n        }\n        else {\n            connectionOptions = {};\n            if (\"port\" in options && options.port != null) {\n                connectionOptions.port = options.port;\n            }\n            if (\"host\" in options && options.host != null) {\n                connectionOptions.host = options.host;\n            }\n            if (\"family\" in options && options.family != null) {\n                connectionOptions.family = options.family;\n            }\n        }\n        if (options.tls) {\n            Object.assign(connectionOptions, options.tls);\n        }\n        // TODO:\n        // We use native Promise here since other Promise\n        // implementation may use different schedulers that\n        // cause issue when the stream is resolved in the\n        // next tick.\n        // Should use the provided promise in the next major\n        // version and do not connect before resolved.\n        return new Promise((resolve, reject) => {\n            process.nextTick(() => {\n                if (!this.connecting) {\n                    reject(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG));\n                    return;\n                }\n                try {\n                    if (options.tls) {\n                        this.stream = (0, tls_1.connect)(connectionOptions);\n                    }\n                    else {\n                        this.stream = (0, net_1.createConnection)(connectionOptions);\n                    }\n                }\n                catch (err) {\n                    reject(err);\n                    return;\n                }\n                this.stream.once(\"error\", (err) => {\n                    this.firstError = err;\n                });\n                resolve(this.stream);\n            });\n        });\n    }\n}\nexports.default = StandaloneConnector;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nfunction isSentinelEql(a, b) {\n    return ((a.host || \"127.0.0.1\") === (b.host || \"127.0.0.1\") &&\n        (a.port || 26379) === (b.port || 26379));\n}\nclass SentinelIterator {\n    constructor(sentinels) {\n        this.cursor = 0;\n        this.sentinels = sentinels.slice(0);\n    }\n    next() {\n        const done = this.cursor >= this.sentinels.length;\n        return { done, value: done ? undefined : this.sentinels[this.cursor++] };\n    }\n    reset(moveCurrentEndpointToFirst) {\n        if (moveCurrentEndpointToFirst &&\n            this.sentinels.length > 1 &&\n            this.cursor !== 1) {\n            this.sentinels.unshift(...this.sentinels.splice(this.cursor - 1));\n        }\n        this.cursor = 0;\n    }\n    add(sentinel) {\n        for (let i = 0; i < this.sentinels.length; i++) {\n            if (isSentinelEql(sentinel, this.sentinels[i])) {\n                return false;\n            }\n        }\n        this.sentinels.push(sentinel);\n        return true;\n    }\n    toString() {\n        return `${JSON.stringify(this.sentinels)} @${this.cursor}`;\n    }\n}\nexports.default = SentinelIterator;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.FailoverDetector = void 0;\nconst utils_1 = require(\"../../utils\");\nconst debug = (0, utils_1.Debug)(\"FailoverDetector\");\nconst CHANNEL_NAME = \"+switch-master\";\nclass FailoverDetector {\n    // sentinels can't be used for regular commands after this\n    constructor(connector, sentinels) {\n        this.isDisconnected = false;\n        this.connector = connector;\n        this.sentinels = sentinels;\n    }\n    cleanup() {\n        this.isDisconnected = true;\n        for (const sentinel of this.sentinels) {\n            sentinel.client.disconnect();\n        }\n    }\n    async subscribe() {\n        debug(\"Starting FailoverDetector\");\n        const promises = [];\n        for (const sentinel of this.sentinels) {\n            const promise = sentinel.client.subscribe(CHANNEL_NAME).catch((err) => {\n                debug(\"Failed to subscribe to failover messages on sentinel %s:%s (%s)\", sentinel.address.host || \"127.0.0.1\", sentinel.address.port || 26739, err.message);\n            });\n            promises.push(promise);\n            sentinel.client.on(\"message\", (channel) => {\n                if (!this.isDisconnected && channel === CHANNEL_NAME) {\n                    this.disconnect();\n                }\n            });\n        }\n        await Promise.all(promises);\n    }\n    disconnect() {\n        // Avoid disconnecting more than once per failover.\n        // A new FailoverDetector will be created after reconnecting.\n        this.isDisconnected = true;\n        debug(\"Failover detected, disconnecting\");\n        // Will call this.cleanup()\n        this.connector.disconnect();\n    }\n}\nexports.FailoverDetector = FailoverDetector;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SentinelIterator = void 0;\nconst net_1 = require(\"net\");\nconst utils_1 = require(\"../../utils\");\nconst tls_1 = require(\"tls\");\nconst SentinelIterator_1 = require(\"./SentinelIterator\");\nexports.SentinelIterator = SentinelIterator_1.default;\nconst AbstractConnector_1 = require(\"../AbstractConnector\");\nconst Redis_1 = require(\"../../Redis\");\nconst FailoverDetector_1 = require(\"./FailoverDetector\");\nconst debug = (0, utils_1.Debug)(\"SentinelConnector\");\nclass SentinelConnector extends AbstractConnector_1.default {\n    constructor(options) {\n        super(options.disconnectTimeout);\n        this.options = options;\n        this.emitter = null;\n        this.failoverDetector = null;\n        if (!this.options.sentinels.length) {\n            throw new Error(\"Requires at least one sentinel to connect to.\");\n        }\n        if (!this.options.name) {\n            throw new Error(\"Requires the name of master.\");\n        }\n        this.sentinelIterator = new SentinelIterator_1.default(this.options.sentinels);\n    }\n    check(info) {\n        const roleMatches = !info.role || this.options.role === info.role;\n        if (!roleMatches) {\n            debug(\"role invalid, expected %s, but got %s\", this.options.role, info.role);\n            // Start from the next item.\n            // Note that `reset` will move the cursor to the previous element,\n            // so we advance two steps here.\n            this.sentinelIterator.next();\n            this.sentinelIterator.next();\n            this.sentinelIterator.reset(true);\n        }\n        return roleMatches;\n    }\n    disconnect() {\n        super.disconnect();\n        if (this.failoverDetector) {\n            this.failoverDetector.cleanup();\n        }\n    }\n    connect(eventEmitter) {\n        this.connecting = true;\n        this.retryAttempts = 0;\n        let lastError;\n        const connectToNext = async () => {\n            const endpoint = this.sentinelIterator.next();\n            if (endpoint.done) {\n                this.sentinelIterator.reset(false);\n                const retryDelay = typeof this.options.sentinelRetryStrategy === \"function\"\n                    ? this.options.sentinelRetryStrategy(++this.retryAttempts)\n                    : null;\n                let errorMsg = typeof retryDelay !== \"number\"\n                    ? \"All sentinels are unreachable and retry is disabled.\"\n                    : `All sentinels are unreachable. Retrying from scratch after ${retryDelay}ms.`;\n                if (lastError) {\n                    errorMsg += ` Last error: ${lastError.message}`;\n                }\n                debug(errorMsg);\n                const error = new Error(errorMsg);\n                if (typeof retryDelay === \"number\") {\n                    eventEmitter(\"error\", error);\n                    await new Promise((resolve) => setTimeout(resolve, retryDelay));\n                    return connectToNext();\n                }\n                else {\n                    throw error;\n                }\n            }\n            let resolved = null;\n            let err = null;\n            try {\n                resolved = await this.resolve(endpoint.value);\n            }\n            catch (error) {\n                err = error;\n            }\n            if (!this.connecting) {\n                throw new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG);\n            }\n            const endpointAddress = endpoint.value.host + \":\" + endpoint.value.port;\n            if (resolved) {\n                debug(\"resolved: %s:%s from sentinel %s\", resolved.host, resolved.port, endpointAddress);\n                if (this.options.enableTLSForSentinelMode && this.options.tls) {\n                    Object.assign(resolved, this.options.tls);\n                    this.stream = (0, tls_1.connect)(resolved);\n                    this.stream.once(\"secureConnect\", this.initFailoverDetector.bind(this));\n                }\n                else {\n                    this.stream = (0, net_1.createConnection)(resolved);\n                    this.stream.once(\"connect\", this.initFailoverDetector.bind(this));\n                }\n                this.stream.once(\"error\", (err) => {\n                    this.firstError = err;\n                });\n                return this.stream;\n            }\n            else {\n                const errorMsg = err\n                    ? \"failed to connect to sentinel \" +\n                        endpointAddress +\n                        \" because \" +\n                        err.message\n                    : \"connected to sentinel \" +\n                        endpointAddress +\n                        \" successfully, but got an invalid reply: \" +\n                        resolved;\n                debug(errorMsg);\n                eventEmitter(\"sentinelError\", new Error(errorMsg));\n                if (err) {\n                    lastError = err;\n                }\n                return connectToNext();\n            }\n        };\n        return connectToNext();\n    }\n    async updateSentinels(client) {\n        if (!this.options.updateSentinels) {\n            return;\n        }\n        const result = await client.sentinel(\"sentinels\", this.options.name);\n        if (!Array.isArray(result)) {\n            return;\n        }\n        result\n            .map(utils_1.packObject)\n            .forEach((sentinel) => {\n            const flags = sentinel.flags ? sentinel.flags.split(\",\") : [];\n            if (flags.indexOf(\"disconnected\") === -1 &&\n                sentinel.ip &&\n                sentinel.port) {\n                const endpoint = this.sentinelNatResolve(addressResponseToAddress(sentinel));\n                if (this.sentinelIterator.add(endpoint)) {\n                    debug(\"adding sentinel %s:%s\", endpoint.host, endpoint.port);\n                }\n            }\n        });\n        debug(\"Updated internal sentinels: %s\", this.sentinelIterator);\n    }\n    async resolveMaster(client) {\n        const result = await client.sentinel(\"get-master-addr-by-name\", this.options.name);\n        await this.updateSentinels(client);\n        return this.sentinelNatResolve(Array.isArray(result)\n            ? { host: result[0], port: Number(result[1]) }\n            : null);\n    }\n    async resolveSlave(client) {\n        const result = await client.sentinel(\"slaves\", this.options.name);\n        if (!Array.isArray(result)) {\n            return null;\n        }\n        const availableSlaves = result\n            .map(utils_1.packObject)\n            .filter((slave) => slave.flags && !slave.flags.match(/(disconnected|s_down|o_down)/));\n        return this.sentinelNatResolve(selectPreferredSentinel(availableSlaves, this.options.preferredSlaves));\n    }\n    sentinelNatResolve(item) {\n        if (!item || !this.options.natMap)\n            return item;\n        const key = `${item.host}:${item.port}`;\n        let result = item;\n        if (typeof this.options.natMap === \"function\") {\n            result = this.options.natMap(key) || item;\n        }\n        else if (typeof this.options.natMap === \"object\") {\n            result = this.options.natMap[key] || item;\n        }\n        return result;\n    }\n    connectToSentinel(endpoint, options) {\n        const redis = new Redis_1.default({\n            port: endpoint.port || 26379,\n            host: endpoint.host,\n            username: this.options.sentinelUsername || null,\n            password: this.options.sentinelPassword || null,\n            family: endpoint.family ||\n                // @ts-expect-error\n                (\"path\" in this.options && this.options.path\n                    ? undefined\n                    : // @ts-expect-error\n                        this.options.family),\n            tls: this.options.sentinelTLS,\n            retryStrategy: null,\n            enableReadyCheck: false,\n            connectTimeout: this.options.connectTimeout,\n            commandTimeout: this.options.sentinelCommandTimeout,\n            ...options,\n        });\n        // @ts-expect-error\n        return redis;\n    }\n    async resolve(endpoint) {\n        const client = this.connectToSentinel(endpoint);\n        // ignore the errors since resolve* methods will handle them\n        client.on(\"error\", noop);\n        try {\n            if (this.options.role === \"slave\") {\n                return await this.resolveSlave(client);\n            }\n            else {\n                return await this.resolveMaster(client);\n            }\n        }\n        finally {\n            client.disconnect();\n        }\n    }\n    async initFailoverDetector() {\n        var _a;\n        if (!this.options.failoverDetector) {\n            return;\n        }\n        // Move the current sentinel to the first position\n        this.sentinelIterator.reset(true);\n        const sentinels = [];\n        // In case of a large amount of sentinels, limit the number of concurrent connections\n        while (sentinels.length < this.options.sentinelMaxConnections) {\n            const { done, value } = this.sentinelIterator.next();\n            if (done) {\n                break;\n            }\n            const client = this.connectToSentinel(value, {\n                lazyConnect: true,\n                retryStrategy: this.options.sentinelReconnectStrategy,\n            });\n            client.on(\"reconnecting\", () => {\n                var _a;\n                // Tests listen to this event\n                (_a = this.emitter) === null || _a === void 0 ? void 0 : _a.emit(\"sentinelReconnecting\");\n            });\n            sentinels.push({ address: value, client });\n        }\n        this.sentinelIterator.reset(false);\n        if (this.failoverDetector) {\n            // Clean up previous detector\n            this.failoverDetector.cleanup();\n        }\n        this.failoverDetector = new FailoverDetector_1.FailoverDetector(this, sentinels);\n        await this.failoverDetector.subscribe();\n        // Tests listen to this event\n        (_a = this.emitter) === null || _a === void 0 ? void 0 : _a.emit(\"failoverSubscribed\");\n    }\n}\nexports.default = SentinelConnector;\nfunction selectPreferredSentinel(availableSlaves, preferredSlaves) {\n    if (availableSlaves.length === 0) {\n        return null;\n    }\n    let selectedSlave;\n    if (typeof preferredSlaves === \"function\") {\n        selectedSlave = preferredSlaves(availableSlaves);\n    }\n    else if (preferredSlaves !== null && typeof preferredSlaves === \"object\") {\n        const preferredSlavesArray = Array.isArray(preferredSlaves)\n            ? preferredSlaves\n            : [preferredSlaves];\n        // sort by priority\n        preferredSlavesArray.sort((a, b) => {\n            // default the priority to 1\n            if (!a.prio) {\n                a.prio = 1;\n            }\n            if (!b.prio) {\n                b.prio = 1;\n            }\n            // lowest priority first\n            if (a.prio < b.prio) {\n                return -1;\n            }\n            if (a.prio > b.prio) {\n                return 1;\n            }\n            return 0;\n        });\n        // loop over preferred slaves and return the first match\n        for (let p = 0; p < preferredSlavesArray.length; p++) {\n            for (let a = 0; a < availableSlaves.length; a++) {\n                const slave = availableSlaves[a];\n                if (slave.ip === preferredSlavesArray[p].ip) {\n                    if (slave.port === preferredSlavesArray[p].port) {\n                        selectedSlave = slave;\n                        break;\n                    }\n                }\n            }\n            if (selectedSlave) {\n                break;\n            }\n        }\n    }\n    // if none of the preferred slaves are available, a random available slave is returned\n    if (!selectedSlave) {\n        selectedSlave = (0, utils_1.sample)(availableSlaves);\n    }\n    return addressResponseToAddress(selectedSlave);\n}\nfunction addressResponseToAddress(input) {\n    return { host: input.ip, port: Number(input.port) };\n}\nfunction noop() { }\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SentinelConnector = exports.StandaloneConnector = void 0;\nconst StandaloneConnector_1 = require(\"./StandaloneConnector\");\nexports.StandaloneConnector = StandaloneConnector_1.default;\nconst SentinelConnector_1 = require(\"./SentinelConnector\");\nexports.SentinelConnector = SentinelConnector_1.default;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst redis_errors_1 = require(\"redis-errors\");\nclass MaxRetriesPerRequestError extends redis_errors_1.AbortError {\n    constructor(maxRetriesPerRequest) {\n        const message = `Reached the max retries per request limit (which is ${maxRetriesPerRequest}). Refer to \"maxRetriesPerRequest\" option for details.`;\n        super(message);\n        Error.captureStackTrace(this, this.constructor);\n    }\n    get name() {\n        return this.constructor.name;\n    }\n}\nexports.default = MaxRetriesPerRequestError;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.MaxRetriesPerRequestError = void 0;\nconst MaxRetriesPerRequestError_1 = require(\"./MaxRetriesPerRequestError\");\nexports.MaxRetriesPerRequestError = MaxRetriesPerRequestError_1.default;\n","'use strict'\n\nconst Buffer = require('buffer').Buffer\nconst StringDecoder = require('string_decoder').StringDecoder\nconst decoder = new StringDecoder()\nconst errors = require('redis-errors')\nconst ReplyError = errors.ReplyError\nconst ParserError = errors.ParserError\nvar bufferPool = Buffer.allocUnsafe(32 * 1024)\nvar bufferOffset = 0\nvar interval = null\nvar counter = 0\nvar notDecreased = 0\n\n/**\n * Used for integer numbers only\n * @param {JavascriptRedisParser} parser\n * @returns {undefined|number}\n */\nfunction parseSimpleNumbers (parser) {\n  const length = parser.buffer.length - 1\n  var offset = parser.offset\n  var number = 0\n  var sign = 1\n\n  if (parser.buffer[offset] === 45) {\n    sign = -1\n    offset++\n  }\n\n  while (offset < length) {\n    const c1 = parser.buffer[offset++]\n    if (c1 === 13) { // \\r\\n\n      parser.offset = offset + 1\n      return sign * number\n    }\n    number = (number * 10) + (c1 - 48)\n  }\n}\n\n/**\n * Used for integer numbers in case of the returnNumbers option\n *\n * Reading the string as parts of n SMI is more efficient than\n * using a string directly.\n *\n * @param {JavascriptRedisParser} parser\n * @returns {undefined|string}\n */\nfunction parseStringNumbers (parser) {\n  const length = parser.buffer.length - 1\n  var offset = parser.offset\n  var number = 0\n  var res = ''\n\n  if (parser.buffer[offset] === 45) {\n    res += '-'\n    offset++\n  }\n\n  while (offset < length) {\n    var c1 = parser.buffer[offset++]\n    if (c1 === 13) { // \\r\\n\n      parser.offset = offset + 1\n      if (number !== 0) {\n        res += number\n      }\n      return res\n    } else if (number > 429496728) {\n      res += (number * 10) + (c1 - 48)\n      number = 0\n    } else if (c1 === 48 && number === 0) {\n      res += 0\n    } else {\n      number = (number * 10) + (c1 - 48)\n    }\n  }\n}\n\n/**\n * Parse a '+' redis simple string response but forward the offsets\n * onto convertBufferRange to generate a string.\n * @param {JavascriptRedisParser} parser\n * @returns {undefined|string|Buffer}\n */\nfunction parseSimpleString (parser) {\n  const start = parser.offset\n  const buffer = parser.buffer\n  const length = buffer.length - 1\n  var offset = start\n\n  while (offset < length) {\n    if (buffer[offset++] === 13) { // \\r\\n\n      parser.offset = offset + 1\n      if (parser.optionReturnBuffers === true) {\n        return parser.buffer.slice(start, offset - 1)\n      }\n      return parser.buffer.toString('utf8', start, offset - 1)\n    }\n  }\n}\n\n/**\n * Returns the read length\n * @param {JavascriptRedisParser} parser\n * @returns {undefined|number}\n */\nfunction parseLength (parser) {\n  const length = parser.buffer.length - 1\n  var offset = parser.offset\n  var number = 0\n\n  while (offset < length) {\n    const c1 = parser.buffer[offset++]\n    if (c1 === 13) {\n      parser.offset = offset + 1\n      return number\n    }\n    number = (number * 10) + (c1 - 48)\n  }\n}\n\n/**\n * Parse a ':' redis integer response\n *\n * If stringNumbers is activated the parser always returns numbers as string\n * This is important for big numbers (number > Math.pow(2, 53)) as js numbers\n * are 64bit floating point numbers with reduced precision\n *\n * @param {JavascriptRedisParser} parser\n * @returns {undefined|number|string}\n */\nfunction parseInteger (parser) {\n  if (parser.optionStringNumbers === true) {\n    return parseStringNumbers(parser)\n  }\n  return parseSimpleNumbers(parser)\n}\n\n/**\n * Parse a '$' redis bulk string response\n * @param {JavascriptRedisParser} parser\n * @returns {undefined|null|string}\n */\nfunction parseBulkString (parser) {\n  const length = parseLength(parser)\n  if (length === undefined) {\n    return\n  }\n  if (length < 0) {\n    return null\n  }\n  const offset = parser.offset + length\n  if (offset + 2 > parser.buffer.length) {\n    parser.bigStrSize = offset + 2\n    parser.totalChunkSize = parser.buffer.length\n    parser.bufferCache.push(parser.buffer)\n    return\n  }\n  const start = parser.offset\n  parser.offset = offset + 2\n  if (parser.optionReturnBuffers === true) {\n    return parser.buffer.slice(start, offset)\n  }\n  return parser.buffer.toString('utf8', start, offset)\n}\n\n/**\n * Parse a '-' redis error response\n * @param {JavascriptRedisParser} parser\n * @returns {ReplyError}\n */\nfunction parseError (parser) {\n  var string = parseSimpleString(parser)\n  if (string !== undefined) {\n    if (parser.optionReturnBuffers === true) {\n      string = string.toString()\n    }\n    return new ReplyError(string)\n  }\n}\n\n/**\n * Parsing error handler, resets parser buffer\n * @param {JavascriptRedisParser} parser\n * @param {number} type\n * @returns {undefined}\n */\nfunction handleError (parser, type) {\n  const err = new ParserError(\n    'Protocol error, got ' + JSON.stringify(String.fromCharCode(type)) + ' as reply type byte',\n    JSON.stringify(parser.buffer),\n    parser.offset\n  )\n  parser.buffer = null\n  parser.returnFatalError(err)\n}\n\n/**\n * Parse a '*' redis array response\n * @param {JavascriptRedisParser} parser\n * @returns {undefined|null|any[]}\n */\nfunction parseArray (parser) {\n  const length = parseLength(parser)\n  if (length === undefined) {\n    return\n  }\n  if (length < 0) {\n    return null\n  }\n  const responses = new Array(length)\n  return parseArrayElements(parser, responses, 0)\n}\n\n/**\n * Push a partly parsed array to the stack\n *\n * @param {JavascriptRedisParser} parser\n * @param {any[]} array\n * @param {number} pos\n * @returns {undefined}\n */\nfunction pushArrayCache (parser, array, pos) {\n  parser.arrayCache.push(array)\n  parser.arrayPos.push(pos)\n}\n\n/**\n * Parse chunked redis array response\n * @param {JavascriptRedisParser} parser\n * @returns {undefined|any[]}\n */\nfunction parseArrayChunks (parser) {\n  const tmp = parser.arrayCache.pop()\n  var pos = parser.arrayPos.pop()\n  if (parser.arrayCache.length) {\n    const res = parseArrayChunks(parser)\n    if (res === undefined) {\n      pushArrayCache(parser, tmp, pos)\n      return\n    }\n    tmp[pos++] = res\n  }\n  return parseArrayElements(parser, tmp, pos)\n}\n\n/**\n * Parse redis array response elements\n * @param {JavascriptRedisParser} parser\n * @param {Array} responses\n * @param {number} i\n * @returns {undefined|null|any[]}\n */\nfunction parseArrayElements (parser, responses, i) {\n  const bufferLength = parser.buffer.length\n  while (i < responses.length) {\n    const offset = parser.offset\n    if (parser.offset >= bufferLength) {\n      pushArrayCache(parser, responses, i)\n      return\n    }\n    const response = parseType(parser, parser.buffer[parser.offset++])\n    if (response === undefined) {\n      if (!(parser.arrayCache.length || parser.bufferCache.length)) {\n        parser.offset = offset\n      }\n      pushArrayCache(parser, responses, i)\n      return\n    }\n    responses[i] = response\n    i++\n  }\n\n  return responses\n}\n\n/**\n * Called the appropriate parser for the specified type.\n *\n * 36: $\n * 43: +\n * 42: *\n * 58: :\n * 45: -\n *\n * @param {JavascriptRedisParser} parser\n * @param {number} type\n * @returns {*}\n */\nfunction parseType (parser, type) {\n  switch (type) {\n    case 36:\n      return parseBulkString(parser)\n    case 43:\n      return parseSimpleString(parser)\n    case 42:\n      return parseArray(parser)\n    case 58:\n      return parseInteger(parser)\n    case 45:\n      return parseError(parser)\n    default:\n      return handleError(parser, type)\n  }\n}\n\n/**\n * Decrease the bufferPool size over time\n *\n * Balance between increasing and decreasing the bufferPool.\n * Decrease the bufferPool by 10% by removing the first 10% of the current pool.\n * @returns {undefined}\n */\nfunction decreaseBufferPool () {\n  if (bufferPool.length > 50 * 1024) {\n    if (counter === 1 || notDecreased > counter * 2) {\n      const minSliceLen = Math.floor(bufferPool.length / 10)\n      const sliceLength = minSliceLen < bufferOffset\n        ? bufferOffset\n        : minSliceLen\n      bufferOffset = 0\n      bufferPool = bufferPool.slice(sliceLength, bufferPool.length)\n    } else {\n      notDecreased++\n      counter--\n    }\n  } else {\n    clearInterval(interval)\n    counter = 0\n    notDecreased = 0\n    interval = null\n  }\n}\n\n/**\n * Check if the requested size fits in the current bufferPool.\n * If it does not, reset and increase the bufferPool accordingly.\n *\n * @param {number} length\n * @returns {undefined}\n */\nfunction resizeBuffer (length) {\n  if (bufferPool.length < length + bufferOffset) {\n    const multiplier = length > 1024 * 1024 * 75 ? 2 : 3\n    if (bufferOffset > 1024 * 1024 * 111) {\n      bufferOffset = 1024 * 1024 * 50\n    }\n    bufferPool = Buffer.allocUnsafe(length * multiplier + bufferOffset)\n    bufferOffset = 0\n    counter++\n    if (interval === null) {\n      interval = setInterval(decreaseBufferPool, 50)\n    }\n  }\n}\n\n/**\n * Concat a bulk string containing multiple chunks\n *\n * Notes:\n * 1) The first chunk might contain the whole bulk string including the \\r\n * 2) We are only safe to fully add up elements that are neither the first nor any of the last two elements\n *\n * @param {JavascriptRedisParser} parser\n * @returns {String}\n */\nfunction concatBulkString (parser) {\n  const list = parser.bufferCache\n  const oldOffset = parser.offset\n  var chunks = list.length\n  var offset = parser.bigStrSize - parser.totalChunkSize\n  parser.offset = offset\n  if (offset <= 2) {\n    if (chunks === 2) {\n      return list[0].toString('utf8', oldOffset, list[0].length + offset - 2)\n    }\n    chunks--\n    offset = list[list.length - 2].length + offset\n  }\n  var res = decoder.write(list[0].slice(oldOffset))\n  for (var i = 1; i < chunks - 1; i++) {\n    res += decoder.write(list[i])\n  }\n  res += decoder.end(list[i].slice(0, offset - 2))\n  return res\n}\n\n/**\n * Concat the collected chunks from parser.bufferCache.\n *\n * Increases the bufferPool size beforehand if necessary.\n *\n * @param {JavascriptRedisParser} parser\n * @returns {Buffer}\n */\nfunction concatBulkBuffer (parser) {\n  const list = parser.bufferCache\n  const oldOffset = parser.offset\n  const length = parser.bigStrSize - oldOffset - 2\n  var chunks = list.length\n  var offset = parser.bigStrSize - parser.totalChunkSize\n  parser.offset = offset\n  if (offset <= 2) {\n    if (chunks === 2) {\n      return list[0].slice(oldOffset, list[0].length + offset - 2)\n    }\n    chunks--\n    offset = list[list.length - 2].length + offset\n  }\n  resizeBuffer(length)\n  const start = bufferOffset\n  list[0].copy(bufferPool, start, oldOffset, list[0].length)\n  bufferOffset += list[0].length - oldOffset\n  for (var i = 1; i < chunks - 1; i++) {\n    list[i].copy(bufferPool, bufferOffset)\n    bufferOffset += list[i].length\n  }\n  list[i].copy(bufferPool, bufferOffset, 0, offset - 2)\n  bufferOffset += offset - 2\n  return bufferPool.slice(start, bufferOffset)\n}\n\nclass JavascriptRedisParser {\n  /**\n   * Javascript Redis Parser constructor\n   * @param {{returnError: Function, returnReply: Function, returnFatalError?: Function, returnBuffers: boolean, stringNumbers: boolean }} options\n   * @constructor\n   */\n  constructor (options) {\n    if (!options) {\n      throw new TypeError('Options are mandatory.')\n    }\n    if (typeof options.returnError !== 'function' || typeof options.returnReply !== 'function') {\n      throw new TypeError('The returnReply and returnError options have to be functions.')\n    }\n    this.setReturnBuffers(!!options.returnBuffers)\n    this.setStringNumbers(!!options.stringNumbers)\n    this.returnError = options.returnError\n    this.returnFatalError = options.returnFatalError || options.returnError\n    this.returnReply = options.returnReply\n    this.reset()\n  }\n\n  /**\n   * Reset the parser values to the initial state\n   *\n   * @returns {undefined}\n   */\n  reset () {\n    this.offset = 0\n    this.buffer = null\n    this.bigStrSize = 0\n    this.totalChunkSize = 0\n    this.bufferCache = []\n    this.arrayCache = []\n    this.arrayPos = []\n  }\n\n  /**\n   * Set the returnBuffers option\n   *\n   * @param {boolean} returnBuffers\n   * @returns {undefined}\n   */\n  setReturnBuffers (returnBuffers) {\n    if (typeof returnBuffers !== 'boolean') {\n      throw new TypeError('The returnBuffers argument has to be a boolean')\n    }\n    this.optionReturnBuffers = returnBuffers\n  }\n\n  /**\n   * Set the stringNumbers option\n   *\n   * @param {boolean} stringNumbers\n   * @returns {undefined}\n   */\n  setStringNumbers (stringNumbers) {\n    if (typeof stringNumbers !== 'boolean') {\n      throw new TypeError('The stringNumbers argument has to be a boolean')\n    }\n    this.optionStringNumbers = stringNumbers\n  }\n\n  /**\n   * Parse the redis buffer\n   * @param {Buffer} buffer\n   * @returns {undefined}\n   */\n  execute (buffer) {\n    if (this.buffer === null) {\n      this.buffer = buffer\n      this.offset = 0\n    } else if (this.bigStrSize === 0) {\n      const oldLength = this.buffer.length\n      const remainingLength = oldLength - this.offset\n      const newBuffer = Buffer.allocUnsafe(remainingLength + buffer.length)\n      this.buffer.copy(newBuffer, 0, this.offset, oldLength)\n      buffer.copy(newBuffer, remainingLength, 0, buffer.length)\n      this.buffer = newBuffer\n      this.offset = 0\n      if (this.arrayCache.length) {\n        const arr = parseArrayChunks(this)\n        if (arr === undefined) {\n          return\n        }\n        this.returnReply(arr)\n      }\n    } else if (this.totalChunkSize + buffer.length >= this.bigStrSize) {\n      this.bufferCache.push(buffer)\n      var tmp = this.optionReturnBuffers ? concatBulkBuffer(this) : concatBulkString(this)\n      this.bigStrSize = 0\n      this.bufferCache = []\n      this.buffer = buffer\n      if (this.arrayCache.length) {\n        this.arrayCache[0][this.arrayPos[0]++] = tmp\n        tmp = parseArrayChunks(this)\n        if (tmp === undefined) {\n          return\n        }\n      }\n      this.returnReply(tmp)\n    } else {\n      this.bufferCache.push(buffer)\n      this.totalChunkSize += buffer.length\n      return\n    }\n\n    while (this.offset < this.buffer.length) {\n      const offset = this.offset\n      const type = this.buffer[this.offset++]\n      const response = parseType(this, type)\n      if (response === undefined) {\n        if (!(this.arrayCache.length || this.bufferCache.length)) {\n          this.offset = offset\n        }\n        return\n      }\n\n      if (type === 45) {\n        this.returnError(response)\n      } else {\n        this.returnReply(response)\n      }\n    }\n\n    this.buffer = null\n  }\n}\n\nmodule.exports = JavascriptRedisParser\n","'use strict'\n\nmodule.exports = require('./lib/parser')\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Tiny class to simplify dealing with subscription set\n */\nclass SubscriptionSet {\n    constructor() {\n        this.set = {\n            subscribe: {},\n            psubscribe: {},\n            ssubscribe: {},\n        };\n    }\n    add(set, channel) {\n        this.set[mapSet(set)][channel] = true;\n    }\n    del(set, channel) {\n        delete this.set[mapSet(set)][channel];\n    }\n    channels(set) {\n        return Object.keys(this.set[mapSet(set)]);\n    }\n    isEmpty() {\n        return (this.channels(\"subscribe\").length === 0 &&\n            this.channels(\"psubscribe\").length === 0 &&\n            this.channels(\"ssubscribe\").length === 0);\n    }\n}\nexports.default = SubscriptionSet;\nfunction mapSet(set) {\n    if (set === \"unsubscribe\") {\n        return \"subscribe\";\n    }\n    if (set === \"punsubscribe\") {\n        return \"psubscribe\";\n    }\n    if (set === \"sunsubscribe\") {\n        return \"ssubscribe\";\n    }\n    return set;\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Command_1 = require(\"./Command\");\nconst utils_1 = require(\"./utils\");\nconst RedisParser = require(\"redis-parser\");\nconst SubscriptionSet_1 = require(\"./SubscriptionSet\");\nconst debug = (0, utils_1.Debug)(\"dataHandler\");\nclass DataHandler {\n    constructor(redis, parserOptions) {\n        this.redis = redis;\n        const parser = new RedisParser({\n            stringNumbers: parserOptions.stringNumbers,\n            returnBuffers: true,\n            returnError: (err) => {\n                this.returnError(err);\n            },\n            returnFatalError: (err) => {\n                this.returnFatalError(err);\n            },\n            returnReply: (reply) => {\n                this.returnReply(reply);\n            },\n        });\n        // prependListener ensures the parser receives and processes data before socket timeout checks are performed\n        redis.stream.prependListener(\"data\", (data) => {\n            parser.execute(data);\n        });\n        // prependListener() doesn't enable flowing mode automatically - we need to resume the stream manually\n        redis.stream.resume();\n    }\n    returnFatalError(err) {\n        err.message += \". Please report this.\";\n        this.redis.recoverFromFatalError(err, err, { offlineQueue: false });\n    }\n    returnError(err) {\n        const item = this.shiftCommand(err);\n        if (!item) {\n            return;\n        }\n        err.command = {\n            name: item.command.name,\n            args: item.command.args,\n        };\n        if (item.command.name == \"ssubscribe\" && err.message.includes(\"MOVED\")) {\n            this.redis.emit(\"moved\");\n            return;\n        }\n        this.redis.handleReconnection(err, item);\n    }\n    returnReply(reply) {\n        if (this.handleMonitorReply(reply)) {\n            return;\n        }\n        if (this.handleSubscriberReply(reply)) {\n            return;\n        }\n        const item = this.shiftCommand(reply);\n        if (!item) {\n            return;\n        }\n        if (Command_1.default.checkFlag(\"ENTER_SUBSCRIBER_MODE\", item.command.name)) {\n            this.redis.condition.subscriber = new SubscriptionSet_1.default();\n            this.redis.condition.subscriber.add(item.command.name, reply[1].toString());\n            if (!fillSubCommand(item.command, reply[2])) {\n                this.redis.commandQueue.unshift(item);\n            }\n        }\n        else if (Command_1.default.checkFlag(\"EXIT_SUBSCRIBER_MODE\", item.command.name)) {\n            if (!fillUnsubCommand(item.command, reply[2])) {\n                this.redis.commandQueue.unshift(item);\n            }\n        }\n        else {\n            item.command.resolve(reply);\n        }\n    }\n    handleSubscriberReply(reply) {\n        if (!this.redis.condition.subscriber) {\n            return false;\n        }\n        const replyType = Array.isArray(reply) ? reply[0].toString() : null;\n        debug('receive reply \"%s\" in subscriber mode', replyType);\n        switch (replyType) {\n            case \"message\":\n                if (this.redis.listeners(\"message\").length > 0) {\n                    // Check if there're listeners to avoid unnecessary `toString()`.\n                    this.redis.emit(\"message\", reply[1].toString(), reply[2] ? reply[2].toString() : \"\");\n                }\n                this.redis.emit(\"messageBuffer\", reply[1], reply[2]);\n                break;\n            case \"pmessage\": {\n                const pattern = reply[1].toString();\n                if (this.redis.listeners(\"pmessage\").length > 0) {\n                    this.redis.emit(\"pmessage\", pattern, reply[2].toString(), reply[3].toString());\n                }\n                this.redis.emit(\"pmessageBuffer\", pattern, reply[2], reply[3]);\n                break;\n            }\n            case \"smessage\": {\n                if (this.redis.listeners(\"smessage\").length > 0) {\n                    this.redis.emit(\"smessage\", reply[1].toString(), reply[2] ? reply[2].toString() : \"\");\n                }\n                this.redis.emit(\"smessageBuffer\", reply[1], reply[2]);\n                break;\n            }\n            case \"ssubscribe\":\n            case \"subscribe\":\n            case \"psubscribe\": {\n                const channel = reply[1].toString();\n                this.redis.condition.subscriber.add(replyType, channel);\n                const item = this.shiftCommand(reply);\n                if (!item) {\n                    return;\n                }\n                if (!fillSubCommand(item.command, reply[2])) {\n                    this.redis.commandQueue.unshift(item);\n                }\n                break;\n            }\n            case \"sunsubscribe\":\n            case \"unsubscribe\":\n            case \"punsubscribe\": {\n                const channel = reply[1] ? reply[1].toString() : null;\n                if (channel) {\n                    this.redis.condition.subscriber.del(replyType, channel);\n                }\n                const count = reply[2];\n                if (Number(count) === 0) {\n                    this.redis.condition.subscriber = false;\n                }\n                const item = this.shiftCommand(reply);\n                if (!item) {\n                    return;\n                }\n                if (!fillUnsubCommand(item.command, count)) {\n                    this.redis.commandQueue.unshift(item);\n                }\n                break;\n            }\n            default: {\n                const item = this.shiftCommand(reply);\n                if (!item) {\n                    return;\n                }\n                item.command.resolve(reply);\n            }\n        }\n        return true;\n    }\n    handleMonitorReply(reply) {\n        if (this.redis.status !== \"monitoring\") {\n            return false;\n        }\n        const replyStr = reply.toString();\n        if (replyStr === \"OK\") {\n            // Valid commands in the monitoring mode are AUTH and MONITOR,\n            // both of which always reply with 'OK'.\n            // So if we got an 'OK', we can make certain that\n            // the reply is made to AUTH & MONITOR.\n            return false;\n        }\n        // Since commands sent in the monitoring mode will trigger an exception,\n        // any replies we received in the monitoring mode should consider to be\n        // realtime monitor data instead of result of commands.\n        const len = replyStr.indexOf(\" \");\n        const timestamp = replyStr.slice(0, len);\n        const argIndex = replyStr.indexOf('\"');\n        const args = replyStr\n            .slice(argIndex + 1, -1)\n            .split('\" \"')\n            .map((elem) => elem.replace(/\\\\\"/g, '\"'));\n        const dbAndSource = replyStr.slice(len + 2, argIndex - 2).split(\" \");\n        this.redis.emit(\"monitor\", timestamp, args, dbAndSource[1], dbAndSource[0]);\n        return true;\n    }\n    shiftCommand(reply) {\n        const item = this.redis.commandQueue.shift();\n        if (!item) {\n            const message = \"Command queue state error. If you can reproduce this, please report it.\";\n            const error = new Error(message +\n                (reply instanceof Error\n                    ? ` Last error: ${reply.message}`\n                    : ` Last reply: ${reply.toString()}`));\n            this.redis.emit(\"error\", error);\n            return null;\n        }\n        return item;\n    }\n}\nexports.default = DataHandler;\nconst remainingRepliesMap = new WeakMap();\nfunction fillSubCommand(command, count) {\n    let remainingReplies = remainingRepliesMap.has(command)\n        ? remainingRepliesMap.get(command)\n        : command.args.length;\n    remainingReplies -= 1;\n    if (remainingReplies <= 0) {\n        command.resolve(count);\n        remainingRepliesMap.delete(command);\n        return true;\n    }\n    remainingRepliesMap.set(command, remainingReplies);\n    return false;\n}\nfunction fillUnsubCommand(command, count) {\n    let remainingReplies = remainingRepliesMap.has(command)\n        ? remainingRepliesMap.get(command)\n        : command.args.length;\n    if (remainingReplies === 0) {\n        if (Number(count) === 0) {\n            remainingRepliesMap.delete(command);\n            command.resolve(count);\n            return true;\n        }\n        return false;\n    }\n    remainingReplies -= 1;\n    if (remainingReplies <= 0) {\n        command.resolve(count);\n        return true;\n    }\n    remainingRepliesMap.set(command, remainingReplies);\n    return false;\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.readyHandler = exports.errorHandler = exports.closeHandler = exports.connectHandler = void 0;\nconst redis_errors_1 = require(\"redis-errors\");\nconst Command_1 = require(\"../Command\");\nconst errors_1 = require(\"../errors\");\nconst utils_1 = require(\"../utils\");\nconst DataHandler_1 = require(\"../DataHandler\");\nconst debug = (0, utils_1.Debug)(\"connection\");\nfunction connectHandler(self) {\n    return function () {\n        var _a;\n        self.setStatus(\"connect\");\n        self.resetCommandQueue();\n        // AUTH command should be processed before any other commands\n        let flushed = false;\n        const { connectionEpoch } = self;\n        if (self.condition.auth) {\n            self.auth(self.condition.auth, function (err) {\n                if (connectionEpoch !== self.connectionEpoch) {\n                    return;\n                }\n                if (err) {\n                    if (err.message.indexOf(\"no password is set\") !== -1) {\n                        console.warn(\"[WARN] Redis server does not require a password, but a password was supplied.\");\n                    }\n                    else if (err.message.indexOf(\"without any password configured for the default user\") !== -1) {\n                        console.warn(\"[WARN] This Redis server's `default` user does not require a password, but a password was supplied\");\n                    }\n                    else if (err.message.indexOf(\"wrong number of arguments for 'auth' command\") !== -1) {\n                        console.warn(`[ERROR] The server returned \"wrong number of arguments for 'auth' command\". You are probably passing both username and password to Redis version 5 or below. You should only pass the 'password' option for Redis version 5 and under.`);\n                    }\n                    else {\n                        flushed = true;\n                        self.recoverFromFatalError(err, err);\n                    }\n                }\n            });\n        }\n        if (self.condition.select) {\n            self.select(self.condition.select).catch((err) => {\n                // If the node is in cluster mode, select is disallowed.\n                // In this case, reconnect won't help.\n                self.silentEmit(\"error\", err);\n            });\n        }\n        /*\n          No need to keep the reference of DataHandler here\n          because we don't need to do the cleanup.\n          `Stream#end()` will remove all listeners for us.\n        */\n        new DataHandler_1.default(self, {\n            stringNumbers: self.options.stringNumbers,\n        });\n        const clientCommandPromises = [];\n        if (self.options.connectionName) {\n            debug(\"set the connection name [%s]\", self.options.connectionName);\n            clientCommandPromises.push(self.client(\"setname\", self.options.connectionName).catch(utils_1.noop));\n        }\n        if (!self.options.disableClientInfo) {\n            debug(\"set the client info\");\n            clientCommandPromises.push((0, utils_1.getPackageMeta)()\n                .then((packageMeta) => {\n                return self\n                    .client(\"SETINFO\", \"LIB-VER\", packageMeta.version)\n                    .catch(utils_1.noop);\n            })\n                .catch(utils_1.noop));\n            clientCommandPromises.push(self\n                .client(\"SETINFO\", \"LIB-NAME\", ((_a = self.options) === null || _a === void 0 ? void 0 : _a.clientInfoTag)\n                ? `ioredis(${self.options.clientInfoTag})`\n                : \"ioredis\")\n                .catch(utils_1.noop));\n        }\n        Promise.all(clientCommandPromises)\n            .catch(utils_1.noop)\n            .finally(() => {\n            if (!self.options.enableReadyCheck) {\n                exports.readyHandler(self)();\n            }\n            if (self.options.enableReadyCheck) {\n                self._readyCheck(function (err, info) {\n                    if (connectionEpoch !== self.connectionEpoch) {\n                        return;\n                    }\n                    if (err) {\n                        if (!flushed) {\n                            self.recoverFromFatalError(new Error(\"Ready check failed: \" + err.message), err);\n                        }\n                    }\n                    else {\n                        if (self.connector.check(info)) {\n                            exports.readyHandler(self)();\n                        }\n                        else {\n                            self.disconnect(true);\n                        }\n                    }\n                });\n            }\n        });\n    };\n}\nexports.connectHandler = connectHandler;\nfunction abortError(command) {\n    const err = new redis_errors_1.AbortError(\"Command aborted due to connection close\");\n    err.command = {\n        name: command.name,\n        args: command.args,\n    };\n    return err;\n}\n// If a contiguous set of pipeline commands starts from index zero then they\n// can be safely reattempted. If however we have a chain of pipelined commands\n// starting at index 1 or more it means we received a partial response before\n// the connection close and those pipelined commands must be aborted. For\n// example, if the queue looks like this: [2, 3, 4, 0, 1, 2] then after\n// aborting and purging we'll have a queue that looks like this: [0, 1, 2]\nfunction abortIncompletePipelines(commandQueue) {\n    var _a;\n    let expectedIndex = 0;\n    for (let i = 0; i < commandQueue.length;) {\n        const command = (_a = commandQueue.peekAt(i)) === null || _a === void 0 ? void 0 : _a.command;\n        const pipelineIndex = command.pipelineIndex;\n        if (pipelineIndex === undefined || pipelineIndex === 0) {\n            expectedIndex = 0;\n        }\n        if (pipelineIndex !== undefined && pipelineIndex !== expectedIndex++) {\n            commandQueue.remove(i, 1);\n            command.reject(abortError(command));\n            continue;\n        }\n        i++;\n    }\n}\n// If only a partial transaction result was received before connection close,\n// we have to abort any transaction fragments that may have ended up in the\n// offline queue\nfunction abortTransactionFragments(commandQueue) {\n    var _a;\n    for (let i = 0; i < commandQueue.length;) {\n        const command = (_a = commandQueue.peekAt(i)) === null || _a === void 0 ? void 0 : _a.command;\n        if (command.name === \"multi\") {\n            break;\n        }\n        if (command.name === \"exec\") {\n            commandQueue.remove(i, 1);\n            command.reject(abortError(command));\n            break;\n        }\n        if (command.inTransaction) {\n            commandQueue.remove(i, 1);\n            command.reject(abortError(command));\n        }\n        else {\n            i++;\n        }\n    }\n}\nfunction closeHandler(self) {\n    return function () {\n        const prevStatus = self.status;\n        self.setStatus(\"close\");\n        if (self.commandQueue.length) {\n            abortIncompletePipelines(self.commandQueue);\n        }\n        if (self.offlineQueue.length) {\n            abortTransactionFragments(self.offlineQueue);\n        }\n        if (prevStatus === \"ready\") {\n            if (!self.prevCondition) {\n                self.prevCondition = self.condition;\n            }\n            if (self.commandQueue.length) {\n                self.prevCommandQueue = self.commandQueue;\n            }\n        }\n        if (self.manuallyClosing) {\n            self.manuallyClosing = false;\n            debug(\"skip reconnecting since the connection is manually closed.\");\n            return close();\n        }\n        if (typeof self.options.retryStrategy !== \"function\") {\n            debug(\"skip reconnecting because `retryStrategy` is not a function\");\n            return close();\n        }\n        const retryDelay = self.options.retryStrategy(++self.retryAttempts);\n        if (typeof retryDelay !== \"number\") {\n            debug(\"skip reconnecting because `retryStrategy` doesn't return a number\");\n            return close();\n        }\n        debug(\"reconnect in %sms\", retryDelay);\n        self.setStatus(\"reconnecting\", retryDelay);\n        self.reconnectTimeout = setTimeout(function () {\n            self.reconnectTimeout = null;\n            self.connect().catch(utils_1.noop);\n        }, retryDelay);\n        const { maxRetriesPerRequest } = self.options;\n        if (typeof maxRetriesPerRequest === \"number\") {\n            if (maxRetriesPerRequest < 0) {\n                debug(\"maxRetriesPerRequest is negative, ignoring...\");\n            }\n            else {\n                const remainder = self.retryAttempts % (maxRetriesPerRequest + 1);\n                if (remainder === 0) {\n                    debug(\"reach maxRetriesPerRequest limitation, flushing command queue...\");\n                    self.flushQueue(new errors_1.MaxRetriesPerRequestError(maxRetriesPerRequest));\n                }\n            }\n        }\n    };\n    function close() {\n        self.setStatus(\"end\");\n        self.flushQueue(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG));\n    }\n}\nexports.closeHandler = closeHandler;\nfunction errorHandler(self) {\n    return function (error) {\n        debug(\"error: %s\", error);\n        self.silentEmit(\"error\", error);\n    };\n}\nexports.errorHandler = errorHandler;\nfunction readyHandler(self) {\n    return function () {\n        self.setStatus(\"ready\");\n        self.retryAttempts = 0;\n        if (self.options.monitor) {\n            self.call(\"monitor\").then(() => self.setStatus(\"monitoring\"), (error) => self.emit(\"error\", error));\n            const { sendCommand } = self;\n            self.sendCommand = function (command) {\n                if (Command_1.default.checkFlag(\"VALID_IN_MONITOR_MODE\", command.name)) {\n                    return sendCommand.call(self, command);\n                }\n                command.reject(new Error(\"Connection is in monitoring mode, can't process commands.\"));\n                return command.promise;\n            };\n            self.once(\"close\", function () {\n                delete self.sendCommand;\n            });\n            return;\n        }\n        const finalSelect = self.prevCondition\n            ? self.prevCondition.select\n            : self.condition.select;\n        if (self.options.readOnly) {\n            debug(\"set the connection to readonly mode\");\n            self.readonly().catch(utils_1.noop);\n        }\n        if (self.prevCondition) {\n            const condition = self.prevCondition;\n            self.prevCondition = null;\n            if (condition.subscriber && self.options.autoResubscribe) {\n                // We re-select the previous db first since\n                // `SELECT` command is not valid in sub mode.\n                if (self.condition.select !== finalSelect) {\n                    debug(\"connect to db [%d]\", finalSelect);\n                    self.select(finalSelect);\n                }\n                const subscribeChannels = condition.subscriber.channels(\"subscribe\");\n                if (subscribeChannels.length) {\n                    debug(\"subscribe %d channels\", subscribeChannels.length);\n                    self.subscribe(subscribeChannels);\n                }\n                const psubscribeChannels = condition.subscriber.channels(\"psubscribe\");\n                if (psubscribeChannels.length) {\n                    debug(\"psubscribe %d channels\", psubscribeChannels.length);\n                    self.psubscribe(psubscribeChannels);\n                }\n                const ssubscribeChannels = condition.subscriber.channels(\"ssubscribe\");\n                if (ssubscribeChannels.length) {\n                    debug(\"ssubscribe %s\", ssubscribeChannels.length);\n                    for (const channel of ssubscribeChannels) {\n                        self.ssubscribe(channel);\n                    }\n                }\n            }\n        }\n        if (self.prevCommandQueue) {\n            if (self.options.autoResendUnfulfilledCommands) {\n                debug(\"resend %d unfulfilled commands\", self.prevCommandQueue.length);\n                while (self.prevCommandQueue.length > 0) {\n                    const item = self.prevCommandQueue.shift();\n                    if (item.select !== self.condition.select &&\n                        item.command.name !== \"select\") {\n                        self.select(item.select);\n                    }\n                    self.sendCommand(item.command, item.stream);\n                }\n            }\n            else {\n                self.prevCommandQueue = null;\n            }\n        }\n        if (self.offlineQueue.length) {\n            debug(\"send %d commands in offline queue\", self.offlineQueue.length);\n            const offlineQueue = self.offlineQueue;\n            self.resetOfflineQueue();\n            while (offlineQueue.length > 0) {\n                const item = offlineQueue.shift();\n                if (item.select !== self.condition.select &&\n                    item.command.name !== \"select\") {\n                    self.select(item.select);\n                }\n                self.sendCommand(item.command, item.stream);\n            }\n        }\n        if (self.condition.select !== finalSelect) {\n            debug(\"connect to db [%d]\", finalSelect);\n            self.select(finalSelect);\n        }\n    };\n}\nexports.readyHandler = readyHandler;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DEFAULT_REDIS_OPTIONS = void 0;\nexports.DEFAULT_REDIS_OPTIONS = {\n    // Connection\n    port: 6379,\n    host: \"localhost\",\n    family: 0,\n    connectTimeout: 10000,\n    disconnectTimeout: 2000,\n    retryStrategy: function (times) {\n        return Math.min(times * 50, 2000);\n    },\n    keepAlive: 0,\n    noDelay: true,\n    connectionName: null,\n    disableClientInfo: false,\n    clientInfoTag: undefined,\n    // Sentinel\n    sentinels: null,\n    name: null,\n    role: \"master\",\n    sentinelRetryStrategy: function (times) {\n        return Math.min(times * 10, 1000);\n    },\n    sentinelReconnectStrategy: function () {\n        // This strategy only applies when sentinels are used for detecting\n        // a failover, not during initial master resolution.\n        // The deployment can still function when some of the sentinels are down\n        // for a long period of time, so we may not want to attempt reconnection\n        // very often. Therefore the default interval is fairly long (1 minute).\n        return 60000;\n    },\n    natMap: null,\n    enableTLSForSentinelMode: false,\n    updateSentinels: true,\n    failoverDetector: false,\n    // Status\n    username: null,\n    password: null,\n    db: 0,\n    // Others\n    enableOfflineQueue: true,\n    enableReadyCheck: true,\n    autoResubscribe: true,\n    autoResendUnfulfilledCommands: true,\n    lazyConnect: false,\n    keyPrefix: \"\",\n    reconnectOnError: null,\n    readOnly: false,\n    stringNumbers: false,\n    maxRetriesPerRequest: 20,\n    maxLoadingRetryTime: 10000,\n    enableAutoPipelining: false,\n    autoPipeliningIgnoredCommands: [],\n    sentinelMaxConnections: 10,\n    blockingTimeoutGrace: 100,\n};\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst commands_1 = require(\"@ioredis/commands\");\nconst events_1 = require(\"events\");\nconst standard_as_callback_1 = require(\"standard-as-callback\");\nconst cluster_1 = require(\"./cluster\");\nconst Command_1 = require(\"./Command\");\nconst connectors_1 = require(\"./connectors\");\nconst SentinelConnector_1 = require(\"./connectors/SentinelConnector\");\nconst eventHandler = require(\"./redis/event_handler\");\nconst RedisOptions_1 = require(\"./redis/RedisOptions\");\nconst ScanStream_1 = require(\"./ScanStream\");\nconst transaction_1 = require(\"./transaction\");\nconst utils_1 = require(\"./utils\");\nconst tracing_1 = require(\"./tracing\");\nconst applyMixin_1 = require(\"./utils/applyMixin\");\nconst Commander_1 = require(\"./utils/Commander\");\nconst lodash_1 = require(\"./utils/lodash\");\nconst Deque = require(\"denque\");\nconst debug = (0, utils_1.Debug)(\"redis\");\n/**\n * This is the major component of ioredis.\n * Use it to connect to a standalone Redis server or Sentinels.\n *\n * ```typescript\n * const redis = new Redis(); // Default port is 6379\n * async function main() {\n *   redis.set(\"foo\", \"bar\");\n *   redis.get(\"foo\", (err, result) => {\n *     // `result` should be \"bar\"\n *     console.log(err, result);\n *   });\n *   // Or use Promise\n *   const result = await redis.get(\"foo\");\n * }\n * ```\n */\nclass Redis extends Commander_1.default {\n    constructor(arg1, arg2, arg3) {\n        super();\n        this.status = \"wait\";\n        /**\n         * @ignore\n         */\n        this.isCluster = false;\n        this.reconnectTimeout = null;\n        this.connectionEpoch = 0;\n        this.retryAttempts = 0;\n        this.manuallyClosing = false;\n        // Prepare autopipelines structures\n        this._autoPipelines = new Map();\n        this._runningAutoPipelines = new Set();\n        this.parseOptions(arg1, arg2, arg3);\n        events_1.EventEmitter.call(this);\n        this.resetCommandQueue();\n        this.resetOfflineQueue();\n        if (this.options.Connector) {\n            this.connector = new this.options.Connector(this.options);\n        }\n        else if (this.options.sentinels) {\n            const sentinelConnector = new SentinelConnector_1.default(this.options);\n            sentinelConnector.emitter = this;\n            this.connector = sentinelConnector;\n        }\n        else {\n            this.connector = new connectors_1.StandaloneConnector(this.options);\n        }\n        if (this.options.scripts) {\n            Object.entries(this.options.scripts).forEach(([name, definition]) => {\n                this.defineCommand(name, definition);\n            });\n        }\n        // end(or wait) -> connecting -> connect -> ready -> end\n        if (this.options.lazyConnect) {\n            this.setStatus(\"wait\");\n        }\n        else {\n            this.connect().catch(lodash_1.noop);\n        }\n    }\n    /**\n     * Create a Redis instance.\n     * This is the same as `new Redis()` but is included for compatibility with node-redis.\n     */\n    static createClient(...args) {\n        return new Redis(...args);\n    }\n    get autoPipelineQueueSize() {\n        let queued = 0;\n        for (const pipeline of this._autoPipelines.values()) {\n            queued += pipeline.length;\n        }\n        return queued;\n    }\n    /**\n     * Create a connection to Redis.\n     * This method will be invoked automatically when creating a new Redis instance\n     * unless `lazyConnect: true` is passed.\n     *\n     * When calling this method manually, a Promise is returned, which will\n     * be resolved when the connection status is ready. The promise can reject\n     * if the connection fails, times out, or if Redis is already connecting/connected.\n     */\n    connect(callback) {\n        const promise = (0, tracing_1.traceConnect)(() => this._connect(), () => {\n            const { address, port } = this._getServerAddress();\n            return {\n                serverAddress: address,\n                serverPort: port,\n                connectionEpoch: this.connectionEpoch,\n            };\n        });\n        return (0, standard_as_callback_1.default)(promise, callback);\n    }\n    _connect() {\n        return new Promise((resolve, reject) => {\n            if (this.status === \"connecting\" ||\n                this.status === \"connect\" ||\n                this.status === \"ready\") {\n                reject(new Error(\"Redis is already connecting/connected\"));\n                return;\n            }\n            this.connectionEpoch += 1;\n            this.setStatus(\"connecting\");\n            const { options } = this;\n            this.condition = {\n                select: options.db,\n                auth: options.username\n                    ? [options.username, options.password]\n                    : options.password,\n                subscriber: false,\n            };\n            const _this = this;\n            (0, standard_as_callback_1.default)(this.connector.connect(function (type, err) {\n                _this.silentEmit(type, err);\n            }), function (err, stream) {\n                if (err) {\n                    _this.flushQueue(err);\n                    _this.silentEmit(\"error\", err);\n                    reject(err);\n                    _this.setStatus(\"end\");\n                    return;\n                }\n                let CONNECT_EVENT = options.tls ? \"secureConnect\" : \"connect\";\n                if (\"sentinels\" in options &&\n                    options.sentinels &&\n                    !options.enableTLSForSentinelMode) {\n                    CONNECT_EVENT = \"connect\";\n                }\n                _this.stream = stream;\n                if (options.noDelay) {\n                    stream.setNoDelay(true);\n                }\n                // Node ignores setKeepAlive before connect, therefore we wait for the event:\n                // https://github.com/nodejs/node/issues/31663\n                if (typeof options.keepAlive === \"number\") {\n                    if (stream.connecting) {\n                        stream.once(CONNECT_EVENT, () => {\n                            stream.setKeepAlive(true, options.keepAlive);\n                        });\n                    }\n                    else {\n                        stream.setKeepAlive(true, options.keepAlive);\n                    }\n                }\n                if (stream.connecting) {\n                    stream.once(CONNECT_EVENT, eventHandler.connectHandler(_this));\n                    if (options.connectTimeout) {\n                        /*\n                         * Typically, Socket#setTimeout(0) will clear the timer\n                         * set before. However, in some platforms (Electron 3.x~4.x),\n                         * the timer will not be cleared. So we introduce a variable here.\n                         *\n                         * See https://github.com/electron/electron/issues/14915\n                         */\n                        let connectTimeoutCleared = false;\n                        stream.setTimeout(options.connectTimeout, function () {\n                            if (connectTimeoutCleared) {\n                                return;\n                            }\n                            stream.setTimeout(0);\n                            stream.destroy();\n                            const err = new Error(\"connect ETIMEDOUT\");\n                            // @ts-expect-error\n                            err.errorno = \"ETIMEDOUT\";\n                            // @ts-expect-error\n                            err.code = \"ETIMEDOUT\";\n                            // @ts-expect-error\n                            err.syscall = \"connect\";\n                            eventHandler.errorHandler(_this)(err);\n                        });\n                        stream.once(CONNECT_EVENT, function () {\n                            connectTimeoutCleared = true;\n                            stream.setTimeout(0);\n                        });\n                    }\n                }\n                else if (stream.destroyed) {\n                    const firstError = _this.connector.firstError;\n                    if (firstError) {\n                        process.nextTick(() => {\n                            eventHandler.errorHandler(_this)(firstError);\n                        });\n                    }\n                    process.nextTick(eventHandler.closeHandler(_this));\n                }\n                else {\n                    process.nextTick(eventHandler.connectHandler(_this));\n                }\n                if (!stream.destroyed) {\n                    stream.once(\"error\", eventHandler.errorHandler(_this));\n                    stream.once(\"close\", eventHandler.closeHandler(_this));\n                }\n                const connectionReadyHandler = function () {\n                    _this.removeListener(\"close\", connectionCloseHandler);\n                    resolve();\n                };\n                var connectionCloseHandler = function () {\n                    _this.removeListener(\"ready\", connectionReadyHandler);\n                    reject(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG));\n                };\n                _this.once(\"ready\", connectionReadyHandler);\n                _this.once(\"close\", connectionCloseHandler);\n            });\n        });\n    }\n    /**\n     * Disconnect from Redis.\n     *\n     * This method closes the connection immediately,\n     * and may lose some pending replies that haven't written to client.\n     * If you want to wait for the pending replies, use Redis#quit instead.\n     */\n    disconnect(reconnect = false) {\n        if (!reconnect) {\n            this.manuallyClosing = true;\n        }\n        if (this.reconnectTimeout && !reconnect) {\n            clearTimeout(this.reconnectTimeout);\n            this.reconnectTimeout = null;\n        }\n        if (this.status === \"wait\") {\n            eventHandler.closeHandler(this)();\n        }\n        else {\n            this.connector.disconnect();\n        }\n    }\n    /**\n     * Disconnect from Redis.\n     *\n     * @deprecated\n     */\n    end() {\n        this.disconnect();\n    }\n    /**\n     * Create a new instance with the same options as the current one.\n     *\n     * @example\n     * ```js\n     * var redis = new Redis(6380);\n     * var anotherRedis = redis.duplicate();\n     * ```\n     */\n    duplicate(override) {\n        return new Redis({ ...this.options, ...override });\n    }\n    /**\n     * Mode of the connection.\n     *\n     * One of `\"normal\"`, `\"subscriber\"`, or `\"monitor\"`. When the connection is\n     * not in `\"normal\"` mode, certain commands are not allowed.\n     */\n    get mode() {\n        var _a;\n        return this.options.monitor\n            ? \"monitor\"\n            : ((_a = this.condition) === null || _a === void 0 ? void 0 : _a.subscriber)\n                ? \"subscriber\"\n                : \"normal\";\n    }\n    /**\n     * Listen for all requests received by the server in real time.\n     *\n     * This command will create a new connection to Redis and send a\n     * MONITOR command via the new connection in order to avoid disturbing\n     * the current connection.\n     *\n     * @param callback The callback function. If omit, a promise will be returned.\n     * @example\n     * ```js\n     * var redis = new Redis();\n     * redis.monitor(function (err, monitor) {\n     *   // Entering monitoring mode.\n     *   monitor.on('monitor', function (time, args, source, database) {\n     *     console.log(time + \": \" + util.inspect(args));\n     *   });\n     * });\n     *\n     * // supports promise as well as other commands\n     * redis.monitor().then(function (monitor) {\n     *   monitor.on('monitor', function (time, args, source, database) {\n     *     console.log(time + \": \" + util.inspect(args));\n     *   });\n     * });\n     * ```\n     */\n    monitor(callback) {\n        const monitorInstance = this.duplicate({\n            monitor: true,\n            lazyConnect: false,\n        });\n        return (0, standard_as_callback_1.default)(new Promise(function (resolve, reject) {\n            monitorInstance.once(\"error\", reject);\n            monitorInstance.once(\"monitoring\", function () {\n                resolve(monitorInstance);\n            });\n        }), callback);\n    }\n    /**\n     * Send a command to Redis\n     *\n     * This method is used internally and in most cases you should not\n     * use it directly. If you need to send a command that is not supported\n     * by the library, you can use the `call` method:\n     *\n     * ```js\n     * const redis = new Redis();\n     *\n     * redis.call('set', 'foo', 'bar');\n     * // or\n     * redis.call(['set', 'foo', 'bar']);\n     * ```\n     *\n     * @ignore\n     */\n    sendCommand(command, stream) {\n        var _a, _b;\n        if (this.status === \"wait\") {\n            this.connect().catch(lodash_1.noop);\n        }\n        if (this.status === \"end\") {\n            command.reject(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG));\n            return command.promise;\n        }\n        if (((_a = this.condition) === null || _a === void 0 ? void 0 : _a.subscriber) &&\n            !Command_1.default.checkFlag(\"VALID_IN_SUBSCRIBER_MODE\", command.name)) {\n            command.reject(new Error(\"Connection in subscriber mode, only subscriber commands may be used\"));\n            return command.promise;\n        }\n        if (typeof this.options.commandTimeout === \"number\") {\n            command.setTimeout(this.options.commandTimeout);\n        }\n        const blockingTimeout = this.getBlockingTimeoutInMs(command);\n        let writable = this.status === \"ready\" ||\n            (!stream &&\n                this.status === \"connect\" &&\n                (0, commands_1.exists)(command.name, { caseInsensitive: true }) &&\n                ((0, commands_1.hasFlag)(command.name, \"loading\", { nameCaseInsensitive: true }) ||\n                    Command_1.default.checkFlag(\"HANDSHAKE_COMMANDS\", command.name)));\n        if (!this.stream) {\n            writable = false;\n        }\n        else if (!this.stream.writable) {\n            writable = false;\n            // @ts-expect-error\n        }\n        else if (this.stream._writableState && this.stream._writableState.ended) {\n            // TODO: We should be able to remove this as the PR has already been merged.\n            // https://github.com/iojs/io.js/pull/1217\n            writable = false;\n        }\n        if (!writable) {\n            if (!this.options.enableOfflineQueue) {\n                command.reject(new Error(\"Stream isn't writeable and enableOfflineQueue options is false\"));\n                return command.promise;\n            }\n            if (command.name === \"quit\" && this.offlineQueue.length === 0) {\n                this.disconnect();\n                command.resolve(Buffer.from(\"OK\"));\n                return command.promise;\n            }\n            // @ts-expect-error\n            if (debug.enabled) {\n                debug(\"queue command[%s]: %d -> %s(%o)\", this._getDescription(), this.condition.select, command.name, command.args);\n            }\n            this.offlineQueue.push({\n                command: command,\n                stream: stream,\n                select: this.condition.select,\n            });\n            // For blocking commands in the offline queue, arm a client-side timeout\n            // only when blockingTimeout is configured. Without this option, queued\n            // blocking commands may wait indefinitely on a dead connection.\n            if (Command_1.default.checkFlag(\"BLOCKING_COMMANDS\", command.name)) {\n                const offlineTimeout = this.getConfiguredBlockingTimeout();\n                if (offlineTimeout !== undefined) {\n                    command.setBlockingTimeout(offlineTimeout);\n                }\n            }\n        }\n        else {\n            // @ts-expect-error\n            if (debug.enabled) {\n                debug(\"write command[%s]: %d -> %s(%o)\", this._getDescription(), (_b = this.condition) === null || _b === void 0 ? void 0 : _b.select, command.name, command.args);\n            }\n            if (stream) {\n                if (\"isPipeline\" in stream && stream.isPipeline) {\n                    stream.write(command.toWritable(stream.destination.redis.stream));\n                }\n                else {\n                    stream.write(command.toWritable(stream));\n                }\n            }\n            else {\n                this.stream.write(command.toWritable(this.stream));\n            }\n            this.commandQueue.push({\n                command: command,\n                stream: stream,\n                select: this.condition.select,\n            });\n            if (blockingTimeout !== undefined) {\n                command.setBlockingTimeout(blockingTimeout);\n            }\n            if (Command_1.default.checkFlag(\"WILL_DISCONNECT\", command.name)) {\n                this.manuallyClosing = true;\n            }\n            if (this.options.socketTimeout !== undefined &&\n                this.socketTimeoutTimer === undefined) {\n                this.setSocketTimeout();\n            }\n        }\n        if (command.name === \"select\" && (0, utils_1.isInt)(command.args[0])) {\n            const db = parseInt(command.args[0], 10);\n            if (this.condition.select !== db) {\n                this.condition.select = db;\n                this.emit(\"select\", db);\n                debug(\"switch to db [%d]\", this.condition.select);\n            }\n        }\n        if (!writable || command.isTraced) {\n            return command.promise;\n        }\n        // Trace on the write path only, and only once per command. Commands may\n        // pass through sendCommand multiple times (offline queue flush,\n        // prevCommandQueue resend after reconnect). The isTraced flag ensures\n        // we don't emit duplicate trace events.\n        command.isTraced = true;\n        return (0, tracing_1.traceCommand)(() => command.promise, () => this._buildCommandContext(command));\n    }\n    getBlockingTimeoutInMs(command) {\n        var _a;\n        if (!Command_1.default.checkFlag(\"BLOCKING_COMMANDS\", command.name)) {\n            return undefined;\n        }\n        // Feature is opt-in: only enabled when blockingTimeout is set to a positive number\n        const configuredTimeout = this.getConfiguredBlockingTimeout();\n        if (configuredTimeout === undefined) {\n            return undefined;\n        }\n        const timeout = command.extractBlockingTimeout();\n        if (typeof timeout === \"number\") {\n            if (timeout > 0) {\n                // Finite timeout from command args - add grace period\n                return (timeout +\n                    ((_a = this.options.blockingTimeoutGrace) !== null && _a !== void 0 ? _a : RedisOptions_1.DEFAULT_REDIS_OPTIONS.blockingTimeoutGrace));\n            }\n            // Command has timeout=0 (block forever), use blockingTimeout option as safety net\n            return configuredTimeout;\n        }\n        if (timeout === null) {\n            // No BLOCK option found (e.g., XREAD without BLOCK), use blockingTimeout as safety net\n            return configuredTimeout;\n        }\n        return undefined;\n    }\n    getConfiguredBlockingTimeout() {\n        if (typeof this.options.blockingTimeout === \"number\" &&\n            this.options.blockingTimeout > 0) {\n            return this.options.blockingTimeout;\n        }\n        return undefined;\n    }\n    setSocketTimeout() {\n        this.socketTimeoutTimer = setTimeout(() => {\n            this.stream.destroy(new Error(`Socket timeout. Expecting data, but didn't receive any in ${this.options.socketTimeout}ms.`));\n            this.socketTimeoutTimer = undefined;\n        }, this.options.socketTimeout);\n        // this handler must run after the \"data\" handler in \"DataHandler\"\n        // so that `this.commandQueue.length` will be updated\n        this.stream.once(\"data\", () => {\n            clearTimeout(this.socketTimeoutTimer);\n            this.socketTimeoutTimer = undefined;\n            if (this.commandQueue.length === 0)\n                return;\n            this.setSocketTimeout();\n        });\n    }\n    scanStream(options) {\n        return this.createScanStream(\"scan\", { options });\n    }\n    scanBufferStream(options) {\n        return this.createScanStream(\"scanBuffer\", { options });\n    }\n    sscanStream(key, options) {\n        return this.createScanStream(\"sscan\", { key, options });\n    }\n    sscanBufferStream(key, options) {\n        return this.createScanStream(\"sscanBuffer\", { key, options });\n    }\n    hscanStream(key, options) {\n        return this.createScanStream(\"hscan\", { key, options });\n    }\n    hscanBufferStream(key, options) {\n        return this.createScanStream(\"hscanBuffer\", { key, options });\n    }\n    zscanStream(key, options) {\n        return this.createScanStream(\"zscan\", { key, options });\n    }\n    zscanBufferStream(key, options) {\n        return this.createScanStream(\"zscanBuffer\", { key, options });\n    }\n    /**\n     * Emit only when there's at least one listener.\n     *\n     * @ignore\n     */\n    silentEmit(eventName, arg) {\n        let error;\n        if (eventName === \"error\") {\n            error = arg;\n            if (this.status === \"end\") {\n                return;\n            }\n            if (this.manuallyClosing) {\n                // ignore connection related errors when manually disconnecting\n                if (error instanceof Error &&\n                    (error.message === utils_1.CONNECTION_CLOSED_ERROR_MSG ||\n                        // @ts-expect-error\n                        error.syscall === \"connect\" ||\n                        // @ts-expect-error\n                        error.syscall === \"read\")) {\n                    return;\n                }\n            }\n        }\n        if (this.listeners(eventName).length > 0) {\n            return this.emit.apply(this, arguments);\n        }\n        if (error && error instanceof Error) {\n            console.error(\"[ioredis] Unhandled error event:\", error.stack);\n        }\n        return false;\n    }\n    /**\n     * @ignore\n     */\n    recoverFromFatalError(_commandError, err, options) {\n        this.flushQueue(err, options);\n        this.silentEmit(\"error\", err);\n        this.disconnect(true);\n    }\n    /**\n     * @ignore\n     */\n    handleReconnection(err, item) {\n        var _a;\n        let needReconnect = false;\n        if (this.options.reconnectOnError &&\n            !Command_1.default.checkFlag(\"IGNORE_RECONNECT_ON_ERROR\", item.command.name)) {\n            needReconnect = this.options.reconnectOnError(err);\n        }\n        switch (needReconnect) {\n            case 1:\n            case true:\n                if (this.status !== \"reconnecting\") {\n                    this.disconnect(true);\n                }\n                item.command.reject(err);\n                break;\n            case 2:\n                if (this.status !== \"reconnecting\") {\n                    this.disconnect(true);\n                }\n                if (((_a = this.condition) === null || _a === void 0 ? void 0 : _a.select) !== item.select &&\n                    item.command.name !== \"select\") {\n                    this.select(item.select);\n                }\n                // TODO\n                // @ts-expect-error\n                this.sendCommand(item.command);\n                break;\n            default:\n                item.command.reject(err);\n        }\n    }\n    /**\n     * @ignore\n     */\n    _getServerAddress() {\n        if (\"path\" in this.options && this.options.path) {\n            return { address: this.options.path, port: undefined };\n        }\n        return {\n            address: (\"host\" in this.options && this.options.host) || \"localhost\",\n            port: (\"port\" in this.options && this.options.port) || 6379,\n        };\n    }\n    _buildCommandContext(command) {\n        var _a, _b, _c;\n        const { address, port } = this._getServerAddress();\n        return {\n            command: command.name,\n            args: (0, tracing_1.sanitizeArgs)(command.name, command.args),\n            database: (_c = (_b = (_a = this.condition) === null || _a === void 0 ? void 0 : _a.select) !== null && _b !== void 0 ? _b : this.options.db) !== null && _c !== void 0 ? _c : 0,\n            serverAddress: address,\n            serverPort: port,\n        };\n    }\n    _buildBatchContext(batchSize) {\n        var _a, _b, _c;\n        const { address, port } = this._getServerAddress();\n        return {\n            batchMode: \"MULTI\",\n            batchSize,\n            database: (_c = (_b = (_a = this.condition) === null || _a === void 0 ? void 0 : _a.select) !== null && _b !== void 0 ? _b : this.options.db) !== null && _c !== void 0 ? _c : 0,\n            serverAddress: address,\n            serverPort: port,\n        };\n    }\n    /**\n     * Get description of the connection. Used for debugging.\n     */\n    _getDescription() {\n        let description;\n        if (\"path\" in this.options && this.options.path) {\n            description = this.options.path;\n        }\n        else if (this.stream &&\n            this.stream.remoteAddress &&\n            this.stream.remotePort) {\n            description = this.stream.remoteAddress + \":\" + this.stream.remotePort;\n        }\n        else if (\"host\" in this.options && this.options.host) {\n            description = this.options.host + \":\" + this.options.port;\n        }\n        else {\n            // Unexpected\n            description = \"\";\n        }\n        if (this.options.connectionName) {\n            description += ` (${this.options.connectionName})`;\n        }\n        return description;\n    }\n    resetCommandQueue() {\n        this.commandQueue = new Deque();\n    }\n    resetOfflineQueue() {\n        this.offlineQueue = new Deque();\n    }\n    parseOptions(...args) {\n        const options = {};\n        let isTls = false;\n        for (let i = 0; i < args.length; ++i) {\n            const arg = args[i];\n            if (arg === null || typeof arg === \"undefined\") {\n                continue;\n            }\n            if (typeof arg === \"object\") {\n                (0, lodash_1.defaults)(options, arg);\n            }\n            else if (typeof arg === \"string\") {\n                (0, lodash_1.defaults)(options, (0, utils_1.parseURL)(arg));\n                if (arg.startsWith(\"rediss://\")) {\n                    isTls = true;\n                }\n            }\n            else if (typeof arg === \"number\") {\n                options.port = arg;\n            }\n            else {\n                throw new Error(\"Invalid argument \" + arg);\n            }\n        }\n        if (isTls) {\n            (0, lodash_1.defaults)(options, { tls: true });\n        }\n        (0, lodash_1.defaults)(options, Redis.defaultOptions);\n        if (typeof options.port === \"string\") {\n            options.port = parseInt(options.port, 10);\n        }\n        if (typeof options.db === \"string\") {\n            options.db = parseInt(options.db, 10);\n        }\n        // @ts-expect-error\n        this.options = (0, utils_1.resolveTLSProfile)(options);\n    }\n    /**\n     * Change instance's status\n     */\n    setStatus(status, arg) {\n        // @ts-expect-error\n        if (debug.enabled) {\n            debug(\"status[%s]: %s -> %s\", this._getDescription(), this.status || \"[empty]\", status);\n        }\n        this.status = status;\n        process.nextTick(this.emit.bind(this, status, arg));\n    }\n    createScanStream(command, { key, options = {} }) {\n        return new ScanStream_1.default({\n            objectMode: true,\n            key: key,\n            redis: this,\n            command: command,\n            ...options,\n        });\n    }\n    /**\n     * Flush offline queue and command queue with error.\n     *\n     * @param error The error object to send to the commands\n     * @param options options\n     */\n    flushQueue(error, options) {\n        options = (0, lodash_1.defaults)({}, options, {\n            offlineQueue: true,\n            commandQueue: true,\n        });\n        let item;\n        if (options.offlineQueue) {\n            while ((item = this.offlineQueue.shift())) {\n                item.command.reject(error);\n            }\n        }\n        if (options.commandQueue) {\n            if (this.commandQueue.length > 0) {\n                if (this.stream) {\n                    this.stream.removeAllListeners(\"data\");\n                }\n                while ((item = this.commandQueue.shift())) {\n                    item.command.reject(error);\n                }\n            }\n        }\n    }\n    /**\n     * Check whether Redis has finished loading the persistent data and is able to\n     * process commands.\n     */\n    _readyCheck(callback) {\n        const _this = this;\n        this.info(function (err, res) {\n            if (err) {\n                if (err.message && err.message.includes(\"NOPERM\")) {\n                    console.warn(`Skipping the ready check because INFO command fails: \"${err.message}\". You can disable ready check with \"enableReadyCheck\". More: https://github.com/luin/ioredis/wiki/Disable-ready-check.`);\n                    return callback(null, {});\n                }\n                return callback(err);\n            }\n            if (typeof res !== \"string\") {\n                return callback(null, res);\n            }\n            const info = {};\n            const lines = res.split(\"\\r\\n\");\n            for (let i = 0; i < lines.length; ++i) {\n                const [fieldName, ...fieldValueParts] = lines[i].split(\":\");\n                const fieldValue = fieldValueParts.join(\":\");\n                if (fieldValue) {\n                    info[fieldName] = fieldValue;\n                }\n            }\n            if (!info.loading || info.loading === \"0\") {\n                callback(null, info);\n            }\n            else {\n                const loadingEtaMs = (info.loading_eta_seconds || 1) * 1000;\n                const retryTime = _this.options.maxLoadingRetryTime &&\n                    _this.options.maxLoadingRetryTime < loadingEtaMs\n                    ? _this.options.maxLoadingRetryTime\n                    : loadingEtaMs;\n                debug(\"Redis server still loading, trying again in \" + retryTime + \"ms\");\n                setTimeout(function () {\n                    _this._readyCheck(callback);\n                }, retryTime);\n            }\n        }).catch(lodash_1.noop);\n    }\n}\nRedis.Cluster = cluster_1.default;\nRedis.Command = Command_1.default;\n/**\n * Default options\n */\nRedis.defaultOptions = RedisOptions_1.DEFAULT_REDIS_OPTIONS;\n(0, applyMixin_1.default)(Redis, events_1.EventEmitter);\n(0, transaction_1.addTransactionSupport)(Redis.prototype);\nexports.default = Redis;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.print = exports.ReplyError = exports.SentinelIterator = exports.SentinelConnector = exports.AbstractConnector = exports.Pipeline = exports.ScanStream = exports.Command = exports.Cluster = exports.Redis = exports.default = void 0;\nexports = module.exports = require(\"./Redis\").default;\nvar Redis_1 = require(\"./Redis\");\nObject.defineProperty(exports, \"default\", { enumerable: true, get: function () { return Redis_1.default; } });\nvar Redis_2 = require(\"./Redis\");\nObject.defineProperty(exports, \"Redis\", { enumerable: true, get: function () { return Redis_2.default; } });\nvar cluster_1 = require(\"./cluster\");\nObject.defineProperty(exports, \"Cluster\", { enumerable: true, get: function () { return cluster_1.default; } });\n/**\n * @ignore\n */\nvar Command_1 = require(\"./Command\");\nObject.defineProperty(exports, \"Command\", { enumerable: true, get: function () { return Command_1.default; } });\n/**\n * @ignore\n */\nvar ScanStream_1 = require(\"./ScanStream\");\nObject.defineProperty(exports, \"ScanStream\", { enumerable: true, get: function () { return ScanStream_1.default; } });\n/**\n * @ignore\n */\nvar Pipeline_1 = require(\"./Pipeline\");\nObject.defineProperty(exports, \"Pipeline\", { enumerable: true, get: function () { return Pipeline_1.default; } });\n/**\n * @ignore\n */\nvar AbstractConnector_1 = require(\"./connectors/AbstractConnector\");\nObject.defineProperty(exports, \"AbstractConnector\", { enumerable: true, get: function () { return AbstractConnector_1.default; } });\n/**\n * @ignore\n */\nvar SentinelConnector_1 = require(\"./connectors/SentinelConnector\");\nObject.defineProperty(exports, \"SentinelConnector\", { enumerable: true, get: function () { return SentinelConnector_1.default; } });\nObject.defineProperty(exports, \"SentinelIterator\", { enumerable: true, get: function () { return SentinelConnector_1.SentinelIterator; } });\n// No TS typings\nexports.ReplyError = require(\"redis-errors\").ReplyError;\n/**\n * @ignore\n */\nObject.defineProperty(exports, \"Promise\", {\n    get() {\n        console.warn(\"ioredis v5 does not support plugging third-party Promise library anymore. Native Promise will be used.\");\n        return Promise;\n    },\n    set(_lib) {\n        console.warn(\"ioredis v5 does not support plugging third-party Promise library anymore. Native Promise will be used.\");\n    },\n});\n/**\n * @ignore\n */\nfunction print(err, reply) {\n    if (err) {\n        console.log(\"Error: \" + err);\n    }\n    else {\n        console.log(\"Reply: \" + reply);\n    }\n}\nexports.print = print;\n","import { _ as users, a as mcpOauthConsent, b as getDbFromContext$1, c as authVerificationsSqlite, d as authJwks, f as authJwksSqlite, g as authAccountsSqlite, h as authAccounts, i as mcpOauthClientSqlite, l as authSessions, m as authDeviceCodesSqlite, n as mcpOauthAccessTokenSqlite, o as mcpOauthConsentSqlite, p as authDeviceCodes, r as mcpOauthClient, s as authVerifications, t as mcpOauthAccessToken, u as authSessionsSqlite, v as usersSqlite, y as getDatabaseHandle$1 } from \"./mcp-oauth-SRTcHMWZ.mjs\";\nimport { createRequire } from \"node:module\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { bigint, boolean, check, doublePrecision, index, integer, jsonb, pgEnum, pgPolicy, pgTable, primaryKey, text, timestamp, uniqueIndex } from \"drizzle-orm/pg-core\";\nimport { check as check$1, index as index$1, integer as integer$1, primaryKey as primaryKey$1, real, sqliteTable, text as text$1, uniqueIndex as uniqueIndex$1 } from \"drizzle-orm/sqlite-core\";\nimport { and, and as and$1, and as and$2, asc, asc as asc$1, count, count as count$1, count as count$2, desc, desc as desc$1, desc as desc$2, eq, eq as eq$1, eq as eq$2, gt, gt as gt$1, gt as gt$2, inArray, inArray as inArray$1, inArray as inArray$2, isNotNull, isNotNull as isNotNull$1, isNull, isNull as isNull$1, isNull as isNull$2, lt, lt as lt$1, lt as lt$2, lte as lte$1, max as max$1, max as max$2, ne, ne as ne$1, ne as ne$2, notInArray as notInArray$1, or, or as or$1, or as or$2, sql, sql as sql$1, sql as sql$2 } from \"drizzle-orm\";\nimport { log } from \"@keystrokehq/telemetry\";\nimport { existsSync, mkdirSync, unlinkSync } 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 { createCipheriv, createDecipheriv, createHash, randomBytes } from \"node:crypto\";\nimport { Redis } from \"ioredis\";\nimport { ClaimableOrganizationSlugSchema, DEFAULT_PLAN_KEY, ORGANIZATION_SLUG_TAKEN_MESSAGE, OrganizationSlugSchema, PROJECT_SLUG_TAKEN_MESSAGE, ProjectSlugSchema, RESERVED_ORGANIZATION_SLUGS, normalizeOrganizationSidebarBranding, slugifyOrganizationName, slugifyProjectName, stripPromptContext } 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\nconst DEFAULT_PLATFORM_DATABASE_URL = \"file:./data/public.db\";\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/**\n* Resolve Postgres client pool size from env.\n* Invalid / non-positive values fall back to {@link DEFAULT_PG_POOL_MAX}.\n*/\nfunction resolvePgPoolMax$1(env = process.env) {\n\tconst raw = env.PG_POOL_MAX?.trim();\n\tif (!raw) return 10;\n\tconst parsed = Number(raw);\n\tif (!Number.isFinite(parsed) || parsed < 1) return 10;\n\treturn Math.floor(parsed);\n}\nconst POSTGRES_ENV_KEYS$1 = [\n\t\"POSTGRES_HOST\",\n\t\"POSTGRES_PORT\",\n\t\"POSTGRES_DB\",\n\t\"POSTGRES_USER\",\n\t\"POSTGRES_PASSWORD\"\n];\nfunction readEnv$1(env, key) {\n\treturn env[key]?.trim() || void 0;\n}\nfunction readPostgresSsl$1(env) {\n\tconst value = readEnv$1(env, \"POSTGRES_SSL\")?.toLowerCase();\n\treturn value === \"true\" || value === \"1\" || value === \"yes\";\n}\nfunction readPostgresSslFromUrl$1(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$1(env, url) {\n\treturn readPostgresSsl$1(env) || (url ? readPostgresSslFromUrl$1(url) : false);\n}\nfunction resolvePostgresBranch$1(env) {\n\tconst explicit = env.POSTGRES_BRANCH?.trim();\n\tif (explicit) return explicit;\n\tconst platformUser = readEnv$1(env, \"POSTGRES_USER\") ?? readPostgresUserFromDatabaseUrl$1(readEnv$1(env, \"DATABASE_URL\"));\n\tif (!platformUser?.includes(\".\")) return;\n\treturn platformUser.slice(platformUser.lastIndexOf(\".\") + 1) || void 0;\n}\nfunction readPostgresUserFromDatabaseUrl$1(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$1(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$1(env) {\n\treturn POSTGRES_ENV_KEYS$1.filter((key) => readEnv$1(env, key) === void 0);\n}\n/** Append POSTGRES_BRANCH to bare role names for providers that use user.branch connections. */\nfunction qualifyConnectionUser$1(user, env = process.env) {\n\tif (user.includes(\".\")) return user;\n\tconst branch = resolvePostgresBranch$1(env);\n\tif (!branch) return user;\n\treturn `${user}.${branch}`;\n}\nfunction buildPostgresUrl$1(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$1(url) : url;\n}\nfunction parsePostgresUrl$1(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$1(env) {\n\tif (missingPostgresEnvKeys$1(env).length > 0) return;\n\tconst port = Number(readEnv$1(env, \"POSTGRES_PORT\"));\n\tif (!Number.isFinite(port)) throw new Error(`Invalid POSTGRES_PORT: ${env.POSTGRES_PORT}`);\n\treturn {\n\t\thost: readEnv$1(env, \"POSTGRES_HOST\"),\n\t\tport,\n\t\tdatabase: readEnv$1(env, \"POSTGRES_DB\"),\n\t\tuser: readEnv$1(env, \"POSTGRES_USER\"),\n\t\tpassword: readEnv$1(env, \"POSTGRES_PASSWORD\"),\n\t\tssl: readPostgresSsl$1(env)\n\t};\n}\n/** Requires POSTGRES_* env vars or a postgres DATABASE_URL. */\nfunction resolvePostgresConfigFromEnv$1(env = process.env) {\n\tconst direct = readEnv$1(env, \"DATABASE_URL\");\n\tif (direct && /^postgres(ql)?:\\/\\//i.test(direct)) return {\n\t\t...parsePostgresUrl$1(direct),\n\t\tssl: resolvePostgresSsl$1(env, direct)\n\t};\n\tconst config = resolvePostgresConfigFromPostgresEnv$1(env);\n\tif (!config) throw new Error(`Missing required Postgres env vars: ${missingPostgresEnvKeys$1(env).join(\", \")}`);\n\treturn config;\n}\n/** Requires POSTGRES_* env vars or a postgres DATABASE_URL. */\nfunction resolvePostgresUrlFromEnv$1(env = process.env) {\n\tconst ssl = readPostgresSsl$1(env);\n\tconst direct = readEnv$1(env, \"DATABASE_URL\");\n\tif (direct && /^postgres(ql)?:\\/\\//i.test(direct)) return ssl ? applyPostgresSslMode$1(direct) : direct;\n\treturn buildPostgresUrl$1(resolvePostgresConfigFromEnv$1(env));\n}\n//#endregion\n//#region src/config/database-url.ts\nfunction resolvePlatformPostgresConfig(env = process.env) {\n\treturn resolvePostgresConfigFromEnv$1(env);\n}\nfunction resolveTenantDatabaseUrl(env = process.env) {\n\tconst url = env.TENANT_DATABASE_URL?.trim();\n\tif (!url) throw new Error(\"TENANT_DATABASE_URL is required for tenant database queries\");\n\tif (inferDialect(url) !== \"postgres\") throw new Error(\"TENANT_DATABASE_URL must be a Postgres URL\");\n\treturn url;\n}\nfunction resolvePlatformDatabaseUrl(env = process.env) {\n\tconst direct = env.DATABASE_URL?.trim();\n\tif (direct) {\n\t\tif (inferDialect(direct) === \"sqlite\") return direct;\n\t\treturn resolvePostgresUrlFromEnv$1(env);\n\t}\n\ttry {\n\t\treturn resolvePostgresUrlFromEnv$1(env);\n\t} catch {\n\t\treturn DEFAULT_PLATFORM_DATABASE_URL;\n\t}\n}\n//#endregion\n//#region src/config/organization-scope.ts\nconst organizationScopeStorage = new AsyncLocalStorage();\n/** Standalone / sqlite single-tenant org id (mirrors DEFAULT_STANDALONE_ORGANIZATION_ID). */\nconst DEFAULT_ORGANIZATION_ID = \"default\";\nfunction runWithOrganizationScope(organizationId, fn) {\n\treturn organizationScopeStorage.run(organizationId, fn);\n}\nfunction getOrganizationScopeId() {\n\treturn organizationScopeStorage.getStore();\n}\n/**\n* Organization id for tenant writes.\n*\n* Prefer ALS (middleware / runWithProjectDatabase). When unset, fall back to the\n* standalone default — hosted postgres still fail-closes via RLS claim checks.\n*/\nfunction requireOrganizationScopeId() {\n\treturn getOrganizationScopeId() ?? DEFAULT_ORGANIZATION_ID;\n}\n/** Bind org scope for the current async resource tree (tests / local init). */\nfunction bindOrganizationScope(organizationId) {\n\torganizationScopeStorage.enterWith(organizationId);\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\tredisUrlCiphertext: text(\"redis_url_ciphertext\"),\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\tredisUrlCiphertext: text$1(\"redis_url_ciphertext\"),\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\turl: text(\"url\"),\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\turl: text$1(\"url\"),\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/templates.ts\nconst templates = pgTable(\"templates\", {\n\tid: text(\"id\").primaryKey(),\n\tslug: text(\"slug\").notNull(),\n\tkind: text(\"kind\").$type().notNull(),\n\ttitle: text(\"title\").notNull(),\n\tdescription: text(\"description\").notNull(),\n\ttags: jsonb(\"tags\").$type().notNull().default([]),\n\trequiredApps: jsonb(\"required_apps\").$type().notNull().default([]),\n\t/** Relative project paths → file contents (e.g. `src/agents/foo.ts`). */\n\tfiles: jsonb(\"files\").$type().notNull().default({}),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [uniqueIndex(\"templates_slug_idx\").on(table.slug)]);\nconst templatesSqlite = sqliteTable(\"templates\", {\n\tid: text$1(\"id\").primaryKey(),\n\tslug: text$1(\"slug\").notNull(),\n\tkind: text$1(\"kind\").$type().notNull(),\n\ttitle: text$1(\"title\").notNull(),\n\tdescription: text$1(\"description\").notNull(),\n\ttags: text$1(\"tags\", { mode: \"json\" }).$type().notNull().default([]),\n\trequiredApps: text$1(\"required_apps\", { mode: \"json\" }).$type().notNull().default([]),\n\tfiles: text$1(\"files\", { mode: \"json\" }).$type().notNull().default({}),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [uniqueIndex$1(\"templates_slug_idx\").on(table.slug)]);\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/oauth-pending-states.ts\nconst oauthPendingStates = pgTable(\"oauth_pending_states\", {\n\tid: text(\"id\").primaryKey(),\n\tpayloadCiphertext: text(\"payload_ciphertext\").notNull(),\n\texpiresAt: timestamp(\"expires_at\", { withTimezone: true }).notNull(),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull()\n}, (table) => [index(\"oauth_pending_states_expires_at_idx\").on(table.expiresAt)]);\nconst oauthPendingStatesSqlite = sqliteTable(\"oauth_pending_states\", {\n\tid: text$1(\"id\").primaryKey(),\n\tpayloadCiphertext: text$1(\"payload_ciphertext\").notNull(),\n\texpiresAt: integer$1(\"expires_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [index$1(\"oauth_pending_states_expires_at_idx\").on(table.expiresAt)]);\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\t/**\n\t* One-active managed deploy lease. Holds the in-flight artifact id from\n\t* candidate construction through health → main promotion (released as soon\n\t* as main points at the candidate, and again on DB cutover as a safety net).\n\t* Null when idle.\n\t*/\n\tdeployLeaseArtifactId: text(\"deploy_lease_artifact_id\"),\n\t/** Absolute expiry for pre-stage lease reclaim after process death. */\n\tdeployLeaseExpiresAt: timestamp(\"deploy_lease_expires_at\", { withTimezone: true }),\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\tdeployLeaseArtifactId: text$1(\"deploy_lease_artifact_id\"),\n\tdeployLeaseExpiresAt: integer$1(\"deploy_lease_expires_at\", { mode: \"timestamp_ms\" }),\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\tsourceRepositoryId: text(\"source_repository_id\"),\n\tsourceCommitSha: text(\"source_commit_sha\"),\n\tbaseMainSha: text(\"base_main_sha\"),\n\tbaseDraftSha: text(\"base_draft_sha\"),\n\tdeployMode: text(\"deploy_mode\").$type(),\n\tcandidateOps: jsonb(\"candidate_ops\").$type(),\n\t/** Provider branch name for the ephemeral/temp deploy candidate. */\n\tcandidateRef: text(\"candidate_ref\"),\n\t/** True when the candidate lives in the provider ephemeral namespace. */\n\tcandidateEphemeral: boolean(\"candidate_ephemeral\"),\n\t/** Protocol state for prepare → publish → upload → complete. */\n\tprotocolState: text(\"protocol_state\"),\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\tsourceRepositoryId: text$1(\"source_repository_id\"),\n\tsourceCommitSha: text$1(\"source_commit_sha\"),\n\tbaseMainSha: text$1(\"base_main_sha\"),\n\tbaseDraftSha: text$1(\"base_draft_sha\"),\n\tdeployMode: text$1(\"deploy_mode\").$type(),\n\tcandidateOps: text$1(\"candidate_ops\", { mode: \"json\" }).$type(),\n\tcandidateRef: text$1(\"candidate_ref\"),\n\tcandidateEphemeral: integer$1(\"candidate_ephemeral\", { mode: \"boolean\" }),\n\tprotocolState: text$1(\"protocol_state\"),\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-repositories.ts\nconst projectGitProviders = [\"github\", \"code_storage\"];\nconst projectRepositoryLifecycleStatuses = [\n\t\"provisioning\",\n\t\"ready\",\n\t\"failed\",\n\t\"deleting\",\n\t\"deleted\"\n];\nconst projectRepositoryContentStatuses = [\n\t\"empty\",\n\t\"awaiting_source\",\n\t\"synced\",\n\t\"failed\"\n];\nconst projectRepositoryDesiredStates = [\"active\", \"deleted\"];\nconst projectGitProviderEnum = pgEnum(\"project_git_provider\", projectGitProviders);\nconst projectRepositoryLifecycleStatusEnum = pgEnum(\"project_repository_lifecycle_status\", projectRepositoryLifecycleStatuses);\nconst projectRepositoryContentStatusEnum = pgEnum(\"project_repository_content_status\", projectRepositoryContentStatuses);\nconst projectRepositoryDesiredStateEnum = pgEnum(\"project_repository_desired_state\", projectRepositoryDesiredStates);\nconst projectRepositories = pgTable(\"project_repositories\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id, { onDelete: \"cascade\" }),\n\tprojectId: text(\"project_id\").notNull().references(() => projects.id, { onDelete: \"cascade\" }),\n\tprovider: projectGitProviderEnum(\"provider\").notNull(),\n\texternalRepositoryId: text(\"external_repository_id\"),\n\towner: text(\"owner\"),\n\tname: text(\"name\"),\n\tdefaultBranch: text(\"default_branch\").notNull().default(\"main\"),\n\tlifecycleStatus: projectRepositoryLifecycleStatusEnum(\"lifecycle_status\").notNull().default(\"provisioning\"),\n\tcontentStatus: projectRepositoryContentStatusEnum(\"content_status\").notNull().default(\"empty\"),\n\tdesiredState: projectRepositoryDesiredStateEnum(\"desired_state\").notNull().default(\"active\"),\n\tlastErrorCode: text(\"last_error_code\"),\n\tlastError: text(\"last_error\"),\n\tprovisionedAt: timestamp(\"provisioned_at\", { withTimezone: true }),\n\t/**\n\t* When set, platform-agent hello-world scaffold already ran for this draft —\n\t* skip repeated resolveRef + listTree bootstrap checks.\n\t*/\n\tplatformAgentScaffoldedAt: timestamp(\"platform_agent_scaffolded_at\", { withTimezone: true }),\n\tdeletedAt: timestamp(\"deleted_at\", { withTimezone: true }),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [\n\tuniqueIndex(\"project_repositories_project_id_unique\").on(table.projectId),\n\tindex(\"project_repositories_organization_id_idx\").on(table.organizationId),\n\tindex(\"project_repositories_lifecycle_status_idx\").on(table.lifecycleStatus),\n\tuniqueIndex(\"project_repositories_provider_external_id_unique\").on(table.provider, table.externalRepositoryId).where(sql`${table.externalRepositoryId} IS NOT NULL`)\n]);\nconst projectRepositoriesSqlite = sqliteTable(\"project_repositories\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id, { onDelete: \"cascade\" }),\n\tprojectId: text$1(\"project_id\").notNull().references(() => projectsSqlite.id, { onDelete: \"cascade\" }),\n\tprovider: text$1(\"provider\").$type().notNull(),\n\texternalRepositoryId: text$1(\"external_repository_id\"),\n\towner: text$1(\"owner\"),\n\tname: text$1(\"name\"),\n\tdefaultBranch: text$1(\"default_branch\").notNull().default(\"main\"),\n\tlifecycleStatus: text$1(\"lifecycle_status\").$type().notNull().default(\"provisioning\"),\n\tcontentStatus: text$1(\"content_status\").$type().notNull().default(\"empty\"),\n\tdesiredState: text$1(\"desired_state\").$type().notNull().default(\"active\"),\n\tlastErrorCode: text$1(\"last_error_code\"),\n\tlastError: text$1(\"last_error\"),\n\tprovisionedAt: integer$1(\"provisioned_at\", { mode: \"timestamp_ms\" }),\n\tplatformAgentScaffoldedAt: integer$1(\"platform_agent_scaffolded_at\", { mode: \"timestamp_ms\" }),\n\tdeletedAt: integer$1(\"deleted_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}, (table) => [\n\tuniqueIndex$1(\"project_repositories_project_id_unique\").on(table.projectId),\n\tindex$1(\"project_repositories_organization_id_idx\").on(table.organizationId),\n\tindex$1(\"project_repositories_lifecycle_status_idx\").on(table.lifecycleStatus),\n\tuniqueIndex$1(\"project_repositories_provider_external_id_unique\").on(table.provider, table.externalRepositoryId).where(sql`${table.externalRepositoryId} IS NOT NULL`)\n]);\n//#endregion\n//#region src/schema/tables/platform-agent-sessions.ts\n/**\n* Control-plane platform-agent conversation (org `/chat`).\n* Durable history lives in `platform_agent_events`; Redis holds in-flight streams.\n*/\nconst platformAgentSessions = pgTable(\"platform_agent_sessions\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id, { onDelete: \"cascade\" }),\n\tprojectId: text(\"project_id\").notNull().references(() => projects.id, { onDelete: \"cascade\" }),\n\tuserId: text(\"user_id\").notNull().references(() => users.id, { onDelete: \"cascade\" }),\n\tstatus: text(\"status\").$type().notNull(),\n\ttitle: text(\"title\"),\n\tmodel: text(\"model\"),\n\tactiveRunId: text(\"active_run_id\"),\n\tlastDraftCommitSha: text(\"last_draft_commit_sha\"),\n\tsandboxId: text(\"sandbox_id\"),\n\tsandboxLastUsedAt: timestamp(\"sandbox_last_used_at\", { withTimezone: true }),\n\t/** Cached so warm prompts skip Modal manifest reads before a project snapshot exists. */\n\tpackageManager: text(\"package_manager\").$type(),\n\terror: text(\"error\"),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [\n\tindex(\"platform_agent_sessions_owner_updated_idx\").on(table.organizationId, table.projectId, table.userId, table.updatedAt),\n\tindex(\"platform_agent_sessions_org_user_updated_idx\").on(table.organizationId, table.userId, table.updatedAt, table.id),\n\tindex(\"platform_agent_sessions_project_id_idx\").on(table.projectId),\n\tindex(\"platform_agent_sessions_sandbox_last_used_at_idx\").on(table.sandboxLastUsedAt).where(sql`${table.sandboxId} IS NOT NULL`)\n]);\nconst platformAgentSessionsSqlite = sqliteTable(\"platform_agent_sessions\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id, { onDelete: \"cascade\" }),\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\tstatus: text$1(\"status\").$type().notNull(),\n\ttitle: text$1(\"title\"),\n\tmodel: text$1(\"model\"),\n\tactiveRunId: text$1(\"active_run_id\"),\n\tlastDraftCommitSha: text$1(\"last_draft_commit_sha\"),\n\tsandboxId: text$1(\"sandbox_id\"),\n\tsandboxLastUsedAt: integer$1(\"sandbox_last_used_at\", { mode: \"timestamp_ms\" }),\n\tpackageManager: text$1(\"package_manager\").$type(),\n\terror: text$1(\"error\"),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [\n\tindex$1(\"platform_agent_sessions_owner_updated_idx\").on(table.organizationId, table.projectId, table.userId, table.updatedAt),\n\tindex$1(\"platform_agent_sessions_org_user_updated_idx\").on(table.organizationId, table.userId, table.updatedAt, table.id),\n\tindex$1(\"platform_agent_sessions_project_id_idx\").on(table.projectId),\n\tindex$1(\"platform_agent_sessions_sandbox_last_used_at_idx\").on(table.sandboxLastUsedAt).where(sql`${table.sandboxId} IS NOT NULL`)\n]);\n//#endregion\n//#region src/schema/tables/platform-agent-events.ts\n/**\n* Append-only control-plane event log for platform-agent chats.\n* Mirrors tenant `agent_events` shape; no tenant RLS (platform ownership is on the session row).\n*/\nconst platformAgentEvents = pgTable(\"platform_agent_events\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id, { onDelete: \"cascade\" }),\n\tsessionId: text(\"session_id\").notNull().references(() => platformAgentSessions.id, { onDelete: \"cascade\" }),\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}, (table) => [index(\"platform_agent_events_organization_id_idx\").on(table.organizationId), index(\"platform_agent_events_session_event_seq_idx\").on(table.sessionId, table.eventType, table.seq)]);\nconst platformAgentEventsSqlite = sqliteTable(\"platform_agent_events\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id, { onDelete: \"cascade\" }),\n\tsessionId: text$1(\"session_id\").notNull().references(() => platformAgentSessionsSqlite.id, { onDelete: \"cascade\" }),\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}, (table) => [index$1(\"platform_agent_events_organization_id_idx\").on(table.organizationId), index$1(\"platform_agent_events_session_event_seq_idx\").on(table.sessionId, table.eventType, table.seq)]);\n//#endregion\n//#region src/schema/tables/platform-agent-project-snapshots.ts\nconst platformAgentProjectSnapshotBuildStatuses = [\n\t\"idle\",\n\t\"building\",\n\t\"ready\",\n\t\"failed\"\n];\n/**\n* Project-wide dirty-recovery marker on the project snapshot image.\n* - null: no outstanding recovery image\n* - ready: dirty snapshot available for any next project run to boot and repair\n* - repairing: legacy value from an earlier claim/lease design (treat like ready)\n*/\nconst platformAgentProjectSnapshotRecoveryStates = [\"repairing\", \"ready\"];\n/**\n* Per-project Modal filesystem snapshot for platform-agent cold boots.\n* One row per project; coalesce rebuilds via `build_status` + `build_started_at`.\n* When `recovery_state` is set, `modal_image_id` is the dirty recovery image\n* (`sync_ready=false`) and any next project run should claim it before new work.\n*/\nconst platformAgentProjectSnapshots = pgTable(\"platform_agent_project_snapshots\", {\n\tprojectId: text(\"project_id\").primaryKey().references(() => projects.id, { onDelete: \"cascade\" }),\n\tmodalImageId: text(\"modal_image_id\"),\n\tdepsFingerprint: text(\"deps_fingerprint\"),\n\t/** Exact HEAD SHA baked into the image at capture time. */\n\theadSha: text(\"head_sha\"),\n\tpackageManager: text(\"package_manager\").$type(),\n\t/**\n\t* Exact `@keystrokehq/cli` version baked into the image at capture time.\n\t* Null means legacy/unknown — callers must probe the sandbox.\n\t*/\n\tcliVersion: text(\"cli_version\"),\n\t/**\n\t* True when the captured checkout was clean, on `ks/draft`, and not\n\t* ahead/behind or mid merge/rebase — safe to skip status probe when tip matches.\n\t*/\n\tsyncReady: boolean(\"sync_ready\").notNull().default(false),\n\t/** Monotonic capture generation for stale-snapshot CAS. */\n\tcaptureGeneration: integer(\"capture_generation\").notNull().default(0),\n\t/**\n\t* When set, the project snapshot is a dirty recovery image that must be\n\t* claimed and repaired before ordinary workspace sync.\n\t*/\n\trecoveryState: text(\"recovery_state\").$type(),\n\t/** Run currently owning repair (`recovery_state = repairing`). */\n\trecoveryClaimantRunId: text(\"recovery_claimant_run_id\"),\n\t/** When the current repair lease started. */\n\trecoveryClaimedAt: timestamp(\"recovery_claimed_at\", { withTimezone: true }),\n\tbuildStatus: text(\"build_status\").$type().notNull(),\n\tbuildStartedAt: timestamp(\"build_started_at\", { withTimezone: true }),\n\tlastError: text(\"last_error\"),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull()\n});\nconst platformAgentProjectSnapshotsSqlite = sqliteTable(\"platform_agent_project_snapshots\", {\n\tprojectId: text$1(\"project_id\").primaryKey().references(() => projectsSqlite.id, { onDelete: \"cascade\" }),\n\tmodalImageId: text$1(\"modal_image_id\"),\n\tdepsFingerprint: text$1(\"deps_fingerprint\"),\n\theadSha: text$1(\"head_sha\"),\n\tpackageManager: text$1(\"package_manager\").$type(),\n\tcliVersion: text$1(\"cli_version\"),\n\tsyncReady: integer$1(\"sync_ready\", { mode: \"boolean\" }).notNull().default(false),\n\tcaptureGeneration: integer$1(\"capture_generation\").notNull().default(0),\n\trecoveryState: text$1(\"recovery_state\").$type(),\n\trecoveryClaimantRunId: text$1(\"recovery_claimant_run_id\"),\n\trecoveryClaimedAt: integer$1(\"recovery_claimed_at\", { mode: \"timestamp_ms\" }),\n\tbuildStatus: text$1(\"build_status\").$type().notNull(),\n\tbuildStartedAt: integer$1(\"build_started_at\", { mode: \"timestamp_ms\" }),\n\tlastError: text$1(\"last_error\"),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull()\n});\n//#endregion\n//#region src/schema/tables/project-agent-env-images.ts\n/**\n* Org-scoped Modal env Images for project-agent `defineSandbox({ setup })`.\n* Keyed by setup fingerprint so agents with identical setup share one Image.\n* No RLS — platform Modal jobs read/write globally by organization id.\n*/\nconst projectAgentEnvImages = pgTable(\"project_agent_env_images\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id, { onDelete: \"cascade\" }),\n\t/** sha256 of setup commands + base image name. */\n\tsetupHash: text(\"setup_hash\").notNull(),\n\tbaseImageName: text(\"base_image_name\").notNull(),\n\t/** JSON array of setup command strings used for this fingerprint. */\n\tsetupCommands: text(\"setup_commands\").notNull(),\n\tmodalImageId: text(\"modal_image_id\"),\n\tbuildStatus: text(\"build_status\").$type().notNull(),\n\tbuildStartedAt: timestamp(\"build_started_at\", { withTimezone: true }),\n\tlastError: text(\"last_error\"),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [uniqueIndex(\"project_agent_env_images_org_hash_idx\").on(table.organizationId, table.setupHash)]);\nconst projectAgentEnvImagesSqlite = sqliteTable(\"project_agent_env_images\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id, { onDelete: \"cascade\" }),\n\tsetupHash: text$1(\"setup_hash\").notNull(),\n\tbaseImageName: text$1(\"base_image_name\").notNull(),\n\tsetupCommands: text$1(\"setup_commands\").notNull(),\n\tmodalImageId: text$1(\"modal_image_id\"),\n\tbuildStatus: text$1(\"build_status\").$type().notNull(),\n\tbuildStartedAt: integer$1(\"build_started_at\", { mode: \"timestamp_ms\" }),\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}, (table) => [uniqueIndex$1(\"project_agent_env_images_org_hash_idx\").on(table.organizationId, table.setupHash)]);\n//#endregion\n//#region src/schema/tables/project-agent-session-sandboxes.ts\n/**\n* Control-plane pointers for hosted project-agent (`mode: \"vm\"`) Modal sandboxes.\n* Keyed by product `agent_sessions.id`. No RLS — maintenance GC lists globally.\n*\n* - `sandbox_id`: live Modal sandbox while warm (cleared on grace detach / GC)\n* - `modal_image_id`: last successful per-session filesystem Image for cold boot\n* - `sandbox_last_used_at`: activity clock for warm touch + 24h idle GC\n*/\nconst projectAgentSessionSandboxes = pgTable(\"project_agent_session_sandboxes\", {\n\tsessionId: text(\"session_id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id, { onDelete: \"cascade\" }),\n\tprojectId: text(\"project_id\").notNull().references(() => projects.id, { onDelete: \"cascade\" }),\n\tagentId: text(\"agent_id\").notNull(),\n\tsandboxId: text(\"sandbox_id\"),\n\tsandboxLastUsedAt: timestamp(\"sandbox_last_used_at\", { withTimezone: true }),\n\tmodalImageId: text(\"modal_image_id\"),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [\n\tindex(\"project_agent_session_sandboxes_project_idx\").on(table.projectId),\n\tindex(\"project_agent_session_sandboxes_sandbox_last_used_idx\").on(table.sandboxLastUsedAt).where(sql`${table.sandboxId} IS NOT NULL`),\n\tindex(\"project_agent_session_sandboxes_image_last_used_idx\").on(table.sandboxLastUsedAt).where(sql`${table.modalImageId} IS NOT NULL`)\n]);\nconst projectAgentSessionSandboxesSqlite = sqliteTable(\"project_agent_session_sandboxes\", {\n\tsessionId: text$1(\"session_id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id, { onDelete: \"cascade\" }),\n\tprojectId: text$1(\"project_id\").notNull().references(() => projectsSqlite.id, { onDelete: \"cascade\" }),\n\tagentId: text$1(\"agent_id\").notNull(),\n\tsandboxId: text$1(\"sandbox_id\"),\n\tsandboxLastUsedAt: integer$1(\"sandbox_last_used_at\", { mode: \"timestamp_ms\" }),\n\tmodalImageId: text$1(\"modal_image_id\"),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [\n\tindex$1(\"project_agent_session_sandboxes_project_idx\").on(table.projectId),\n\tindex$1(\"project_agent_session_sandboxes_sandbox_last_used_idx\").on(table.sandboxLastUsedAt).where(sql`${table.sandboxId} IS NOT NULL`),\n\tindex$1(\"project_agent_session_sandboxes_image_last_used_idx\").on(table.sandboxLastUsedAt).where(sql`${table.modalImageId} IS NOT NULL`)\n]);\n//#endregion\n//#region src/schema/tables/published-forms.ts\nconst publishedForms = pgTable(\"published_forms\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id, { onDelete: \"cascade\" }),\n\tprojectId: text(\"project_id\").notNull().references(() => projects.id, { onDelete: \"cascade\" }),\n\tworkflowSlug: text(\"workflow_slug\").notNull(),\n\ttoken: text(\"token\").notNull(),\n\tenabled: boolean(\"enabled\").notNull().default(true),\n\ttitle: text(\"title\"),\n\tdescription: text(\"description\"),\n\tfieldConfig: jsonb(\"field_config\").$type().notNull().default({}),\n\tcreatedByUserId: text(\"created_by_user_id\").references(() => users.id, { onDelete: \"set null\" }),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [\n\tuniqueIndex(\"published_forms_token_unique\").on(table.token),\n\tuniqueIndex(\"published_forms_workflow_unique\").on(table.organizationId, table.projectId, table.workflowSlug),\n\tindex(\"published_forms_project_id_idx\").on(table.projectId)\n]);\nconst publishedFormsSqlite = sqliteTable(\"published_forms\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id, { onDelete: \"cascade\" }),\n\tprojectId: text$1(\"project_id\").notNull().references(() => projectsSqlite.id, { onDelete: \"cascade\" }),\n\tworkflowSlug: text$1(\"workflow_slug\").notNull(),\n\ttoken: text$1(\"token\").notNull(),\n\tenabled: integer$1(\"enabled\", { mode: \"boolean\" }).notNull().default(true),\n\ttitle: text$1(\"title\"),\n\tdescription: text$1(\"description\"),\n\tfieldConfig: text$1(\"field_config\", { mode: \"json\" }).$type().notNull().default({}),\n\tcreatedByUserId: text$1(\"created_by_user_id\").references(() => usersSqlite.id, { onDelete: \"set null\" }),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [\n\tuniqueIndex$1(\"published_forms_token_unique\").on(table.token),\n\tuniqueIndex$1(\"published_forms_workflow_unique\").on(table.organizationId, table.projectId, table.workflowSlug),\n\tindex$1(\"published_forms_project_id_idx\").on(table.projectId)\n]);\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)]);\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)]);\n//#endregion\n//#region src/schema/tables/organization-billing.ts\n/**\n* One row per org: the Stripe/account record. Plan presets and limit shapes\n* live as code in the cloud billing package; `limitOverrides` is a\n* Zod-validated partial of those preset limits (null = inherit).\n*/\nconst organizationBilling = pgTable(\"organization_billing\", {\n\torganizationId: text(\"organization_id\").primaryKey().references(() => organizations.id, { onDelete: \"cascade\" }),\n\tplanKey: text(\"plan_key\").notNull().default(\"free\"),\n\tstripeCustomerId: text(\"stripe_customer_id\"),\n\tstripeSubscriptionId: text(\"stripe_subscription_id\"),\n\tstripePaymentMethodId: text(\"stripe_payment_method_id\"),\n\tsubscriptionStatus: text(\"subscription_status\").$type().notNull().default(\"none\"),\n\tcurrentPeriodStart: timestamp(\"current_period_start\", { withTimezone: true }),\n\tcurrentPeriodEnd: timestamp(\"current_period_end\", { withTimezone: true }),\n\tmonthlyCreditMicroCreditsOverride: bigint(\"monthly_credit_micro_credits_override\", { mode: \"number\" }),\n\tlimitOverrides: jsonb(\"limit_overrides\"),\n\tautoTopupEnabled: boolean(\"auto_topup_enabled\").notNull().default(false),\n\tautoTopupThresholdMicroCredits: bigint(\"auto_topup_threshold_micro_credits\", { mode: \"number\" }),\n\tautoTopupAmountMicroCredits: bigint(\"auto_topup_amount_micro_credits\", { mode: \"number\" }),\n\tautoTopupPendingIntentId: text(\"auto_topup_pending_intent_id\"),\n\tcreditWarningSentAt: timestamp(\"credit_warning_sent_at\", { withTimezone: true }),\n\tcreditExhaustedSentAt: timestamp(\"credit_exhausted_sent_at\", { withTimezone: true }),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [index(\"organization_billing_stripe_customer_id_idx\").on(table.stripeCustomerId)]);\nconst organizationBillingSqlite = sqliteTable(\"organization_billing\", {\n\torganizationId: text$1(\"organization_id\").primaryKey().references(() => organizationsSqlite.id, { onDelete: \"cascade\" }),\n\tplanKey: text$1(\"plan_key\").notNull().default(\"free\"),\n\tstripeCustomerId: text$1(\"stripe_customer_id\"),\n\tstripeSubscriptionId: text$1(\"stripe_subscription_id\"),\n\tstripePaymentMethodId: text$1(\"stripe_payment_method_id\"),\n\tsubscriptionStatus: text$1(\"subscription_status\").$type().notNull().default(\"none\"),\n\tcurrentPeriodStart: integer$1(\"current_period_start\", { mode: \"timestamp_ms\" }),\n\tcurrentPeriodEnd: integer$1(\"current_period_end\", { mode: \"timestamp_ms\" }),\n\tmonthlyCreditMicroCreditsOverride: integer$1(\"monthly_credit_micro_credits_override\"),\n\tlimitOverrides: text$1(\"limit_overrides\", { mode: \"json\" }),\n\tautoTopupEnabled: integer$1(\"auto_topup_enabled\", { mode: \"boolean\" }).notNull().default(false),\n\tautoTopupThresholdMicroCredits: integer$1(\"auto_topup_threshold_micro_credits\"),\n\tautoTopupAmountMicroCredits: integer$1(\"auto_topup_amount_micro_credits\"),\n\tautoTopupPendingIntentId: text$1(\"auto_topup_pending_intent_id\"),\n\tcreditWarningSentAt: integer$1(\"credit_warning_sent_at\", { mode: \"timestamp_ms\" }),\n\tcreditExhaustedSentAt: integer$1(\"credit_exhausted_sent_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}, (table) => [index$1(\"organization_billing_stripe_customer_id_idx\").on(table.stripeCustomerId)]);\n//#endregion\n//#region src/schema/tables/billing-events.ts\n/**\n* Best-effort audit log of Stripe webhook handling — NOT the grant-idempotency\n* authority (that is the unique `(entryType, reference)` index in the org DB's\n* `usage_records`). Written after the org-DB grant succeeds.\n*/\nconst billingEvents = pgTable(\"billing_events\", {\n\tid: text(\"id\").primaryKey(),\n\tstripeEventId: text(\"stripe_event_id\").notNull(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id, { onDelete: \"cascade\" }),\n\ttype: text(\"type\").$type().notNull(),\n\tamountMicroCredits: bigint(\"amount_micro_credits\", { mode: \"number\" }),\n\tcreditsGrantedMicroCredits: bigint(\"credits_granted_micro_credits\", { mode: \"number\" }),\n\tbucket: text(\"bucket\").$type(),\n\tstatus: text(\"status\").$type().notNull(),\n\tstripeObjectId: text(\"stripe_object_id\"),\n\tmetadata: jsonb(\"metadata\"),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull()\n}, (table) => [uniqueIndex(\"billing_events_stripe_event_id_unique\").on(table.stripeEventId), index(\"billing_events_organization_id_idx\").on(table.organizationId)]);\nconst billingEventsSqlite = sqliteTable(\"billing_events\", {\n\tid: text$1(\"id\").primaryKey(),\n\tstripeEventId: text$1(\"stripe_event_id\").notNull(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id, { onDelete: \"cascade\" }),\n\ttype: text$1(\"type\").$type().notNull(),\n\tamountMicroCredits: integer$1(\"amount_micro_credits\"),\n\tcreditsGrantedMicroCredits: integer$1(\"credits_granted_micro_credits\"),\n\tbucket: text$1(\"bucket\").$type(),\n\tstatus: text$1(\"status\").$type().notNull(),\n\tstripeObjectId: text$1(\"stripe_object_id\"),\n\tmetadata: text$1(\"metadata\", { mode: \"json\" }),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [uniqueIndex$1(\"billing_events_stripe_event_id_unique\").on(table.stripeEventId), index$1(\"billing_events_organization_id_idx\").on(table.organizationId)]);\n//#endregion\n//#region src/schema/tables/billing-wallet.ts\n/**\n* Platform billing authority: one narrow wallet projection per organization.\n* Plan limits stay in `organization_billing` / pushed-down runtime config.\n*/\nconst billingWallet = pgTable(\"billing_wallet\", {\n\torganizationId: text(\"organization_id\").primaryKey().references(() => organizations.id, { onDelete: \"cascade\" }),\n\tplanCreditMicroCredits: bigint(\"plan_credit_micro_credits\", { mode: \"number\" }).notNull().default(0),\n\tprepaidCreditMicroCredits: bigint(\"prepaid_credit_micro_credits\", { mode: \"number\" }).notNull().default(0),\n\tperiodStart: timestamp(\"period_start\", { withTimezone: true }),\n\tperiodEnd: timestamp(\"period_end\", { withTimezone: true }),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n});\nconst billingWalletSqlite = sqliteTable(\"billing_wallet\", {\n\torganizationId: text$1(\"organization_id\").primaryKey().references(() => organizationsSqlite.id, { onDelete: \"cascade\" }),\n\tplanCreditMicroCredits: integer$1(\"plan_credit_micro_credits\").notNull().default(0),\n\tprepaidCreditMicroCredits: integer$1(\"prepaid_credit_micro_credits\").notNull().default(0),\n\tperiodStart: integer$1(\"period_start\", { mode: \"timestamp_ms\" }),\n\tperiodEnd: integer$1(\"period_end\", { mode: \"timestamp_ms\" }),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n});\n//#endregion\n//#region src/schema/tables/billing-ledger.ts\n/** Immutable platform financial history. */\nconst billingLedger = pgTable(\"billing_ledger\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id, { onDelete: \"cascade\" }),\n\tentryType: text(\"entry_type\").$type().notNull(),\n\tplanDeltaMicroCredits: bigint(\"plan_delta_micro_credits\", { mode: \"number\" }).notNull().default(0),\n\tprepaidDeltaMicroCredits: bigint(\"prepaid_delta_micro_credits\", { mode: \"number\" }).notNull().default(0),\n\tsource: text(\"source\").notNull(),\n\tidempotencyKey: text(\"idempotency_key\").notNull(),\n\trunId: text(\"run_id\"),\n\tprojectId: text(\"project_id\"),\n\tproviderReference: text(\"provider_reference\"),\n\tmetadata: jsonb(\"metadata\"),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull()\n}, (table) => [uniqueIndex(\"billing_ledger_org_idempotency_unique\").on(table.organizationId, table.idempotencyKey), index(\"billing_ledger_org_created_at_idx\").on(table.organizationId, table.createdAt)]);\nconst billingLedgerSqlite = sqliteTable(\"billing_ledger\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id, { onDelete: \"cascade\" }),\n\tentryType: text$1(\"entry_type\").$type().notNull(),\n\tplanDeltaMicroCredits: integer$1(\"plan_delta_micro_credits\").notNull().default(0),\n\tprepaidDeltaMicroCredits: integer$1(\"prepaid_delta_micro_credits\").notNull().default(0),\n\tsource: text$1(\"source\").notNull(),\n\tidempotencyKey: text$1(\"idempotency_key\").notNull(),\n\trunId: text$1(\"run_id\"),\n\tprojectId: text$1(\"project_id\"),\n\tproviderReference: text$1(\"provider_reference\"),\n\tmetadata: text$1(\"metadata\", { mode: \"json\" }),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [uniqueIndex$1(\"billing_ledger_org_idempotency_unique\").on(table.organizationId, table.idempotencyKey), index$1(\"billing_ledger_org_created_at_idx\").on(table.organizationId, table.createdAt)]);\n//#endregion\n//#region src/schema/tables/usage-events.ts\n/** Append-only platform meter facts, priced before insertion by the server. */\nconst usageEvents = pgTable(\"usage_events\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id, { onDelete: \"cascade\" }),\n\tprojectId: text(\"project_id\"),\n\trunId: text(\"run_id\"),\n\trunKind: text(\"run_kind\").$type(),\n\tsource: text(\"source\").notNull(),\n\tsourceEventId: text(\"source_event_id\").notNull(),\n\tmeterKey: text(\"meter_key\").notNull(),\n\tquantity: doublePrecision(\"quantity\").notNull(),\n\tunit: text(\"unit\").notNull(),\n\tproviderCostUsd: doublePrecision(\"provider_cost_usd\"),\n\tkeySource: text(\"key_source\").$type(),\n\tpriceVersion: text(\"price_version\").notNull(),\n\tchargeMicroCredits: bigint(\"charge_micro_credits\", { mode: \"number\" }).notNull(),\n\tsettledLedgerId: text(\"settled_ledger_id\"),\n\toccurredAt: timestamp(\"occurred_at\", { withTimezone: true }).notNull(),\n\tacceptedAt: timestamp(\"accepted_at\", { withTimezone: true }).notNull(),\n\tmetadata: jsonb(\"metadata\")\n}, (table) => [uniqueIndex(\"usage_events_org_source_event_unique\").on(table.organizationId, table.source, table.sourceEventId), index(\"usage_events_org_run_occurred_idx\").on(table.organizationId, table.runId, table.occurredAt)]);\nconst usageEventsSqlite = sqliteTable(\"usage_events\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id, { onDelete: \"cascade\" }),\n\tprojectId: text$1(\"project_id\"),\n\trunId: text$1(\"run_id\"),\n\trunKind: text$1(\"run_kind\").$type(),\n\tsource: text$1(\"source\").notNull(),\n\tsourceEventId: text$1(\"source_event_id\").notNull(),\n\tmeterKey: text$1(\"meter_key\").notNull(),\n\tquantity: real(\"quantity\").notNull(),\n\tunit: text$1(\"unit\").notNull(),\n\tproviderCostUsd: real(\"provider_cost_usd\"),\n\tkeySource: text$1(\"key_source\").$type(),\n\tpriceVersion: text$1(\"price_version\").notNull(),\n\tchargeMicroCredits: integer$1(\"charge_micro_credits\").notNull(),\n\tsettledLedgerId: text$1(\"settled_ledger_id\"),\n\toccurredAt: integer$1(\"occurred_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tacceptedAt: integer$1(\"accepted_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tmetadata: text$1(\"metadata\", { mode: \"json\" })\n}, (table) => [uniqueIndex$1(\"usage_events_org_source_event_unique\").on(table.organizationId, table.source, table.sourceEventId), index$1(\"usage_events_org_run_occurred_idx\").on(table.organizationId, table.runId, table.occurredAt)]);\n//#endregion\n//#region src/schema/tables/managed-service-credentials.ts\nconst managedServiceCredentials = pgTable(\"managed_service_credentials\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id, { onDelete: \"cascade\" }),\n\tkind: text(\"kind\").$type().notNull(),\n\tprovider: text(\"provider\").notNull(),\n\tvalueCiphertext: text(\"value_ciphertext\").notNull(),\n\tkeyPreview: text(\"key_preview\").notNull(),\n\tcreatedByUserId: text(\"created_by_user_id\").notNull(),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [uniqueIndex(\"managed_service_credentials_org_kind_provider_unique\").on(table.organizationId, table.kind, table.provider), index(\"managed_service_credentials_org_kind_idx\").on(table.organizationId, table.kind)]);\nconst managedServiceCredentialsSqlite = sqliteTable(\"managed_service_credentials\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id, { onDelete: \"cascade\" }),\n\tkind: text$1(\"kind\").$type().notNull(),\n\tprovider: text$1(\"provider\").notNull(),\n\tvalueCiphertext: text$1(\"value_ciphertext\").notNull(),\n\tkeyPreview: text$1(\"key_preview\").notNull(),\n\tcreatedByUserId: text$1(\"created_by_user_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(\"managed_service_credentials_org_kind_provider_unique\").on(table.organizationId, table.kind, table.provider), index$1(\"managed_service_credentials_org_kind_idx\").on(table.organizationId, table.kind)]);\n//#endregion\n//#region src/schema/tenant-policy.ts\n/**\n* Tenant isolation for public runtime tables.\n*\n* Organization identity comes from `keystroke.current_organization_id()`, which\n* verifies a short-lived signed claim set by trusted platform code via\n* `set_config('keystroke.org_claim', …, true)` for the current transaction.\n*/\nfunction tenantOrganizationPolicy(organizationId) {\n\tconst match = sql`${organizationId} = (SELECT keystroke.current_organization_id())`;\n\treturn pgPolicy(\"tenant_organization_isolation\", {\n\t\tas: \"permissive\",\n\t\tfor: \"all\",\n\t\tto: \"public\",\n\t\tusing: match,\n\t\twithCheck: match\n\t});\n}\n//#endregion\n//#region src/schema/tables/tenant/agents.ts\nconst agents = pgTable(\"agents\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id),\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\tsandboxMode: text(\"sandbox_mode\").$type(),\n\tappSlugs: jsonb(\"app_slugs\").$type(),\n\tbrainSlugs: jsonb(\"brain_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) => [\n\tindex(\"agents_organization_id_idx\").on(table.organizationId),\n\tuniqueIndex(\"agents_project_id_slug_idx\").on(table.projectId, table.slug),\n\tuniqueIndex(\"agents_project_id_route_idx\").on(table.projectId, table.route),\n\ttenantOrganizationPolicy(table.organizationId)\n]).enableRLS();\nconst agentsSqlite = sqliteTable(\"agents\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id),\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\tsandboxMode: text$1(\"sandbox_mode\").$type(),\n\tappSlugs: text$1(\"app_slugs\", { mode: \"json\" }).$type(),\n\tbrainSlugs: text$1(\"brain_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) => [\n\tindex$1(\"agents_organization_id_idx\").on(table.organizationId),\n\tuniqueIndex$1(\"agents_project_id_slug_idx\").on(table.projectId, table.slug),\n\tuniqueIndex$1(\"agents_project_id_route_idx\").on(table.projectId, table.route)\n]);\n//#endregion\n//#region src/schema/tables/tenant/agent-sessions.ts\nconst agentSessions = pgTable(\"agent_sessions\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id),\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\tstatus: text(\"status\").$type(),\n\ttotalDurationMs: integer(\"total_duration_ms\").notNull().default(0),\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) => [\n\tindex(\"agent_sessions_organization_id_idx\").on(table.organizationId),\n\tindex(\"agent_sessions_agent_updated_idx\").on(table.agentId, table.updatedAt),\n\ttenantOrganizationPolicy(table.organizationId)\n]).enableRLS();\nconst agentSessionsSqlite = sqliteTable(\"agent_sessions\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id),\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\tstatus: text$1(\"status\").$type(),\n\ttotalDurationMs: integer$1(\"total_duration_ms\").notNull().default(0),\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_organization_id_idx\").on(table.organizationId), index$1(\"agent_sessions_agent_updated_idx\").on(table.agentId, table.updatedAt)]);\n//#endregion\n//#region src/schema/tables/tenant/agent-events.ts\nconst agentEvents = pgTable(\"agent_events\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id),\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}, (table) => [\n\tindex(\"agent_events_organization_id_idx\").on(table.organizationId),\n\tindex(\"agent_events_session_event_seq_idx\").on(table.sessionId, table.eventType, table.seq),\n\ttenantOrganizationPolicy(table.organizationId)\n]).enableRLS();\nconst agentEventsSqlite = sqliteTable(\"agent_events\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id),\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}, (table) => [index$1(\"agent_events_organization_id_idx\").on(table.organizationId), index$1(\"agent_events_session_event_seq_idx\").on(table.sessionId, table.eventType, table.seq)]);\n//#endregion\n//#region src/schema/tables/tenant/triggers.ts\nconst triggers = pgTable(\"triggers\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id),\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\tstate: jsonb(\"state\").$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) => [\n\tindex(\"triggers_organization_id_idx\").on(table.organizationId),\n\tuniqueIndex(\"triggers_project_id_slug_idx\").on(table.projectId, table.slug),\n\tindex(\"triggers_next_run_at_enabled_idx\").on(table.nextRunAt, table.enabled),\n\ttenantOrganizationPolicy(table.organizationId)\n]).enableRLS();\nconst triggersSqlite = sqliteTable(\"triggers\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id),\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\tstate: text$1(\"state\", { 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) => [\n\tindex$1(\"triggers_organization_id_idx\").on(table.organizationId),\n\tuniqueIndex$1(\"triggers_project_id_slug_idx\").on(table.projectId, table.slug),\n\tindex$1(\"triggers_next_run_at_enabled_idx\").on(table.nextRunAt, table.enabled)\n]);\n//#endregion\n//#region src/schema/tables/tenant/trigger-attachments.ts\nconst triggerAttachments = pgTable(\"trigger_attachments\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id),\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\tdisabledAt: timestamp(\"disabled_at\", { withTimezone: true }),\n\tdeletedAt: timestamp(\"deleted_at\", { withTimezone: true })\n}, (table) => [\n\tindex(\"trigger_attachments_organization_id_idx\").on(table.organizationId),\n\tuniqueIndex(\"trigger_attachments_project_id_slug_idx\").on(table.projectId, table.slug),\n\ttenantOrganizationPolicy(table.organizationId)\n]).enableRLS();\nconst triggerAttachmentsSqlite = sqliteTable(\"trigger_attachments\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id),\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\tdisabledAt: integer$1(\"disabled_at\", { mode: \"timestamp_ms\" }),\n\tdeletedAt: integer$1(\"deleted_at\", { mode: \"timestamp_ms\" })\n}, (table) => [index$1(\"trigger_attachments_organization_id_idx\").on(table.organizationId), uniqueIndex$1(\"trigger_attachments_project_id_slug_idx\").on(table.projectId, table.slug)]);\n//#endregion\n//#region src/schema/tables/tenant/trigger-runs.ts\nconst triggerRuns = pgTable(\"trigger_runs\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id),\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) => [\n\tindex(\"trigger_runs_organization_id_idx\").on(table.organizationId),\n\tindex(\"trigger_runs_project_trigger_triggered_idx\").on(table.projectId, table.triggerId, table.triggeredAt),\n\tindex(\"trigger_runs_project_triggered_idx\").on(table.projectId, table.triggeredAt),\n\ttenantOrganizationPolicy(table.organizationId)\n]).enableRLS();\nconst triggerRunsSqlite = sqliteTable(\"trigger_runs\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id),\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) => [\n\tindex$1(\"trigger_runs_organization_id_idx\").on(table.organizationId),\n\tindex$1(\"trigger_runs_project_trigger_triggered_idx\").on(table.projectId, table.triggerId, table.triggeredAt),\n\tindex$1(\"trigger_runs_project_triggered_idx\").on(table.projectId, table.triggeredAt)\n]);\n//#endregion\n//#region src/schema/tables/tenant/workflow-subscriptions.ts\nconst workflowSubscriptions = pgTable(\"workflow_subscriptions\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id),\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) => [\n\tindex(\"workflow_subscriptions_organization_id_idx\").on(table.organizationId),\n\tuniqueIndex(\"workflow_subscriptions_project_workflow_user\").on(table.projectId, table.workflowSlug, table.userId),\n\ttenantOrganizationPolicy(table.organizationId)\n]).enableRLS();\nconst workflowSubscriptionsSqlite = sqliteTable(\"workflow_subscriptions\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id),\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) => [index$1(\"workflow_subscriptions_organization_id_idx\").on(table.organizationId), uniqueIndex$1(\"workflow_subscriptions_project_workflow_user\").on(table.projectId, table.workflowSlug, table.userId)]);\n//#endregion\n//#region src/schema/tables/tenant/workflow-runs.ts\nconst workflowRuns = pgTable(\"workflow_runs\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id),\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\tcredentialContext: jsonb(\"credential_context\").$type(),\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) => [\n\tindex(\"workflow_runs_organization_id_idx\").on(table.organizationId),\n\tindex(\"workflow_runs_project_workflow_triggered_idx\").on(table.projectId, table.workflowSlug, table.triggeredAt),\n\ttenantOrganizationPolicy(table.organizationId)\n]).enableRLS();\nconst workflowRunsSqlite = sqliteTable(\"workflow_runs\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id),\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\tcredentialContext: text$1(\"credential_context\", { mode: \"json\" }).$type(),\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_organization_id_idx\").on(table.organizationId), index$1(\"workflow_runs_project_workflow_triggered_idx\").on(table.projectId, table.workflowSlug, table.triggeredAt)]);\n//#endregion\n//#region src/schema/tables/tenant/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\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id),\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\tindex(\"workflow_events_organization_id_idx\").on(table.organizationId),\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\ttenantOrganizationPolicy(table.organizationId)\n]).enableRLS();\nconst workflowEventsSqlite = sqliteTable(\"workflow_events\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id),\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\tindex$1(\"workflow_events_organization_id_idx\").on(table.organizationId),\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/tenant/workflow-hooks.ts\nconst workflowHooks = pgTable(\"workflow_hooks\", {\n\thookId: text(\"hook_id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id),\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\tschema: jsonb(\"schema\"),\n\tpayload: jsonb(\"payload\"),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tresumedAt: timestamp(\"resumed_at\", { withTimezone: true })\n}, (table) => [\n\tindex(\"workflow_hooks_organization_id_idx\").on(table.organizationId),\n\tuniqueIndex(\"workflow_hooks_token_unique\").on(table.token),\n\tindex(\"workflow_hooks_run_id_idx\").on(table.runId),\n\ttenantOrganizationPolicy(table.organizationId)\n]).enableRLS();\nconst workflowHooksSqlite = sqliteTable(\"workflow_hooks\", {\n\thookId: text$1(\"hook_id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id),\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\tschema: text$1(\"schema\", { mode: \"json\" }),\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) => [\n\tindex$1(\"workflow_hooks_organization_id_idx\").on(table.organizationId),\n\tuniqueIndex$1(\"workflow_hooks_token_unique\").on(table.token),\n\tindex$1(\"workflow_hooks_run_id_idx\").on(table.runId)\n]);\n//#endregion\n//#region src/schema/tables/tenant/credential-instances.ts\nconst credentialInstances = pgTable(\"credential_instances\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id),\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) => [\n\tindex(\"credential_instances_organization_id_idx\").on(table.organizationId),\n\tuniqueIndex(\"credential_instances_project_scope_slug_unique\").on(table.projectId, table.scopeType, table.scopeId, table.slug),\n\tindex(\"credential_instances_project_app_slug_scope_idx\").on(table.projectId, table.appSlug, table.scopeType, table.scopeId),\n\ttenantOrganizationPolicy(table.organizationId)\n]).enableRLS();\nconst credentialInstancesSqlite = sqliteTable(\"credential_instances\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id),\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) => [\n\tindex$1(\"credential_instances_organization_id_idx\").on(table.organizationId),\n\tuniqueIndex$1(\"credential_instances_project_scope_slug_unique\").on(table.projectId, table.scopeType, table.scopeId, table.slug),\n\tindex$1(\"credential_instances_project_app_slug_scope_idx\").on(table.projectId, table.appSlug, table.scopeType, table.scopeId)\n]);\n//#endregion\n//#region src/schema/tables/tenant/credential-assignments.ts\nconst credentialAssignments = pgTable(\"credential_assignments\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id),\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) => [\n\tindex(\"credential_assignments_organization_id_idx\").on(table.organizationId),\n\tuniqueIndex(\"credential_assignments_project_target_consumer_slug\").on(table.projectId, table.targetType, table.targetKey, table.consumerId, table.credentialSlug),\n\ttenantOrganizationPolicy(table.organizationId)\n]).enableRLS();\nconst credentialAssignmentsSqlite = sqliteTable(\"credential_assignments\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id),\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) => [index$1(\"credential_assignments_organization_id_idx\").on(table.organizationId), uniqueIndex$1(\"credential_assignments_project_target_consumer_slug\").on(table.projectId, table.targetType, table.targetKey, table.consumerId, table.credentialSlug)]);\n//#endregion\n//#region src/schema/tables/tenant/jobs.ts\nconst jobs = pgTable(\"jobs\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id),\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\tparent: jsonb(\"parent\").$type(),\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}, (table) => [index(\"jobs_organization_id_idx\").on(table.organizationId), tenantOrganizationPolicy(table.organizationId)]).enableRLS();\nconst jobsSqlite = sqliteTable(\"jobs\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id),\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\tparent: text$1(\"parent\", { mode: \"json\" }).$type(),\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}, (table) => [index$1(\"jobs_organization_id_idx\").on(table.organizationId)]);\n//#endregion\n//#region src/schema/tables/tenant/gateway-attachments.ts\nconst gatewayAttachments = pgTable(\"gateway_attachments\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id),\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) => [\n\tindex(\"gateway_attachments_organization_id_idx\").on(table.organizationId),\n\tuniqueIndex(\"gateway_attachments_project_id_slug_idx\").on(table.projectId, table.slug),\n\tuniqueIndex(\"gateway_attachments_project_platform_channel_active\").on(table.projectId, table.platform, table.channelId).where(sql`${table.deletedAt} is null`),\n\ttenantOrganizationPolicy(table.organizationId)\n]).enableRLS();\nconst gatewayAttachmentsSqlite = sqliteTable(\"gateway_attachments\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id),\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) => [\n\tindex$1(\"gateway_attachments_organization_id_idx\").on(table.organizationId),\n\tuniqueIndex$1(\"gateway_attachments_project_id_slug_idx\").on(table.projectId, table.slug),\n\tuniqueIndex$1(\"gateway_attachments_project_platform_channel_active\").on(table.projectId, table.platform, table.channelId).where(sql`${table.deletedAt} is null`)\n]);\nfunction gatewayAttachmentKeyForChannel(platform, channelId) {\n\treturn `${platform}:${channelId}`;\n}\n//#endregion\n//#region src/schema/tables/tenant/gateway-thread-sessions.ts\nconst gatewayThreadSessions = pgTable(\"gateway_thread_sessions\", {\n\tthreadId: text(\"thread_id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id),\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}, (table) => [index(\"gateway_thread_sessions_organization_id_idx\").on(table.organizationId), tenantOrganizationPolicy(table.organizationId)]).enableRLS();\nconst gatewayThreadSessionsSqlite = sqliteTable(\"gateway_thread_sessions\", {\n\tthreadId: text$1(\"thread_id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id),\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}, (table) => [index$1(\"gateway_thread_sessions_organization_id_idx\").on(table.organizationId)]);\n//#endregion\n//#region src/schema/tables/tenant/trace-spans.ts\nconst traceSpans = pgTable(\"trace_spans\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id),\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}, (table) => [\n\tindex(\"trace_spans_organization_id_idx\").on(table.organizationId),\n\tindex(\"trace_spans_trace_id_started_at_idx\").on(table.traceId, table.startedAt),\n\tindex(\"trace_spans_ref_id_kind_started_at_idx\").on(table.refId, table.kind, table.startedAt),\n\ttenantOrganizationPolicy(table.organizationId)\n]).enableRLS();\nconst traceSpansSqlite = sqliteTable(\"trace_spans\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id),\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}, (table) => [\n\tindex$1(\"trace_spans_organization_id_idx\").on(table.organizationId),\n\tindex$1(\"trace_spans_trace_id_started_at_idx\").on(table.traceId, table.startedAt),\n\tindex$1(\"trace_spans_ref_id_kind_started_at_idx\").on(table.refId, table.kind, table.startedAt)\n]);\n//#endregion\n//#region src/schema/tables/tenant/trace-logs.ts\nconst traceLogs = pgTable(\"trace_logs\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id),\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) => [\n\tindex(\"trace_logs_organization_id_idx\").on(table.organizationId),\n\tindex(\"trace_logs_trace_id_seq_idx\").on(table.traceId, table.seq),\n\tindex(\"trace_logs_span_id_seq_idx\").on(table.spanId, table.seq),\n\ttenantOrganizationPolicy(table.organizationId)\n]).enableRLS();\nconst traceLogsSqlite = sqliteTable(\"trace_logs\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id),\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) => [\n\tindex$1(\"trace_logs_organization_id_idx\").on(table.organizationId),\n\tindex$1(\"trace_logs_trace_id_seq_idx\").on(table.traceId, table.seq),\n\tindex$1(\"trace_logs_span_id_seq_idx\").on(table.spanId, table.seq)\n]);\n//#endregion\n//#region src/schema/tables/tenant/skills.ts\nconst skills = pgTable(\"skills\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id),\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) => [\n\tindex(\"skills_organization_id_idx\").on(table.organizationId),\n\tuniqueIndex(\"skills_project_id_slug_idx\").on(table.projectId, table.slug),\n\ttenantOrganizationPolicy(table.organizationId)\n]).enableRLS();\nconst skillsSqlite = sqliteTable(\"skills\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id),\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) => [index$1(\"skills_organization_id_idx\").on(table.organizationId), uniqueIndex$1(\"skills_project_id_slug_idx\").on(table.projectId, table.slug)]);\n//#endregion\n//#region src/schema/tables/tenant/workflows.ts\nconst workflows = pgTable(\"workflows\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id),\n\tprojectId: text(\"project_id\").notNull(),\n\tslug: text(\"slug\").notNull(),\n\tname: text(\"name\").notNull(),\n\tdescription: text(\"description\").notNull(),\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\trequestSchema: jsonb(\"request_schema\").$type().notNull().default({}),\n\trunInputValues: jsonb(\"run_input_values\").$type(),\n\tcanvasAnnotationsJson: jsonb(\"canvas_annotations_json\").$type(),\n\tcanvasAnnotationsHash: text(\"canvas_annotations_hash\"),\n\tcanvasAnnotationsModel: text(\"canvas_annotations_model\"),\n\tcanvasAnnotationsStatus: text(\"canvas_annotations_status\").$type().notNull().default(\"idle\"),\n\tcanvasAnnotationsGeneratedAt: timestamp(\"canvas_annotations_generated_at\", { withTimezone: true }),\n\toverviewSummary: text(\"overview_summary\"),\n\toverviewPhasesJson: jsonb(\"overview_phases_json\").$type(),\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}, (table) => [\n\tindex(\"workflows_organization_id_idx\").on(table.organizationId),\n\tuniqueIndex(\"workflows_project_id_slug_idx\").on(table.projectId, table.slug),\n\ttenantOrganizationPolicy(table.organizationId)\n]).enableRLS();\nconst workflowsSqlite = sqliteTable(\"workflows\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id),\n\tprojectId: text$1(\"project_id\").notNull(),\n\tslug: text$1(\"slug\").notNull(),\n\tname: text$1(\"name\").notNull(),\n\tdescription: text$1(\"description\").notNull(),\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\trequestSchema: text$1(\"request_schema\", { mode: \"json\" }).$type().notNull().default({}),\n\trunInputValues: text$1(\"run_input_values\", { mode: \"json\" }).$type(),\n\tcanvasAnnotationsJson: text$1(\"canvas_annotations_json\", { mode: \"json\" }).$type(),\n\tcanvasAnnotationsHash: text$1(\"canvas_annotations_hash\"),\n\tcanvasAnnotationsModel: text$1(\"canvas_annotations_model\"),\n\tcanvasAnnotationsStatus: text$1(\"canvas_annotations_status\").$type().notNull().default(\"idle\"),\n\tcanvasAnnotationsGeneratedAt: integer$1(\"canvas_annotations_generated_at\", { mode: \"timestamp_ms\" }),\n\toverviewSummary: text$1(\"overview_summary\"),\n\toverviewPhasesJson: text$1(\"overview_phases_json\", { mode: \"json\" }).$type(),\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}, (table) => [index$1(\"workflows_organization_id_idx\").on(table.organizationId), uniqueIndex$1(\"workflows_project_id_slug_idx\").on(table.projectId, table.slug)]);\n//#endregion\n//#region src/schema/tables/tenant/resource-activity.ts\nconst resourceActivity = pgTable(\"resource_activity\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id),\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) => [\n\tindex(\"resource_activity_organization_id_idx\").on(table.organizationId),\n\tuniqueIndex(\"resource_activity_project_user_kind_resource\").on(table.projectId, table.userId, table.resourceKind, table.resourceId),\n\tindex(\"resource_activity_user_last_opened_at\").on(table.userId, table.lastOpenedAt),\n\ttenantOrganizationPolicy(table.organizationId)\n]).enableRLS();\nconst resourceActivitySqlite = sqliteTable(\"resource_activity\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id),\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) => [\n\tindex$1(\"resource_activity_organization_id_idx\").on(table.organizationId),\n\tuniqueIndex$1(\"resource_activity_project_user_kind_resource\").on(table.projectId, table.userId, table.resourceKind, table.resourceId),\n\tindex$1(\"resource_activity_user_last_opened_at\").on(table.userId, table.lastOpenedAt)\n]);\n//#endregion\n//#region src/schema/tables/tenant/brains.ts\n/**\n* A Brain owns documents, an index config, and one vector namespace per\n* generation. Brains are organization-scoped resources administered by user\n* members (`brain_members`); read narrowing lives in `brain_filters` and\n* project runtime access in `brain_grants`. Slugs are unique per organization\n* and colon-free so `{brain}:{filter}` references resolve unambiguously.\n*/\nconst brains = pgTable(\"brains\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id),\n\tslug: text(\"slug\").notNull(),\n\tname: text(\"name\").notNull(),\n\tdescription: text(\"description\").notNull(),\n\t/** Embedding model / chunking defaults / language. */\n\tindexConfig: jsonb(\"index_config\").$type().notNull(),\n\t/** Namespace generation the Brain serves; bumped by rebuild cut-over. */\n\tactiveGeneration: integer(\"active_generation\").notNull().default(1),\n\t/** Persisted rebuild target; null outside `rebuilding`. */\n\tpendingGeneration: integer(\"pending_generation\"),\n\t/** Config used by every proxy call targeting pendingGeneration. */\n\tpendingIndexConfig: jsonb(\"pending_index_config\").$type(),\n\t/**\n\t* Vector dimension observed for the active generation; null until the\n\t* first successful embedding (set once via CAS). Validates later\n\t* writes/queries without hardcoding model-specific values.\n\t*/\n\tactiveVectorDimensions: integer(\"active_vector_dimensions\"),\n\t/** Pending-generation equivalent; promoted to active on rebuild cut-over. */\n\tpendingVectorDimensions: integer(\"pending_vector_dimensions\"),\n\t/** CAS fence incremented by every accepted document mutation. */\n\tmutationEpoch: integer(\"mutation_epoch\").notNull().default(0),\n\tstatus: text(\"status\").notNull(),\n\tcreatedByUserId: text(\"created_by_user_id\"),\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) => [\n\tindex(\"brains_organization_id_idx\").on(table.organizationId),\n\tuniqueIndex(\"brains_organization_id_slug_idx\").on(table.organizationId, table.slug).where(sql`${table.deletedAt} IS NULL`),\n\ttenantOrganizationPolicy(table.organizationId)\n]).enableRLS();\nconst brainsSqlite = sqliteTable(\"brains\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id),\n\tslug: text$1(\"slug\").notNull(),\n\tname: text$1(\"name\").notNull(),\n\tdescription: text$1(\"description\").notNull(),\n\tindexConfig: text$1(\"index_config\", { mode: \"json\" }).$type().notNull(),\n\tactiveGeneration: integer$1(\"active_generation\").notNull().default(1),\n\tpendingGeneration: integer$1(\"pending_generation\"),\n\tpendingIndexConfig: text$1(\"pending_index_config\", { mode: \"json\" }).$type(),\n\tactiveVectorDimensions: integer$1(\"active_vector_dimensions\"),\n\tpendingVectorDimensions: integer$1(\"pending_vector_dimensions\"),\n\tmutationEpoch: integer$1(\"mutation_epoch\").notNull().default(0),\n\tstatus: text$1(\"status\").notNull(),\n\tcreatedByUserId: text$1(\"created_by_user_id\"),\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(\"brains_organization_id_idx\").on(table.organizationId), uniqueIndex$1(\"brains_organization_id_slug_idx\").on(table.organizationId, table.slug).where(sql`${table.deletedAt} IS NULL`)]);\n//#endregion\n//#region src/schema/tables/tenant/brain-members.ts\n/**\n* Brain resource membership. Creating a Brain creates an `owner` row for the\n* caller in the same transaction. Owners manage members and deletion; admins\n* manage settings, documents, filters, and project grants. The \\u22651-owner\n* invariant is enforced transactionally in the membership queries (multiple\n* owners are allowed, so no index can express it).\n*/\nconst brainMembers = pgTable(\"brain_members\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id),\n\tbrainId: text(\"brain_id\").notNull().references(() => brains.id),\n\tuserId: text(\"user_id\").notNull(),\n\t/** `owner` | `admin` */\n\trole: text(\"role\").notNull(),\n\tcreatedByUserId: text(\"created_by_user_id\"),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [\n\tindex(\"brain_members_organization_id_idx\").on(table.organizationId),\n\tindex(\"brain_members_brain_id_idx\").on(table.brainId),\n\tindex(\"brain_members_user_id_idx\").on(table.userId),\n\tuniqueIndex(\"brain_members_brain_user_idx\").on(table.brainId, table.userId),\n\tcheck(\"brain_members_role_check\", sql`${table.role} IN ('owner', 'admin')`),\n\ttenantOrganizationPolicy(table.organizationId)\n]).enableRLS();\nconst brainMembersSqlite = sqliteTable(\"brain_members\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id),\n\tbrainId: text$1(\"brain_id\").notNull().references(() => brainsSqlite.id),\n\tuserId: text$1(\"user_id\").notNull(),\n\trole: text$1(\"role\").notNull(),\n\tcreatedByUserId: text$1(\"created_by_user_id\"),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [\n\tindex$1(\"brain_members_organization_id_idx\").on(table.organizationId),\n\tindex$1(\"brain_members_brain_id_idx\").on(table.brainId),\n\tindex$1(\"brain_members_user_id_idx\").on(table.userId),\n\tuniqueIndex$1(\"brain_members_brain_user_idx\").on(table.brainId, table.userId),\n\tcheck$1(\"brain_members_role_check\", sql`${table.role} IN ('owner', 'admin')`)\n]);\n//#endregion\n//#region src/schema/tables/tenant/brain-filters.ts\n/**\n* A filter narrows reads against its Brain: it owns no documents, index,\n* generation, or grants. Externally addressable as `{brain-slug}:{slug}`;\n* the parent Brain's project grant governs access. Deleting a Brain cascades\n* its filters (application-managed, matching the other tenant tables).\n*/\nconst brainFilters = pgTable(\"brain_filters\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id),\n\tbrainId: text(\"brain_id\").notNull().references(() => brains.id),\n\t/** Local colon-free slug, unique per Brain. */\n\tslug: text(\"slug\").notNull(),\n\tname: text(\"name\").notNull(),\n\tdescription: text(\"description\").notNull(),\n\t/** Filter expression: `{ source?, metadata? }`, ANDed at read time. */\n\tfilter: jsonb(\"filter\").$type().notNull(),\n\tcreatedByUserId: text(\"created_by_user_id\"),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [\n\tindex(\"brain_filters_organization_id_idx\").on(table.organizationId),\n\tindex(\"brain_filters_brain_id_idx\").on(table.brainId),\n\tuniqueIndex(\"brain_filters_brain_slug_idx\").on(table.brainId, table.slug),\n\ttenantOrganizationPolicy(table.organizationId)\n]).enableRLS();\nconst brainFiltersSqlite = sqliteTable(\"brain_filters\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id),\n\tbrainId: text$1(\"brain_id\").notNull().references(() => brainsSqlite.id),\n\tslug: text$1(\"slug\").notNull(),\n\tname: text$1(\"name\").notNull(),\n\tdescription: text$1(\"description\").notNull(),\n\tfilter: text$1(\"filter\", { mode: \"json\" }).$type().notNull(),\n\tcreatedByUserId: text$1(\"created_by_user_id\"),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [\n\tindex$1(\"brain_filters_organization_id_idx\").on(table.organizationId),\n\tindex$1(\"brain_filters_brain_id_idx\").on(table.brainId),\n\tuniqueIndex$1(\"brain_filters_brain_slug_idx\").on(table.brainId, table.slug)\n]);\n//#endregion\n//#region src/schema/tables/tenant/brain-grants.ts\n/**\n* Explicit per-project runtime capability on a Brain: `read` for agent\n* attach/search/read and workflow reads, `write` additionally for workflow\n* document mutations (`write` implies read). One row per (brain, project);\n* upgrading access updates the row. Creation never auto-grants and there are\n* no organization-wide grants. A grant governs the Brain's filters too.\n*/\nconst brainGrants = pgTable(\"brain_grants\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id),\n\tbrainId: text(\"brain_id\").notNull().references(() => brains.id),\n\tprojectId: text(\"project_id\").notNull(),\n\t/** `read` | `write` */\n\taccess: text(\"access\").notNull(),\n\tcreatedByUserId: text(\"created_by_user_id\"),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull()\n}, (table) => [\n\tindex(\"brain_grants_organization_id_idx\").on(table.organizationId),\n\tindex(\"brain_grants_brain_id_idx\").on(table.brainId),\n\tindex(\"brain_grants_project_id_idx\").on(table.projectId),\n\tuniqueIndex(\"brain_grants_brain_project_idx\").on(table.brainId, table.projectId),\n\tcheck(\"brain_grants_access_check\", sql`${table.access} IN ('read', 'write')`),\n\ttenantOrganizationPolicy(table.organizationId)\n]).enableRLS();\nconst brainGrantsSqlite = sqliteTable(\"brain_grants\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id),\n\tbrainId: text$1(\"brain_id\").notNull().references(() => brainsSqlite.id),\n\tprojectId: text$1(\"project_id\").notNull(),\n\taccess: text$1(\"access\").notNull(),\n\tcreatedByUserId: text$1(\"created_by_user_id\"),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [\n\tindex$1(\"brain_grants_organization_id_idx\").on(table.organizationId),\n\tindex$1(\"brain_grants_brain_id_idx\").on(table.brainId),\n\tindex$1(\"brain_grants_project_id_idx\").on(table.projectId),\n\tuniqueIndex$1(\"brain_grants_brain_project_idx\").on(table.brainId, table.projectId),\n\tcheck$1(\"brain_grants_access_check\", sql`${table.access} IN ('read', 'write')`)\n]);\n//#endregion\n//#region src/schema/tables/tenant/brain-document-versions.ts\n/**\n* Bounded two-phase-commit staging row for async ingestion — NOT version\n* history. A document has the live ready version plus at most a few in-flight\n* rows; superseded rows are pruned after promote. Object keys are denormalized\n* here: file uploads point at isolated staging bytes until a worker verifies\n* and promotes them to a content-addressed key. There are no separate\n* blob/artifact registry tables — dedupe and GC are queries over `actualSha256`.\n*/\nconst brainDocumentVersions = pgTable(\"brain_document_versions\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id),\n\tbrainId: text(\"brain_id\").notNull().references(() => brains.id),\n\t/** Internal row id of the owning brain_documents row. */\n\tdocumentRowId: text(\"document_row_id\").notNull().references(() => brainDocuments.id),\n\t/** Monotonic per document; settles concurrent put ordering. */\n\trevision: integer(\"revision\").notNull(),\n\t/** Document deletion epoch captured when this immutable candidate was prepared. */\n\tdeletionEpoch: integer(\"deletion_epoch\").notNull().default(0),\n\tclientIdempotencyId: text(\"client_idempotency_id\").notNull(),\n\t/** Index-affecting logical fields are snapshotted so concurrent puts cannot mix inputs. */\n\ttitle: text(\"title\").notNull(),\n\tmetadata: jsonb(\"metadata\").$type(),\n\tuserRevision: text(\"user_revision\"),\n\tindexingFingerprint: text(\"indexing_fingerprint\"),\n\t/** Where the candidate content originated; part of the indexing fingerprint. */\n\tsource: text(\"source\").notNull(),\n\t/** `content` | `blocks` | `file` — how the raw object is interpreted. */\n\tinputKind: text(\"input_kind\").notNull(),\n\t/** `pending_upload` | `pending_ingest` | `queued` | `processing` | `ready` | `failed` */\n\tstatus: text(\"status\").notNull(),\n\tfailureCode: text(\"failure_code\"),\n\tfailureMessage: text(\"failure_message\"),\n\t/** Caller-declared sha256 (file flow); null for inline puts (server computes). */\n\tdeclaredSha256: text(\"declared_sha256\"),\n\t/** Server-verified content hash; the dedupe / GC key. */\n\tactualSha256: text(\"actual_sha256\"),\n\tcontentType: text(\"content_type\"),\n\tdetectedFormat: text(\"detected_format\"),\n\t/** Staging key while pending; verified content-addressed original bytes afterward. */\n\trawObjectKey: text(\"raw_object_key\"),\n\trawByteCount: integer(\"raw_byte_count\"),\n\t/** Extraction cache for expensive formats; null = derive from raw on the fly. */\n\tcanonicalObjectKey: text(\"canonical_object_key\"),\n\tcanonicalByteCount: integer(\"canonical_byte_count\"),\n\textractorVersion: text(\"extractor_version\"),\n\tchunkerVersion: text(\"chunker_version\"),\n\tindexVersion: text(\"index_version\"),\n\t/** Namespace generation this version's index rows were written into. */\n\tindexGeneration: integer(\"index_generation\"),\n\tchunkCount: integer(\"chunk_count\"),\n\t/** Extra text prefixed into chunk embeddings; kept for rebuilds. */\n\tembeddingContext: text(\"embedding_context\"),\n\t/** Per-document chunking override; kept for rebuilds. */\n\tchunkingOverride: jsonb(\"chunking_override\").$type(),\n\t/** Expiring worker ownership; only the current token may settle processing. */\n\tleaseToken: text(\"lease_token\"),\n\tleaseExpiresAt: timestamp(\"lease_expires_at\", { withTimezone: true }),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [\n\tindex(\"brain_document_versions_organization_id_idx\").on(table.organizationId),\n\tindex(\"brain_document_versions_brain_id_idx\").on(table.brainId),\n\tindex(\"brain_document_versions_document_row_id_idx\").on(table.documentRowId),\n\tindex(\"brain_document_versions_sha256_idx\").on(table.organizationId, table.actualSha256),\n\tuniqueIndex(\"brain_document_versions_document_revision_idx\").on(table.documentRowId, table.revision),\n\tuniqueIndex(\"brain_document_versions_document_idempotency_idx\").on(table.documentRowId, table.clientIdempotencyId),\n\ttenantOrganizationPolicy(table.organizationId)\n]).enableRLS();\nconst brainDocumentVersionsSqlite = sqliteTable(\"brain_document_versions\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id),\n\tbrainId: text$1(\"brain_id\").notNull().references(() => brainsSqlite.id),\n\tdocumentRowId: text$1(\"document_row_id\").notNull().references(() => brainDocumentsSqlite.id),\n\trevision: integer$1(\"revision\").notNull(),\n\tdeletionEpoch: integer$1(\"deletion_epoch\").notNull().default(0),\n\tclientIdempotencyId: text$1(\"client_idempotency_id\").notNull(),\n\ttitle: text$1(\"title\").notNull(),\n\tmetadata: text$1(\"metadata\", { mode: \"json\" }).$type(),\n\tuserRevision: text$1(\"user_revision\"),\n\tindexingFingerprint: text$1(\"indexing_fingerprint\"),\n\tsource: text$1(\"source\").notNull(),\n\tinputKind: text$1(\"input_kind\").notNull(),\n\tstatus: text$1(\"status\").notNull(),\n\tfailureCode: text$1(\"failure_code\"),\n\tfailureMessage: text$1(\"failure_message\"),\n\tdeclaredSha256: text$1(\"declared_sha256\"),\n\tactualSha256: text$1(\"actual_sha256\"),\n\tcontentType: text$1(\"content_type\"),\n\tdetectedFormat: text$1(\"detected_format\"),\n\trawObjectKey: text$1(\"raw_object_key\"),\n\trawByteCount: integer$1(\"raw_byte_count\"),\n\tcanonicalObjectKey: text$1(\"canonical_object_key\"),\n\tcanonicalByteCount: integer$1(\"canonical_byte_count\"),\n\textractorVersion: text$1(\"extractor_version\"),\n\tchunkerVersion: text$1(\"chunker_version\"),\n\tindexVersion: text$1(\"index_version\"),\n\tindexGeneration: integer$1(\"index_generation\"),\n\tchunkCount: integer$1(\"chunk_count\"),\n\tembeddingContext: text$1(\"embedding_context\"),\n\tchunkingOverride: text$1(\"chunking_override\", { mode: \"json\" }).$type(),\n\tleaseToken: text$1(\"lease_token\"),\n\tleaseExpiresAt: integer$1(\"lease_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}, (table) => [\n\tindex$1(\"brain_document_versions_organization_id_idx\").on(table.organizationId),\n\tindex$1(\"brain_document_versions_brain_id_idx\").on(table.brainId),\n\tindex$1(\"brain_document_versions_document_row_id_idx\").on(table.documentRowId),\n\tindex$1(\"brain_document_versions_sha256_idx\").on(table.organizationId, table.actualSha256),\n\tuniqueIndex$1(\"brain_document_versions_document_revision_idx\").on(table.documentRowId, table.revision),\n\tuniqueIndex$1(\"brain_document_versions_document_idempotency_idx\").on(table.documentRowId, table.clientIdempotencyId)\n]);\n//#endregion\n//#region src/schema/tables/tenant/brain-documents.ts\n/**\n* Logical document in a Brain, keyed by the caller-supplied `documentId`\n* (unique per Brain among live documents; soft-deleted rows are revived on\n* re-put). `currentVersionId` points at the live ready version; in-flight\n* ingests live in `brain_document_versions` and never clobber it.\n*/\nconst brainDocuments = pgTable(\"brain_documents\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id),\n\tbrainId: text(\"brain_id\").notNull().references(() => brains.id),\n\t/** Caller-supplied stable key (`slack:C123:169…`, a relative path, …). */\n\tdocumentId: text(\"document_id\").notNull(),\n\ttitle: text(\"title\").notNull(),\n\t/** Where the current content originated (`linear`, `notion`, `manual`, …). */\n\tsource: text(\"source\").notNull(),\n\t/** Filterable metadata attributes; mirrored into the index, never embedded. */\n\tmetadata: jsonb(\"metadata\").$type(),\n\t/** Opaque caller revision fingerprint for the current committed content. */\n\tuserRevision: text(\"user_revision\"),\n\t/**\n\t* Monotonic put counter. Atomically incremented (`latest_revision + 1 …\n\t* RETURNING`) to allocate version revisions — the row lock serializes\n\t* concurrent puts, so allocation never races the unique revision index.\n\t*/\n\tlatestRevision: integer(\"latest_revision\").notNull().default(0),\n\t/** Orders independently patchable metadata against in-flight content candidates. */\n\tmetadataRevision: integer(\"metadata_revision\").notNull().default(0),\n\t/** Incremented on delete; candidates may only promote in the epoch they captured. */\n\tdeletionEpoch: integer(\"deletion_epoch\").notNull().default(0),\n\tcurrentVersionId: text(\"current_version_id\").references(() => brainDocumentVersions.id),\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) => [\n\tindex(\"brain_documents_organization_id_idx\").on(table.organizationId),\n\tindex(\"brain_documents_brain_id_idx\").on(table.brainId),\n\tuniqueIndex(\"brain_documents_brain_document_id_idx\").on(table.brainId, table.documentId),\n\ttenantOrganizationPolicy(table.organizationId)\n]).enableRLS();\nconst brainDocumentsSqlite = sqliteTable(\"brain_documents\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id),\n\tbrainId: text$1(\"brain_id\").notNull().references(() => brainsSqlite.id),\n\tdocumentId: text$1(\"document_id\").notNull(),\n\ttitle: text$1(\"title\").notNull(),\n\tsource: text$1(\"source\").notNull(),\n\tmetadata: text$1(\"metadata\", { mode: \"json\" }).$type(),\n\tuserRevision: text$1(\"user_revision\"),\n\tlatestRevision: integer$1(\"latest_revision\").notNull().default(0),\n\tmetadataRevision: integer$1(\"metadata_revision\").notNull().default(0),\n\tdeletionEpoch: integer$1(\"deletion_epoch\").notNull().default(0),\n\tcurrentVersionId: text$1(\"current_version_id\").references(() => brainDocumentVersionsSqlite.id),\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) => [\n\tindex$1(\"brain_documents_organization_id_idx\").on(table.organizationId),\n\tindex$1(\"brain_documents_brain_id_idx\").on(table.brainId),\n\tuniqueIndex$1(\"brain_documents_brain_document_id_idx\").on(table.brainId, table.documentId)\n]);\n//#endregion\n//#region src/schema/tables/tenant/brain-document-write-events.ts\n/**\n* Retained provenance for accepted Brain content writes. This is not ingestion\n* state: version rows may be pruned while these events remain queryable.\n* Pending is represented by a null outcome; terminal outcomes settle once.\n*/\nconst brainDocumentWriteEvents = pgTable(\"brain_document_write_events\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id),\n\tbrainId: text(\"brain_id\").notNull().references(() => brains.id),\n\t/**\n\t* Attached after document preparation. Nullable only during the short\n\t* begin/prepare window; the FK intentionally survives soft deletion.\n\t*/\n\tdocumentRowId: text(\"document_row_id\").references(() => brainDocuments.id),\n\tdocumentId: text(\"document_id\").notNull(),\n\tclientIdempotencyId: text(\"client_idempotency_id\").notNull(),\n\trequestFingerprint: text(\"request_fingerprint\").notNull(),\n\t/** `workflow` | `manual` — how this version entered the Brain. */\n\tprovisionerKind: text(\"provisioner_kind\").notNull(),\n\t/** Originating project for workflow writes; null for org-scoped manual writes. */\n\tprovisionerProjectId: text(\"provisioner_project_id\"),\n\tprovisionerWorkflowRunId: text(\"provisioner_workflow_run_id\"),\n\tprovisionerWorkflowSlug: text(\"provisioner_workflow_slug\"),\n\tprovisionerCorrelationId: text(\"provisioner_correlation_id\"),\n\tprovisionerManualUserId: text(\"provisioner_manual_user_id\"),\n\t/** No FK: versions are bounded staging state and may be pruned. */\n\tversionId: text(\"version_id\"),\n\t/** `content` | `blocks` | `file`. */\n\tinputKind: text(\"input_kind\").notNull(),\n\t/** Null while pending; `ready` | `unchanged` | `failed` after terminal settlement. */\n\toutcome: text(\"outcome\"),\n\tmetadataUpdated: boolean(\"metadata_updated\").notNull().default(sql`false`),\n\tfailureCode: text(\"failure_code\"),\n\tfailureMessage: text(\"failure_message\"),\n\tsubmittedAt: timestamp(\"submitted_at\", { withTimezone: true }).notNull(),\n\tcontentReceivedAt: timestamp(\"content_received_at\", { withTimezone: true }),\n\tcompletedAt: timestamp(\"completed_at\", { withTimezone: true })\n}, (table) => [\n\tindex(\"brain_document_write_events_organization_id_idx\").on(table.organizationId),\n\tindex(\"brain_document_write_events_brain_id_idx\").on(table.brainId),\n\tindex(\"brain_document_write_events_history_idx\").on(table.brainId, table.documentRowId, table.submittedAt, table.id),\n\tuniqueIndex(\"brain_document_write_events_brain_idempotency_idx\").on(table.brainId, table.clientIdempotencyId),\n\tuniqueIndex(\"brain_document_write_events_version_id_idx\").on(table.versionId),\n\tcheck(\"brain_document_write_events_provisioner_check\", sql`(\n        (${table.provisionerKind} = 'workflow'\n          AND ${table.provisionerProjectId} IS NOT NULL\n          AND ${table.provisionerWorkflowRunId} IS NOT NULL\n          AND ${table.provisionerWorkflowSlug} IS NOT NULL\n          AND ${table.provisionerCorrelationId} IS NOT NULL\n          AND ${table.provisionerManualUserId} IS NULL)\n        OR\n        (${table.provisionerKind} = 'manual'\n          AND ${table.provisionerProjectId} IS NULL\n          AND ${table.provisionerWorkflowRunId} IS NULL\n          AND ${table.provisionerWorkflowSlug} IS NULL\n          AND ${table.provisionerCorrelationId} IS NULL\n          AND ${table.provisionerManualUserId} IS NOT NULL)\n      )`),\n\tcheck(\"brain_document_write_events_input_kind_check\", sql`${table.inputKind} IN ('content', 'blocks', 'file')`),\n\tcheck(\"brain_document_write_events_outcome_check\", sql`(\n        (${table.outcome} IS NULL\n          AND ${table.completedAt} IS NULL\n          AND ${table.failureCode} IS NULL\n          AND ${table.failureMessage} IS NULL)\n        OR\n        (${table.outcome} IN ('ready', 'unchanged')\n          AND ${table.completedAt} IS NOT NULL\n          AND ${table.failureCode} IS NULL\n          AND ${table.failureMessage} IS NULL)\n        OR\n        (${table.outcome} = 'failed' AND ${table.completedAt} IS NOT NULL)\n      )`),\n\ttenantOrganizationPolicy(table.organizationId)\n]).enableRLS();\nconst brainDocumentWriteEventsSqlite = sqliteTable(\"brain_document_write_events\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id),\n\tbrainId: text$1(\"brain_id\").notNull().references(() => brainsSqlite.id),\n\tdocumentRowId: text$1(\"document_row_id\").references(() => brainDocumentsSqlite.id),\n\tdocumentId: text$1(\"document_id\").notNull(),\n\tclientIdempotencyId: text$1(\"client_idempotency_id\").notNull(),\n\trequestFingerprint: text$1(\"request_fingerprint\").notNull(),\n\tprovisionerKind: text$1(\"provisioner_kind\").notNull(),\n\tprovisionerProjectId: text$1(\"provisioner_project_id\"),\n\tprovisionerWorkflowRunId: text$1(\"provisioner_workflow_run_id\"),\n\tprovisionerWorkflowSlug: text$1(\"provisioner_workflow_slug\"),\n\tprovisionerCorrelationId: text$1(\"provisioner_correlation_id\"),\n\tprovisionerManualUserId: text$1(\"provisioner_manual_user_id\"),\n\tversionId: text$1(\"version_id\"),\n\tinputKind: text$1(\"input_kind\").notNull(),\n\toutcome: text$1(\"outcome\"),\n\tmetadataUpdated: integer$1(\"metadata_updated\", { mode: \"boolean\" }).notNull().default(sql`false`),\n\tfailureCode: text$1(\"failure_code\"),\n\tfailureMessage: text$1(\"failure_message\"),\n\tsubmittedAt: integer$1(\"submitted_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tcontentReceivedAt: integer$1(\"content_received_at\", { mode: \"timestamp_ms\" }),\n\tcompletedAt: integer$1(\"completed_at\", { mode: \"timestamp_ms\" })\n}, (table) => [\n\tindex$1(\"brain_document_write_events_organization_id_idx\").on(table.organizationId),\n\tindex$1(\"brain_document_write_events_brain_id_idx\").on(table.brainId),\n\tindex$1(\"brain_document_write_events_history_idx\").on(table.brainId, table.documentRowId, table.submittedAt, table.id),\n\tuniqueIndex$1(\"brain_document_write_events_brain_idempotency_idx\").on(table.brainId, table.clientIdempotencyId),\n\tuniqueIndex$1(\"brain_document_write_events_version_id_idx\").on(table.versionId),\n\tcheck$1(\"brain_document_write_events_provisioner_check\", sql`(\n        (${table.provisionerKind} = 'workflow'\n          AND ${table.provisionerProjectId} IS NOT NULL\n          AND ${table.provisionerWorkflowRunId} IS NOT NULL\n          AND ${table.provisionerWorkflowSlug} IS NOT NULL\n          AND ${table.provisionerCorrelationId} IS NOT NULL\n          AND ${table.provisionerManualUserId} IS NULL)\n        OR\n        (${table.provisionerKind} = 'manual'\n          AND ${table.provisionerProjectId} IS NULL\n          AND ${table.provisionerWorkflowRunId} IS NULL\n          AND ${table.provisionerWorkflowSlug} IS NULL\n          AND ${table.provisionerCorrelationId} IS NULL\n          AND ${table.provisionerManualUserId} IS NOT NULL)\n      )`),\n\tcheck$1(\"brain_document_write_events_input_kind_check\", sql`${table.inputKind} IN ('content', 'blocks', 'file')`),\n\tcheck$1(\"brain_document_write_events_outcome_check\", sql`(\n        (${table.outcome} IS NULL\n          AND ${table.completedAt} IS NULL\n          AND ${table.failureCode} IS NULL\n          AND ${table.failureMessage} IS NULL)\n        OR\n        (${table.outcome} IN ('ready', 'unchanged')\n          AND ${table.completedAt} IS NOT NULL\n          AND ${table.failureCode} IS NULL\n          AND ${table.failureMessage} IS NULL)\n        OR\n        (${table.outcome} = 'failed' AND ${table.completedAt} IS NOT NULL)\n      )`)\n]);\n//#endregion\n//#region src/schema/registrations.ts\n/**\n* Platform control-plane tables — Postgres (hosted) or SQLite (local dev).\n*\n* Tenant (project-runtime) tables live under `./tables/tenant/` in the public\n* schema with `organization_id` + RLS. Runtime queries live in `src/runtime/`.\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\tprojectRepositories: {\n\t\tpg: projectRepositories,\n\t\tsqlite: projectRepositoriesSqlite\n\t},\n\tplatformAgentSessions: {\n\t\tpg: platformAgentSessions,\n\t\tsqlite: platformAgentSessionsSqlite\n\t},\n\tplatformAgentEvents: {\n\t\tpg: platformAgentEvents,\n\t\tsqlite: platformAgentEventsSqlite\n\t},\n\tplatformAgentProjectSnapshots: {\n\t\tpg: platformAgentProjectSnapshots,\n\t\tsqlite: platformAgentProjectSnapshotsSqlite\n\t},\n\tprojectAgentSessionSandboxes: {\n\t\tpg: projectAgentSessionSandboxes,\n\t\tsqlite: projectAgentSessionSandboxesSqlite\n\t},\n\tprojectAgentEnvImages: {\n\t\tpg: projectAgentEnvImages,\n\t\tsqlite: projectAgentEnvImagesSqlite\n\t},\n\tpublishedForms: {\n\t\tpg: publishedForms,\n\t\tsqlite: publishedFormsSqlite\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\ttemplates: {\n\t\tpg: templates,\n\t\tsqlite: templatesSqlite\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\toauthPendingStates: {\n\t\tpg: oauthPendingStates,\n\t\tsqlite: oauthPendingStatesSqlite\n\t},\n\tmcpOauthClient: {\n\t\tpg: mcpOauthClient,\n\t\tsqlite: mcpOauthClientSqlite\n\t},\n\tmcpOauthAccessToken: {\n\t\tpg: mcpOauthAccessToken,\n\t\tsqlite: mcpOauthAccessTokenSqlite\n\t},\n\tmcpOauthConsent: {\n\t\tpg: mcpOauthConsent,\n\t\tsqlite: mcpOauthConsentSqlite\n\t},\n\tsecretValues: {\n\t\tpg: secretValues,\n\t\tsqlite: secretValuesSqlite\n\t},\n\torganizationBilling: {\n\t\tpg: organizationBilling,\n\t\tsqlite: organizationBillingSqlite\n\t},\n\tbillingEvents: {\n\t\tpg: billingEvents,\n\t\tsqlite: billingEventsSqlite\n\t},\n\tbillingWallet: {\n\t\tpg: billingWallet,\n\t\tsqlite: billingWalletSqlite\n\t},\n\tbillingLedger: {\n\t\tpg: billingLedger,\n\t\tsqlite: billingLedgerSqlite\n\t},\n\tusageEvents: {\n\t\tpg: usageEvents,\n\t\tsqlite: usageEventsSqlite\n\t},\n\tmanagedServiceCredentials: {\n\t\tpg: managedServiceCredentials,\n\t\tsqlite: managedServiceCredentialsSqlite\n\t},\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\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\tbrains: {\n\t\tpg: brains,\n\t\tsqlite: brainsSqlite\n\t},\n\tbrainMembers: {\n\t\tpg: brainMembers,\n\t\tsqlite: brainMembersSqlite\n\t},\n\tbrainFilters: {\n\t\tpg: brainFilters,\n\t\tsqlite: brainFiltersSqlite\n\t},\n\tbrainGrants: {\n\t\tpg: brainGrants,\n\t\tsqlite: brainGrantsSqlite\n\t},\n\tbrainDocuments: {\n\t\tpg: brainDocuments,\n\t\tsqlite: brainDocumentsSqlite\n\t},\n\tbrainDocumentVersions: {\n\t\tpg: brainDocumentVersions,\n\t\tsqlite: brainDocumentVersionsSqlite\n\t},\n\tbrainDocumentWriteEvents: {\n\t\tpg: brainDocumentWriteEvents,\n\t\tsqlite: brainDocumentWriteEventsSqlite\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/pool-error-telemetry.ts\nconst LOG_INTERVAL_MS = 1e4;\nconst SAFE_VALUE = /^[a-zA-Z0-9_.-]+$/;\nfunction safeValue(value) {\n\tif (typeof value !== \"string\" || !SAFE_VALUE.test(value)) return;\n\treturn value.slice(0, 64);\n}\nfunction errorField(error, key) {\n\tif (typeof error !== \"object\" || error === null || !(key in error)) return;\n\treturn safeValue(error[key]);\n}\nfunction errorCause$1(error) {\n\treturn typeof error === \"object\" && error !== null && \"cause\" in error ? error.cause : void 0;\n}\nfunction attachPoolErrorTelemetry(pool, options = {}) {\n\tconst env = options.env ?? process.env;\n\tconst now = options.now ?? Date.now;\n\tlet lastLoggedAt = Number.NEGATIVE_INFINITY;\n\tlet suppressed = 0;\n\tpool.on(\"error\", (error) => {\n\t\tconst timestamp = now();\n\t\tif (timestamp - lastLoggedAt < LOG_INTERVAL_MS) {\n\t\t\tsuppressed += 1;\n\t\t\treturn;\n\t\t}\n\t\tconst cause = errorCause$1(error);\n\t\tconst machineId = safeValue(env.FLY_MACHINE_ID?.trim());\n\t\tlog.error(\"postgres.pool.error\", {\n\t\t\tpool_total_count: pool.totalCount,\n\t\t\tpool_idle_count: pool.idleCount,\n\t\t\tpool_waiting_count: pool.waitingCount,\n\t\t\t...machineId ? { fly_machine_id: machineId } : {},\n\t\t\t...errorField(error, \"name\") ? { error_name: errorField(error, \"name\") } : {},\n\t\t\t...errorField(error, \"code\") ? { error_code: errorField(error, \"code\") } : {},\n\t\t\t...errorField(cause, \"name\") ? { cause_name: errorField(cause, \"name\") } : {},\n\t\t\t...errorField(cause, \"code\") ? { cause_code: errorField(cause, \"code\") } : {},\n\t\t\t...suppressed > 0 ? { suppressed_count: suppressed } : {}\n\t\t});\n\t\tlastLoggedAt = timestamp;\n\t\tsuppressed = 0;\n\t});\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 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//#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 ?? resolvePgPoolMax$1(),\n\t\tconnectionTimeoutMillis: 5e3,\n\t\tidleTimeoutMillis: 3e4,\n\t\tkeepAlive: true\n\t});\n\tattachPoolErrorTelemetry(pool);\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/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 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 SqliteClient(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/connection/pg/scoped-pool.ts\nconst RETRY_TOTAL_BUDGET_MS = 10100;\nconst SAFE_ERROR_VALUE = /^[a-zA-Z0-9_.-]+$/;\nfunction asError(value) {\n\treturn value instanceof Error ? value : new Error(String(value));\n}\nfunction dirtyConnectionError(reason) {\n\treturn /* @__PURE__ */ new Error(`discarding connection with uncertain transaction state: ${reason}`);\n}\nfunction safeErrorField(error, key) {\n\tif (typeof error !== \"object\" || error === null || !(key in error)) return;\n\tconst value = error[key];\n\tif (typeof value !== \"string\" || !SAFE_ERROR_VALUE.test(value)) return;\n\treturn value.slice(0, 64);\n}\nfunction logRollbackFailure(error, stage) {\n\tlog.error(\"postgres.scoped.rollback_failed\", {\n\t\tstage,\n\t\t...safeErrorField(error, \"name\") ? { error_name: safeErrorField(error, \"name\") } : {},\n\t\t...safeErrorField(error, \"code\") ? { error_code: safeErrorField(error, \"code\") } : {}\n\t});\n}\nfunction errorCode(error) {\n\treturn typeof error === \"object\" && error !== null && \"code\" in error ? String(error.code) : void 0;\n}\nfunction errorCause(error) {\n\treturn typeof error === \"object\" && error !== null && \"cause\" in error ? error.cause : void 0;\n}\nfunction isTransientConnectionAcquisitionError(error) {\n\tconst message = error instanceof Error ? error.message : \"\";\n\tconst code = errorCode(error);\n\tconst cause = errorCause(error);\n\tif (message === \"timeout exceeded when trying to connect\" || code === \"53300\") return false;\n\treturn message === \"Connection terminated due to connection timeout\" || message === \"Connection terminated unexpectedly\" || code === \"ETIMEDOUT\" || code === \"ECONNRESET\" || code === \"EAI_AGAIN\" || cause !== void 0 && cause !== error && isTransientConnectionAcquisitionError(cause);\n}\n/** Postgres SQLSTATE 25006 — session/backend rejecting writes as read-only. */\nconst READ_ONLY_SQLSTATE = \"25006\";\nfunction isReadOnlyTransactionError(error) {\n\tif (errorCode(error) === READ_ONLY_SQLSTATE) return true;\n\tconst message = (error instanceof Error ? error.message : String(error)).toLowerCase();\n\tif (message.includes(\"read-only transaction\") || message.includes(\"read only transaction\") || message.includes(\"cluster is read-only\")) return true;\n\tconst cause = errorCause(error);\n\treturn cause !== void 0 && cause !== error && isReadOnlyTransactionError(cause);\n}\nfunction jitterDelayMs() {\n\treturn Math.floor(Math.random() * 51);\n}\nasync function connectWithRetry(pool) {\n\tconst startedAt = Date.now();\n\ttry {\n\t\treturn await pool.connect();\n\t} catch (error) {\n\t\tif (!isTransientConnectionAcquisitionError(error)) throw error;\n\t\tconst delayMs = jitterDelayMs();\n\t\tif (Date.now() - startedAt + delayMs + 5e3 > RETRY_TOTAL_BUDGET_MS) throw error;\n\t\tif (delayMs > 0) await new Promise((resolve) => setTimeout(resolve, delayMs));\n\t\treturn pool.connect();\n\t}\n}\nfunction connectWithRetryCallback(pool, callback) {\n\tconnectWithRetry(pool).then((client) => callback(void 0, client), (error) => callback(asError(error)));\n}\nfunction bindQuery(originalQuery) {\n\treturn (...args) => Promise.resolve(originalQuery(...args));\n}\nfunction queryText(args) {\n\tconst first = args[0];\n\treturn typeof first === \"string\" ? first : first.text;\n}\nfunction commandText(text) {\n\treturn text?.trim().toUpperCase() ?? \"\";\n}\nfunction command(text) {\n\treturn commandText(text).split(/\\s+/)[0] || void 0;\n}\nfunction isFullRollback(text) {\n\treturn commandText(text) === \"ROLLBACK\";\n}\nfunction isChainedTerminal(text) {\n\treturn /^(COMMIT|ROLLBACK)\\s+AND\\s+(NO\\s+)?CHAIN\\b/.test(commandText(text));\n}\nfunction scopeClient(client, beginScope, releaseClient = client.release.bind(client)) {\n\tconst originalQueryMethod = client.query;\n\tconst originalReleaseMethod = client.release;\n\tconst query = bindQuery(originalQueryMethod.bind(client));\n\tlet transactionOpen = false;\n\tlet mustDestroy = false;\n\tlet released = false;\n\tclient.query = (async (...args) => {\n\t\tconst sql = queryText(args);\n\t\tconst sqlCommand = command(sql);\n\t\tif (isChainedTerminal(sql)) {\n\t\t\tmustDestroy = true;\n\t\t\tthrow new Error(\"COMMIT/ROLLBACK AND CHAIN is unsupported on scoped database clients\");\n\t\t}\n\t\tif (sqlCommand === \"BEGIN\" && !transactionOpen) {\n\t\t\ttransactionOpen = true;\n\t\t\ttry {\n\t\t\t\treturn await beginScope(query);\n\t\t\t} catch (error) {\n\t\t\t\tmustDestroy = true;\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t\tif (sqlCommand === \"COMMIT\" || sqlCommand === \"ROLLBACK\" && isFullRollback(sql)) try {\n\t\t\tconst result = await query(...args);\n\t\t\ttransactionOpen = false;\n\t\t\treturn result;\n\t\t} catch (error) {\n\t\t\tmustDestroy = true;\n\t\t\tthrow error;\n\t\t}\n\t\treturn query(...args);\n\t});\n\tconst release = (error) => {\n\t\tif (released) {\n\t\t\treleaseClient(error);\n\t\t\treturn;\n\t\t}\n\t\treleased = true;\n\t\tclient.query = originalQueryMethod;\n\t\tclient.release = originalReleaseMethod;\n\t\treleaseClient(error ?? (mustDestroy ? dirtyConnectionError(\"failed_terminal\") : transactionOpen ? dirtyConnectionError(\"open_transaction\") : void 0));\n\t};\n\tclient.release = release;\n\treturn {\n\t\tclient,\n\t\trelease\n\t};\n}\nasync function runScopedQueryOnce(pool, beginScope, args) {\n\tconst client = await connectWithRetry(pool);\n\tconst query = bindQuery(client.query.bind(client));\n\tlet releaseError;\n\tlet stage = \"begin\";\n\ttry {\n\t\tawait beginScope(query);\n\t\tstage = \"query\";\n\t\tconst result = await query(...args);\n\t\tstage = \"commit\";\n\t\tawait query(\"COMMIT\");\n\t\treturn result;\n\t} catch (error) {\n\t\tif (stage !== \"query\" || isReadOnlyTransactionError(error)) releaseError = asError(error);\n\t\ttry {\n\t\t\tawait query(\"ROLLBACK\");\n\t\t} catch (rollbackError) {\n\t\t\tlogRollbackFailure(rollbackError, stage);\n\t\t\treleaseError = asError(rollbackError);\n\t\t}\n\t\tthrow error;\n\t} finally {\n\t\tclient.release(releaseError);\n\t}\n}\nasync function runScopedQuery(pool, beginScope, args) {\n\ttry {\n\t\treturn await runScopedQueryOnce(pool, beginScope, args);\n\t} catch (error) {\n\t\tif (!isReadOnlyTransactionError(error)) throw error;\n\t\tconst delayMs = jitterDelayMs();\n\t\tif (delayMs > 0) await new Promise((resolve) => setTimeout(resolve, delayMs));\n\t\treturn runScopedQueryOnce(pool, beginScope, args);\n\t}\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/**\n* Ensure the tenant schema exists — check first, create only when missing.\n*\n* Cloud org schemas always exist here (the platform admin creates them at\n* provision) and the org login could not create one anyway: it has no\n* database-level CREATE, which Postgres checks *before* the IF-NOT-EXISTS\n* short-circuit. The create branch is for standalone/self-hosted Postgres,\n* where no provisioning step exists and the user's login does the first-boot\n* schema creation.\n*/\nasync function ensureTenantSchema(db, schemaName) {\n\tif ((await db.execute(sql`SELECT 1 FROM information_schema.schemata WHERE schema_name = ${schemaName}`)).rows.length > 0) return;\n\tawait db.execute(sql`CREATE SCHEMA IF NOT EXISTS ${sql.identifier(schemaName)}`);\n}\n/**\n* Drizzle's migrator adapted for tenant schemas: same journal table and\n* folderMillis comparison, but with a permission-tolerant ensure-schema step\n* (see {@link ensureTenantSchema}) and a per-schema advisory lock so\n* concurrent runs (worker restarts, rollout overlap) serialize instead of\n* racing the same pending migration — the journal is read *inside* the locked\n* transaction, so the second runner sees the winner's work and no-ops.\n*/\nasync function migratePgTenantSchema(db, config, migrations) {\n\tconst journal = sql.identifier(config.migrationsSchema);\n\tconst table = sql.identifier(config.migrationsTable ?? \"__drizzle_migrations\");\n\tawait ensureTenantSchema(db, config.migrationsSchema);\n\tawait db.execute(sql`\n    CREATE TABLE IF NOT EXISTS ${journal}.${table} (\n      id SERIAL PRIMARY KEY,\n      hash text NOT NULL,\n      created_at bigint\n    )\n  `);\n\tawait db.transaction(async (tx) => {\n\t\tawait tx.execute(sql`SELECT pg_advisory_xact_lock(hashtext(${`migrate:${config.migrationsSchema}`}))`);\n\t\tconst lastMillisRaw = (await tx.execute(sql`SELECT created_at FROM ${journal}.${table} ORDER BY created_at DESC LIMIT 1`)).rows[0]?.created_at;\n\t\tconst lastMillis = lastMillisRaw === void 0 ? void 0 : Number(lastMillisRaw);\n\t\tfor (const migration of migrations) {\n\t\t\tif (lastMillis !== void 0 && lastMillis >= migration.folderMillis) continue;\n\t\t\tfor (const statement of migration.sql) await tx.execute(sql.raw(statement));\n\t\t\tawait tx.execute(sql`INSERT INTO ${journal}.${table} (\"hash\", \"created_at\") VALUES (${migration.hash}, ${migration.folderMillis})`);\n\t\t}\n\t});\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\tconst folder = dialect === \"postgres\" ? \"pg\" : \"sqlite\";\n\ttry {\n\t\treturn join(resolvePackageRoot(), \"drizzle\", folder);\n\t} catch {\n\t\treturn join(dirname(fileURLToPath(import.meta.url)), \"..\", \"..\", \"drizzle\", folder);\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\t{\n\t\t\"sql\": [\n\t\t\t\"CREATE TABLE \\\"mcp_oauth_access_token\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"access_token\\\" text NOT NULL,\\n\t\\\"refresh_token\\\" text,\\n\t\\\"access_token_expires_at\\\" timestamp with time zone,\\n\t\\\"refresh_token_expires_at\\\" timestamp with time zone,\\n\t\\\"client_id\\\" text NOT NULL,\\n\t\\\"user_id\\\" text,\\n\t\\\"scopes\\\" text,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\tCONSTRAINT \\\"mcp_oauth_access_token_access_token_unique\\\" UNIQUE(\\\"access_token\\\"),\\n\tCONSTRAINT \\\"mcp_oauth_access_token_refresh_token_unique\\\" UNIQUE(\\\"refresh_token\\\")\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"mcp_oauth_client\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"name\\\" text NOT NULL,\\n\t\\\"icon\\\" text,\\n\t\\\"metadata\\\" text,\\n\t\\\"client_id\\\" text NOT NULL,\\n\t\\\"client_secret\\\" text,\\n\t\\\"redirect_urls\\\" text NOT NULL,\\n\t\\\"type\\\" text NOT NULL,\\n\t\\\"disabled\\\" boolean DEFAULT false NOT NULL,\\n\t\\\"user_id\\\" text,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\tCONSTRAINT \\\"mcp_oauth_client_client_id_unique\\\" UNIQUE(\\\"client_id\\\")\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"mcp_oauth_consent\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"client_id\\\" text NOT NULL,\\n\t\\\"user_id\\\" text NOT NULL,\\n\t\\\"scopes\\\" text,\\n\t\\\"consent_given\\\" boolean DEFAULT false 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 \\\"mcp_oauth_access_token\\\" ADD CONSTRAINT \\\"mcp_oauth_access_token_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 \\\"mcp_oauth_client\\\" ADD CONSTRAINT \\\"mcp_oauth_client_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 \\\"mcp_oauth_consent\\\" ADD CONSTRAINT \\\"mcp_oauth_consent_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 \\\"mcp_oauth_access_token_client_id_idx\\\" ON \\\"mcp_oauth_access_token\\\" USING btree (\\\"client_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"mcp_oauth_access_token_user_id_idx\\\" ON \\\"mcp_oauth_access_token\\\" USING btree (\\\"user_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"mcp_oauth_client_user_id_idx\\\" ON \\\"mcp_oauth_client\\\" USING btree (\\\"user_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"mcp_oauth_consent_client_id_idx\\\" ON \\\"mcp_oauth_consent\\\" USING btree (\\\"client_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"mcp_oauth_consent_user_id_idx\\\" ON \\\"mcp_oauth_consent\\\" USING btree (\\\"user_id\\\");\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1782492431786,\n\t\t\"hash\": \"7253f63af93f3e5666ef069762be85bf338e646ff59ecbe154e161317b54e5a1\"\n\t},\n\t{\n\t\t\"sql\": [\"ALTER TABLE \\\"apps\\\" ADD COLUMN \\\"mcp_url\\\" text;\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1782507417125,\n\t\t\"hash\": \"23ce50823d9a3509f8fab79640ae554585f2789913592e918c76eee291f0dd9c\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"ALTER TABLE \\\"apps\\\" ADD COLUMN IF NOT EXISTS \\\"url\\\" text;\",\n\t\t\t\"\\nUPDATE \\\"apps\\\" SET \\\"url\\\" = \\\"mcp_url\\\" WHERE \\\"url\\\" IS NULL AND \\\"mcp_url\\\" IS NOT NULL;\",\n\t\t\t\"\\nALTER TABLE \\\"apps\\\" DROP COLUMN IF EXISTS \\\"mcp_url\\\";\\n\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 178251e7,\n\t\t\"hash\": \"470832e835329b20d4b22f83f3103869e94effd66de83bc573001d603a5c87b1\"\n\t},\n\t{\n\t\t\"sql\": [\"DROP INDEX \\\"secret_values_ref_idx\\\";\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1782679241250,\n\t\t\"hash\": \"95263d7c86d9b02c9d0c1a9233227cb449f500ae523d8423eb2b829bfa39f7cf\"\n\t},\n\t{\n\t\t\"sql\": [\"ALTER TABLE \\\"organizations\\\" ADD COLUMN \\\"redis_url_ciphertext\\\" text;\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1782847877006,\n\t\t\"hash\": \"79321e24c3a532a301ad4924722ff43d32bd85d2324e5f3079fccfecf4084692\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"CREATE TABLE \\\"billing_events\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"stripe_event_id\\\" text NOT NULL,\\n\t\\\"organization_id\\\" text NOT NULL,\\n\t\\\"type\\\" text NOT NULL,\\n\t\\\"amount_micro_credits\\\" bigint,\\n\t\\\"credits_granted_micro_credits\\\" bigint,\\n\t\\\"bucket\\\" text,\\n\t\\\"status\\\" text NOT NULL,\\n\t\\\"stripe_object_id\\\" text,\\n\t\\\"metadata\\\" jsonb,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"organization_billing\\\" (\\n\t\\\"organization_id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"plan_key\\\" text DEFAULT 'free' NOT NULL,\\n\t\\\"stripe_customer_id\\\" text,\\n\t\\\"stripe_subscription_id\\\" text,\\n\t\\\"stripe_payment_method_id\\\" text,\\n\t\\\"subscription_status\\\" text DEFAULT 'none' NOT NULL,\\n\t\\\"current_period_start\\\" timestamp with time zone,\\n\t\\\"current_period_end\\\" timestamp with time zone,\\n\t\\\"monthly_credit_micro_credits_override\\\" bigint,\\n\t\\\"limit_overrides\\\" jsonb,\\n\t\\\"auto_topup_enabled\\\" boolean DEFAULT false NOT NULL,\\n\t\\\"auto_topup_threshold_micro_credits\\\" bigint,\\n\t\\\"auto_topup_amount_micro_credits\\\" bigint,\\n\t\\\"auto_topup_pending_intent_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\"\\nALTER TABLE \\\"billing_events\\\" ADD CONSTRAINT \\\"billing_events_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_billing\\\" ADD CONSTRAINT \\\"organization_billing_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 \\\"billing_events_stripe_event_id_unique\\\" ON \\\"billing_events\\\" USING btree (\\\"stripe_event_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"billing_events_organization_id_idx\\\" ON \\\"billing_events\\\" USING btree (\\\"organization_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"organization_billing_stripe_customer_id_idx\\\" ON \\\"organization_billing\\\" USING btree (\\\"stripe_customer_id\\\");\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1783034589431,\n\t\t\"hash\": \"1a7071777f49cf31b027de19c79db93d3d46d96f2583319883ef2110befc6394\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"CREATE TABLE \\\"managed_service_credentials\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text NOT NULL,\\n\t\\\"kind\\\" text NOT NULL,\\n\t\\\"provider\\\" text NOT NULL,\\n\t\\\"value_ciphertext\\\" text NOT NULL,\\n\t\\\"key_preview\\\" text NOT NULL,\\n\t\\\"created_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);\\n\",\n\t\t\t\"\\nALTER TABLE \\\"managed_service_credentials\\\" ADD CONSTRAINT \\\"managed_service_credentials_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 \\\"managed_service_credentials_org_kind_provider_unique\\\" ON \\\"managed_service_credentials\\\" USING btree (\\\"organization_id\\\",\\\"kind\\\",\\\"provider\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"managed_service_credentials_org_kind_idx\\\" ON \\\"managed_service_credentials\\\" USING btree (\\\"organization_id\\\",\\\"kind\\\");\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1783449667603,\n\t\t\"hash\": \"955105c49aeb167fb783596091c09861eb284a913a8aab8ac5cfd43f7fb0bfe4\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"CREATE TABLE \\\"billing_ledger\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text NOT NULL,\\n\t\\\"entry_type\\\" text NOT NULL,\\n\t\\\"plan_delta_micro_credits\\\" bigint DEFAULT 0 NOT NULL,\\n\t\\\"prepaid_delta_micro_credits\\\" bigint DEFAULT 0 NOT NULL,\\n\t\\\"source\\\" text NOT NULL,\\n\t\\\"idempotency_key\\\" text NOT NULL,\\n\t\\\"run_id\\\" text,\\n\t\\\"project_id\\\" text,\\n\t\\\"provider_reference\\\" text,\\n\t\\\"metadata\\\" jsonb,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"billing_wallet\\\" (\\n\t\\\"organization_id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"plan_credit_micro_credits\\\" bigint DEFAULT 0 NOT NULL,\\n\t\\\"prepaid_credit_micro_credits\\\" bigint DEFAULT 0 NOT NULL,\\n\t\\\"period_start\\\" timestamp with time zone,\\n\t\\\"period_end\\\" timestamp with time zone,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"usage_events\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text NOT NULL,\\n\t\\\"project_id\\\" text,\\n\t\\\"run_id\\\" text,\\n\t\\\"run_kind\\\" text,\\n\t\\\"source\\\" text NOT NULL,\\n\t\\\"source_event_id\\\" text NOT NULL,\\n\t\\\"meter_key\\\" text NOT NULL,\\n\t\\\"quantity\\\" double precision NOT NULL,\\n\t\\\"unit\\\" text NOT NULL,\\n\t\\\"provider_cost_usd\\\" double precision,\\n\t\\\"key_source\\\" text,\\n\t\\\"price_version\\\" text NOT NULL,\\n\t\\\"charge_micro_credits\\\" bigint NOT NULL,\\n\t\\\"settled_ledger_id\\\" text,\\n\t\\\"occurred_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"accepted_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"metadata\\\" jsonb\\n);\\n\",\n\t\t\t\"\\nALTER TABLE \\\"billing_ledger\\\" ADD CONSTRAINT \\\"billing_ledger_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 \\\"billing_wallet\\\" ADD CONSTRAINT \\\"billing_wallet_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 \\\"usage_events\\\" ADD CONSTRAINT \\\"usage_events_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 \\\"billing_ledger_org_idempotency_unique\\\" ON \\\"billing_ledger\\\" USING btree (\\\"organization_id\\\",\\\"idempotency_key\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"billing_ledger_org_created_at_idx\\\" ON \\\"billing_ledger\\\" USING btree (\\\"organization_id\\\",\\\"created_at\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"usage_events_org_source_event_unique\\\" ON \\\"usage_events\\\" USING btree (\\\"organization_id\\\",\\\"source\\\",\\\"source_event_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"usage_events_org_run_occurred_idx\\\" ON \\\"usage_events\\\" USING btree (\\\"organization_id\\\",\\\"run_id\\\",\\\"occurred_at\\\");\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1783744084041,\n\t\t\"hash\": \"9b6b4209e0167283fc17b30adcb78610053e6ab757ca567d86483831385c36fa\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"CREATE TABLE \\\"agent_events\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text 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\\\"organization_id\\\" text 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\\\"ran_by_user_id\\\" text,\\n\t\\\"title\\\" text,\\n\t\\\"canceled_at\\\" timestamp with time zone,\\n\t\\\"status\\\" text,\\n\t\\\"total_duration_ms\\\" integer DEFAULT 0 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 \\\"agents\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text 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\\\"app_slugs\\\" jsonb,\\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_assignments\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text 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 TABLE \\\"credential_instances\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"app_slug\\\" text NOT NULL,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"name\\\" text,\\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\\\"shared_connection_id\\\" text,\\n\t\\\"granted_scopes\\\" jsonb,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"last_used_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"gateway_attachments\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text 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\\\"organization_id\\\" text 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\\\"organization_id\\\" text 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\\\"parent\\\" 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 \\\"resource_activity\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text 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 \\\"skills\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text 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\\\"organization_id\\\" text 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\\\"organization_id\\\" text 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\\\"organization_id\\\" text NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"trigger_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\\\"prompt\\\" text,\\n\t\\\"registered_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"disabled_at\\\" timestamp with time zone,\\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\\\"organization_id\\\" text NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"trigger_id\\\" text NOT NULL,\\n\t\\\"source_path\\\" text,\\n\t\\\"trigger_type\\\" text NOT NULL,\\n\t\\\"outcome\\\" text DEFAULT 'dispatched' NOT NULL,\\n\t\\\"reason\\\" text,\\n\t\\\"detail\\\" text,\\n\t\\\"payload\\\" jsonb,\\n\t\\\"triggered_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"triggers\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text 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\\\"state\\\" 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\\\"trigger_hash\\\" text,\\n\t\\\"overview_markdown\\\" text,\\n\t\\\"overview_hash\\\" text,\\n\t\\\"overview_model\\\" text,\\n\t\\\"overview_status\\\" text DEFAULT 'idle' NOT NULL,\\n\t\\\"overview_generated_at\\\" timestamp with time zone,\\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 \\\"workflow_events\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text 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\\\"organization_id\\\" text 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\\\"schema\\\" jsonb,\\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\\\"organization_id\\\" text 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\\\"ran_by_user_id\\\" text,\\n\t\\\"credential_context\\\" jsonb,\\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\\\"organization_id\\\" text 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\\\"organization_id\\\" text NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"name\\\" text NOT NULL,\\n\t\\\"description\\\" text NOT NULL,\\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\t\\\"request_schema\\\" jsonb DEFAULT '{}'::jsonb NOT NULL,\\n\t\\\"run_input_values\\\" jsonb,\\n\t\\\"canvas_annotations_json\\\" jsonb,\\n\t\\\"canvas_annotations_hash\\\" text,\\n\t\\\"canvas_annotations_model\\\" text,\\n\t\\\"canvas_annotations_status\\\" text DEFAULT 'idle' NOT NULL,\\n\t\\\"canvas_annotations_generated_at\\\" timestamp with time zone,\\n\t\\\"overview_summary\\\" text,\\n\t\\\"overview_phases_json\\\" jsonb,\\n\t\\\"overview_hash\\\" text,\\n\t\\\"overview_model\\\" text,\\n\t\\\"overview_status\\\" text DEFAULT 'idle' NOT NULL,\\n\t\\\"overview_generated_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nALTER TABLE \\\"agent_events\\\" ADD CONSTRAINT \\\"agent_events_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\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_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"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 \\\"agents\\\" ADD CONSTRAINT \\\"agents_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"credential_assignments\\\" ADD CONSTRAINT \\\"credential_assignments_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"credential_instances\\\" ADD CONSTRAINT \\\"credential_instances_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"gateway_attachments\\\" ADD CONSTRAINT \\\"gateway_attachments_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"gateway_thread_sessions\\\" ADD CONSTRAINT \\\"gateway_thread_sessions_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"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 \\\"jobs\\\" ADD CONSTRAINT \\\"jobs_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"resource_activity\\\" ADD CONSTRAINT \\\"resource_activity_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"skills\\\" ADD CONSTRAINT \\\"skills_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"trace_logs\\\" ADD CONSTRAINT \\\"trace_logs_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE no action 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 \\\"trace_spans\\\" ADD CONSTRAINT \\\"trace_spans_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_attachments\\\" ADD CONSTRAINT \\\"trigger_attachments_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\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\"\\nALTER TABLE \\\"trigger_runs\\\" ADD CONSTRAINT \\\"trigger_runs_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\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\"\\nALTER TABLE \\\"triggers\\\" ADD CONSTRAINT \\\"triggers_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"workflow_events\\\" ADD CONSTRAINT \\\"workflow_events_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"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_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"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_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"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\"\\nALTER TABLE \\\"workflow_subscriptions\\\" ADD CONSTRAINT \\\"workflow_subscriptions_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"workflows\\\" ADD CONSTRAINT \\\"workflows_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nCREATE INDEX \\\"agent_events_organization_id_idx\\\" ON \\\"agent_events\\\" USING btree (\\\"organization_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"agent_events_session_event_seq_idx\\\" ON \\\"agent_events\\\" USING btree (\\\"session_id\\\",\\\"event_type\\\",\\\"seq\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"agent_sessions_organization_id_idx\\\" ON \\\"agent_sessions\\\" USING btree (\\\"organization_id\\\");\",\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 INDEX \\\"agents_organization_id_idx\\\" ON \\\"agents\\\" USING btree (\\\"organization_id\\\");\",\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 INDEX \\\"credential_assignments_organization_id_idx\\\" ON \\\"credential_assignments\\\" USING btree (\\\"organization_id\\\");\",\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_instances_organization_id_idx\\\" ON \\\"credential_instances\\\" USING btree (\\\"organization_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\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 INDEX \\\"gateway_attachments_organization_id_idx\\\" ON \\\"gateway_attachments\\\" USING btree (\\\"organization_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 INDEX \\\"gateway_thread_sessions_organization_id_idx\\\" ON \\\"gateway_thread_sessions\\\" USING btree (\\\"organization_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"jobs_organization_id_idx\\\" ON \\\"jobs\\\" USING btree (\\\"organization_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"resource_activity_organization_id_idx\\\" ON \\\"resource_activity\\\" USING btree (\\\"organization_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 INDEX \\\"skills_organization_id_idx\\\" ON \\\"skills\\\" USING btree (\\\"organization_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_organization_id_idx\\\" ON \\\"trace_logs\\\" USING btree (\\\"organization_id\\\");\",\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 INDEX \\\"trace_spans_organization_id_idx\\\" ON \\\"trace_spans\\\" USING btree (\\\"organization_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"trace_spans_trace_id_started_at_idx\\\" ON \\\"trace_spans\\\" USING btree (\\\"trace_id\\\",\\\"started_at\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"trace_spans_ref_id_kind_started_at_idx\\\" ON \\\"trace_spans\\\" USING btree (\\\"ref_id\\\",\\\"kind\\\",\\\"started_at\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"trigger_attachments_organization_id_idx\\\" ON \\\"trigger_attachments\\\" USING btree (\\\"organization_id\\\");\",\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 INDEX \\\"trigger_runs_organization_id_idx\\\" ON \\\"trigger_runs\\\" USING btree (\\\"organization_id\\\");\",\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\"\\nCREATE INDEX \\\"trigger_runs_project_triggered_idx\\\" ON \\\"trigger_runs\\\" USING btree (\\\"project_id\\\",\\\"triggered_at\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"triggers_organization_id_idx\\\" ON \\\"triggers\\\" USING btree (\\\"organization_id\\\");\",\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\"\\nCREATE INDEX \\\"workflow_events_organization_id_idx\\\" ON \\\"workflow_events\\\" USING btree (\\\"organization_id\\\");\",\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 INDEX \\\"workflow_hooks_organization_id_idx\\\" ON \\\"workflow_hooks\\\" USING btree (\\\"organization_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_organization_id_idx\\\" ON \\\"workflow_runs\\\" USING btree (\\\"organization_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 INDEX \\\"workflow_subscriptions_organization_id_idx\\\" ON \\\"workflow_subscriptions\\\" USING btree (\\\"organization_id\\\");\",\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 INDEX \\\"workflows_organization_id_idx\\\" ON \\\"workflows\\\" USING btree (\\\"organization_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\": 1784080881350,\n\t\t\"hash\": \"5e217589338a68687d97a99b284d6868b886fcd4b024abaa4d1208e4c8cd0401\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"CREATE TABLE \\\"published_forms\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"workflow_slug\\\" text NOT NULL,\\n\t\\\"token\\\" text NOT NULL,\\n\t\\\"enabled\\\" boolean DEFAULT true NOT NULL,\\n\t\\\"title\\\" text,\\n\t\\\"description\\\" text,\\n\t\\\"field_config\\\" jsonb DEFAULT '{}'::jsonb NOT NULL,\\n\t\\\"created_by_user_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\"\\nALTER TABLE \\\"published_forms\\\" ADD CONSTRAINT \\\"published_forms_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 \\\"published_forms\\\" ADD CONSTRAINT \\\"published_forms_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 \\\"published_forms\\\" ADD CONSTRAINT \\\"published_forms_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\"\\nCREATE UNIQUE INDEX \\\"published_forms_token_unique\\\" ON \\\"published_forms\\\" USING btree (\\\"token\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"published_forms_workflow_unique\\\" ON \\\"published_forms\\\" USING btree (\\\"organization_id\\\",\\\"project_id\\\",\\\"workflow_slug\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"published_forms_project_id_idx\\\" ON \\\"published_forms\\\" USING btree (\\\"project_id\\\");\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1784085067439,\n\t\t\"hash\": \"5f05b43b392f8dccc5bfa61a8db7f8f9f67fe2b8abd7a5e6de7985337de07754\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"-- Claim verification for tenant RLS (signed by platform via DATABASE_RLS_CLAIM_SECRET).\\nCREATE EXTENSION IF NOT EXISTS pgcrypto;\",\n\t\t\t\"\\nCREATE SCHEMA IF NOT EXISTS keystroke;\",\n\t\t\t\"\\nCREATE SCHEMA IF NOT EXISTS keystroke_private;\",\n\t\t\t\"\\nREVOKE ALL ON SCHEMA keystroke_private FROM PUBLIC;\",\n\t\t\t\"\\nCREATE TABLE IF NOT EXISTS keystroke_private.claim_secret (\\n  singleton boolean PRIMARY KEY DEFAULT true CHECK (singleton),\\n  secret text NOT NULL,\\n  updated_at timestamptz NOT NULL DEFAULT now()\\n);\",\n\t\t\t\"\\nREVOKE ALL ON TABLE keystroke_private.claim_secret FROM PUBLIC;\",\n\t\t\t\"\\nCREATE OR REPLACE FUNCTION keystroke.current_organization_id()\\nRETURNS text\\nLANGUAGE plpgsql\\nSTABLE\\nSECURITY DEFINER\\nSET search_path = pg_catalog, keystroke_private, public\\nAS $$\\nDECLARE\\n  claim text;\\n  parts text[];\\n  payload text;\\n  expected_signature text;\\n  provided_signature text;\\n  organization_id text;\\n  expires_at bigint;\\n  signing_secret text;\\nBEGIN\\n  claim := current_setting('keystroke.org_claim', true);\\n\\n  IF claim IS NULL OR claim = '' THEN\\n    RAISE EXCEPTION 'missing organization claim'\\n      USING ERRCODE = '42501';\\n  END IF;\\n\\n  parts := string_to_array(claim, '.');\\n\\n  IF array_length(parts, 1) <> 5 OR parts[1] <> 'v1' THEN\\n    RAISE EXCEPTION 'invalid organization claim'\\n      USING ERRCODE = '42501';\\n  END IF;\\n\\n  organization_id := parts[2];\\n  expires_at := parts[3]::bigint;\\n  payload := concat_ws('.', parts[1], parts[2], parts[3], parts[4]);\\n  provided_signature := parts[5];\\n\\n  IF organization_id IS NULL OR organization_id = '' THEN\\n    RAISE EXCEPTION 'invalid organization claim'\\n      USING ERRCODE = '42501';\\n  END IF;\\n\\n  IF expires_at < extract(epoch FROM statement_timestamp())::bigint THEN\\n    RAISE EXCEPTION 'expired organization claim'\\n      USING ERRCODE = '42501';\\n  END IF;\\n\\n  SELECT secret\\n  INTO signing_secret\\n  FROM keystroke_private.claim_secret\\n  WHERE singleton = true;\\n\\n  IF signing_secret IS NULL THEN\\n    RAISE EXCEPTION 'organization claim secret is not configured'\\n      USING ERRCODE = '42501';\\n  END IF;\\n\\n  expected_signature := encode(hmac(payload, signing_secret, 'sha256'), 'hex');\\n\\n  IF digest(expected_signature, 'sha256') <> digest(provided_signature, 'sha256') THEN\\n    RAISE EXCEPTION 'invalid organization claim signature'\\n      USING ERRCODE = '42501';\\n  END IF;\\n\\n  RETURN organization_id;\\nEND;\\n$$;\",\n\t\t\t\"\\nREVOKE ALL ON FUNCTION keystroke.current_organization_id() FROM PUBLIC;\",\n\t\t\t\"\\nGRANT EXECUTE ON FUNCTION keystroke.current_organization_id() TO PUBLIC;\",\n\t\t\t\"\\nALTER TABLE \\\"agent_events\\\" ENABLE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"agent_sessions\\\" ENABLE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"agents\\\" ENABLE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"credential_assignments\\\" ENABLE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"credential_instances\\\" ENABLE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"gateway_attachments\\\" ENABLE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"gateway_thread_sessions\\\" ENABLE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"jobs\\\" ENABLE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"resource_activity\\\" ENABLE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"skills\\\" ENABLE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"trace_logs\\\" ENABLE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"trace_spans\\\" ENABLE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_attachments\\\" ENABLE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_runs\\\" ENABLE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"triggers\\\" ENABLE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"workflow_events\\\" ENABLE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"workflow_hooks\\\" ENABLE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"workflow_runs\\\" ENABLE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"workflow_subscriptions\\\" ENABLE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"workflows\\\" ENABLE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"agent_events\\\" FORCE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"agent_sessions\\\" FORCE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"agents\\\" FORCE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"credential_assignments\\\" FORCE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"credential_instances\\\" FORCE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"gateway_attachments\\\" FORCE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"gateway_thread_sessions\\\" FORCE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"jobs\\\" FORCE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"resource_activity\\\" FORCE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"skills\\\" FORCE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"trace_logs\\\" FORCE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"trace_spans\\\" FORCE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_attachments\\\" FORCE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_runs\\\" FORCE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"triggers\\\" FORCE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"workflow_events\\\" FORCE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"workflow_hooks\\\" FORCE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"workflow_runs\\\" FORCE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"workflow_subscriptions\\\" FORCE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"workflows\\\" FORCE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nCREATE POLICY \\\"tenant_organization_isolation\\\" ON \\\"agent_events\\\" AS PERMISSIVE FOR ALL TO public USING (\\\"agent_events\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id())) WITH CHECK (\\\"agent_events\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id()));\",\n\t\t\t\"\\nCREATE POLICY \\\"tenant_organization_isolation\\\" ON \\\"agent_sessions\\\" AS PERMISSIVE FOR ALL TO public USING (\\\"agent_sessions\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id())) WITH CHECK (\\\"agent_sessions\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id()));\",\n\t\t\t\"\\nCREATE POLICY \\\"tenant_organization_isolation\\\" ON \\\"agents\\\" AS PERMISSIVE FOR ALL TO public USING (\\\"agents\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id())) WITH CHECK (\\\"agents\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id()));\",\n\t\t\t\"\\nCREATE POLICY \\\"tenant_organization_isolation\\\" ON \\\"credential_assignments\\\" AS PERMISSIVE FOR ALL TO public USING (\\\"credential_assignments\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id())) WITH CHECK (\\\"credential_assignments\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id()));\",\n\t\t\t\"\\nCREATE POLICY \\\"tenant_organization_isolation\\\" ON \\\"credential_instances\\\" AS PERMISSIVE FOR ALL TO public USING (\\\"credential_instances\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id())) WITH CHECK (\\\"credential_instances\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id()));\",\n\t\t\t\"\\nCREATE POLICY \\\"tenant_organization_isolation\\\" ON \\\"gateway_attachments\\\" AS PERMISSIVE FOR ALL TO public USING (\\\"gateway_attachments\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id())) WITH CHECK (\\\"gateway_attachments\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id()));\",\n\t\t\t\"\\nCREATE POLICY \\\"tenant_organization_isolation\\\" ON \\\"gateway_thread_sessions\\\" AS PERMISSIVE FOR ALL TO public USING (\\\"gateway_thread_sessions\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id())) WITH CHECK (\\\"gateway_thread_sessions\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id()));\",\n\t\t\t\"\\nCREATE POLICY \\\"tenant_organization_isolation\\\" ON \\\"jobs\\\" AS PERMISSIVE FOR ALL TO public USING (\\\"jobs\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id())) WITH CHECK (\\\"jobs\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id()));\",\n\t\t\t\"\\nCREATE POLICY \\\"tenant_organization_isolation\\\" ON \\\"resource_activity\\\" AS PERMISSIVE FOR ALL TO public USING (\\\"resource_activity\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id())) WITH CHECK (\\\"resource_activity\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id()));\",\n\t\t\t\"\\nCREATE POLICY \\\"tenant_organization_isolation\\\" ON \\\"skills\\\" AS PERMISSIVE FOR ALL TO public USING (\\\"skills\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id())) WITH CHECK (\\\"skills\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id()));\",\n\t\t\t\"\\nCREATE POLICY \\\"tenant_organization_isolation\\\" ON \\\"trace_logs\\\" AS PERMISSIVE FOR ALL TO public USING (\\\"trace_logs\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id())) WITH CHECK (\\\"trace_logs\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id()));\",\n\t\t\t\"\\nCREATE POLICY \\\"tenant_organization_isolation\\\" ON \\\"trace_spans\\\" AS PERMISSIVE FOR ALL TO public USING (\\\"trace_spans\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id())) WITH CHECK (\\\"trace_spans\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id()));\",\n\t\t\t\"\\nCREATE POLICY \\\"tenant_organization_isolation\\\" ON \\\"trigger_attachments\\\" AS PERMISSIVE FOR ALL TO public USING (\\\"trigger_attachments\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id())) WITH CHECK (\\\"trigger_attachments\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id()));\",\n\t\t\t\"\\nCREATE POLICY \\\"tenant_organization_isolation\\\" ON \\\"trigger_runs\\\" AS PERMISSIVE FOR ALL TO public USING (\\\"trigger_runs\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id())) WITH CHECK (\\\"trigger_runs\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id()));\",\n\t\t\t\"\\nCREATE POLICY \\\"tenant_organization_isolation\\\" ON \\\"triggers\\\" AS PERMISSIVE FOR ALL TO public USING (\\\"triggers\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id())) WITH CHECK (\\\"triggers\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id()));\",\n\t\t\t\"\\nCREATE POLICY \\\"tenant_organization_isolation\\\" ON \\\"workflow_events\\\" AS PERMISSIVE FOR ALL TO public USING (\\\"workflow_events\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id())) WITH CHECK (\\\"workflow_events\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id()));\",\n\t\t\t\"\\nCREATE POLICY \\\"tenant_organization_isolation\\\" ON \\\"workflow_hooks\\\" AS PERMISSIVE FOR ALL TO public USING (\\\"workflow_hooks\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id())) WITH CHECK (\\\"workflow_hooks\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id()));\",\n\t\t\t\"\\nCREATE POLICY \\\"tenant_organization_isolation\\\" ON \\\"workflow_runs\\\" AS PERMISSIVE FOR ALL TO public USING (\\\"workflow_runs\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id())) WITH CHECK (\\\"workflow_runs\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id()));\",\n\t\t\t\"\\nCREATE POLICY \\\"tenant_organization_isolation\\\" ON \\\"workflow_subscriptions\\\" AS PERMISSIVE FOR ALL TO public USING (\\\"workflow_subscriptions\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id())) WITH CHECK (\\\"workflow_subscriptions\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id()));\",\n\t\t\t\"\\nCREATE POLICY \\\"tenant_organization_isolation\\\" ON \\\"workflows\\\" AS PERMISSIVE FOR ALL TO public USING (\\\"workflows\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id())) WITH CHECK (\\\"workflows\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id()));\\n\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1784085067440,\n\t\t\"hash\": \"7ab2ff6278040d569d4a3a5153863e395be71cc130afc9a5c74273921ed92a82\"\n\t},\n\t{\n\t\t\"sql\": [\"CREATE TABLE \\\"templates\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"kind\\\" text NOT NULL,\\n\t\\\"title\\\" text NOT NULL,\\n\t\\\"description\\\" text NOT NULL,\\n\t\\\"tags\\\" jsonb DEFAULT '[]'::jsonb NOT NULL,\\n\t\\\"required_apps\\\" jsonb DEFAULT '[]'::jsonb NOT NULL,\\n\t\\\"files\\\" jsonb DEFAULT '{}'::jsonb NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\", \"\\nCREATE UNIQUE INDEX \\\"templates_slug_idx\\\" ON \\\"templates\\\" USING btree (\\\"slug\\\");\\n\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1784156597496,\n\t\t\"hash\": \"3a66099122296864304a9f3212cd03d1fbcb3b3994abfbec1f4d97841d652e28\"\n\t},\n\t{\n\t\t\"sql\": [\"CREATE TABLE \\\"oauth_pending_states\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"payload_ciphertext\\\" text NOT NULL,\\n\t\\\"expires_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL\\n);\\n\", \"\\nCREATE INDEX \\\"oauth_pending_states_expires_at_idx\\\" ON \\\"oauth_pending_states\\\" USING btree (\\\"expires_at\\\");\\n\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1784270606695,\n\t\t\"hash\": \"e49def2756e98201eaf4cf8d9cfdd194fc0ff097249647a5d182272ca7624bc0\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"CREATE TYPE \\\"public\\\".\\\"project_git_provider\\\" AS ENUM('github', 'code_storage');\",\n\t\t\t\"\\nCREATE TYPE \\\"public\\\".\\\"project_repository_content_status\\\" AS ENUM('empty', 'awaiting_source', 'synced', 'failed');\",\n\t\t\t\"\\nCREATE TYPE \\\"public\\\".\\\"project_repository_desired_state\\\" AS ENUM('active', 'deleted');\",\n\t\t\t\"\\nCREATE TYPE \\\"public\\\".\\\"project_repository_lifecycle_status\\\" AS ENUM('provisioning', 'ready', 'failed', 'deleting', 'deleted');\",\n\t\t\t\"\\nCREATE TABLE \\\"platform_agent_events\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text 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 \\\"platform_agent_project_snapshots\\\" (\\n\t\\\"project_id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"modal_image_id\\\" text,\\n\t\\\"deps_fingerprint\\\" text,\\n\t\\\"build_status\\\" text NOT NULL,\\n\t\\\"build_started_at\\\" timestamp with time zone,\\n\t\\\"last_error\\\" text,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"platform_agent_sessions\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"user_id\\\" text NOT NULL,\\n\t\\\"status\\\" text NOT NULL,\\n\t\\\"title\\\" text,\\n\t\\\"model\\\" text,\\n\t\\\"active_run_id\\\" text,\\n\t\\\"last_draft_commit_sha\\\" text,\\n\t\\\"sandbox_id\\\" text,\\n\t\\\"sandbox_last_used_at\\\" timestamp with time zone,\\n\t\\\"error\\\" 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 \\\"project_repositories\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"provider\\\" \\\"project_git_provider\\\" NOT NULL,\\n\t\\\"external_repository_id\\\" text,\\n\t\\\"owner\\\" text,\\n\t\\\"name\\\" text,\\n\t\\\"default_branch\\\" text DEFAULT 'main' NOT NULL,\\n\t\\\"lifecycle_status\\\" \\\"project_repository_lifecycle_status\\\" DEFAULT 'provisioning' NOT NULL,\\n\t\\\"content_status\\\" \\\"project_repository_content_status\\\" DEFAULT 'empty' NOT NULL,\\n\t\\\"desired_state\\\" \\\"project_repository_desired_state\\\" DEFAULT 'active' NOT NULL,\\n\t\\\"last_error_code\\\" text,\\n\t\\\"last_error\\\" text,\\n\t\\\"provisioned_at\\\" timestamp with time zone,\\n\t\\\"deleted_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);\\n\",\n\t\t\t\"\\nALTER TABLE \\\"project_artifacts\\\" ADD COLUMN \\\"source_repository_id\\\" text;\",\n\t\t\t\"\\nALTER TABLE \\\"project_artifacts\\\" ADD COLUMN \\\"source_commit_sha\\\" text;\",\n\t\t\t\"\\nALTER TABLE \\\"project_artifacts\\\" ADD COLUMN \\\"base_main_sha\\\" text;\",\n\t\t\t\"\\nALTER TABLE \\\"project_artifacts\\\" ADD COLUMN \\\"base_draft_sha\\\" text;\",\n\t\t\t\"\\nALTER TABLE \\\"project_artifacts\\\" ADD COLUMN \\\"deploy_mode\\\" text;\",\n\t\t\t\"\\nALTER TABLE \\\"project_artifacts\\\" ADD COLUMN \\\"candidate_ops\\\" jsonb;\",\n\t\t\t\"\\nALTER TABLE \\\"project_artifacts\\\" ADD COLUMN \\\"candidate_ref\\\" text;\",\n\t\t\t\"\\nALTER TABLE \\\"project_artifacts\\\" ADD COLUMN \\\"candidate_ephemeral\\\" boolean;\",\n\t\t\t\"\\nALTER TABLE \\\"project_artifacts\\\" ADD COLUMN \\\"protocol_state\\\" text;\",\n\t\t\t\"\\nALTER TABLE \\\"projects\\\" ADD COLUMN \\\"deploy_lease_artifact_id\\\" text;\",\n\t\t\t\"\\nALTER TABLE \\\"projects\\\" ADD COLUMN \\\"deploy_lease_expires_at\\\" timestamp with time zone;\",\n\t\t\t\"\\nALTER TABLE \\\"platform_agent_events\\\" ADD CONSTRAINT \\\"platform_agent_events_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 \\\"platform_agent_events\\\" ADD CONSTRAINT \\\"platform_agent_events_session_id_platform_agent_sessions_id_fk\\\" FOREIGN KEY (\\\"session_id\\\") REFERENCES \\\"public\\\".\\\"platform_agent_sessions\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"platform_agent_project_snapshots\\\" ADD CONSTRAINT \\\"platform_agent_project_snapshots_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 \\\"platform_agent_sessions\\\" ADD CONSTRAINT \\\"platform_agent_sessions_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 \\\"platform_agent_sessions\\\" ADD CONSTRAINT \\\"platform_agent_sessions_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 \\\"platform_agent_sessions\\\" ADD CONSTRAINT \\\"platform_agent_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 \\\"project_repositories\\\" ADD CONSTRAINT \\\"project_repositories_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 \\\"project_repositories\\\" ADD CONSTRAINT \\\"project_repositories_project_id_projects_id_fk\\\" FOREIGN KEY (\\\"project_id\\\") REFERENCES \\\"public\\\".\\\"projects\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nCREATE INDEX \\\"platform_agent_events_organization_id_idx\\\" ON \\\"platform_agent_events\\\" USING btree (\\\"organization_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"platform_agent_events_session_event_seq_idx\\\" ON \\\"platform_agent_events\\\" USING btree (\\\"session_id\\\",\\\"event_type\\\",\\\"seq\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"platform_agent_sessions_owner_updated_idx\\\" ON \\\"platform_agent_sessions\\\" USING btree (\\\"organization_id\\\",\\\"project_id\\\",\\\"user_id\\\",\\\"updated_at\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"platform_agent_sessions_org_user_updated_idx\\\" ON \\\"platform_agent_sessions\\\" USING btree (\\\"organization_id\\\",\\\"user_id\\\",\\\"updated_at\\\",\\\"id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"platform_agent_sessions_project_id_idx\\\" ON \\\"platform_agent_sessions\\\" USING btree (\\\"project_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"platform_agent_sessions_sandbox_last_used_at_idx\\\" ON \\\"platform_agent_sessions\\\" USING btree (\\\"sandbox_last_used_at\\\") WHERE \\\"platform_agent_sessions\\\".\\\"sandbox_id\\\" IS NOT NULL;\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"project_repositories_project_id_unique\\\" ON \\\"project_repositories\\\" USING btree (\\\"project_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"project_repositories_organization_id_idx\\\" ON \\\"project_repositories\\\" USING btree (\\\"organization_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"project_repositories_lifecycle_status_idx\\\" ON \\\"project_repositories\\\" USING btree (\\\"lifecycle_status\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"project_repositories_provider_external_id_unique\\\" ON \\\"project_repositories\\\" USING btree (\\\"provider\\\",\\\"external_repository_id\\\") WHERE \\\"project_repositories\\\".\\\"external_repository_id\\\" IS NOT NULL;\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1784970607235,\n\t\t\"hash\": \"efc4f000b34a5c69343047cebd1574217e823c83c5c10bb8262de23690383eb7\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"ALTER TABLE \\\"platform_agent_project_snapshots\\\" ADD COLUMN \\\"head_sha\\\" text;\",\n\t\t\t\"\\nALTER TABLE \\\"platform_agent_project_snapshots\\\" ADD COLUMN \\\"package_manager\\\" text;\",\n\t\t\t\"\\nALTER TABLE \\\"platform_agent_project_snapshots\\\" ADD COLUMN \\\"sync_ready\\\" boolean DEFAULT false NOT NULL;\",\n\t\t\t\"\\nALTER TABLE \\\"platform_agent_project_snapshots\\\" ADD COLUMN \\\"capture_generation\\\" integer DEFAULT 0 NOT NULL;\",\n\t\t\t\"\\nALTER TABLE \\\"platform_agent_sessions\\\" ADD COLUMN \\\"package_manager\\\" text;\",\n\t\t\t\"\\nALTER TABLE \\\"project_repositories\\\" ADD COLUMN \\\"platform_agent_scaffolded_at\\\" timestamp with time zone;\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1785195531248,\n\t\t\"hash\": \"9bd95b3bcc8884b0fb2d1975dabd306291eeca6f696ac3de7ddc97e963de6560\"\n\t},\n\t{\n\t\t\"sql\": [\"ALTER TABLE \\\"platform_agent_project_snapshots\\\" ADD COLUMN \\\"cli_version\\\" text;\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1785267772246,\n\t\t\"hash\": \"c908899490be6a98374253623a5d7edd116d4ec949808dc59a9fef976ccd41b0\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"ALTER TABLE \\\"platform_agent_project_snapshots\\\" ADD COLUMN \\\"recovery_state\\\" text;\",\n\t\t\t\"\\nALTER TABLE \\\"platform_agent_project_snapshots\\\" ADD COLUMN \\\"recovery_claimant_run_id\\\" text;\",\n\t\t\t\"\\nALTER TABLE \\\"platform_agent_project_snapshots\\\" ADD COLUMN \\\"recovery_claimed_at\\\" timestamp with time zone;\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1785337307233,\n\t\t\"hash\": \"a39998e2bdc75645fb2de38442f2a900fabcd38a18d5702205d7af2f0509658e\"\n\t},\n\t{\n\t\t\"sql\": [\"ALTER TABLE \\\"organization_billing\\\" ADD COLUMN \\\"credit_warning_sent_at\\\" timestamp with time zone;\", \"\\nALTER TABLE \\\"organization_billing\\\" ADD COLUMN \\\"credit_exhausted_sent_at\\\" timestamp with time zone;\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1785444766708,\n\t\t\"hash\": \"2e0c509be4a404303c263e9dddab22a91c7fa7aaab6a75d73e2e95e0cabc442b\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"CREATE TABLE \\\"project_agent_session_sandboxes\\\" (\\n\t\\\"session_id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"agent_id\\\" text NOT NULL,\\n\t\\\"sandbox_id\\\" text,\\n\t\\\"sandbox_last_used_at\\\" timestamp with time zone,\\n\t\\\"modal_image_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\"\\nALTER TABLE \\\"project_agent_session_sandboxes\\\" ADD CONSTRAINT \\\"project_agent_session_sandboxes_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 \\\"project_agent_session_sandboxes\\\" ADD CONSTRAINT \\\"project_agent_session_sandboxes_project_id_projects_id_fk\\\" FOREIGN KEY (\\\"project_id\\\") REFERENCES \\\"public\\\".\\\"projects\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nCREATE INDEX \\\"project_agent_session_sandboxes_project_idx\\\" ON \\\"project_agent_session_sandboxes\\\" USING btree (\\\"project_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"project_agent_session_sandboxes_sandbox_last_used_idx\\\" ON \\\"project_agent_session_sandboxes\\\" USING btree (\\\"sandbox_last_used_at\\\") WHERE \\\"project_agent_session_sandboxes\\\".\\\"sandbox_id\\\" IS NOT NULL;\",\n\t\t\t\"\\nCREATE INDEX \\\"project_agent_session_sandboxes_image_last_used_idx\\\" ON \\\"project_agent_session_sandboxes\\\" USING btree (\\\"sandbox_last_used_at\\\") WHERE \\\"project_agent_session_sandboxes\\\".\\\"modal_image_id\\\" IS NOT NULL;\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1785531302752,\n\t\t\"hash\": \"d2e685147bcb99386a63e77483443e8e4dd6bc3a3746d81b77ce10ffde173eca\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"CREATE TABLE \\\"project_agent_env_images\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text NOT NULL,\\n\t\\\"setup_hash\\\" text NOT NULL,\\n\t\\\"base_image_name\\\" text NOT NULL,\\n\t\\\"setup_commands\\\" text NOT NULL,\\n\t\\\"modal_image_id\\\" text,\\n\t\\\"build_status\\\" text NOT NULL,\\n\t\\\"build_started_at\\\" timestamp with time zone,\\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);\\n\",\n\t\t\t\"\\nALTER TABLE \\\"project_agent_env_images\\\" ADD CONSTRAINT \\\"project_agent_env_images_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 \\\"project_agent_env_images_org_hash_idx\\\" ON \\\"project_agent_env_images\\\" USING btree (\\\"organization_id\\\",\\\"setup_hash\\\");\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1785536253085,\n\t\t\"hash\": \"686741fa6be7f7d3ab6cfb3409e3471c73476dfaf2cb5b9af43698e740b8fb19\"\n\t},\n\t{\n\t\t\"sql\": [\"ALTER TABLE \\\"agents\\\" ADD COLUMN \\\"sandbox_mode\\\" text;\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1785799480457,\n\t\t\"hash\": \"9310fd2aa0857df9ad72f96bbebcd9290a056d9da8cf76bc8db13460c30b4793\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"CREATE TABLE \\\"brain_document_versions\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text NOT NULL,\\n\t\\\"brain_id\\\" text NOT NULL,\\n\t\\\"document_row_id\\\" text NOT NULL,\\n\t\\\"revision\\\" integer NOT NULL,\\n\t\\\"deletion_epoch\\\" integer DEFAULT 0 NOT NULL,\\n\t\\\"client_idempotency_id\\\" text NOT NULL,\\n\t\\\"title\\\" text NOT NULL,\\n\t\\\"metadata\\\" jsonb,\\n\t\\\"user_revision\\\" text,\\n\t\\\"indexing_fingerprint\\\" text,\\n\t\\\"source\\\" text NOT NULL,\\n\t\\\"input_kind\\\" text NOT NULL,\\n\t\\\"status\\\" text NOT NULL,\\n\t\\\"failure_code\\\" text,\\n\t\\\"failure_message\\\" text,\\n\t\\\"declared_sha256\\\" text,\\n\t\\\"actual_sha256\\\" text,\\n\t\\\"content_type\\\" text,\\n\t\\\"detected_format\\\" text,\\n\t\\\"raw_object_key\\\" text,\\n\t\\\"raw_byte_count\\\" integer,\\n\t\\\"canonical_object_key\\\" text,\\n\t\\\"canonical_byte_count\\\" integer,\\n\t\\\"extractor_version\\\" text,\\n\t\\\"chunker_version\\\" text,\\n\t\\\"index_version\\\" text,\\n\t\\\"index_generation\\\" integer,\\n\t\\\"chunk_count\\\" integer,\\n\t\\\"embedding_context\\\" text,\\n\t\\\"chunking_override\\\" jsonb,\\n\t\\\"lease_token\\\" text,\\n\t\\\"lease_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);\\n\",\n\t\t\t\"\\nALTER TABLE \\\"brain_document_versions\\\" ENABLE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nCREATE TABLE \\\"brain_document_write_events\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text NOT NULL,\\n\t\\\"brain_id\\\" text NOT NULL,\\n\t\\\"document_row_id\\\" text,\\n\t\\\"document_id\\\" text NOT NULL,\\n\t\\\"client_idempotency_id\\\" text NOT NULL,\\n\t\\\"request_fingerprint\\\" text NOT NULL,\\n\t\\\"provisioner_kind\\\" text NOT NULL,\\n\t\\\"provisioner_project_id\\\" text,\\n\t\\\"provisioner_workflow_run_id\\\" text,\\n\t\\\"provisioner_workflow_slug\\\" text,\\n\t\\\"provisioner_correlation_id\\\" text,\\n\t\\\"provisioner_manual_user_id\\\" text,\\n\t\\\"version_id\\\" text,\\n\t\\\"input_kind\\\" text NOT NULL,\\n\t\\\"outcome\\\" text,\\n\t\\\"metadata_updated\\\" boolean DEFAULT false NOT NULL,\\n\t\\\"failure_code\\\" text,\\n\t\\\"failure_message\\\" text,\\n\t\\\"submitted_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"content_received_at\\\" timestamp with time zone,\\n\t\\\"completed_at\\\" timestamp with time zone,\\n\tCONSTRAINT \\\"brain_document_write_events_provisioner_check\\\" CHECK ((\\n        (\\\"brain_document_write_events\\\".\\\"provisioner_kind\\\" = 'workflow'\\n          AND \\\"brain_document_write_events\\\".\\\"provisioner_project_id\\\" IS NOT NULL\\n          AND \\\"brain_document_write_events\\\".\\\"provisioner_workflow_run_id\\\" IS NOT NULL\\n          AND \\\"brain_document_write_events\\\".\\\"provisioner_workflow_slug\\\" IS NOT NULL\\n          AND \\\"brain_document_write_events\\\".\\\"provisioner_correlation_id\\\" IS NOT NULL\\n          AND \\\"brain_document_write_events\\\".\\\"provisioner_manual_user_id\\\" IS NULL)\\n        OR\\n        (\\\"brain_document_write_events\\\".\\\"provisioner_kind\\\" = 'manual'\\n          AND \\\"brain_document_write_events\\\".\\\"provisioner_project_id\\\" IS NULL\\n          AND \\\"brain_document_write_events\\\".\\\"provisioner_workflow_run_id\\\" IS NULL\\n          AND \\\"brain_document_write_events\\\".\\\"provisioner_workflow_slug\\\" IS NULL\\n          AND \\\"brain_document_write_events\\\".\\\"provisioner_correlation_id\\\" IS NULL\\n          AND \\\"brain_document_write_events\\\".\\\"provisioner_manual_user_id\\\" IS NOT NULL)\\n      )),\\n\tCONSTRAINT \\\"brain_document_write_events_input_kind_check\\\" CHECK (\\\"brain_document_write_events\\\".\\\"input_kind\\\" IN ('content', 'blocks', 'file')),\\n\tCONSTRAINT \\\"brain_document_write_events_outcome_check\\\" CHECK ((\\n        (\\\"brain_document_write_events\\\".\\\"outcome\\\" IS NULL\\n          AND \\\"brain_document_write_events\\\".\\\"completed_at\\\" IS NULL\\n          AND \\\"brain_document_write_events\\\".\\\"failure_code\\\" IS NULL\\n          AND \\\"brain_document_write_events\\\".\\\"failure_message\\\" IS NULL)\\n        OR\\n        (\\\"brain_document_write_events\\\".\\\"outcome\\\" IN ('ready', 'unchanged')\\n          AND \\\"brain_document_write_events\\\".\\\"completed_at\\\" IS NOT NULL\\n          AND \\\"brain_document_write_events\\\".\\\"failure_code\\\" IS NULL\\n          AND \\\"brain_document_write_events\\\".\\\"failure_message\\\" IS NULL)\\n        OR\\n        (\\\"brain_document_write_events\\\".\\\"outcome\\\" = 'failed' AND \\\"brain_document_write_events\\\".\\\"completed_at\\\" IS NOT NULL)\\n      ))\\n);\\n\",\n\t\t\t\"\\nALTER TABLE \\\"brain_document_write_events\\\" ENABLE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nCREATE TABLE \\\"brain_documents\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text NOT NULL,\\n\t\\\"brain_id\\\" text NOT NULL,\\n\t\\\"document_id\\\" text NOT NULL,\\n\t\\\"title\\\" text NOT NULL,\\n\t\\\"source\\\" text NOT NULL,\\n\t\\\"metadata\\\" jsonb,\\n\t\\\"user_revision\\\" text,\\n\t\\\"latest_revision\\\" integer DEFAULT 0 NOT NULL,\\n\t\\\"metadata_revision\\\" integer DEFAULT 0 NOT NULL,\\n\t\\\"deletion_epoch\\\" integer DEFAULT 0 NOT NULL,\\n\t\\\"current_version_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\"\\nALTER TABLE \\\"brain_documents\\\" ENABLE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nCREATE TABLE \\\"brain_filters\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text NOT NULL,\\n\t\\\"brain_id\\\" text NOT NULL,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"name\\\" text NOT NULL,\\n\t\\\"description\\\" text NOT NULL,\\n\t\\\"filter\\\" jsonb NOT NULL,\\n\t\\\"created_by_user_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\"\\nALTER TABLE \\\"brain_filters\\\" ENABLE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nCREATE TABLE \\\"brain_grants\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text NOT NULL,\\n\t\\\"brain_id\\\" text NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"access\\\" text NOT NULL,\\n\t\\\"created_by_user_id\\\" text,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\tCONSTRAINT \\\"brain_grants_access_check\\\" CHECK (\\\"brain_grants\\\".\\\"access\\\" IN ('read', 'write'))\\n);\\n\",\n\t\t\t\"\\nALTER TABLE \\\"brain_grants\\\" ENABLE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nCREATE TABLE \\\"brain_members\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text NOT NULL,\\n\t\\\"brain_id\\\" text NOT NULL,\\n\t\\\"user_id\\\" text NOT NULL,\\n\t\\\"role\\\" text NOT NULL,\\n\t\\\"created_by_user_id\\\" text,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\tCONSTRAINT \\\"brain_members_role_check\\\" CHECK (\\\"brain_members\\\".\\\"role\\\" IN ('owner', 'admin'))\\n);\\n\",\n\t\t\t\"\\nALTER TABLE \\\"brain_members\\\" ENABLE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nCREATE TABLE \\\"brains\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text NOT NULL,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"name\\\" text NOT NULL,\\n\t\\\"description\\\" text NOT NULL,\\n\t\\\"index_config\\\" jsonb NOT NULL,\\n\t\\\"active_generation\\\" integer DEFAULT 1 NOT NULL,\\n\t\\\"pending_generation\\\" integer,\\n\t\\\"pending_index_config\\\" jsonb,\\n\t\\\"active_vector_dimensions\\\" integer,\\n\t\\\"pending_vector_dimensions\\\" integer,\\n\t\\\"mutation_epoch\\\" integer DEFAULT 0 NOT NULL,\\n\t\\\"status\\\" text NOT NULL,\\n\t\\\"created_by_user_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\"\\nALTER TABLE \\\"brains\\\" ENABLE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"agents\\\" ADD COLUMN \\\"brain_slugs\\\" jsonb;\",\n\t\t\t\"\\nALTER TABLE \\\"brain_document_versions\\\" ADD CONSTRAINT \\\"brain_document_versions_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"brain_document_versions\\\" ADD CONSTRAINT \\\"brain_document_versions_brain_id_brains_id_fk\\\" FOREIGN KEY (\\\"brain_id\\\") REFERENCES \\\"public\\\".\\\"brains\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"brain_document_versions\\\" ADD CONSTRAINT \\\"brain_document_versions_document_row_id_brain_documents_id_fk\\\" FOREIGN KEY (\\\"document_row_id\\\") REFERENCES \\\"public\\\".\\\"brain_documents\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"brain_document_write_events\\\" ADD CONSTRAINT \\\"brain_document_write_events_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"brain_document_write_events\\\" ADD CONSTRAINT \\\"brain_document_write_events_brain_id_brains_id_fk\\\" FOREIGN KEY (\\\"brain_id\\\") REFERENCES \\\"public\\\".\\\"brains\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"brain_document_write_events\\\" ADD CONSTRAINT \\\"brain_document_write_events_document_row_id_brain_documents_id_fk\\\" FOREIGN KEY (\\\"document_row_id\\\") REFERENCES \\\"public\\\".\\\"brain_documents\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"brain_documents\\\" ADD CONSTRAINT \\\"brain_documents_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"brain_documents\\\" ADD CONSTRAINT \\\"brain_documents_brain_id_brains_id_fk\\\" FOREIGN KEY (\\\"brain_id\\\") REFERENCES \\\"public\\\".\\\"brains\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"brain_documents\\\" ADD CONSTRAINT \\\"brain_documents_current_version_id_brain_document_versions_id_fk\\\" FOREIGN KEY (\\\"current_version_id\\\") REFERENCES \\\"public\\\".\\\"brain_document_versions\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"brain_filters\\\" ADD CONSTRAINT \\\"brain_filters_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"brain_filters\\\" ADD CONSTRAINT \\\"brain_filters_brain_id_brains_id_fk\\\" FOREIGN KEY (\\\"brain_id\\\") REFERENCES \\\"public\\\".\\\"brains\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"brain_grants\\\" ADD CONSTRAINT \\\"brain_grants_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"brain_grants\\\" ADD CONSTRAINT \\\"brain_grants_brain_id_brains_id_fk\\\" FOREIGN KEY (\\\"brain_id\\\") REFERENCES \\\"public\\\".\\\"brains\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"brain_members\\\" ADD CONSTRAINT \\\"brain_members_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"brain_members\\\" ADD CONSTRAINT \\\"brain_members_brain_id_brains_id_fk\\\" FOREIGN KEY (\\\"brain_id\\\") REFERENCES \\\"public\\\".\\\"brains\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"brains\\\" ADD CONSTRAINT \\\"brains_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nCREATE INDEX \\\"brain_document_versions_organization_id_idx\\\" ON \\\"brain_document_versions\\\" USING btree (\\\"organization_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"brain_document_versions_brain_id_idx\\\" ON \\\"brain_document_versions\\\" USING btree (\\\"brain_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"brain_document_versions_document_row_id_idx\\\" ON \\\"brain_document_versions\\\" USING btree (\\\"document_row_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"brain_document_versions_sha256_idx\\\" ON \\\"brain_document_versions\\\" USING btree (\\\"organization_id\\\",\\\"actual_sha256\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"brain_document_versions_document_revision_idx\\\" ON \\\"brain_document_versions\\\" USING btree (\\\"document_row_id\\\",\\\"revision\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"brain_document_versions_document_idempotency_idx\\\" ON \\\"brain_document_versions\\\" USING btree (\\\"document_row_id\\\",\\\"client_idempotency_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"brain_document_write_events_organization_id_idx\\\" ON \\\"brain_document_write_events\\\" USING btree (\\\"organization_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"brain_document_write_events_brain_id_idx\\\" ON \\\"brain_document_write_events\\\" USING btree (\\\"brain_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"brain_document_write_events_history_idx\\\" ON \\\"brain_document_write_events\\\" USING btree (\\\"brain_id\\\",\\\"document_row_id\\\",\\\"submitted_at\\\",\\\"id\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"brain_document_write_events_brain_idempotency_idx\\\" ON \\\"brain_document_write_events\\\" USING btree (\\\"brain_id\\\",\\\"client_idempotency_id\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"brain_document_write_events_version_id_idx\\\" ON \\\"brain_document_write_events\\\" USING btree (\\\"version_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"brain_documents_organization_id_idx\\\" ON \\\"brain_documents\\\" USING btree (\\\"organization_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"brain_documents_brain_id_idx\\\" ON \\\"brain_documents\\\" USING btree (\\\"brain_id\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"brain_documents_brain_document_id_idx\\\" ON \\\"brain_documents\\\" USING btree (\\\"brain_id\\\",\\\"document_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"brain_filters_organization_id_idx\\\" ON \\\"brain_filters\\\" USING btree (\\\"organization_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"brain_filters_brain_id_idx\\\" ON \\\"brain_filters\\\" USING btree (\\\"brain_id\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"brain_filters_brain_slug_idx\\\" ON \\\"brain_filters\\\" USING btree (\\\"brain_id\\\",\\\"slug\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"brain_grants_organization_id_idx\\\" ON \\\"brain_grants\\\" USING btree (\\\"organization_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"brain_grants_brain_id_idx\\\" ON \\\"brain_grants\\\" USING btree (\\\"brain_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"brain_grants_project_id_idx\\\" ON \\\"brain_grants\\\" USING btree (\\\"project_id\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"brain_grants_brain_project_idx\\\" ON \\\"brain_grants\\\" USING btree (\\\"brain_id\\\",\\\"project_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"brain_members_organization_id_idx\\\" ON \\\"brain_members\\\" USING btree (\\\"organization_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"brain_members_brain_id_idx\\\" ON \\\"brain_members\\\" USING btree (\\\"brain_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"brain_members_user_id_idx\\\" ON \\\"brain_members\\\" USING btree (\\\"user_id\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"brain_members_brain_user_idx\\\" ON \\\"brain_members\\\" USING btree (\\\"brain_id\\\",\\\"user_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"brains_organization_id_idx\\\" ON \\\"brains\\\" USING btree (\\\"organization_id\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"brains_organization_id_slug_idx\\\" ON \\\"brains\\\" USING btree (\\\"organization_id\\\",\\\"slug\\\") WHERE \\\"brains\\\".\\\"deleted_at\\\" IS NULL;\",\n\t\t\t\"\\nCREATE POLICY \\\"tenant_organization_isolation\\\" ON \\\"brain_document_versions\\\" AS PERMISSIVE FOR ALL TO public USING (\\\"brain_document_versions\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id())) WITH CHECK (\\\"brain_document_versions\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id()));\",\n\t\t\t\"\\nCREATE POLICY \\\"tenant_organization_isolation\\\" ON \\\"brain_document_write_events\\\" AS PERMISSIVE FOR ALL TO public USING (\\\"brain_document_write_events\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id())) WITH CHECK (\\\"brain_document_write_events\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id()));\",\n\t\t\t\"\\nCREATE POLICY \\\"tenant_organization_isolation\\\" ON \\\"brain_documents\\\" AS PERMISSIVE FOR ALL TO public USING (\\\"brain_documents\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id())) WITH CHECK (\\\"brain_documents\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id()));\",\n\t\t\t\"\\nCREATE POLICY \\\"tenant_organization_isolation\\\" ON \\\"brain_filters\\\" AS PERMISSIVE FOR ALL TO public USING (\\\"brain_filters\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id())) WITH CHECK (\\\"brain_filters\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id()));\",\n\t\t\t\"\\nCREATE POLICY \\\"tenant_organization_isolation\\\" ON \\\"brain_grants\\\" AS PERMISSIVE FOR ALL TO public USING (\\\"brain_grants\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id())) WITH CHECK (\\\"brain_grants\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id()));\",\n\t\t\t\"\\nCREATE POLICY \\\"tenant_organization_isolation\\\" ON \\\"brain_members\\\" AS PERMISSIVE FOR ALL TO public USING (\\\"brain_members\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id())) WITH CHECK (\\\"brain_members\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id()));\",\n\t\t\t\"\\nCREATE POLICY \\\"tenant_organization_isolation\\\" ON \\\"brains\\\" AS PERMISSIVE FOR ALL TO public USING (\\\"brains\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id())) WITH CHECK (\\\"brains\\\".\\\"organization_id\\\" = (SELECT keystroke.current_organization_id()));\",\n\t\t\t\"\\nALTER TABLE \\\"brain_document_versions\\\" FORCE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"brain_document_write_events\\\" FORCE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"brain_documents\\\" FORCE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"brain_filters\\\" FORCE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"brain_grants\\\" FORCE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"brain_members\\\" FORCE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nALTER TABLE \\\"brains\\\" FORCE ROW LEVEL SECURITY;\\n\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1786059463342,\n\t\t\"hash\": \"e7c7257aacef98e4d076a9242cebee28fbe1f76ce8b858b2213df121f706680a\"\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 migrationsSchema = resolveMigrationsSchema(handle.searchPath);\n\tconst loaded = loadMigrations(migrationsFolder, platformPgMigrations);\n\tconst migrations = handle.searchPath ? adaptPgMigrationsForSearchPath(loaded) : loaded;\n\tif (handle.searchPath) {\n\t\tawait migratePgTenantSchema(handle.db, { migrationsSchema }, migrations);\n\t\treturn;\n\t}\n\tawait migratePgDatabase(handle.db, {\n\t\tmigrationsFolder,\n\t\tmigrationsSchema\n\t}, migrations);\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/runtime/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/runtime/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/runtime/config/postgres-url.ts\n/** Default `node-pg` pool size when `PG_POOL_MAX` / `options.max` are unset. */\nconst DEFAULT_PG_POOL_MAX = 10;\n/**\n* Resolve Postgres client pool size from env.\n* Invalid / non-positive values fall back to {@link DEFAULT_PG_POOL_MAX}.\n*/\nfunction resolvePgPoolMax(env = process.env) {\n\tconst raw = env.PG_POOL_MAX?.trim();\n\tif (!raw) return 10;\n\tconst parsed = Number(raw);\n\tif (!Number.isFinite(parsed) || parsed < 1) return 10;\n\treturn Math.floor(parsed);\n}\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/connection/pg/pg-ident.ts\nconst PG_IDENT = /^[a-zA-Z_][a-zA-Z0-9_]*$/;\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/names.ts\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}\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}\n/** Deterministic Redis ACL username for an org (mirrors orgDbRoleName without _user suffix). */\nfunction orgRedisUsername(organizationId) {\n\treturn `org_${sanitizeIdForPgIdent(organizationId)}`;\n}\n/** BullMQ queue segment — colons forbidden in queue names. */\nfunction orgRedisQueueSegment(organizationId) {\n\treturn organizationId.replaceAll(\":\", \"-\");\n}\n//#endregion\n//#region src/project-database/provision.ts\n/** Placeholder columns for legacy NOT NULL org DB fields (postgres public+RLS). */\nconst UNUSED_PG_ORG_DB = {\n\tdbSchema: \"public\",\n\tdbUser: \"unused\",\n\tdbPasswordCiphertext: \"unused\"\n};\nasync function provisionOrgDatabaseSqlite(organizationId) {\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}\n/**\n* Postgres orgs share the platform DB (`public` + RLS). No per-org role or schema.\n*/\nasync function provisionOrgDatabasePostgres() {\n\treturn { ...UNUSED_PG_ORG_DB };\n}\nasync function provisionOrgDatabase(organizationId) {\n\tif (inferDialect(resolvePlatformDatabaseUrl()) === \"sqlite\") return provisionOrgDatabaseSqlite(organizationId);\n\treturn provisionOrgDatabasePostgres();\n}\nfunction isLegacyOrgSchema(dbSchema, dbUser) {\n\treturn dbSchema.startsWith(\"org_\") && dbUser.startsWith(\"org_\");\n}\nasync function deprovisionOrgDatabase(input) {\n\tif (inferDialect(resolvePlatformDatabaseUrl()) === \"sqlite\") {\n\t\ttry {\n\t\t\tunlinkSync(input.dbSchema);\n\t\t} catch {}\n\t\treturn;\n\t}\n\tif (!isLegacyOrgSchema(input.dbSchema, input.dbUser)) return;\n\tconst { Pool: PgPool } = loadPg();\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\tawait pool.query(`DROP OWNED BY ${roleIdent}`);\n\t\tawait pool.query(`DROP ROLE IF EXISTS ${roleIdent}`);\n\t} finally {\n\t\tawait pool.end();\n\t}\n}\n//#endregion\n//#region src/project-database/redis-provision.ts\nconst DEFAULT_QUEUE_PREFIX = \"keystroke\";\nfunction resolveAdminRedisUrl(env = process.env) {\n\treturn env.UPSTASH_REDIS_URL?.trim() || env.REDIS_URL?.trim() || void 0;\n}\nfunction resolveQueuePrefix(env = process.env) {\n\treturn env.KEYSTROKE_QUEUE_PREFIX?.trim() || DEFAULT_QUEUE_PREFIX;\n}\n/** Swap org ACL credentials into the shared admin Redis URL (preserves host/port/TLS). */\nfunction buildOrgRedisUrl(adminUrl, username, password) {\n\tconst url = new URL(adminUrl);\n\turl.username = username;\n\turl.password = password;\n\treturn url.toString();\n}\n/** Upstash Fly Redis rejects arbitrary `>password` modifiers — passwords must come from ACL GENTOKEN. */\nfunction usesUpstashGentokenPassword(adminUrl) {\n\ttry {\n\t\treturn new URL(adminUrl).hostname.endsWith(\".upstash.io\");\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** ACL permission rules for a tenant-scoped org user (keys + cancel channel only). */\nfunction orgRedisAclPermissionRules(organizationId, env = process.env) {\n\tconst queueSegment = orgRedisQueueSegment(organizationId);\n\tconst prefix = resolveQueuePrefix(env);\n\treturn [\n\t\t`~${prefix}:org-${queueSegment}:*`,\n\t\t`&${prefix}:cancel:org-${queueSegment}`,\n\t\t`~as:${organizationId}:*`,\n\t\t\"+@all\",\n\t\t\"-@admin\",\n\t\t\"-@dangerous\",\n\t\t\"+info\"\n\t];\n}\n/** ACL SETUSER args for a tenant-scoped org user (keys + cancel channel only). */\nfunction orgRedisAclSetUserArgs(organizationId, password, env = process.env) {\n\treturn [\n\t\t\"SETUSER\",\n\t\torgRedisUsername(organizationId),\n\t\t\"reset\",\n\t\t\"on\",\n\t\t`>${password}`,\n\t\t...orgRedisAclPermissionRules(organizationId, env)\n\t];\n}\nasync function resolveOrgRedisPassword(admin, organizationId, adminUrl) {\n\tconst username = orgRedisUsername(organizationId);\n\tif (usesUpstashGentokenPassword(adminUrl)) return String(await admin.call(\"ACL\", \"GENTOKEN\", username));\n\treturn randomBytes(32).toString(\"base64url\");\n}\nasync function provisionOrgRedis(organizationId, env = process.env) {\n\tconst adminUrl = resolveAdminRedisUrl(env);\n\tif (!adminUrl) return { redisUrlCiphertext: \"\" };\n\tconst username = orgRedisUsername(organizationId);\n\tconst admin = new Redis(adminUrl);\n\ttry {\n\t\tconst password = await resolveOrgRedisPassword(admin, organizationId, adminUrl);\n\t\tawait admin.call(\"ACL\", \"SETUSER\", username, \"reset\", \"on\", `>${password}`, ...orgRedisAclPermissionRules(organizationId, env));\n\t\treturn { redisUrlCiphertext: encryptCredentialPayload(buildOrgRedisUrl(adminUrl, username, password)) };\n\t} finally {\n\t\tawait admin.quit().catch(() => void 0);\n\t}\n}\nasync function deprovisionOrgRedis(organizationId, env = process.env) {\n\tconst adminUrl = resolveAdminRedisUrl(env);\n\tif (!adminUrl) return;\n\tconst admin = new Redis(adminUrl);\n\ttry {\n\t\tawait admin.call(\"ACL\", \"DELUSER\", orgRedisUsername(organizationId));\n\t} finally {\n\t\tawait admin.quit().catch(() => void 0);\n\t}\n}\n//#endregion\n//#region src/queries/_internal.ts\n/** Internal: only `queries/**` may call this. */\nfunction getDb$1() {\n\treturn getDbFromContext$1();\n}\nfunction isSqliteDialect() {\n\treturn getDatabaseHandle$1().dialect === \"sqlite\";\n}\n/** Drizzle sqlite handle when the control-plane runs on sqlite. */\nfunction getSqliteDb() {\n\treturn getDbFromContext$1();\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}\nfunction resolveAvailableProjectSlugSqlite(executor, organizationId, name) {\n\tconst base = slugifyProjectName(name);\n\tconst isTaken = (slug) => executor.select({ id: projectsSqlite.id }).from(projectsSqlite).where(and(eq(projectsSqlite.organizationId, organizationId), eq(projectsSqlite.slug, slug), isNull(projectsSqlite.deletedAt))).limit(1).get() !== void 0;\n\tif (!isTaken(base)) return base;\n\tfor (let suffix = 2; suffix < 1e4; suffix += 1) {\n\t\tconst candidate = ProjectSlugSchema.parse(`${base}-${suffix}`);\n\t\tif (!isTaken(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$1(), organizationId, parsed, excludeProjectId)) return {\n\t\tslug: parsed,\n\t\tavailable: false,\n\t\treason: \"taken\",\n\t\tsuggestion: await resolveAvailableProjectSlug(getDb$1(), 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/** Auto-created org project — `{Org name} Project`. */\nfunction buildDefaultOrgProjectName(organizationName) {\n\treturn `${organizationName.trim() || \"Organization\"} Project`;\n}\n/** Pre-rename title; still accepted when resolving an org's default project. */\nfunction buildLegacyDefaultOrgProjectName(organizationName) {\n\treturn `${organizationName.trim() || \"Organization\"} Default`;\n}\nasync function selectProjectByName(executor, organizationId, name) {\n\treturn (await executor.select().from(projects).where(and$2(eq$2(projects.organizationId, organizationId), eq$2(projects.name, name), isNull$2(projects.deletedAt))).orderBy(asc$1(projects.createdAt), asc$1(projects.id)).limit(1))[0];\n}\nasync function selectDefaultOrgProject(executor, organizationId, organizationName) {\n\tconst current = await selectProjectByName(executor, organizationId, buildDefaultOrgProjectName(organizationName));\n\tif (current) return current;\n\treturn selectProjectByName(executor, organizationId, buildLegacyDefaultOrgProjectName(organizationName));\n}\n/**\n* Creates the organization's default project when it has none yet.\n* Named `{Org name} Project`; creator becomes project admin.\n*/\nasync function ensureDefaultOrgProjectInTransaction(tx, organizationId, organizationName, creatorUserId, repositoryProvider) {\n\tconst existing = await selectDefaultOrgProject(tx, organizationId, organizationName);\n\tif (existing) return existing;\n\tconst now = /* @__PURE__ */ new Date();\n\tconst projectId = crypto.randomUUID();\n\tconst name = buildDefaultOrgProjectName(organizationName);\n\tconst slug = await resolveAvailableProjectSlug(tx, organizationId, name);\n\tconst [inserted] = await tx.insert(projects).values({\n\t\tid: projectId,\n\t\torganizationId,\n\t\tname,\n\t\tslug,\n\t\tdescription: null,\n\t\tdefaultMemberRole: \"builder\",\n\t\tinvitePermission: \"admin\",\n\t\tcreatedByUserId: creatorUserId,\n\t\tstatus: \"inactive\",\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t}).returning();\n\tif (inserted) {\n\t\tawait tx.insert(projectUsers).values({\n\t\t\tprojectId: inserted.id,\n\t\t\tuserId: creatorUserId,\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\tif (repositoryProvider) await tx.insert(projectRepositories).values({\n\t\t\tid: crypto.randomUUID(),\n\t\t\torganizationId,\n\t\t\tprojectId: inserted.id,\n\t\t\tprovider: repositoryProvider,\n\t\t\tlifecycleStatus: \"provisioning\",\n\t\t\tcontentStatus: \"empty\",\n\t\t\tdesiredState: \"active\",\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now\n\t\t});\n\t\treturn inserted;\n\t}\n\treturn selectDefaultOrgProject(tx, organizationId, organizationName);\n}\n/**\n* Adds a joining org member to the org's default project (`{Org name} Project`).\n* No-op when that default project is missing (e.g. deleted) — never falls back\n* to another project.\n*/\nasync function addUserToDefaultOrgProjectInTransaction(tx, organizationId, userId) {\n\tconst [organization] = await tx.select({ name: organizations.name }).from(organizations).where(eq$2(organizations.id, organizationId)).limit(1);\n\tif (!organization) return;\n\tconst project = await selectDefaultOrgProject(tx, organizationId, organization.name);\n\tif (!project) return;\n\tconst now = /* @__PURE__ */ new Date();\n\tconst [existing] = await tx.select().from(projectUsers).where(and$2(eq$2(projectUsers.projectId, project.id), eq$2(projectUsers.userId, userId))).limit(1);\n\tif (!existing) {\n\t\tawait tx.insert(projectUsers).values({\n\t\t\tprojectId: project.id,\n\t\t\tuserId,\n\t\t\trole: project.defaultMemberRole,\n\t\t\tstatus: \"active\",\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now\n\t\t});\n\t\treturn;\n\t}\n\tif (existing.deletedAt != null || existing.status !== \"active\") await tx.update(projectUsers).set({\n\t\trole: project.defaultMemberRole,\n\t\tstatus: \"active\",\n\t\tupdatedAt: now,\n\t\tdeletedAt: null\n\t}).where(and$2(eq$2(projectUsers.projectId, project.id), eq$2(projectUsers.userId, userId)));\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$1().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$1();\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$1().select().from(organizations).where(eq(organizations.id, id)).limit(1))[0];\n}\nasync function selectOrganizationBySlug(slug) {\n\treturn (await getDb$1().select().from(organizations).where(eq(organizations.slug, slug)).limit(1))[0];\n}\nasync function isOrganizationStorageBucketInUse(bucket) {\n\treturn (await getDb$1().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$1().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$1().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$1().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$1();\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$1();\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$1();\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$1();\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$1();\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 verifiedAt = now;\n\tconst database = await provisionOrgDatabase(organizationId);\n\tconst redis = await provisionOrgRedis(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\tredisUrlCiphertext: redis.redisUrlCiphertext || null,\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\tverifiedAt\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 ensureDefaultOrgProjectInTransaction(tx, organizationId, trimmedName, userId, options.repositoryProvider);\n\t\t\tawait tx.insert(organizationBilling).values({\n\t\t\t\torganizationId,\n\t\t\t\tplanKey: DEFAULT_PLAN_KEY,\n\t\t\t\tcreatedAt: now,\n\t\t\t\tupdatedAt: now\n\t\t\t});\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\tawait deprovisionOrgRedis(organizationId).catch(() => void 0);\n\t\tif (isOrganizationSlugUniqueViolation(error)) throw new OrganizationSlugTakenError();\n\t\tthrow error;\n\t}\n}\n//#endregion\n//#region src/queries/projects/index.ts\n/** Five-minute sliding lease; clients heartbeat during long local builds. */\nconst PROJECT_DEPLOY_LEASE_TTL_MS = 2 * 6e4;\nfunction deployLeaseExpiry(from = /* @__PURE__ */ new Date()) {\n\treturn new Date(from.getTime() + PROJECT_DEPLOY_LEASE_TTL_MS);\n}\nasync function selectProjectById(projectId) {\n\treturn (await getDb$1().select().from(projects).where(eq(projects.id, projectId)).limit(1))[0];\n}\n/** Non-deleted projects in the org — used for plan quota checks. */\nasync function countActiveProjectsForOrganization(organizationId) {\n\treturn (await getDb$1().select({ total: count() }).from(projects).where(and(eq(projects.organizationId, organizationId), isNull(projects.deletedAt))))[0]?.total ?? 0;\n}\nasync function selectProjectsByOrganizationId(organizationId, options) {\n\tconst db = getDb$1();\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\tconst query = db.select().from(projects).where(and(...conditions)).orderBy(desc(projects.updatedAt), desc(projects.id));\n\treturn options?.all ? query : query.limit(options?.limit ?? 200);\n}\nasync function selectProjectForOrganization(organizationId, projectId) {\n\treturn (await getDb$1().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$1();\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(organizationIdOrInput, name, description, createdByUserId) {\n\tconst input = typeof organizationIdOrInput === \"string\" ? {\n\t\torganizationId: organizationIdOrInput,\n\t\tname: name ?? \"\",\n\t\tdescription,\n\t\tcreatedByUserId\n\t} : organizationIdOrInput;\n\tconst trimmedName = input.name.trim();\n\tif (!trimmedName) throw new Error(\"Project name is required\");\n\tconst trimmedDescription = input.description === void 0 || input.description === null ? null : input.description.trim() || null;\n\tif (isSqliteDialect()) return getSqliteDb().transaction((tx) => {\n\t\tconst now = /* @__PURE__ */ new Date();\n\t\tconst projectId = crypto.randomUUID();\n\t\tconst slug = resolveAvailableProjectSlugSqlite(tx, input.organizationId, trimmedName);\n\t\tconst project = tx.insert(projectsSqlite).values({\n\t\t\tid: projectId,\n\t\t\torganizationId: input.organizationId,\n\t\t\tname: trimmedName,\n\t\t\tslug,\n\t\t\tdescription: trimmedDescription,\n\t\t\tdefaultMemberRole: \"builder\",\n\t\t\tinvitePermission: \"admin\",\n\t\t\tcreatedByUserId: input.createdByUserId ?? null,\n\t\t\tstatus: \"inactive\",\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now\n\t\t}).returning().get();\n\t\tif (!project) throw new Error(\"Failed to create project\");\n\t\tif (input.createdByUserId) tx.insert(projectUsersSqlite).values({\n\t\t\tprojectId: project.id,\n\t\t\tuserId: input.createdByUserId,\n\t\t\trole: \"admin\",\n\t\t\tstatus: \"active\",\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now\n\t\t}).run();\n\t\tif (input.repositoryProvider) tx.insert(projectRepositoriesSqlite).values({\n\t\t\tid: crypto.randomUUID(),\n\t\t\torganizationId: input.organizationId,\n\t\t\tprojectId: project.id,\n\t\t\tprovider: input.repositoryProvider,\n\t\t\tdefaultBranch: \"main\",\n\t\t\tlifecycleStatus: \"provisioning\",\n\t\t\tcontentStatus: \"empty\",\n\t\t\tdesiredState: \"active\",\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now\n\t\t}).run();\n\t\treturn project;\n\t});\n\treturn getDb$1().transaction(async (tx) => {\n\t\tconst now = /* @__PURE__ */ new Date();\n\t\tconst projectId = crypto.randomUUID();\n\t\tconst slug = await resolveAvailableProjectSlug(tx, input.organizationId, trimmedName);\n\t\tconst [project] = await tx.insert(projects).values({\n\t\t\tid: projectId,\n\t\t\torganizationId: input.organizationId,\n\t\t\tname: trimmedName,\n\t\t\tslug,\n\t\t\tdescription: trimmedDescription,\n\t\t\tdefaultMemberRole: \"builder\",\n\t\t\tinvitePermission: \"admin\",\n\t\t\tcreatedByUserId: input.createdByUserId ?? null,\n\t\t\tstatus: \"inactive\",\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now\n\t\t}).returning();\n\t\tif (!project) throw new Error(\"Failed to create project\");\n\t\tif (input.createdByUserId) await tx.insert(projectUsers).values({\n\t\t\tprojectId: project.id,\n\t\t\tuserId: input.createdByUserId,\n\t\t\trole: \"admin\",\n\t\t\tstatus: \"active\",\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now\n\t\t});\n\t\tif (input.repositoryProvider) await tx.insert(projectRepositories).values({\n\t\t\tid: crypto.randomUUID(),\n\t\t\torganizationId: input.organizationId,\n\t\t\tprojectId: project.id,\n\t\t\tprovider: input.repositoryProvider,\n\t\t\tdefaultBranch: \"main\",\n\t\t\tlifecycleStatus: \"provisioning\",\n\t\t\tcontentStatus: \"empty\",\n\t\t\tdesiredState: \"active\",\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now\n\t\t});\n\t\treturn project;\n\t});\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$1();\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$1().update(projects).set(updates).where(eq(projects.id, projectId)).returning())[0];\n}\nasync function deleteProjectForOrganization(organizationId, projectId) {\n\tconst now = /* @__PURE__ */ new Date();\n\tif (isSqliteDialect()) return getSqliteDb().transaction((tx) => {\n\t\tconst deleted = tx.update(projectsSqlite).set({\n\t\t\tdeletedAt: now,\n\t\t\tupdatedAt: now\n\t\t}).where(and(eq(projectsSqlite.id, projectId), eq(projectsSqlite.organizationId, organizationId), isNull(projectsSqlite.deletedAt))).returning().get();\n\t\tif (!deleted) return;\n\t\ttx.update(projectRepositoriesSqlite).set({\n\t\t\tdesiredState: \"deleted\",\n\t\t\tlifecycleStatus: \"deleting\",\n\t\t\tupdatedAt: now\n\t\t}).where(eq(projectRepositoriesSqlite.projectId, projectId)).run();\n\t\treturn deleted;\n\t});\n\treturn getDb$1().transaction(async (tx) => {\n\t\tconst rows = await tx.update(projects).set({\n\t\t\tdeletedAt: now,\n\t\t\tupdatedAt: now\n\t\t}).where(and(eq(projects.id, projectId), eq(projects.organizationId, organizationId), isNull(projects.deletedAt))).returning();\n\t\tif (!rows[0]) return;\n\t\tawait tx.update(projectRepositories).set({\n\t\t\tdesiredState: \"deleted\",\n\t\t\tlifecycleStatus: \"deleting\",\n\t\t\tupdatedAt: now\n\t\t}).where(eq(projectRepositories.projectId, projectId));\n\t\treturn rows[0];\n\t});\n}\nasync function updateProjectActive(projectId, input) {\n\tconst db = getDb$1();\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$1();\n\tconst now = /* @__PURE__ */ new Date();\n\treturn (await db.update(projects).set({\n\t\tstatus: \"failed\",\n\t\tlastError,\n\t\tpendingArtifactId: null,\n\t\tdeployLeaseArtifactId: null,\n\t\tdeployLeaseExpiresAt: null,\n\t\tupdatedAt: now\n\t}).where(eq(projects.id, projectId)).returning())[0];\n}\n/**\n* Abort a deploy that already staged `pendingArtifactId` (e.g. enqueue failed\n* after `completeProjectArtifact`). Clears pending + lease atomically, leaves\n* `activeArtifactId` untouched, and marks the project failed with `lastError`.\n*/\nasync function abortStagedProjectDeploy(input) {\n\tconst db = getDb$1();\n\tconst now = /* @__PURE__ */ new Date();\n\treturn (await db.update(projects).set({\n\t\tstatus: \"failed\",\n\t\tlastError: input.lastError,\n\t\tpendingArtifactId: null,\n\t\tdeployLeaseArtifactId: null,\n\t\tdeployLeaseExpiresAt: null,\n\t\tupdatedAt: now\n\t}).where(and(eq(projects.id, input.projectId), or(eq(projects.pendingArtifactId, input.artifactId), eq(projects.deployLeaseArtifactId, input.artifactId)))).returning())[0];\n}\n/** Cancel a non-active deploy without marking the last-good project failed. */\nasync function cancelProjectDeploy(input) {\n\tconst db = getDb$1();\n\tconst [current] = await db.select().from(projects).where(eq(projects.id, input.projectId)).limit(1);\n\tif (!current || current.activeArtifactId === input.artifactId) return;\n\tconst [updated] = await db.update(projects).set({\n\t\tstatus: current.activeArtifactId ? \"active\" : \"inactive\",\n\t\tlastError: null,\n\t\tpendingArtifactId: null,\n\t\tdeployLeaseArtifactId: null,\n\t\tdeployLeaseExpiresAt: null,\n\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t}).where(and(eq(projects.id, input.projectId), or(isNull(projects.activeArtifactId), ne(projects.activeArtifactId, input.artifactId)), or(eq(projects.pendingArtifactId, input.artifactId), eq(projects.deployLeaseArtifactId, input.artifactId)))).returning();\n\treturn updated;\n}\n/**\n* Atomically acquire the one-active managed deploy lease.\n* Reclaims an expired lease only when nothing is staged (`pendingArtifactId`\n* is null). Once pending is set, the lease blocks reclaim until terminal cleanup.\n*/\nasync function tryAcquireProjectDeployLease(input) {\n\tconst db = getDb$1();\n\tconst now = /* @__PURE__ */ new Date();\n\tconst expiresAt = deployLeaseExpiry(now);\n\tconst [before] = await db.select({\n\t\tdeployLeaseArtifactId: projects.deployLeaseArtifactId,\n\t\tdeployLeaseExpiresAt: projects.deployLeaseExpiresAt\n\t}).from(projects).where(eq(projects.id, input.projectId)).limit(1);\n\tconst project = (await db.update(projects).set({\n\t\tdeployLeaseArtifactId: input.artifactId,\n\t\tdeployLeaseExpiresAt: expiresAt,\n\t\tupdatedAt: now\n\t}).where(and(eq(projects.id, input.projectId), isNull(projects.pendingArtifactId), or(isNull(projects.deployLeaseArtifactId), lt(projects.deployLeaseExpiresAt, now)))).returning())[0];\n\tif (!project) return { acquired: false };\n\treturn {\n\t\tacquired: true,\n\t\tproject,\n\t\treclaimedArtifactId: before?.deployLeaseArtifactId && before.deployLeaseExpiresAt && before.deployLeaseExpiresAt < now ? before.deployLeaseArtifactId : null\n\t};\n}\n/** Extend lease expiry while the holder still owns it. */\nasync function refreshProjectDeployLease(input) {\n\tconst db = getDb$1();\n\tconst now = /* @__PURE__ */ new Date();\n\tconst project = (await db.update(projects).set({\n\t\tdeployLeaseExpiresAt: deployLeaseExpiry(now),\n\t\tupdatedAt: now\n\t}).where(and(eq(projects.id, input.projectId), eq(projects.deployLeaseArtifactId, input.artifactId), gt(projects.deployLeaseExpiresAt, now))).returning())[0];\n\tif (!project) return { refreshed: false };\n\treturn {\n\t\trefreshed: true,\n\t\tproject\n\t};\n}\n/** Release the deploy lease only when it still matches `artifactId` (idempotent). */\nasync function releaseProjectDeployLease(input) {\n\tconst db = getDb$1();\n\tconst now = /* @__PURE__ */ new Date();\n\treturn (await db.update(projects).set({\n\t\tdeployLeaseArtifactId: null,\n\t\tdeployLeaseExpiresAt: null,\n\t\tupdatedAt: now\n\t}).where(and(eq(projects.id, input.projectId), eq(projects.deployLeaseArtifactId, input.artifactId))).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\tconst redis = await provisionOrgRedis(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\tredisUrlCiphertext: redis.redisUrlCiphertext || null,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now,\n\t\tverifiedAt: now\n\t});\n\telse await getDb$1().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\tredisUrlCiphertext: redis.redisUrlCiphertext || null,\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$1().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/runtime/schema/pg.ts\nvar pg_exports = /* @__PURE__ */ __exportAll({\n\tagentEvents: () => agentEvents,\n\tagentSessions: () => agentSessions,\n\tagents: () => agents,\n\tbrainDocumentVersions: () => brainDocumentVersions,\n\tbrainDocumentWriteEvents: () => brainDocumentWriteEvents,\n\tbrainDocuments: () => brainDocuments,\n\tbrainFilters: () => brainFilters,\n\tbrainGrants: () => brainGrants,\n\tbrainMembers: () => brainMembers,\n\tbrains: () => brains,\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\tworkflowEvents: () => workflowEvents,\n\tworkflowHooks: () => workflowHooks,\n\tworkflowRuns: () => workflowRuns,\n\tworkflowSubscriptions: () => workflowSubscriptions,\n\tworkflows: () => workflows\n});\n//#endregion\n//#region src/runtime/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/runtime/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/runtime/queries/_internal.ts\n/** Internal: only `queries/**` may call this. */\nfunction getDb() {\n\treturn getDbFromContext();\n}\nfunction rowsFromResult(result) {\n\tif (Array.isArray(result)) return result;\n\tconst rows = result.rows;\n\treturn Array.isArray(rows) ? rows : [];\n}\n//#endregion\n//#region src/runtime/queries/_internal/organization-scope.ts\nfunction organizationScopeId() {\n\treturn requireOrganizationScopeId();\n}\nfunction eqOrganizationScope(table) {\n\treturn eq$1(table.organizationId, organizationScopeId());\n}\nfunction orgScopedAnd(table, ...conditions) {\n\treturn and$1(eqOrganizationScope(table), ...conditions);\n}\n//#endregion\n//#region src/runtime/queries/brains/members.ts\n/** No operation may remove or demote the last owner of a Brain. */\nvar BrainLastOwnerError = class extends Error {\n\tconstructor() {\n\t\tsuper(\"A Brain must retain at least one owner\");\n\t\tthis.name = \"BrainLastOwnerError\";\n\t}\n};\n/**\n* Creates a Brain and the creator's owner membership in one transaction.\n* SQLite (single-process local database) runs the writes sequentially because\n* better-sqlite3 transactions require synchronous callbacks.\n*/\nasync function createBrainWithOwner(input) {\n\tconst db = getDb();\n\tconst create = async (tx) => {\n\t\tawait tx.insert(brains).values({\n\t\t\tid: input.id,\n\t\t\torganizationId: organizationScopeId(),\n\t\t\tslug: input.slug,\n\t\t\tname: input.name,\n\t\t\tdescription: input.description,\n\t\t\tindexConfig: input.indexConfig,\n\t\t\tactiveGeneration: 1,\n\t\t\tstatus: \"active\",\n\t\t\tcreatedByUserId: input.ownerUserId,\n\t\t\tcreatedAt: input.now,\n\t\t\tupdatedAt: input.now,\n\t\t\tdeletedAt: null\n\t\t});\n\t\tawait tx.insert(brainMembers).values({\n\t\t\tid: crypto.randomUUID(),\n\t\t\torganizationId: organizationScopeId(),\n\t\t\tbrainId: input.id,\n\t\t\tuserId: input.ownerUserId,\n\t\t\trole: \"owner\",\n\t\t\tcreatedByUserId: input.ownerUserId,\n\t\t\tcreatedAt: input.now,\n\t\t\tupdatedAt: input.now\n\t\t});\n\t};\n\tif (getDatabaseHandle().dialect === \"sqlite\") await create(db);\n\telse await db.transaction(create);\n\tconst brain = (await db.select().from(brains).where(orgScopedAnd(brains, eq$1(brains.id, input.id))).limit(1))[0];\n\tif (!brain) throw new Error(\"Failed to create brain\");\n\treturn brain;\n}\nasync function listBrainMembers(brainId) {\n\treturn getDb().select().from(brainMembers).where(orgScopedAnd(brainMembers, eq$1(brainMembers.brainId, brainId))).orderBy(asc(brainMembers.createdAt), asc(brainMembers.userId));\n}\nasync function selectBrainMember(brainId, userId) {\n\treturn (await getDb().select().from(brainMembers).where(orgScopedAnd(brainMembers, eq$1(brainMembers.brainId, brainId), eq$1(brainMembers.userId, userId))).limit(1))[0];\n}\n/** Adds a member; an existing membership is returned unchanged (role updates are explicit). */\nasync function addBrainMember(input) {\n\tawait getDb().insert(brainMembers).values({\n\t\tid: input.id,\n\t\torganizationId: organizationScopeId(),\n\t\tbrainId: input.brainId,\n\t\tuserId: input.userId,\n\t\trole: input.role,\n\t\tcreatedByUserId: input.createdByUserId,\n\t\tcreatedAt: input.now,\n\t\tupdatedAt: input.now\n\t}).onConflictDoNothing({ target: [brainMembers.brainId, brainMembers.userId] });\n\tconst member = await selectBrainMember(input.brainId, input.userId);\n\tif (!member) throw new Error(\"Failed to add brain member\");\n\treturn member;\n}\nfunction countOwnersQuery(tx, brainId) {\n\treturn tx.select({ value: count$1() }).from(brainMembers).where(orgScopedAnd(brainMembers, eq$1(brainMembers.brainId, brainId), eq$1(brainMembers.role, \"owner\")));\n}\n/**\n* Changes a member's role. Demoting an owner requires at least one other\n* owner; the check and the update run in one transaction (Postgres locks the\n* membership rows, SQLite serializes writes in-process) so concurrent\n* demotions cannot leave zero owners.\n*/\nasync function updateBrainMemberRole(input) {\n\tconst db = getDb();\n\tconst dialect = getDatabaseHandle().dialect;\n\tconst run = async (tx) => {\n\t\tif (input.role === \"admin\") {\n\t\t\tconst memberQuery = tx.select().from(brainMembers).where(orgScopedAnd(brainMembers, eq$1(brainMembers.brainId, input.brainId), eq$1(brainMembers.userId, input.userId))).limit(1);\n\t\t\tconst member = (dialect === \"sqlite\" ? await memberQuery : await memberQuery.for(\"update\"))[0];\n\t\t\tif (!member) return void 0;\n\t\t\tif (member.role === \"owner\") {\n\t\t\t\tconst ownersQuery = countOwnersQuery(tx, input.brainId);\n\t\t\t\tif (((dialect === \"sqlite\" ? await ownersQuery : await ownersQuery.for(\"update\"))[0]?.value ?? 0) <= 1) throw new BrainLastOwnerError();\n\t\t\t}\n\t\t}\n\t\treturn (await tx.update(brainMembers).set({\n\t\t\trole: input.role,\n\t\t\tupdatedAt: input.now\n\t\t}).where(orgScopedAnd(brainMembers, eq$1(brainMembers.brainId, input.brainId), eq$1(brainMembers.userId, input.userId))).returning())[0];\n\t};\n\tif (dialect === \"sqlite\") return run(db);\n\treturn db.transaction(run);\n}\n/** Removes a member; removing an owner requires at least one other owner. */\nasync function removeBrainMember(input) {\n\tconst db = getDb();\n\tconst dialect = getDatabaseHandle().dialect;\n\tconst run = async (tx) => {\n\t\tconst memberQuery = tx.select().from(brainMembers).where(orgScopedAnd(brainMembers, eq$1(brainMembers.brainId, input.brainId), eq$1(brainMembers.userId, input.userId))).limit(1);\n\t\tconst member = (dialect === \"sqlite\" ? await memberQuery : await memberQuery.for(\"update\"))[0];\n\t\tif (!member) return false;\n\t\tif (member.role === \"owner\") {\n\t\t\tconst ownersQuery = countOwnersQuery(tx, input.brainId);\n\t\t\tif (((dialect === \"sqlite\" ? await ownersQuery : await ownersQuery.for(\"update\"))[0]?.value ?? 0) <= 1) throw new BrainLastOwnerError();\n\t\t}\n\t\treturn (await tx.delete(brainMembers).where(orgScopedAnd(brainMembers, eq$1(brainMembers.id, member.id))).returning({ id: brainMembers.id })).length > 0;\n\t};\n\tif (dialect === \"sqlite\") return run(db);\n\treturn db.transaction(run);\n}\n/** Brains the user owns or administers — the organization-level management list. */\nasync function listBrainsForMember(userId) {\n\treturn (await getDb().select({\n\t\tbrain: brains,\n\t\trole: brainMembers.role\n\t}).from(brains).innerJoin(brainMembers, eq$1(brainMembers.brainId, brains.id)).where(orgScopedAnd(brains, isNull$1(brains.deletedAt), ne$1(brains.status, \"deleting\"), eq$1(brainMembers.userId, userId))).orderBy(asc(brains.slug))).map((row) => ({\n\t\tbrain: row.brain,\n\t\trole: row.role\n\t}));\n}\n/** Removes all membership rows of a Brain (deletion cleanup). */\nasync function deleteBrainMembers(brainId) {\n\tawait getDb().delete(brainMembers).where(orgScopedAnd(brainMembers, eq$1(brainMembers.brainId, brainId)));\n}\n/**\n* Slugs of live Brains where the user is the only owner, with an explicit\n* organization id so the control-plane member-removal path (which runs\n* outside tenant ALS scope) can reject removals that would orphan a Brain.\n*/\nasync function listBrainSlugsWhereUserIsSoleOwner(organizationId, userId) {\n\tconst db = getDb();\n\tconst owned = await db.select({\n\t\tbrainId: brainMembers.brainId,\n\t\tslug: brains.slug\n\t}).from(brainMembers).innerJoin(brains, eq$1(brains.id, brainMembers.brainId)).where(and$1(eq$1(brainMembers.organizationId, organizationId), eq$1(brainMembers.userId, userId), eq$1(brainMembers.role, \"owner\"), eq$1(brains.organizationId, organizationId), isNull$1(brains.deletedAt)));\n\tif (owned.length === 0) return [];\n\tconst soleOwned = [];\n\tfor (const row of owned) if (((await db.select({ value: count$1() }).from(brainMembers).where(and$1(eq$1(brainMembers.organizationId, organizationId), eq$1(brainMembers.brainId, row.brainId), eq$1(brainMembers.role, \"owner\"), ne$1(brainMembers.userId, userId))))[0]?.value ?? 0) === 0) soleOwned.push(row.slug);\n\treturn soleOwned.sort();\n}\n//#endregion\n//#region src/runtime/agents/sanitize-message.ts\nfunction isRecord(value) {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\nfunction sanitizeTextPart(part) {\n\tif (part.type !== \"text\" || typeof part.text !== \"string\") return part;\n\treturn {\n\t\t...part,\n\t\ttext: stripPromptContext(part.text)\n\t};\n}\nfunction sanitizeParts(parts) {\n\tif (!Array.isArray(parts)) return typeof parts === \"string\" ? stripPromptContext(parts) : parts;\n\treturn parts.map((part) => isRecord(part) ? sanitizeTextPart(part) : part);\n}\n/** Strip wrapped prompt context from user message payloads for UI-facing reads. */\nfunction sanitizeMessagePayloadContext(payload) {\n\tif (!isRecord(payload) || payload.role !== \"user\") return payload;\n\tif (\"parts\" in payload) return {\n\t\t...payload,\n\t\tparts: sanitizeParts(payload.parts)\n\t};\n\tif (\"content\" in payload) return {\n\t\t...payload,\n\t\tcontent: sanitizeParts(payload.content)\n\t};\n\treturn payload;\n}\n//#endregion\nexport { cancelProjectDeploy as $, traceLogs as $n, oauthConnections as $r, buildOrgRedisUrl as $t, gt$1 as A, loadMigrations as An, projectAgentSessionSandboxesSqlite as Ar, checkOrganizationSlugAvailability as At, sql$1 as B, attachPoolErrorTelemetry as Bn, platformAgentSessionsSqlite as Br, eq$2 as Bt, runWithRequestDatabaseHandle as C, runWithTenantScope as Cn, organizationBilling as Cr, selectUserOrganizations as Ct, count$1 as D, runMigrations as Dn, publishedForms as Dr, updateOrganizationSlug as Dt, asc as E, encryptCredentialPayload as En, projectUsers as Er, updateOrganizationName as Et, lte$1 as F, scopeClient as Fn, platformAgentProjectSnapshots as Fr, checkProjectSlugAvailability as Ft, DEFAULT_STANDALONE_PROJECT_SLUG as G, brainDocumentVersions as Gn, projectStatuses as Gr, lt$2 as Gt, DEFAULT_STANDALONE_ORGANIZATION_NAME as H, schema as Hn, projectRepositoriesSqlite as Hr, inArray$2 as Ht, max$1 as I, createConnection as In, platformAgentProjectSnapshotsSqlite as Ir, and$2 as It, ensureDefaultProject as J, brainMembers as Jn, organizationInvitationStatuses as Jr, or$2 as Jt, ensureDefaultOrganization as K, brainGrants as Kn, projects as Kr, max$2 as Kt, ne$1 as L, createSqliteConnection as Ln, platformAgentEvents as Lr, asc$1 as Lt, isNotNull as M, connectWithRetry as Mn, projectAgentEnvImagesSqlite as Mr, buildDefaultOrgProjectName as Mt, isNull$1 as N, connectWithRetryCallback as Nn, platformAgentProjectSnapshotBuildStatuses as Nr, ensureDefaultOrgProjectInTransaction as Nt, desc$1 as O, resolveMigrationsFolder as On, publishedFormsSqlite as Or, organizationRowToSidebarBranding as Ot, lt$1 as P, runScopedQuery as Pn, platformAgentProjectSnapshotRecoveryStates as Pr, ProjectSlugTakenError as Pt, abortStagedProjectDeploy as Q, skills as Qn, oauthPendingStates as Qr, isSqliteDialect as Qt, notInArray$1 as R, createPgConnection as Rn, platformAgentEventsSqlite as Rr, count$2 as Rt, getRequestDatabaseHandle as S, getServerTenantScopeId as Sn, billingEvents as Sr, selectUserOrganizationMembership as St, and$1 as T, decryptCredentialPayload as Tn, secretValues as Tr, updateOrganizationFailed as Tt, DEFAULT_STANDALONE_ORGANIZATION_SLUG as U, brainDocumentWriteEvents as Un, projectArtifactStatuses as Ur, isNotNull$1 as Ut, DEFAULT_STANDALONE_ORGANIZATION_ID as V, createPgDb as Vn, projectRepositories as Vr, gt$2 as Vt, DEFAULT_STANDALONE_PROJECT_NAME as W, brainDocuments as Wn, projectArtifacts as Wr, isNull$2 as Wt, runWithStandaloneScope as X, resourceActivity as Xn, organizationUserRoles as Xr, getDb$1 as Xt, isStandaloneMode as Y, brains as Yn, organizationInvitations as Yr, sql$2 as Yt, PROJECT_DEPLOY_LEASE_TTL_MS as Z, workflows as Zn, organizationUsers as Zr, getSqliteDb as Zt, getDatabaseHandle as _, inferDialect as _i, resolveProjectDatabaseUrlFromEnv as _n, managedServiceCredentials as _r, resolveNewOrganizationIdentity as _t, deleteBrainMembers as a, authApiKeys as ai, orgDbRoleName as an, credentialAssignments as ar, selectProjectById as at, isDatabaseInitialized as b, getProjectScopeId as bn, billingLedger as br, selectOrganizationBySlug as bt, listBrainsForMember as c, getOrganizationScopeId as ci, orgRedisUsername as cn, workflowEvents as cr, selectProjectsByOrganizationId as ct, updateBrainMemberRole as d, resolvePlatformDatabaseUrl as di, parsePostgresUrl as dn, triggerRuns as dr, updateProjectFailed as dt, oauthApps as ei, deprovisionOrgRedis as en, traceSpans as er, countActiveProjectsForOrganization as et, eqOrganizationScope as f, resolvePlatformPostgresConfig as fi, qualifyConnectionUser as fn, triggerAttachments as fr, updateProjectForOrganization as ft, rowsFromResult as g, qualifyConnectionUser$1 as gi, resolvePostgresUrlFromEnv as gn, agents as gr, isOrganizationStorageBucketInUse as gt, getDb as h, parsePostgresUrl$1 as hi, resolvePostgresConfigFromEnv as hn, agentSessions as hr, createOrganizationForUser as ht, createBrainWithOwner as i, organizationsSqlite as ii, provisionOrgDatabase as in, jobs as ir, releaseProjectDeployLease as it, inArray$1 as j, adaptPgMigrationsForSearchPath as jn, projectAgentEnvImages as jr, addUserToDefaultOrgProjectInTransaction as jt, eq$1 as k, migratePgDatabase as kn, projectAgentSessionSandboxes as kr, updateOrganizationSidebarBranding as kt, removeBrainMember as l, requireOrganizationScopeId as li, DEFAULT_PG_POOL_MAX as ln, workflowRuns as lr, tryAcquireProjectDeployLease as lt, organizationScopeId as m, buildPostgresUrl$1 as mi, resolvePgPoolMax as mn, agentEvents as mr, OrganizationSlugTakenError as mt, BrainLastOwnerError as n, apps as ni, provisionOrgRedis as nn, gatewayAttachmentKeyForChannel as nr, deleteProjectForOrganization as nt, listBrainMembers as o, authApiKeysSqlite as oi, orgDbSchemaName as on, credentialInstances as or, selectProjectForOrganization as ot, orgScopedAnd as p, resolveTenantDatabaseUrl as pi, resolveDatabaseUrlFromEnv as pn, triggers as pr, updateProjectSettings as pt, ensureDefaultOrganizationAndProject as q, brainFilters as qn, projectsSqlite as qr, ne$2 as qt, addBrainMember as r, organizations as ri, deprovisionOrgDatabase as rn, gatewayAttachments as rr, refreshProjectDeployLease as rt, listBrainSlugsWhereUserIsSoleOwner as s, bindOrganizationScope as si, orgRedisQueueSegment as sn, workflowHooks as sr, selectProjectForOrganizationBySlug as st, sanitizeMessagePayloadContext as t, templates as ti, orgRedisAclSetUserArgs as tn, gatewayThreadSessions as tr, createProjectForOrganization as tt, selectBrainMember as u, runWithOrganizationScope as ui, buildPostgresUrl as un, workflowSubscriptions as ur, updateProjectActive as ut, getDbFromContext as v, DEFAULT_PLATFORM_DATABASE_URL as vi, DEFAULT_PROJECT_ID as vn, managedServiceCredentialsSqlite as vr, selectActiveOrganizationIds as vt, pg_exports as w, DEFAULT_DATABASE_URL as wn, organizationBillingSqlite as wr, updateOrganizationActive as wt, setDatabaseHandle as x, runWithProjectScope as xn, billingWallet as xr, selectUserOrganization as xt, getDefaultDatabaseHandle as y, getBoundProjectScopeId as yn, usageEvents as yr, selectOrganizationById as yt, or$1 as z, resolveSearchPath as zn, platformAgentSessions as zr, desc$2 as zt };\n\n//# sourceMappingURL=sanitize-message-JfOafIe_.mjs.map","import { $n as traceLogs, A as gt$1, An as loadMigrations, B as sql$1, Bn as attachPoolErrorTelemetry, C as runWithRequestDatabaseHandle, Cn as runWithTenantScope, D as count$1, Dn as runMigrations, E as asc, F as lte$1, Fn as scopeClient, Gn as brainDocumentVersions, H as DEFAULT_STANDALONE_ORGANIZATION_NAME, Hn as schema, I as max$1, Jn as brainMembers, Kn as brainGrants, L as ne$1, M as isNotNull, Mn as connectWithRetry, N as isNull$1, Nn as connectWithRetryCallback, O as desc$1, On as resolveMigrationsFolder, P as lt$1, Pn as runScopedQuery, Qn as skills, R as notInArray$1, S as getRequestDatabaseHandle, Sn as getServerTenantScopeId, T as and$1, U as DEFAULT_STANDALONE_ORGANIZATION_SLUG, Un as brainDocumentWriteEvents, V as DEFAULT_STANDALONE_ORGANIZATION_ID, Wn as brainDocuments, Xn as resourceActivity, Yn as brains, Zn as workflows, _ as getDatabaseHandle, _n as resolveProjectDatabaseUrlFromEnv, a as deleteBrainMembers, ar as credentialAssignments, b as isDatabaseInitialized, bn as getProjectScopeId, c as listBrainsForMember, cr as workflowEvents, d as updateBrainMemberRole, dn as parsePostgresUrl, dr as triggerRuns, er as traceSpans, f as eqOrganizationScope, fn as qualifyConnectionUser, fr as triggerAttachments, g as rowsFromResult, gn as resolvePostgresUrlFromEnv, gr as agents, h as getDb, hn as resolvePostgresConfigFromEnv, hr as agentSessions, i as createBrainWithOwner, ii as organizationsSqlite, ir as jobs, j as inArray$1, jn as adaptPgMigrationsForSearchPath, k as eq$1, kn as migratePgDatabase, l as removeBrainMember, ln as DEFAULT_PG_POOL_MAX, lr as workflowRuns, m as organizationScopeId, mn as resolvePgPoolMax, mr as agentEvents, n as BrainLastOwnerError, nr as gatewayAttachmentKeyForChannel, o as listBrainMembers, or as credentialInstances, p as orgScopedAnd, pn as resolveDatabaseUrlFromEnv, pr as triggers, qn as brainFilters, r as addBrainMember, rr as gatewayAttachments, s as listBrainSlugsWhereUserIsSoleOwner, si as bindOrganizationScope, sr as workflowHooks, t as sanitizeMessagePayloadContext, tr as gatewayThreadSessions, u as selectBrainMember, ui as runWithOrganizationScope, un as buildPostgresUrl, ur as workflowSubscriptions, v as getDbFromContext, vn as DEFAULT_PROJECT_ID, w as pg_exports, wn as DEFAULT_DATABASE_URL, x as setDatabaseHandle, xn as runWithProjectScope, y as getDefaultDatabaseHandle, yn as getBoundProjectScopeId, z as or$1 } from \"../sanitize-message-JfOafIe_.mjs\";\nimport { createRequire } from \"node:module\";\nimport { and, eq, inArray, max } from \"drizzle-orm\";\nimport { mkdirSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport SqliteClient from \"better-sqlite3\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\nimport { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes, timingSafeEqual } from \"node:crypto\";\nimport { buildCredentialInstanceLabel, deriveCredentialInstanceSlug, displayCredentialAppName, resolveUniqueCredentialInstanceLabel, stepCompletedInput, stepCompletedOutput } from \"@keystrokehq/shared\";\nimport { drizzle as drizzle$1 } from \"drizzle-orm/pg-proxy\";\nimport { getTraceContext } from \"@keystrokehq/tracing\";\n//#region src/runtime/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/runtime/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/runtime/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/runtime/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 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//#endregion\n//#region src/runtime/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 ?? resolvePgPoolMax(),\n\t\tconnectionTimeoutMillis: 5e3,\n\t\tidleTimeoutMillis: 3e4,\n\t\tkeepAlive: true\n\t});\n\tattachPoolErrorTelemetry(pool);\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/runtime/connection/pg/proxy.ts\nfunction proxyEndpoint(proxyUrl, path) {\n\treturn `${proxyUrl.replace(/\\/$/, \"\")}${path}`;\n}\nasync function postProxy(proxyUrl, token, path, body) {\n\tconst response = await fetch(proxyEndpoint(proxyUrl, path), {\n\t\tmethod: \"POST\",\n\t\theaders: {\n\t\t\tauthorization: `Bearer ${token}`,\n\t\t\t\"content-type\": \"application/json\"\n\t\t},\n\t\tbody: JSON.stringify(body)\n\t});\n\tif (!response.ok) {\n\t\tconst text = await response.text().catch(() => \"\");\n\t\tthrow new Error(`Database proxy request failed (${response.status}): ${text}`);\n\t}\n\treturn await response.json();\n}\nfunction unsupportedPool() {\n\tconst fail = () => {\n\t\tthrow new Error(\"Raw pg pool is unavailable when using the database proxy\");\n\t};\n\treturn {\n\t\tquery: fail,\n\t\tconnect: fail,\n\t\tend: async () => void 0\n\t};\n}\nfunction createPgProxyConnection(options) {\n\tconst searchPath = resolveSearchPath(options.url, options.searchPath);\n\treturn {\n\t\tdialect: \"postgres\",\n\t\tdb: drizzle$1(async (sql, params, method) => {\n\t\t\treturn { rows: (await postProxy(options.proxyUrl, options.proxyToken, \"/query\", {\n\t\t\t\tsql,\n\t\t\t\tparams,\n\t\t\t\tmethod\n\t\t\t})).rows };\n\t\t}, { schema }),\n\t\tpool: unsupportedPool(),\n\t\tsearchPath,\n\t\tclose: async () => void 0\n\t};\n}\n//#endregion\n//#region src/runtime/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/runtime/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/runtime/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/runtime/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/runtime/connection/index.ts\nfunction createConnection(options) {\n\tif ((options.dialect ?? inferDialect(options.url)) === \"postgres\") {\n\t\tif (options.proxy) return createPgProxyConnection({\n\t\t\turl: options.url,\n\t\t\tmax: options.max,\n\t\t\tsearchPath: options.searchPath,\n\t\t\tproxyUrl: options.proxy.url,\n\t\t\tproxyToken: options.proxy.token\n\t\t});\n\t\treturn createPgConnection({\n\t\t\turl: options.url,\n\t\t\tmax: options.max,\n\t\t\tsearchPath: options.searchPath\n\t\t});\n\t}\n\treturn createSqliteConnection({ url: options.url });\n}\n//#endregion\n//#region src/runtime/tenant-claim/sign.ts\nconst CLAIM_VERSION = \"v1\";\nconst DEFAULT_TTL_SECONDS = 30;\nfunction resolveClaimSecret(env = process.env) {\n\tconst secret = env.DATABASE_RLS_CLAIM_SECRET?.trim();\n\tif (!secret) throw new Error(\"DATABASE_RLS_CLAIM_SECRET is required for tenant database claims\");\n\treturn secret;\n}\nfunction signPayload(payload, secret) {\n\treturn createHmac(\"sha256\", secret).update(payload).digest(\"hex\");\n}\n/** Mint a short-lived claim for `set_config('keystroke.org_claim', …, true)`. */\nfunction createOrganizationClaim(organizationId, options = {}) {\n\tconst trimmed = organizationId.trim();\n\tif (!trimmed) throw new Error(\"organizationId is required\");\n\tconst payload = `${CLAIM_VERSION}.${trimmed}.${Math.floor(Date.now() / 1e3) + (options.ttlSeconds ?? DEFAULT_TTL_SECONDS)}.${randomBytes(16).toString(\"hex\")}`;\n\treturn `${payload}.${signPayload(payload, resolveClaimSecret(options.env))}`;\n}\n/** Parse + verify a claim (Node-side; Postgres has its own verifier). */\nfunction verifyOrganizationClaim(claim, options = {}) {\n\tconst parts = claim.split(\".\");\n\tif (parts.length !== 5 || parts[0] !== CLAIM_VERSION) throw new Error(\"invalid organization claim\");\n\tconst [, organizationId, expiresAtRaw, nonce, providedSignature] = parts;\n\tif (!organizationId || !expiresAtRaw || !nonce || !providedSignature) throw new Error(\"invalid organization claim\");\n\tconst expiresAt = Number(expiresAtRaw);\n\tif (!Number.isFinite(expiresAt)) throw new Error(\"invalid organization claim expiry\");\n\tif (expiresAt < (options.nowSeconds ?? Math.floor(Date.now() / 1e3))) throw new Error(\"expired organization claim\");\n\tconst expected = signPayload(`${CLAIM_VERSION}.${organizationId}.${expiresAtRaw}.${nonce}`, resolveClaimSecret(options.env));\n\tconst expectedBuf = Buffer.from(expected, \"utf8\");\n\tconst providedBuf = Buffer.from(providedSignature, \"utf8\");\n\tif (expectedBuf.length !== providedBuf.length || !timingSafeEqual(expectedBuf, providedBuf)) throw new Error(\"invalid organization claim signature\");\n\treturn {\n\t\torganizationId,\n\t\texpiresAt,\n\t\tnonce\n\t};\n}\n//#endregion\n//#region src/runtime/connection/pg/claim-scoped-pool.ts\nasync function applyOrganizationClaim(query, organizationId, createClaim) {\n\tawait query(`SELECT set_config('keystroke.org_claim', $1, true)`, [createClaim(organizationId)]);\n}\nfunction claimScopeBegin(organizationId, createClaim) {\n\treturn async (query) => {\n\t\tconst result = await query(\"BEGIN\");\n\t\tawait applyOrganizationClaim(query, organizationId, createClaim);\n\t\treturn result;\n\t};\n}\n/**\n* Wrap a shared runtime pool so each checkout/query runs inside a transaction\n* with a signed organization claim (RLS input). No SET ROLE.\n*/\nfunction createClaimScopedPool(options) {\n\tconst { pool, organizationId } = options;\n\tconst createClaim = options.createClaim ?? ((orgId) => createOrganizationClaim(orgId));\n\tif (!organizationId.trim()) throw new Error(\"Claim-scoped pool requires organizationId\");\n\tconst scopedPool = Object.create(pool);\n\tconst beginScope = claimScopeBegin(organizationId, createClaim);\n\tscopedPool.query = ((...args) => runScopedQuery(pool, beginScope, args));\n\tscopedPool.connect = ((callback) => {\n\t\tif (callback) {\n\t\t\tconnectWithRetryCallback(pool, (error, client) => {\n\t\t\t\tif (error || !client) {\n\t\t\t\t\tcallback(error ?? /* @__PURE__ */ new Error(\"failed to connect\"), client, () => void 0);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst scoped = scopeClient(client, beginScope);\n\t\t\t\tcallback(null, scoped.client, scoped.release);\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\treturn connectWithRetry(pool).then((client) => scopeClient(client, beginScope).client);\n\t});\n\treturn scopedPool;\n}\n//#endregion\n//#region src/runtime/connection/pg/claim-scoped-handle.ts\nfunction createClaimScopedHandle(options) {\n\tconst scopedPool = createClaimScopedPool(options);\n\treturn {\n\t\tdialect: \"postgres\",\n\t\tdb: createPgDb(scopedPool),\n\t\tpool: scopedPool,\n\t\tsearchPath: \"public\",\n\t\tclose: async () => void 0\n\t};\n}\n//#endregion\n//#region src/runtime/connection/pg/pg-ident.ts\nconst PG_IDENT = /^[a-zA-Z_][a-zA-Z0-9_]*$/;\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/runtime/connection/pg/org-scoped-pool.ts\n/** Single multi-statement round trip: BEGIN + SET LOCAL ROLE + SET LOCAL search_path. */\nfunction buildOrgScopeBegin(role, searchPath) {\n\treturn `BEGIN; SET LOCAL ROLE ${quotePgIdent(role)}; SET LOCAL search_path TO ${quotePgIdent(primarySearchPathSchema(searchPath))}`;\n}\nfunction orgScopeBegin(role, searchPath) {\n\treturn (query) => query(buildOrgScopeBegin(role, searchPath));\n}\nfunction createOrgScopedClient(client, role, searchPath) {\n\treturn scopeClient(client, orgScopeBegin(role, searchPath));\n}\nfunction createOrgScopedPool(options) {\n\tconst { pool, role, searchPath } = options;\n\tassertOrgScope(role, searchPath);\n\tconst scopedPool = Object.create(pool);\n\tconst beginScope = orgScopeBegin(role, searchPath);\n\tscopedPool.query = ((...args) => runScopedQuery(pool, beginScope, args));\n\tscopedPool.connect = ((callback) => {\n\t\tif (callback) {\n\t\t\tconnectWithRetryCallback(pool, (error, client) => {\n\t\t\t\tif (error || !client) {\n\t\t\t\t\tcallback(error ?? /* @__PURE__ */ new Error(\"failed to connect\"), client, () => void 0);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst scoped = createOrgScopedClient(client, role, searchPath);\n\t\t\t\tcallback(null, scoped.client, scoped.release);\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\treturn connectWithRetry(pool).then((client) => createOrgScopedClient(client, role, searchPath).client);\n\t});\n\treturn scopedPool;\n}\nfunction createOrgScopedHandle(options) {\n\tconst searchPath = primarySearchPathSchema(options.searchPath);\n\tconst scopedPool = createOrgScopedPool({\n\t\t...options,\n\t\tsearchPath\n\t});\n\treturn {\n\t\tdialect: \"postgres\",\n\t\tdb: createPgDb(scopedPool),\n\t\tpool: scopedPool,\n\t\tsearchPath,\n\t\tclose: async () => void 0\n\t};\n}\nfunction assertOrgScope(role, searchPath) {\n\tif (!role?.trim()) throw new Error(\"Shared-login tenant access requires role\");\n\tif (!searchPath?.trim()) throw new Error(\"Shared-login tenant access requires searchPath\");\n\tquotePgIdent(role);\n\tprimarySearchPathSchema(searchPath);\n}\n//#endregion\n//#region src/runtime/client/pool-cache.ts\nconst IDLE_EVICT_MS = 6e4;\nconst EVICT_INTERVAL_MS = 3e4;\nconst cache = /* @__PURE__ */ new Map();\nlet evictTimer;\nfunction sharedPoolCacheKey(url, max) {\n\treturn `${url}\\0shared-login\\0${max ?? \"\"}`;\n}\n/** Legacy untrusted proxy pools — authenticated as the org login. */\nfunction orgLoginPoolCacheKey(url, searchPath, max) {\n\treturn `${url}\\0org-login\\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 acquireSharedLoginPool(url, dialect, max) {\n\tconst key = sharedPoolCacheKey(url, max);\n\tlet entry = cache.get(key);\n\tif (!entry) {\n\t\tentry = {\n\t\t\thandle: createConnection({\n\t\t\t\turl,\n\t\t\t\tdialect,\n\t\t\t\tmax\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;\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 organizationId = options.organizationId?.trim();\n\tconst role = options.role?.trim();\n\tconst searchPath = resolveSearchPath(options.url, options.searchPath);\n\tconst max = options.max ?? resolvePgPoolMax();\n\tif (organizationId) {\n\t\tconst entry = await acquireSharedLoginPool(options.url, dialect, max);\n\t\tif (entry.handle.dialect !== \"postgres\") {\n\t\t\tentry.refs = Math.max(0, entry.refs - 1);\n\t\t\tthrow new Error(\"Claim-scoped tenant access requires postgres\");\n\t\t}\n\t\treturn createClaimScopedHandle({\n\t\t\tpool: entry.handle.pool,\n\t\t\torganizationId\n\t\t});\n\t}\n\tif (role) {\n\t\tif (!options.searchPath?.trim()) throw new Error(\"Shared-login tenant access requires role and searchPath\");\n\t\tconst entry = await acquireSharedLoginPool(options.url, dialect, max);\n\t\tif (entry.handle.dialect !== \"postgres\") {\n\t\t\tentry.refs = Math.max(0, entry.refs - 1);\n\t\t\tthrow new Error(\"Shared-login tenant access requires postgres\");\n\t\t}\n\t\treturn createOrgScopedHandle({\n\t\t\tpool: entry.handle.pool,\n\t\t\trole,\n\t\t\tsearchPath: options.searchPath\n\t\t});\n\t}\n\tconst key = orgLoginPoolCacheKey(options.url, searchPath, max);\n\tlet entry = cache.get(key);\n\tif (!entry) {\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 max = options.max ?? resolvePgPoolMax();\n\tconst organizationId = options.organizationId?.trim();\n\tconst role = options.role?.trim();\n\tconst key = organizationId || role ? sharedPoolCacheKey(options.url, max) : orgLoginPoolCacheKey(options.url, resolveSearchPath(options.url, options.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/runtime/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/runtime/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 ensureDefaultOrganizationRow() {\n\tconst db = getDbFromContext();\n\tif ((await db.select({ id: organizationsSqlite.id }).from(organizationsSqlite).where(eq(organizationsSqlite.id, \"default\")).limit(1))[0]) return;\n\tconst now = /* @__PURE__ */ new Date();\n\tawait db.insert(organizationsSqlite).values({\n\t\tid: DEFAULT_STANDALONE_ORGANIZATION_ID,\n\t\tname: DEFAULT_STANDALONE_ORGANIZATION_NAME,\n\t\tslug: DEFAULT_STANDALONE_ORGANIZATION_SLUG,\n\t\tdbSchema: \"default\",\n\t\tdbUser: \"default\",\n\t\tdbPasswordCiphertext: \"unused\",\n\t\tcreatedAt: now,\n\t\tupdatedAt: now,\n\t\tverifiedAt: now\n\t});\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\tproxy: options.proxy\n\t});\n\tsetDatabaseHandle(next);\n\tif (options.migrate ?? true) {\n\t\tif (!options.proxy) await runMigrations(next, resolveMigrationsFolder(dialect, options.migrationsFolder));\n\t}\n\tif (next.dialect === \"sqlite\") {\n\t\tawait ensureDefaultOrganizationRow();\n\t\tbindOrganizationScope(DEFAULT_STANDALONE_ORGANIZATION_ID);\n\t} else if (options.proxy) {\n\t\tconst organizationId = process.env.ORGANIZATION_ID?.trim();\n\t\tif (organizationId) bindOrganizationScope(organizationId);\n\t}\n}\n//#endregion\n//#region src/runtime/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 organizationId = options.organizationId?.trim();\n\tconst poolOptions = {\n\t\turl: options.url,\n\t\tsearchPath: options.searchPath,\n\t\tmax: options.max,\n\t\torganizationId,\n\t\trole: options.role\n\t};\n\tconst run = async () => {\n\t\tconst handle = await acquireProjectDatabasePool(poolOptions);\n\t\tconst closeOnRelease = inferDialect(options.url) !== \"postgres\";\n\t\treturn runWithRequestDatabaseHandle(handle, async () => {\n\t\t\ttry {\n\t\t\t\treturn await fn();\n\t\t\t} finally {\n\t\t\t\tif (closeOnRelease) await handle.close();\n\t\t\t\telse releaseProjectDatabasePool(poolOptions);\n\t\t\t}\n\t\t});\n\t};\n\tif (organizationId) return runWithOrganizationScope(organizationId, run);\n\treturn run();\n}\n//#endregion\n//#region src/runtime/connection/pg/public-scoped-pool.ts\nconst PUBLIC_SEARCH_PATH = \"public\";\n/** Single multi-statement round trip: BEGIN + SET LOCAL search_path. */\nconst PUBLIC_SCOPE_BEGIN = `BEGIN; SET LOCAL search_path TO ${PUBLIC_SEARCH_PATH}`;\nfunction beginPublicScope(query) {\n\treturn query(PUBLIC_SCOPE_BEGIN);\n}\nfunction createPublicScopedClient(client) {\n\treturn scopeClient(client, beginPublicScope);\n}\nfunction createPublicScopedPool(pool) {\n\tconst scopedPool = Object.create(pool);\n\tscopedPool.query = ((...args) => runScopedQuery(pool, beginPublicScope, args));\n\tscopedPool.connect = ((callback) => {\n\t\tif (callback) {\n\t\t\tconnectWithRetryCallback(pool, (error, client) => {\n\t\t\t\tif (error || !client) {\n\t\t\t\t\tcallback(error ?? /* @__PURE__ */ new Error(\"failed to connect\"), client, () => void 0);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst scoped = createPublicScopedClient(client);\n\t\t\t\tcallback(null, scoped.client, scoped.release);\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\treturn connectWithRetry(pool).then((client) => createPublicScopedClient(client).client);\n\t});\n\treturn scopedPool;\n}\nfunction createPublicScopedHandle(options) {\n\tconst scopedPool = createPublicScopedPool(options.pool);\n\treturn {\n\t\tdialect: \"postgres\",\n\t\tdb: createPgDb(scopedPool),\n\t\tpool: scopedPool,\n\t\tsearchPath: PUBLIC_SEARCH_PATH,\n\t\tclose: async () => void 0\n\t};\n}\n//#endregion\n//#region src/runtime/queries/list-limit.ts\n/** Safety cap for unbounded account list queries (agents, workflows, skills, …). */\nconst DEFAULT_LIST_LIMIT = 200;\n//#endregion\n//#region src/runtime/queries/agents/list-active.ts\n/**\n* List every active agent in the current organization (all projects). Not project-scoped —\n* organization identity comes from ALS / signed claim.\n*/\nasync function listActiveAgents(options) {\n\tconst db = getDb();\n\tif (options?.projectIds !== void 0 && options.projectIds.length === 0) return [];\n\tconst conditions = [eqOrganizationScope(agents), isNull$1(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$1(agents.updatedAt), desc$1(agents.id)).limit(options?.limit ?? 200);\n}\n//#endregion\n//#region src/runtime/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$1(eq$1(workflowRuns.projectId, getProjectScopeId()), eq$1(triggerRuns.projectId, getProjectScopeId()), eq$1(agentSessions.projectId, getProjectScopeId()));\n}\n//#endregion\n//#region src/runtime/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$1(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$1(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$1(agents.deletedAt))).limit(1))[0];\n}\n//#endregion\n//#region src/runtime/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/runtime/queries/agents/write.ts\nasync function insertAgent(values) {\n\tawait getDb().insert(agents).values({\n\t\t...values,\n\t\torganizationId: organizationScopeId(),\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$1(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$1(agents.deletedAt), notInArray$1(agents.slug, slugs)));\n}\n//#endregion\n//#region src/runtime/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/runtime/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\torganizationId: organizationScopeId(),\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$1(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$1(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$1(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$1(agentSessions.deletedAt)));\n}\nasync function updateAgentSessionTitle(sessionId, title) {\n\tawait getDb().update(agentSessions).set({ title }).where(scopedAnd(agentSessions, eq$1(agentSessions.id, sessionId), isNull$1(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$1(agentSessions.deletedAt)));\n}\nfunction cursorBefore$2(cursor) {\n\treturn or$1(lt$1(agentSessions.updatedAt, cursor.updatedAt), and$1(eq$1(agentSessions.updatedAt, cursor.updatedAt), lt$1(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$1(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$1(agentSessions.updatedAt), desc$1(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}\n/**\n* Explicit session status write. Cancellation wins: once `canceled_at` is set,\n* a late `failed`/`completed` from the aborted run must not overwrite it.\n*/\nasync function updateAgentSessionStatus(sessionId, status) {\n\tawait getDb().update(agentSessions).set({ status }).where(scopedAnd(agentSessions, eq$1(agentSessions.id, sessionId), isNull$1(agentSessions.deletedAt), status === \"canceled\" || status === \"running\" ? void 0 : isNull$1(agentSessions.canceledAt)));\n}\nasync function cancelAgentSessionRow(sessionId, canceledAt) {\n\treturn (await getDb().update(agentSessions).set({\n\t\tcanceledAt,\n\t\tupdatedAt: canceledAt,\n\t\tstatus: \"canceled\"\n\t}).where(scopedAnd(agentSessions, eq$1(agentSessions.id, sessionId), isNull$1(agentSessions.deletedAt), isNull$1(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-prompt conversation, so a new prompt must not be blocked\n* (or perpetually shown as \"canceled\") just because an earlier prompt was canceled. No-ops\n* when the session was not canceled.\n*/\nasync function clearAgentSessionCancellation(sessionId) {\n\tawait getDb().update(agentSessions).set({\n\t\tcanceledAt: null,\n\t\tstatus: null\n\t}).where(scopedAnd(agentSessions, eq$1(agentSessions.id, sessionId), isNull$1(agentSessions.deletedAt), isNotNull(agentSessions.canceledAt)));\n}\n//#endregion\n//#region src/runtime/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$1(agentEvents.deletedAt))))[0]?.value ?? 0;\n}\nasync function insertAgentEvent(values) {\n\tawait getDb().insert(agentEvents).values({\n\t\t...values,\n\t\torganizationId: organizationScopeId()\n\t});\n}\nasync function listMessagePayloads(sessionId, messageEventType) {\n\treturn (await listMessageEventsForSession(sessionId, messageEventType)).map((row) => row.payload);\n}\nasync function listMessageEventsForSession(sessionId, messageEventType, afterSeq) {\n\treturn await getDb().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), ...afterSeq === void 0 ? [] : [gt$1(agentEvents.seq, afterSeq)], isNull$1(agentEvents.deletedAt))).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$1(agentEvents.deletedAt)));\n\treturn Number(rows[0]?.count ?? 0);\n}\n/** The highest-seq event of one of the given types, without scanning the full log. */\nasync function selectLatestAgentEventByTypes(sessionId, eventTypes) {\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), inArray$1(agentEvents.eventType, eventTypes), isNull$1(agentEvents.deletedAt))).orderBy(desc$1(agentEvents.seq)).limit(1))[0]?.event;\n}\nasync function hasAgentEventAfterSeq(sessionId, eventType, afterSeq) {\n\treturn (await getDb().select({ seq: agentEvents.seq }).from(agentEvents).innerJoin(agentSessions, eq$1(agentSessions.id, agentEvents.sessionId)).where(scopedAnd(agentSessions, eq$1(agentEvents.sessionId, sessionId), eq$1(agentEvents.eventType, eventType), gt$1(agentEvents.seq, afterSeq), isNull$1(agentEvents.deletedAt))).limit(1)).length > 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$1(agentEvents.deletedAt))).orderBy(asc(agentEvents.seq))).map((row) => row.event);\n}\n//#endregion\n//#region src/runtime/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\t...source.timezone ? { timezone: source.timezone } : {},\n\t\t...source.payload !== void 0 ? { payload: source.payload } : {}\n\t};\n\treturn {\n\t\tkind: \"poll\",\n\t\tslug,\n\t\tschedule: source.schedule,\n\t\t...source.timezone ? { timezone: source.timezone } : {},\n\t\t...source.code ? { code: source.code } : {},\n\t\t...source.id ? { id: source.id } : {}\n\t};\n}\n//#endregion\n//#region src/runtime/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\") {\n\t\tconst config = {\n\t\t\t...source.code ? { code: source.code } : {},\n\t\t\t...source.id ? { id: source.id } : {},\n\t\t\t...source.timezone ? { timezone: source.timezone } : {}\n\t\t};\n\t\treturn Object.keys(config).length > 0 ? config : null;\n\t}\n\tif (source.kind === \"cron\") {\n\t\tconst config = {\n\t\t\t...source.payload !== void 0 ? { payload: source.payload } : {},\n\t\t\t...source.timezone ? { timezone: source.timezone } : {}\n\t\t};\n\t\treturn Object.keys(config).length > 0 ? config : null;\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/** IANA timezone from a cron/poll source, or undefined when schedules evaluate in UTC. */\nfunction triggerTimezoneFromSource(source) {\n\tif (source.kind === \"cron\" || source.kind === \"poll\") return source.timezone;\n}\n/** IANA timezone stored on a trigger row's kind config, if any. */\nfunction triggerTimezoneFromConfig(config) {\n\tif (config && \"timezone\" in config && typeof config.timezone === \"string\") return config.timezone;\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\tconst meta = {\n\t\tname: trigger.name,\n\t\tdescription: trigger.description\n\t};\n\tif (trigger.kind === \"webhook\") {\n\t\tconst config = trigger.config ?? {};\n\t\treturn {\n\t\t\t...meta,\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\") {\n\t\tconst config = trigger.config ?? null;\n\t\treturn {\n\t\t\t...meta,\n\t\t\tkind: \"cron\",\n\t\t\tslug: trigger.slug,\n\t\t\tschedule: trigger.schedule ?? \"\",\n\t\t\t...config?.timezone ? { timezone: config.timezone } : {},\n\t\t\t...config?.payload !== void 0 ? { payload: config.payload } : {}\n\t\t};\n\t}\n\tconst config = trigger.config ?? {};\n\treturn {\n\t\t...meta,\n\t\tkind: \"poll\",\n\t\tslug: trigger.slug,\n\t\tschedule: trigger.schedule ?? \"\",\n\t\t...config.timezone ? { timezone: config.timezone } : {},\n\t\t...config.code ? { code: config.code } : {},\n\t\t...config.id ? { id: config.id } : {}\n\t};\n}\n//#endregion\n//#region src/runtime/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}\n/** Active project trigger by id across the org schema (no project-scope filter). */\nasync function selectActiveTriggerById(id) {\n\treturn (await getDb().select().from(triggers).where(and$1(eq$1(triggers.id, id), isNull$1(triggers.deletedAt), eq$1(triggers.origin, \"project\"))).limit(1))[0];\n}\nasync function insertTrigger(values) {\n\tawait getDb().insert(triggers).values({\n\t\t...values,\n\t\torganizationId: organizationScopeId(),\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 updateTriggerState(id, state, now = /* @__PURE__ */ new Date()) {\n\tawait getDb().update(triggers).set({\n\t\tstate,\n\t\tupdatedAt: now\n\t}).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$1(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$1(triggers.deletedAt), eq$1(triggers.origin, \"project\"), notInArray$1(triggers.slug, slugs)));\n}\nasync function listActiveTriggersByProjectIds(projectIds, options) {\n\tconst db = getDb();\n\tif (projectIds !== void 0 && projectIds.length === 0) return [];\n\tconst conditions = [\n\t\teqOrganizationScope(triggers),\n\t\tisNull$1(triggers.deletedAt),\n\t\teq$1(triggers.origin, \"project\")\n\t];\n\tif (projectIds !== void 0) conditions.push(inArray$1(triggers.projectId, projectIds));\n\tconst query = db.select().from(triggers).where(and$1(...conditions)).orderBy(asc(triggers.registeredAt), asc(triggers.id));\n\tif (options?.limit !== void 0) return query.limit(options.limit);\n\treturn query;\n}\nasync function listActiveEphemeralTriggers() {\n\treturn getDb().select().from(triggers).where(scopedAnd(triggers, isNull$1(triggers.deletedAt), eq$1(triggers.origin, \"ephemeral\")));\n}\nasync function selectWebhookTriggers() {\n\treturn (await getDb().select().from(triggers).where(scopedAnd(triggers, isNull$1(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$1(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$1(triggers.deletedAt))).orderBy(asc(triggers.slug));\n}\nasync function claimDueTriggers(now, resolveNextRunAt, limit = 10) {\n\tconst db = getDb();\n\tif (getDatabaseHandle().dialect === \"postgres\") {\n\t\tconst due = await db.select().from(triggers).where(scopedAnd(triggers, eq$1(triggers.enabled, 1), inArray$1(triggers.kind, [\"cron\", \"poll\"]), isNull$1(triggers.deletedAt), lte$1(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, triggerTimezoneFromConfig(row.config));\n\t\t\tconst [updated] = await db.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$1(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$1(triggers.deletedAt), lte$1(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, triggerTimezoneFromConfig(row.config));\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$1(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\") {\n\t\tconst due = await db.select().from(triggers).where(and$1(eqOrganizationScope(triggers), eq$1(triggers.enabled, 1), inArray$1(triggers.kind, [\"cron\", \"poll\"]), isNull$1(triggers.deletedAt), lte$1(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, triggerTimezoneFromConfig(row.config));\n\t\t\tconst [updated] = await db.update(triggers).set({\n\t\t\t\tnextRunAt,\n\t\t\t\tupdatedAt: now\n\t\t\t}).where(and$1(eqOrganizationScope(triggers), eq$1(triggers.id, row.id), eq$1(triggers.projectId, row.projectId), lte$1(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(eqOrganizationScope(triggers), eq$1(triggers.enabled, 1), inArray$1(triggers.kind, [\"cron\", \"poll\"]), isNull$1(triggers.deletedAt), lte$1(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, triggerTimezoneFromConfig(row.config));\n\t\tawait db.update(triggers).set({\n\t\t\tnextRunAt,\n\t\t\tupdatedAt: now\n\t\t}).where(and$1(eqOrganizationScope(triggers), eq$1(triggers.id, row.id), eq$1(triggers.projectId, row.projectId), lte$1(triggers.nextRunAt, now)));\n\t\tconst trigger = (await db.select().from(triggers).where(and$1(eqOrganizationScope(triggers), 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/runtime/queries/trigger-attachments/helpers.ts\n/** Non-deleted and not user-disabled — eligible for trigger execution. */\nfunction isTriggerAttachmentExecutable(row) {\n\treturn row.deletedAt === null && row.disabledAt === null;\n}\nfunction triggerAttachmentStatusFromRow(row) {\n\tif (row.deletedAt !== null || row.disabledAt !== null) return \"disabled\";\n\treturn \"active\";\n}\n//#endregion\n//#region src/runtime/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\torganizationId: organizationScopeId(),\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 setTriggerAttachmentEnabled(id, enabled, now = /* @__PURE__ */ new Date()) {\n\tawait updateTriggerAttachmentById(id, {\n\t\tdisabledAt: enabled ? null : now,\n\t\tupdatedAt: now\n\t});\n}\nasync function softDeleteAllTriggerAttachments(now) {\n\tconst db = getDb();\n\tconst { triggers } = await import(\"../sanitize-message-JfOafIe_.mjs\").then((n) => n.w);\n\tconst ids = (await db.select({ id: triggers.id }).from(triggers).where(scopedAnd(triggers, isNull$1(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$1(triggerAttachments.deletedAt), inArray$1(triggerAttachments.triggerId, ids)));\n}\nasync function softDeleteTriggerAttachmentsNotInSlugs(slugs, now) {\n\tconst db = getDb();\n\tconst { triggers } = await import(\"../sanitize-message-JfOafIe_.mjs\").then((n) => n.w);\n\tconst projectTriggerIds = (await db.select({ id: triggers.id }).from(triggers).where(scopedAnd(triggers, isNull$1(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$1(triggerAttachments.deletedAt), notInArray$1(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 import(\"../sanitize-message-JfOafIe_.mjs\").then((n) => n.w);\n\treturn (await db.select({ attachment: triggerAttachments }).from(triggerAttachments).innerJoin(triggers, eq$1(triggerAttachments.triggerId, triggers.id)).where(scopedAnd(triggerAttachments, isNull$1(triggerAttachments.deletedAt), isNull$1(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(eqOrganizationScope(triggerAttachments), isNull$1(triggerAttachments.deletedAt), inArray$1(triggerAttachments.triggerId, triggerIds)));\n}\n/** Non-deleted attachments that are not user-disabled — for trigger execution. */\nasync function listExecutableAttachmentsByTriggerIds(triggerIds) {\n\tif (triggerIds.length === 0) return [];\n\treturn getDb().select().from(triggerAttachments).where(and$1(eqOrganizationScope(triggerAttachments), isNull$1(triggerAttachments.deletedAt), isNull$1(triggerAttachments.disabledAt), inArray$1(triggerAttachments.triggerId, triggerIds)));\n}\nasync function selectEphemeralTriggerAttachmentsByAgentSlug(agentSlug) {\n\tconst db = getDb();\n\tconst { triggers } = await import(\"../sanitize-message-JfOafIe_.mjs\").then((n) => n.w);\n\treturn db.select({ attachment: triggerAttachments }).from(triggerAttachments).innerJoin(triggers, eq$1(triggerAttachments.triggerId, triggers.id)).where(scopedAnd(triggerAttachments, isNull$1(triggerAttachments.deletedAt), isNull$1(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$1(triggerAttachments.deletedAt), eq$1(triggerAttachments.agentSlug, agentSlug)));\n}\nasync function selectEphemeralTriggerAttachments() {\n\tconst db = getDb();\n\tconst { triggers } = await import(\"../sanitize-message-JfOafIe_.mjs\").then((n) => n.w);\n\treturn db.select({ attachment: triggerAttachments }).from(triggerAttachments).innerJoin(triggers, eq$1(triggerAttachments.triggerId, triggers.id)).where(scopedAnd(triggerAttachments, isNull$1(triggerAttachments.deletedAt), isNull$1(triggers.deletedAt), eq$1(triggers.origin, \"ephemeral\"))).then((rows) => rows.map((row) => row.attachment));\n}\n/** Slugs of non-deleted attachments that are user-disabled. */\nasync function selectDisabledAttachmentSlugs(slugs) {\n\tif (slugs.length === 0) return /* @__PURE__ */ new Set();\n\tconst rows = await getDb().select({ slug: triggerAttachments.slug }).from(triggerAttachments).where(scopedAnd(triggerAttachments, inArray$1(triggerAttachments.slug, slugs), isNull$1(triggerAttachments.deletedAt), isNotNull(triggerAttachments.disabledAt)));\n\treturn new Set(rows.map((row) => row.slug));\n}\n/** @deprecated Use selectWebhookTriggers + listAttachmentsByTriggerIds */\nasync function selectWebhookTriggerAttachments() {\n\tconst db = getDb();\n\tconst { triggers } = await import(\"../sanitize-message-JfOafIe_.mjs\").then((n) => n.w);\n\treturn db.select({ attachment: triggerAttachments }).from(triggerAttachments).innerJoin(triggers, eq$1(triggerAttachments.triggerId, triggers.id)).where(scopedAnd(triggerAttachments, isNull$1(triggerAttachments.deletedAt), isNull$1(triggers.deletedAt), eq$1(triggers.kind, \"webhook\"))).then((rows) => rows.map((row) => row.attachment));\n}\n//#endregion\n//#region src/runtime/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/runtime/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\tparentWorkflowRunId: row.parentWorkflowRunId ?? 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\tinput: stepCompletedInput(row.data),\n\t\toutput: stepCompletedOutput(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/runtime/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\tcredentialContext: values.credentialContext ?? null,\n\t\torganizationId: organizationScopeId(),\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$1(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$1(workflowRuns.status, \"canceled\")));\n}\nconst CANCELABLE_WORKFLOW_STATUSES = [\n\t\"pending\",\n\t\"running\",\n\t\"sleeping\",\n\t\"waiting_hook\",\n\t\"waiting_children\"\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 listWorkflowRunsByParentRunIds(parentRunIds) {\n\tif (parentRunIds.length === 0) return /* @__PURE__ */ new Map();\n\tconst rows = await getDb().select().from(workflowRuns).where(scopedAnd(workflowRuns, inArray$1(workflowRuns.parentWorkflowRunId, parentRunIds)));\n\tconst byParentRunId = /* @__PURE__ */ new Map();\n\tfor (const row of rows) if (row.parentWorkflowRunId) {\n\t\tconst bucket = byParentRunId.get(row.parentWorkflowRunId) ?? [];\n\t\tbucket.push(row);\n\t\tbyParentRunId.set(row.parentWorkflowRunId, bucket);\n\t}\n\treturn byParentRunId;\n}\nasync function listWorkflowRunsBySourceIds(options) {\n\tif (options.sourceIds.length === 0) return /* @__PURE__ */ new Map();\n\tconst rows = await getDb().select().from(workflowRuns).where(scopedAnd(workflowRuns, eq$1(workflowRuns.sourceKind, options.sourceKind), inArray$1(workflowRuns.sourceId, options.sourceIds)));\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 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$1(lt$1(workflowRuns.triggeredAt, cursor.triggeredAt), and$1(eq$1(workflowRuns.triggeredAt, cursor.triggeredAt), lt$1(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$1(workflowRuns.triggeredAt), desc$1(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/runtime/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 organizationId = organizationScopeId();\n\tconst projectId = projectScopeId();\n\tconst createdAt = /* @__PURE__ */ new Date();\n\tfor (let attempt = 0; attempt < 64; attempt += 1) {\n\t\tconst seq = await selectMaxEventSeq(values.runId) + 1;\n\t\tif ((await db.insert(workflowEvents).values({\n\t\t\tid,\n\t\t\trunId: values.runId,\n\t\t\torganizationId,\n\t\t\tprojectId,\n\t\t\tseq,\n\t\t\ttype: values.type,\n\t\t\tcorrelationId: values.correlationId ?? null,\n\t\t\tdata: values.data ?? null,\n\t\t\tcreatedAt\n\t\t}).onConflictDoNothing().returning({ id: workflowEvents.id })).length > 0) return true;\n\t\tif ((await db.select({ id: workflowEvents.id }).from(workflowEvents).where(scopedAnd(workflowEvents, eq$1(workflowEvents.id, id)))).length > 0) return false;\n\t}\n\tthrow new Error(\"Failed to allocate a workflow event sequence after concurrent appends\");\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/** `child_dispatched` events for parent→child linking in run detail. */\nasync function listChildDispatchedEvents(runId) {\n\treturn getDb().select().from(workflowEvents).where(scopedAnd(workflowEvents, eq$1(workflowEvents.runId, runId), eq$1(workflowEvents.type, \"child_dispatched\"))).orderBy(asc(workflowEvents.seq));\n}\n//#endregion\n//#region src/runtime/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\torganizationId: organizationScopeId(),\n\t\tprojectId: projectScopeId(),\n\t\ttoken: values.token,\n\t\tcorrelationId: values.correlationId,\n\t\tstatus: \"waiting\",\n\t\tschema: values.schema ?? null,\n\t\tpayload: values.payload ?? null,\n\t\tcreatedAt: /* @__PURE__ */ new Date(),\n\t\tresumedAt: null\n\t}).onConflictDoNothing({ target: workflowHooks.token });\n}\n/** Hooks for a run (newest-creation last), optionally filtered by status. */\nasync function listWorkflowHooksByRun(runId, options) {\n\tconst db = getDb();\n\tconst conditions = [eq$1(workflowHooks.runId, runId)];\n\tif (options?.status) conditions.push(eq$1(workflowHooks.status, options.status));\n\treturn db.select().from(workflowHooks).where(scopedAnd(workflowHooks, ...conditions)).orderBy(asc(workflowHooks.createdAt));\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/runtime/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/runtime/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/runtime/queries/trigger-runs/prune-skipped-webhook.ts\n/** Skipped webhook delivery rows are retained for debugging, then pruned. */\nconst SKIPPED_WEBHOOK_TRIGGER_RUN_RETENTION_MS = 10080 * 60 * 1e3;\nconst DEFAULT_PRUNE_LIMIT = 100;\n/**\n* ponytail: opportunistic prune on skipped-row insert — upgrade to a scheduled job if\n* skipped volume grows beyond what insert-path cleanup can keep up with.\n*/\nasync function pruneSkippedWebhookTriggerRuns(options) {\n\tconst cutoff = options?.olderThan ?? /* @__PURE__ */ new Date(Date.now() - 6048e5);\n\tconst limit = options?.limit ?? DEFAULT_PRUNE_LIMIT;\n\tconst db = getDb();\n\tconst rows = await db.select({ id: triggerRuns.id }).from(triggerRuns).where(scopedAnd(triggerRuns, eq$1(triggerRuns.outcome, \"skipped\"), eq$1(triggerRuns.triggerType, \"webhook\"), lt$1(triggerRuns.triggeredAt, cutoff))).limit(limit);\n\tif (rows.length === 0) return 0;\n\tconst ids = rows.map((row) => row.id);\n\tawait db.delete(triggerRuns).where(scopedAnd(triggerRuns, inArray$1(triggerRuns.id, ids)));\n\treturn ids.length;\n}\n//#endregion\n//#region src/runtime/queries/trigger-runs/index.ts\n/**\n* Insert a trigger fire row. Idempotent on `id` so queue retries after a successful\n* fire record (then a later throw) do not fail on duplicate primary key.\n* @returns true when a new row was inserted, false when the id already existed.\n*/\nasync function insertTriggerRun(values) {\n\treturn (await 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\torganizationId: organizationScopeId(),\n\t\tprojectId: projectScopeId()\n\t}).onConflictDoNothing({ target: triggerRuns.id }).returning({ id: triggerRuns.id })).length > 0;\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$1(lt$1(triggerRuns.triggeredAt, cursor.triggeredAt), and$1(eq$1(triggerRuns.triggeredAt, cursor.triggeredAt), lt$1(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.outcome) conditions.push(eq$1(triggerRuns.outcome, options.outcome));\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$1(triggerRuns.triggeredAt), desc$1(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$1()\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/runtime/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\torganizationId: organizationScopeId(),\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$1(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 rowsFromResult(await db.execute(sql$1`\n      UPDATE jobs\n      SET\n        status = 'leased',\n        leased_by = ${workerId},\n        lease_expires_at = ${leaseExpiresAt}\n      WHERE id = (\n        SELECT id\n        FROM jobs\n        WHERE project_id = ${projectScopeId()}\n          AND status = 'pending'\n          AND scheduled_at <= ${now}\n        ORDER BY scheduled_at ASC\n        FOR UPDATE SKIP LOCKED\n        LIMIT 1\n      )\n      RETURNING\n        id,\n        project_id AS \"projectId\",\n        kind,\n        target_id AS \"targetId\",\n        run_id AS \"runId\",\n        trigger,\n        payload,\n        parent,\n        status,\n        scheduled_at AS \"scheduledAt\",\n        attempt,\n        max_attempts AS \"maxAttempts\",\n        leased_by AS \"leasedBy\",\n        lease_expires_at AS \"leaseExpiresAt\",\n        completed_at AS \"completedAt\",\n        error\n    `))[0];\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$1(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/runtime/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 selectGatewayAttachmentsByIds([id])).get(id);\n}\nasync function selectGatewayAttachmentsByIds(ids) {\n\tif (ids.length === 0) return /* @__PURE__ */ new Map();\n\tconst rows = await getDb().select().from(gatewayAttachments).where(scopedAnd(gatewayAttachments, inArray$1(gatewayAttachments.id, ids)));\n\treturn new Map(rows.map((row) => [row.id, row]));\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/** Org-scoped (project-unscoped) active binding — enforces org-unique channel ownership. */\nasync function getActiveOrgGatewayAttachmentByChannel(platform, channelId) {\n\treturn (await getDb().select().from(gatewayAttachments).where(and$1(eq$1(gatewayAttachments.organizationId, organizationScopeId()), eq$1(gatewayAttachments.platform, platform), eq$1(gatewayAttachments.channelId, channelId), isNull$1(gatewayAttachments.deletedAt))).limit(1))[0];\n}\n/** Org-scoped binding for a Slack workspace channel (used for multi-install routing). */\nasync function getActiveOrgGatewayAttachmentByTeamAndChannel(platform, teamId, channelId) {\n\treturn (await getDb().select().from(gatewayAttachments).where(and$1(eq$1(gatewayAttachments.organizationId, organizationScopeId()), eq$1(gatewayAttachments.platform, platform), eq$1(gatewayAttachments.teamId, teamId), eq$1(gatewayAttachments.channelId, channelId), isNull$1(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$1(gatewayAttachments.deletedAt))).limit(1))[0];\n}\nasync function listActiveGatewayAttachments() {\n\treturn getDb().select().from(gatewayAttachments).where(scopedAnd(gatewayAttachments, isNull$1(gatewayAttachments.deletedAt)));\n}\n/**\n* Project-unscoped: every active attachment for a platform across all projects in the current org,\n* joined to its agent's registry id. Used by the platform ingress, which routes by channel before a\n* 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.organizationId, gatewayAttachments.organizationId), eq$1(agents.projectId, gatewayAttachments.projectId), eq$1(agents.slug, gatewayAttachments.agentSlug), isNull$1(agents.deletedAt))).where(and$1(eqOrganizationScope(gatewayAttachments), eq$1(gatewayAttachments.platform, platform), isNull$1(gatewayAttachments.deletedAt)));\n}\nasync function listActiveGatewayAttachmentsByAgentSlug(agentSlug) {\n\treturn getDb().select().from(gatewayAttachments).where(scopedAnd(gatewayAttachments, eq$1(gatewayAttachments.agentSlug, agentSlug), isNull$1(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$1(gatewayAttachments.deletedAt)));\n}\nasync function insertGatewayAttachment(values) {\n\tawait getDb().insert(gatewayAttachments).values({\n\t\t...values,\n\t\torganizationId: organizationScopeId(),\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/runtime/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 selectGatewayThreadSessionsBySessionIds([sessionId])).get(sessionId);\n}\nasync function selectGatewayThreadSessionsBySessionIds(sessionIds) {\n\tif (sessionIds.length === 0) return /* @__PURE__ */ new Map();\n\tconst rows = await getDb().select({ session: gatewayThreadSessions }).from(gatewayThreadSessions).innerJoin(gatewayAttachments, eq$1(gatewayAttachments.id, gatewayThreadSessions.attachmentId)).where(scopedAnd(gatewayAttachments, inArray$1(gatewayThreadSessions.sessionId, sessionIds)));\n\treturn new Map(rows.map((row) => [row.session.sessionId, row.session]));\n}\nasync function upsertGatewayThreadSession(values) {\n\tawait getDb().insert(gatewayThreadSessions).values({\n\t\t...values,\n\t\torganizationId: organizationScopeId()\n\t}).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/runtime/queries/workflows/list-active.ts\n/**\n* List every active workflow in the current organization (all projects). Not project-scoped —\n* organization identity comes from ALS / signed claim.\n*/\nasync function listActiveWorkflows(options) {\n\tconst db = getDb();\n\tif (options?.projectIds !== void 0 && options.projectIds.length === 0) return [];\n\tconst conditions = [eqOrganizationScope(workflows), isNull$1(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$1(workflows.updatedAt), desc$1(workflows.id)).limit(options?.limit ?? 200);\n}\n//#endregion\n//#region src/runtime/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$1(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$1(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$1(workflows.deletedAt))).limit(1))[0];\n}\n//#endregion\n//#region src/runtime/queries/workflows/write.ts\nasync function insertWorkflow(values) {\n\tawait getDb().insert(workflows).values({\n\t\t...values,\n\t\torganizationId: organizationScopeId(),\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\trequestSchema: values.requestSchema,\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$1(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$1(workflows.deletedAt), notInArray$1(workflows.slug, slugs)));\n}\n//#endregion\n//#region src/runtime/queries/workflows/run-inputs.ts\nasync function selectWorkflowRunInputValues(workflowId) {\n\treturn (await getDb().select({ runInputValues: workflows.runInputValues }).from(workflows).where(scopedAnd(workflows, eq$1(workflows.id, workflowId))).limit(1))[0]?.runInputValues ?? null;\n}\nasync function updateWorkflowRunInputValues(workflowId, values) {\n\tawait getDb().update(workflows).set({\n\t\trunInputValues: values,\n\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t}).where(scopedAnd(workflows, eq$1(workflows.id, workflowId)));\n}\n//#endregion\n//#region src/runtime/queries/workflows/canvas-annotations.ts\nasync function selectWorkflowCanvasAnnotations(workflowId) {\n\tconst row = (await getDb().select({\n\t\tstatus: workflows.canvasAnnotationsStatus,\n\t\thash: workflows.canvasAnnotationsHash,\n\t\tmodel: workflows.canvasAnnotationsModel,\n\t\tannotations: workflows.canvasAnnotationsJson,\n\t\tgeneratedAt: workflows.canvasAnnotationsGeneratedAt\n\t}).from(workflows).where(scopedAnd(workflows, eq$1(workflows.id, workflowId))).limit(1))[0];\n\tif (!row) return;\n\treturn {\n\t\tstatus: row.status,\n\t\thash: row.hash ?? null,\n\t\tmodel: row.model ?? null,\n\t\tannotations: row.annotations ?? null,\n\t\tgeneratedAt: row.generatedAt ?? null\n\t};\n}\nasync function setWorkflowCanvasAnnotationsGenerating(workflowId, hash, now = /* @__PURE__ */ new Date()) {\n\tawait getDb().update(workflows).set({\n\t\tcanvasAnnotationsStatus: \"generating\",\n\t\tcanvasAnnotationsHash: hash,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(workflows, eq$1(workflows.id, workflowId)));\n}\nasync function updateWorkflowCanvasAnnotations(workflowId, values, now = /* @__PURE__ */ new Date()) {\n\tconst db = getDb();\n\tconst set = {\n\t\tcanvasAnnotationsStatus: values.status,\n\t\tupdatedAt: now\n\t};\n\tif (values.annotations !== void 0) {\n\t\tset.canvasAnnotationsJson = values.annotations;\n\t\tset.canvasAnnotationsGeneratedAt = now;\n\t}\n\tif (values.hash !== void 0) set.canvasAnnotationsHash = values.hash;\n\tif (values.model !== void 0) set.canvasAnnotationsModel = values.model;\n\tawait db.update(workflows).set(set).where(scopedAnd(workflows, eq$1(workflows.id, workflowId)));\n}\n//#endregion\n//#region src/runtime/queries/workflows/overview.ts\nasync function selectWorkflowOverview(workflowId) {\n\tconst row = (await getDb().select({\n\t\tstatus: workflows.overviewStatus,\n\t\tsummary: workflows.overviewSummary,\n\t\tphases: workflows.overviewPhasesJson,\n\t\thash: workflows.overviewHash,\n\t\tmodel: workflows.overviewModel,\n\t\tgeneratedAt: workflows.overviewGeneratedAt\n\t}).from(workflows).where(scopedAnd(workflows, eq$1(workflows.id, workflowId))).limit(1))[0];\n\tif (!row) return;\n\treturn {\n\t\tstatus: row.status,\n\t\tsummary: row.summary ?? null,\n\t\tphases: row.phases ?? null,\n\t\thash: row.hash ?? null,\n\t\tmodel: row.model ?? null,\n\t\tgeneratedAt: row.generatedAt ?? null\n\t};\n}\nasync function setWorkflowOverviewGenerating(workflowId, hash, now = /* @__PURE__ */ new Date()) {\n\tawait getDb().update(workflows).set({\n\t\toverviewStatus: \"generating\",\n\t\toverviewHash: hash,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(workflows, eq$1(workflows.id, workflowId)));\n}\nasync function updateWorkflowOverview(workflowId, 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.summary !== void 0) {\n\t\tset.overviewSummary = values.summary;\n\t\tset.overviewGeneratedAt = now;\n\t}\n\tif (values.phases !== void 0) set.overviewPhasesJson = values.phases;\n\tif (values.hash !== void 0) set.overviewHash = values.hash;\n\tif (values.model !== void 0) set.overviewModel = values.model;\n\tawait db.update(workflows).set(set).where(scopedAnd(workflows, eq$1(workflows.id, workflowId)));\n}\n//#endregion\n//#region src/runtime/queries/skills/list-active.ts\n/**\n* List every active skill in the current organization (all projects). Not project-scoped —\n* organization identity comes from ALS / signed claim.\n*/\nasync function listActiveSkills(options) {\n\tconst db = getDb();\n\tif (options?.projectIds !== void 0 && options.projectIds.length === 0) return [];\n\tconst conditions = [eqOrganizationScope(skills), isNull$1(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$1(skills.updatedAt), desc$1(skills.id)).limit(options?.limit ?? 200);\n}\n//#endregion\n//#region src/runtime/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 slug for the current project scope. */\nasync function selectActiveSkillsBySlugs(slugs) {\n\tif (slugs.length === 0) return [];\n\treturn getDb().select().from(skills).where(scopedAnd(skills, inArray$1(skills.slug, slugs), isNull$1(skills.deletedAt)));\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$1(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$1(skills.deletedAt))).limit(1))[0];\n}\n//#endregion\n//#region src/runtime/queries/skills/write.ts\nasync function insertSkill(values) {\n\tawait getDb().insert(skills).values({\n\t\t...values,\n\t\torganizationId: organizationScopeId(),\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$1(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$1(skills.deletedAt), notInArray$1(skills.slug, slugs)));\n}\n//#endregion\n//#region src/runtime/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\torganizationId: organizationScopeId(),\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/runtime/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\torganizationId: organizationScopeId(),\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$1(resourceActivity.lastOpenedAt)).limit(limit);\n}\n//#endregion\n//#region src/runtime/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/runtime/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$1(agents.deletedAt)];\n\tconst workflowConditions = [isNull$1(workflows.deletedAt)];\n\tconst skillConditions = [isNull$1(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$1()\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$1()\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$1()\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$1()\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/runtime/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}\n/**\n* Session status: the explicit `status` column when written, falling back to\n* trace-span derivation for rows that predate it. Cancellation always wins —\n* a cancel can land while the aborted run's own status writes are in flight.\n*\n* ponytail: the span fallback only exists for rows created before the status\n* column; once those are backfilled (or aged out), drop it and\n* `agentSessionStatusFromSpan` so the column is the single source of truth.\n*/\nfunction agentSessionStatusFromRow(row, span, messageCount) {\n\tif (row.canceledAt) return \"canceled\";\n\treturn row.status ?? agentSessionStatusFromSpan(span, messageCount, null);\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\ttitle: options.row.title ?? 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/runtime/agents/types.ts\nconst MESSAGE_EVENT_TYPE = \"message\";\n//#endregion\n//#region src/runtime/agents/compaction-events.ts\nconst CONTEXT_COMPACTED_EVENT_TYPE = \"context_compacted\";\n/** Sanitize a persisted `context_compacted` payload into the wire marker shape. */\nfunction compactionEventFromRow(event) {\n\tconst payload = typeof event.payload === \"object\" && event.payload !== null ? event.payload : null;\n\tconst checkpoint = payload && typeof payload.checkpoint === \"object\" && payload.checkpoint !== null ? payload.checkpoint : payload;\n\tif (!checkpoint || typeof checkpoint.compactionModel !== \"string\" || typeof checkpoint.sourceModel !== \"string\" || typeof checkpoint.durable !== \"boolean\") return null;\n\treturn {\n\t\tseq: event.seq,\n\t\tcreatedAt: event.createdAt.toISOString(),\n\t\tcompactionModel: checkpoint.compactionModel,\n\t\tsourceModel: checkpoint.sourceModel,\n\t\tdurable: checkpoint.durable,\n\t\t...typeof checkpoint.estimatedBeforeTokens === \"number\" ? { estimatedBeforeTokens: checkpoint.estimatedBeforeTokens } : {},\n\t\t...typeof checkpoint.retainedTailEstimate === \"number\" ? { retainedTailEstimate: checkpoint.retainedTailEstimate } : {}\n\t};\n}\n/**\n* Sanitized compaction markers for a session — an indexed lookup on\n* (session_id, event_type), never a full event-log scan.\n*/\nasync function listCompactionEventsForSession(sessionId) {\n\treturn (await listMessageEventsForSession(sessionId, CONTEXT_COMPACTED_EVENT_TYPE)).flatMap((row) => {\n\t\tconst event = compactionEventFromRow(row);\n\t\treturn event ? [event] : [];\n\t});\n}\n//#endregion\n//#region src/runtime/agents/prompt-finish-events.ts\nconst AGENT_END_EVENT_TYPE = \"agent_end\";\nfunction isAbnormalDiagnostics(diagnostics) {\n\treturn diagnostics.outcome !== \"completed\" || diagnostics.hitStepLimit;\n}\n/** Sanitize a persisted `agent_end` payload into a History prompt-finish marker. */\nfunction promptFinishEventFromRow(event) {\n\tconst payload = typeof event.payload === \"object\" && event.payload !== null ? event.payload : null;\n\tconst diagnostics = payload && typeof payload.diagnostics === \"object\" && payload.diagnostics !== null ? payload.diagnostics : null;\n\tif (!diagnostics || typeof diagnostics.outcome !== \"string\" || typeof diagnostics.stepCount !== \"number\" || typeof diagnostics.maxSteps !== \"number\" || typeof diagnostics.hitStepLimit !== \"boolean\" || !(diagnostics.finishReason === null || typeof diagnostics.finishReason === \"string\")) return null;\n\tif (!isAbnormalDiagnostics({\n\t\toutcome: diagnostics.outcome,\n\t\thitStepLimit: diagnostics.hitStepLimit\n\t})) return null;\n\tif (diagnostics.outcome !== \"completed\" && diagnostics.outcome !== \"error\" && diagnostics.outcome !== \"aborted\") return null;\n\tconst errorRaw = typeof diagnostics.error === \"object\" && diagnostics.error !== null ? diagnostics.error : null;\n\tconst error = errorRaw && typeof errorRaw.message === \"string\" ? {\n\t\tmessage: errorRaw.message,\n\t\t...typeof errorRaw.name === \"string\" ? { name: errorRaw.name } : {}\n\t} : void 0;\n\treturn {\n\t\tseq: event.seq,\n\t\tcreatedAt: event.createdAt.toISOString(),\n\t\t...typeof payload?.promptId === \"string\" ? { promptId: payload.promptId } : {},\n\t\toutcome: diagnostics.outcome,\n\t\tfinishReason: diagnostics.finishReason,\n\t\t...typeof diagnostics.rawFinishReason === \"string\" ? { rawFinishReason: diagnostics.rawFinishReason } : {},\n\t\tstepCount: diagnostics.stepCount,\n\t\tmaxSteps: diagnostics.maxSteps,\n\t\thitStepLimit: diagnostics.hitStepLimit,\n\t\t...error ? { error } : {}\n\t};\n}\n/**\n* Abnormal prompt-finish markers for a session — indexed lookup on\n* (session_id, event_type=agent_end), never a full event-log scan.\n*/\nasync function listPromptFinishEventsForSession(sessionId) {\n\treturn (await listMessageEventsForSession(sessionId, AGENT_END_EVENT_TYPE)).flatMap((row) => {\n\t\tconst event = promptFinishEventFromRow(row);\n\t\treturn event ? [event] : [];\n\t});\n}\n//#endregion\n//#region src/runtime/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$1(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}\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$1(agentSessions.deletedAt))).orderBy(desc$1(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/runtime/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/runtime/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/runtime/agents/session-api.ts\nasync function enrichSessionRows(rows) {\n\tconst sessionIds = rows.map((row) => row.id);\n\tconst triggerRunIds = rows.map((row) => row.sourceKind === \"trigger\" ? row.sourceId : null).filter((id) => Boolean(id));\n\tconst gatewayAttachmentIds = [...new Set(rows.map((row) => row.sourceKind === \"gateway\" ? row.sourceId : null).filter((id) => Boolean(id)))];\n\tconst [spansBySessionId, messageCounts, triggerTypes, gatewayAttachments] = await Promise.all([\n\t\tselectLatestAgentSessionSpansByRefIds(sessionIds),\n\t\tcountMessageEventsBySessionIds(sessionIds, MESSAGE_EVENT_TYPE),\n\t\tselectTriggerTypesByIds(triggerRunIds),\n\t\tselectGatewayAttachmentsByIds(gatewayAttachmentIds)\n\t]);\n\treturn rows.map((row) => {\n\t\tconst span = spansBySessionId.get(row.id);\n\t\tconst messageCount = messageCounts.get(row.id) ?? 0;\n\t\tconst gatewayPlatform = row.sourceKind === \"gateway\" && row.sourceId ? gatewayAttachments.get(row.sourceId)?.platform ?? null : null;\n\t\tconst triggerType = row.sourceKind === \"trigger\" && row.sourceId ? triggerTypes.get(row.sourceId) ?? null : null;\n\t\treturn {\n\t\t\trow,\n\t\t\tspan,\n\t\t\tmessageCount,\n\t\t\tstatus: agentSessionStatusFromRow(row, span, messageCount),\n\t\t\tgatewayPlatform,\n\t\t\ttriggerType\n\t\t};\n\t});\n}\nasync function buildAgentSessionSummaries(rows, options) {\n\tconst enriched = await enrichSessionRows(rows);\n\tconst userIds = [...new Set(enriched.map((entry) => entry.row.ranByUserId).filter((id) => Boolean(id) && Boolean(options?.resolveUserName)))];\n\tconst userNames = /* @__PURE__ */ new Map();\n\tif (options?.resolveUserName && userIds.length > 0) await Promise.all(userIds.map(async (userId) => {\n\t\tuserNames.set(userId, await options.resolveUserName(userId));\n\t}));\n\treturn enriched.map((entry) => agentSessionSummaryFromParts({\n\t\trow: entry.row,\n\t\tstatus: entry.status,\n\t\tmessageCount: entry.messageCount,\n\t\tgatewayPlatform: entry.gatewayPlatform,\n\t\ttriggerType: entry.triggerType,\n\t\tranByUserName: entry.row.ranByUserId ? userNames.get(entry.row.ranByUserId) ?? null : null\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\tconst summaries = await buildAgentSessionSummaries(page.rows, { resolveUserName: options.resolveUserName });\n\t\tfor (const summary of summaries) {\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 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\tconst [enrichedRows, gatewayThread, messages, compactionEvents, promptFinishEvents, events, traceData] = await Promise.all([\n\t\tenrichSessionRows([row]),\n\t\tincludeGateway ? selectGatewayThreadSessionBySessionId(row.id) : Promise.resolve(void 0),\n\t\tincludeMessages ? listMessageEventsForSession(row.id, MESSAGE_EVENT_TYPE).then((events) => events.map((event) => {\n\t\t\tconst payload = sanitizeMessagePayloadContext(event.payload);\n\t\t\treturn {\n\t\t\t\t...typeof payload === \"object\" && payload !== null && !Array.isArray(payload) ? payload : { value: payload },\n\t\t\t\tseq: event.seq\n\t\t\t};\n\t\t})) : Promise.resolve([]),\n\t\tincludeMessages ? listCompactionEventsForSession(row.id) : Promise.resolve([]),\n\t\tincludeMessages ? listPromptFinishEventsForSession(row.id) : Promise.resolve([]),\n\t\tincludeEvents ? listAgentEventsForSession(row.id).then((rows) => rows.map(agentEventFromRow)) : Promise.resolve([]),\n\t\tincludeTrace ? getTraceForAgentSession(row.id) : Promise.resolve(null)\n\t]);\n\tconst enriched = enrichedRows[0];\n\tlet gateway = null;\n\tif (includeGateway && gatewayThread) gateway = gatewaySessionDetailFromParts(gatewayThread, (await selectGatewayAttachmentById(gatewayThread.attachmentId))?.slug ?? null);\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\tcompactionEvents,\n\t\tpromptFinishEvents,\n\t\ttrace: traceData ? traceResponseToJson(traceData) : null\n\t};\n}\n//#endregion\n//#region src/runtime/workflows/run-detail.ts\n/** Max nested child-detail depth when `children` is in include (parent = 1, grandchild = 2). */\nconst MAX_CHILD_DETAIL_DEPTH = 2;\nfunction childDispatchData(data) {\n\tif (!data || typeof data !== \"object\") return {};\n\treturn data;\n}\nasync function loadTriggerDetail(row) {\n\tif (!row.triggerRunId) return null;\n\tconst triggerRun = await selectTriggerRunById(row.triggerRunId);\n\tif (!triggerRun) return null;\n\tlet attachmentSlug = null;\n\tif (row.attachmentId) attachmentSlug = (await selectTriggerAttachmentById(row.attachmentId))?.slug ?? null;\n\treturn triggerRunDetailFromRow(triggerRun, attachmentSlug);\n}\nasync function buildChildren(options) {\n\tconst events = await listChildDispatchedEvents(options.parentRunId);\n\tconst nestDetails = options.include.includes(\"children\") && options.nestDepth > 0;\n\tconst childInclude = options.include.filter((part) => part !== \"children\");\n\tif (nestDetails) childInclude.push(\"children\");\n\tconst children = [];\n\tfor (const event of events) {\n\t\tconst data = childDispatchData(event.data);\n\t\tconst correlationId = event.correlationId ?? event.id;\n\t\tif ((data.childKind === \"agent\" ? \"agent\" : \"workflow\") === \"agent\") {\n\t\t\tconst sessionId = data.childSessionId ?? data.childRunId;\n\t\t\tif (!sessionId) continue;\n\t\t\tconst session = await selectAgentSessionById(sessionId);\n\t\t\tconst agent = session ? await selectActiveAgentById(session.agentId) : void 0;\n\t\t\tconst link = {\n\t\t\t\tkind: \"agent\",\n\t\t\t\trunId: sessionId,\n\t\t\t\t...agent ? { agentSlug: agent.slug } : {},\n\t\t\t\tcorrelationId,\n\t\t\t\tstatus: session?.status ?? \"unknown\"\n\t\t\t};\n\t\t\tchildren.push(link);\n\t\t\tcontinue;\n\t\t}\n\t\tconst childRunId = data.childRunId;\n\t\tif (!childRunId) continue;\n\t\tif (nestDetails) {\n\t\t\tconst nested = await buildWorkflowRunDetail({\n\t\t\t\trunId: childRunId,\n\t\t\t\tinclude: childInclude,\n\t\t\t\tnestDepth: options.nestDepth - 1\n\t\t\t});\n\t\t\tif (nested) {\n\t\t\t\tchildren.push({\n\t\t\t\t\tkind: \"workflow\",\n\t\t\t\t\tcorrelationId,\n\t\t\t\t\trun: nested.run,\n\t\t\t\t\ttrigger: nested.trigger,\n\t\t\t\t\tsteps: nested.steps,\n\t\t\t\t\ttrace: nested.trace,\n\t\t\t\t\tchildren: nested.children,\n\t\t\t\t\thooks: nested.hooks\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tconst childRow = await selectWorkflowRunById(childRunId);\n\t\tconst link = {\n\t\t\tkind: \"workflow\",\n\t\t\trunId: childRunId,\n\t\t\t...childRow ? { workflowSlug: childRow.workflowSlug } : {},\n\t\t\tcorrelationId,\n\t\t\tstatus: childRow?.status ?? \"unknown\"\n\t\t};\n\t\tchildren.push(link);\n\t}\n\treturn children;\n}\n/**\n* Build a workflow run detail payload.\n* Pass `workflowSlug` to require the compound key; omit it for bare run-id lookup.\n*/\nasync function buildWorkflowRunDetail(options) {\n\tconst row = options.workflowSlug !== void 0 ? await selectWorkflowRunForWorkflow(options.workflowSlug, options.runId) : await selectWorkflowRunById(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\tconst nestDepth = options.nestDepth ?? (options.include.includes(\"children\") ? MAX_CHILD_DETAIL_DEPTH : 0);\n\tconst trigger = includeTrigger ? await loadTriggerDetail(row) : null;\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\tconst children = await buildChildren({\n\t\tparentRunId: row.id,\n\t\tinclude: options.include,\n\t\tnestDepth\n\t});\n\treturn {\n\t\trun: workflowRunRecordFromRow(row),\n\t\ttrigger,\n\t\tsteps,\n\t\ttrace,\n\t\tchildren,\n\t\thooks: []\n\t};\n}\n/** Resolve why a slug+runId lookup failed (for clearer CLI/API errors). */\nasync function explainMissingWorkflowRun(options) {\n\tconst byId = await selectWorkflowRunById(options.runId);\n\tif (byId) return `Workflow run not found for slug \"${options.workflowSlug}\". Found under workflow \"${byId.workflowSlug}\".`;\n\tif (await selectTriggerRunById(options.runId)) return \"Workflow run not found. That id looks like a trigger run — try: keystroke triggers runs get <triggerSlug> <runId>\";\n\treturn \"Workflow run not found\";\n}\n//#endregion\n//#region src/runtime/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}\n/**\n* Empty usage block for a `HistoryRunDetail` core. Usage lives in platform\n* `usage_events`; the platform history route overlays the real line items.\n*/\nfunction stubHistoryUsage(durationMs) {\n\treturn {\n\t\trunDurationMs: durationMs,\n\t\tlineItems: [],\n\t\ttotalBilledUsd: 0,\n\t\texternalProviderCostUsd: 0\n\t};\n}\n//#endregion\n//#region src/runtime/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/runtime/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\tparentWorkflowRunId: run.parentWorkflowRunId ?? null\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\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\tparentWorkflowRunId: detail.run.parentWorkflowRunId,\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: stubHistoryUsage(durationMs)\n\t};\n}\nasync function buildHistoryAgentSessionDetail(agentSlug, sessionId) {\n\tconst [detail, messageEvents, compactionEvents, promptFinishEvents] = await Promise.all([\n\t\tbuildAgentSessionDetail({\n\t\t\tagentSlug,\n\t\t\tsessionId,\n\t\t\tinclude: [\"gateway\", \"trace\"]\n\t\t}),\n\t\tlistMessageEventsForSession(sessionId, MESSAGE_EVENT_TYPE),\n\t\tlistCompactionEventsForSession(sessionId),\n\t\tlistPromptFinishEventsForSession(sessionId)\n\t]);\n\tif (!detail) return null;\n\tconst sanitizedMessageEvents = messageEvents.map((event) => ({\n\t\t...event,\n\t\tpayload: sanitizeMessagePayloadContext(event.payload)\n\t}));\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: sanitizedMessageEvents.map((event) => {\n\t\t\treturn {\n\t\t\t\t...typeof event.payload === \"object\" && event.payload !== null ? event.payload : { value: event.payload },\n\t\t\t\tseq: event.seq,\n\t\t\t\tsentAt: event.createdAt.toISOString()\n\t\t\t};\n\t\t}),\n\t\tcompactionEvents,\n\t\tpromptFinishEvents,\n\t\ttrace: detail.trace ? mapTrace(detail.trace, sanitizedMessageEvents) : null,\n\t\tusage: stubHistoryUsage(detail.session.totalDurationMs ?? null)\n\t};\n}\n//#endregion\n//#region src/runtime/queries/history/list-runs.ts\nasync function listWorkflowHistoryRuns(options, fetchLimit) {\n\tconst filter = options.projectIds !== void 0 ? { projectIds: options.projectIds } : void 0;\n\tconst conditions = [eqOrganizationScope(workflowRuns), ...historyProjectConditions(workflowRuns.projectId, filter)];\n\tif (filter?.projectIds !== void 0 && filter.projectIds.length === 0) return [];\n\tif (options.workflow) {\n\t\tconditions.push(eq$1(workflowRuns.projectId, options.workflow.projectId));\n\t\tconditions.push(eq$1(workflowRuns.workflowSlug, options.workflow.slug));\n\t}\n\tif (options.status) if (options.status === \"running\") conditions.push(inArray$1(workflowRuns.status, [\"running\", \"pending\"]));\n\telse conditions.push(eq$1(workflowRuns.status, options.status));\n\tconst rows = await getDb().select({\n\t\trun: workflowRuns,\n\t\tworkflow: workflows\n\t}).from(workflowRuns).leftJoin(workflows, and$1(eq$1(workflows.organizationId, workflowRuns.organizationId), eq$1(workflows.projectId, workflowRuns.projectId), eq$1(workflows.slug, workflowRuns.workflowSlug), isNull$1(workflows.deletedAt))).where(and$1(...conditions)).orderBy(desc$1(workflowRuns.triggeredAt), desc$1(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] = await Promise.all([countStepCompletedEventsByRunIds(runIds), selectTriggerTypesByIds(triggerRunIds)]);\n\treturn rows.map((row) => historyRunFromWorkflow({\n\t\trun: row.run,\n\t\tworkflow: row.workflow,\n\t\tstepCount: stepCounts.get(row.run.id) ?? 0,\n\t\ttriggerRaw: resolveWorkflowTriggerRaw(row.run, triggerTypes)\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 = [\n\t\teqOrganizationScope(agentSessions),\n\t\tisNull$1(agentSessions.deletedAt),\n\t\tisNull$1(agents.deletedAt)\n\t];\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, and$1(eq$1(agents.id, agentSessions.agentId), eq$1(agents.organizationId, agentSessions.organizationId))).where(and$1(...conditions)).orderBy(desc$1(agentSessions.updatedAt), desc$1(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] = await Promise.all([\n\t\tcountMessageEventsBySessionIds(sessionIds, MESSAGE_EVENT_TYPE),\n\t\tselectTriggerTypesByIds(triggerRunIds),\n\t\tselectLatestAgentSessionSpansByRefIds(sessionIds)\n\t]);\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\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});\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 workflowFetchLimit = limit;\n\tconst agentFetchLimit = options.status && options.kind !== \"workflow\" ? resolveFetchLimit(limit, options.status) : limit;\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(options, workflowFetchLimit) : Promise.resolve([]), includeAgents ? listAgentHistoryRuns(projectFilter, agentFetchLimit) : Promise.resolve([])]);\n\tlet items = sortHistoryRuns([...workflowItems, ...agentItems]);\n\tif (options.status && includeAgents) items = items.filter((item) => matchesStatusFilter(item.status, options.status));\n\treturn items.slice(0, limit);\n}\n//#endregion\n//#region src/runtime/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.organizationId, workflowRuns.organizationId), eq$1(workflows.projectId, workflowRuns.projectId), eq$1(workflows.slug, workflowRuns.workflowSlug), isNull$1(workflows.deletedAt))).where(and$1(eqOrganizationScope(workflowRuns), eq$1(workflowRuns.id, runId))).limit(1))[0];\n\tif (workflowRow) {\n\t\tconst [stepCount, triggerTypes] = await Promise.all([countStepCompletedEvents(workflowRow.run.id), selectTriggerTypesByIds(workflowRow.run.sourceKind === \"trigger\" && workflowRow.run.triggerRunId ? [workflowRow.run.triggerRunId] : [])]);\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});\n\t}\n\tconst agentRow = (await db.select({\n\t\tsession: agentSessions,\n\t\tagent: agents\n\t}).from(agentSessions).innerJoin(agents, and$1(eq$1(agents.id, agentSessions.agentId), eq$1(agents.organizationId, agentSessions.organizationId))).where(and$1(eqOrganizationScope(agentSessions), eq$1(agentSessions.id, runId), isNull$1(agentSessions.deletedAt), isNull$1(agents.deletedAt))).limit(1))[0];\n\tif (!agentRow) return null;\n\tconst sessionId = agentRow.session.id;\n\tconst [messageCounts, triggerTypes, spansBySessionId] = 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]);\n\tconst messageCount = messageCounts.get(sessionId) ?? 0;\n\tconst span = spansBySessionId.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});\n}\n//#endregion\n//#region src/runtime/queries/list-cursor.ts\nfunction encodeCreatedAtIdCursor(cursor) {\n\treturn Buffer.from(JSON.stringify({\n\t\tcreatedAt: cursor.createdAt.toISOString(),\n\t\tid: cursor.id\n\t})).toString(\"base64url\");\n}\nfunction decodeCreatedAtIdCursor(value) {\n\ttry {\n\t\tconst parsed = JSON.parse(Buffer.from(value, \"base64url\").toString(\"utf8\"));\n\t\tif (typeof parsed.createdAt !== \"string\" || typeof parsed.id !== \"string\") return null;\n\t\tconst createdAt = new Date(parsed.createdAt);\n\t\tif (Number.isNaN(createdAt.getTime())) return null;\n\t\treturn {\n\t\t\tcreatedAt,\n\t\t\tid: parsed.id\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\n//#endregion\n//#region src/runtime/queries/credential-instances/index.ts\n/** Org/user credentials live once per organization; project scope stays per-project. */\nfunction credentialScopeAnd(scopeType, ...conditions) {\n\tif (scopeType === \"project\") return scopedAnd(credentialInstances, eqOrganizationScope(credentialInstances), ...conditions);\n\treturn and$1(eqOrganizationScope(credentialInstances), ...conditions.filter(Boolean));\n}\nfunction resolveCredentialProjectId(scopeType) {\n\tif (scopeType === \"project\") return projectScopeId();\n\treturn getServerTenantScopeId();\n}\nfunction credentialVisibilityCondition(projectIds) {\n\tif (projectIds === void 0) return;\n\tif (projectIds.length === 0) return ne$1(credentialInstances.scopeType, \"project\");\n\treturn or$1(ne$1(credentialInstances.scopeType, \"project\"), inArray$1(credentialInstances.projectId, projectIds), inArray$1(credentialInstances.scopeId, projectIds));\n}\n/** Credential instances in the current organization, optionally narrowed to accessible projects. */\nasync function listAllCredentialInstances(options = {}) {\n\tconst db = getDb();\n\tconst limit = options.limit ?? 200;\n\tconst conditions = [eqOrganizationScope(credentialInstances)];\n\tconst visibility = credentialVisibilityCondition(options.projectIds);\n\tif (visibility) conditions.push(visibility);\n\tif (options.cursor) {\n\t\tconst decoded = decodeCreatedAtIdCursor(options.cursor);\n\t\tif (!decoded) throw new Error(\"Invalid cursor\");\n\t\tconditions.push(or$1(lt$1(credentialInstances.createdAt, decoded.createdAt), and$1(eq$1(credentialInstances.createdAt, decoded.createdAt), lt$1(credentialInstances.id, decoded.id))));\n\t}\n\tconst rows = await db.select().from(credentialInstances).where(and$1(...conditions)).orderBy(desc$1(credentialInstances.createdAt), desc$1(credentialInstances.id)).limit(limit + 1);\n\tconst hasMore = rows.length > limit;\n\tconst items = hasMore ? rows.slice(0, limit) : rows;\n\tconst last = items[items.length - 1];\n\treturn {\n\t\titems,\n\t\tnextCursor: hasMore && last ? encodeCreatedAtIdCursor({\n\t\t\tcreatedAt: last.createdAt,\n\t\t\tid: last.id\n\t\t}) : null\n\t};\n}\nasync function listCredentialInstancesByConnectionId(connectionId) {\n\treturn getDb().select().from(credentialInstances).where(and$1(eqOrganizationScope(credentialInstances), eq$1(credentialInstances.connectionId, connectionId)));\n}\nasync function selectCredentialInstanceById(id) {\n\treturn (await getDb().select().from(credentialInstances).where(and$1(eqOrganizationScope(credentialInstances), eq$1(credentialInstances.id, id))).limit(1))[0];\n}\n/**\n* Credentials for an app in the current organization.\n* When a project ALS is bound, include org/user rows plus that project's rows — not only\n* `projectId === ALS` (org/user rows store the tenant id in `projectId`).\n*/\nasync function selectCredentialInstancesByAppSlug(appSlug) {\n\tconst db = getDb();\n\tconst conditions = [eqOrganizationScope(credentialInstances), eq$1(credentialInstances.appSlug, appSlug)];\n\tconst boundProjectId = getBoundProjectScopeId();\n\tif (boundProjectId !== void 0) conditions.push(or$1(ne$1(credentialInstances.scopeType, \"project\"), eq$1(credentialInstances.projectId, boundProjectId), eq$1(credentialInstances.scopeId, boundProjectId)));\n\treturn db.select().from(credentialInstances).where(and$1(...conditions));\n}\nasync function listCredentialInstancesByScope(options) {\n\tconst db = getDb();\n\tconst conditions = [options.scopeId === null ? and$1(eq$1(credentialInstances.scopeType, options.scopeType), isNull$1(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$1(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}\n/** Batch fetch instances for many (appSlug, scopeType, scopeId) tuples in one query. */\nasync function selectCredentialInstancesForScopes(scopes) {\n\tif (scopes.length === 0) return [];\n\tconst db = getDb();\n\tconst conditions = scopes.map((scope) => and$1(eq$1(credentialInstances.appSlug, scope.appSlug), eq$1(credentialInstances.scopeType, scope.scopeType), eq$1(credentialInstances.scopeId, scope.scopeId)));\n\treturn db.select().from(credentialInstances).where(and$1(eqOrganizationScope(credentialInstances), or$1(...conditions)));\n}\nasync function selectCredentialInstancesByIds(ids) {\n\tif (ids.length === 0) return [];\n\treturn getDb().select().from(credentialInstances).where(and$1(eqOrganizationScope(credentialInstances), inArray$1(credentialInstances.id, ids)));\n}\nasync function insertCredentialInstance(values) {\n\tawait getDb().insert(credentialInstances).values({\n\t\t...values,\n\t\torganizationId: organizationScopeId(),\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\tprojectId: resolveCredentialProjectId(values.scopeType),\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(and$1(eqOrganizationScope(credentialInstances), 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(and$1(eqOrganizationScope(credentialInstances), eq$1(credentialInstances.id, id)));\n}\nasync function deleteCredentialInstanceById(id) {\n\tif (!await selectCredentialInstanceById(id)) return false;\n\tawait getDb().delete(credentialInstances).where(and$1(eqOrganizationScope(credentialInstances), 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$1(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$1(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/runtime/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\torganizationId: organizationScopeId(),\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/**\n* Strip the per-occurrence suffix from a step correlation id so a loop's\n* iterations collapse to one consumer: `step:<callSiteId>#3` → `step:<callSiteId>`.\n* Credential bindings are keyed by the occurrence-independent call-site id, the\n* same key the workflow-canvas credential overlay uses (one binding per node).\n*/\nfunction stepConsumerId(correlationId) {\n\tconst hash = correlationId.lastIndexOf(\"#\");\n\treturn hash === -1 ? correlationId : correlationId.slice(0, hash);\n}\n/**\n* Distinct occurrence-independent step consumer ids (`step:<callSiteId>`) from\n* recent completed workflow runs — the credential-assignment consumer keys.\n*/\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$1(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\tif (!event.correlationId) continue;\n\t\tconst id = stepConsumerId(event.correlationId);\n\t\tif (seen.has(id)) continue;\n\t\tseen.add(id);\n\t\tconsumers.push(id);\n\t}\n\treturn consumers;\n}\n//#endregion\n//#region src/runtime/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\torganizationId: organizationScopeId(),\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$1(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/runtime/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\torganizationId: organizationScopeId(),\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$1(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/runtime/queries/brains/filter-sql.ts\n/**\n* Compiles a Brain filter expression into SQL over `brain_documents` for the\n* document-table listing. This is the relational sibling of the Turbopuffer\n* filter compiler in `@keystroke-cloud/brain`; both are tested against the\n* shared conformance corpus (`BRAIN_FILTER_CONFORMANCE_CASES`) so their\n* semantics cannot drift.\n*\n* Semantics: entries AND; a scalar value equals a scalar attribute or is\n* contained by an array attribute; an array value is any-of over that rule.\n*/\nconst METADATA_KEY_REGEX = /^[a-zA-Z][a-zA-Z0-9_]{0,63}$/;\nfunction compileBrainFilterExpressionSql(filter, dialect) {\n\tconst conditions = [];\n\tif (filter.source !== void 0) {\n\t\tconst sources = Array.isArray(filter.source) ? filter.source : [filter.source];\n\t\tconditions.push(sources.length === 1 && sources[0] !== void 0 ? eq$1(brainDocuments.source, sources[0]) : inArray$1(brainDocuments.source, sources));\n\t}\n\tif (filter.metadata !== void 0) for (const [key, expected] of Object.entries(filter.metadata)) {\n\t\tif (!METADATA_KEY_REGEX.test(key)) throw new Error(`Invalid metadata filter key: ${key}`);\n\t\tconst condition = or$1(...(Array.isArray(expected) ? expected : [expected]).map((value) => metadataValueCondition(key, value, dialect)));\n\t\tif (condition) conditions.push(condition);\n\t}\n\treturn and$1(...conditions);\n}\nfunction metadataValueCondition(key, value, dialect) {\n\tif (dialect === \"pg\") {\n\t\tconst scalar = JSON.stringify({ [key]: value });\n\t\tconst array = JSON.stringify({ [key]: [value] });\n\t\treturn sql$1`(${brainDocuments.metadata} @> ${scalar}::jsonb OR ${brainDocuments.metadata} @> ${array}::jsonb)`;\n\t}\n\tconst path = `$.${key}`;\n\tconst bound = typeof value === \"boolean\" ? value ? 1 : 0 : value;\n\treturn sql$1`(\n    json_extract(${brainDocuments.metadata}, ${path}) = ${bound}\n    OR EXISTS (\n      SELECT 1 FROM json_each(\n        CASE\n          WHEN json_type(${brainDocuments.metadata}, ${path}) = 'array'\n          THEN json_extract(${brainDocuments.metadata}, ${path})\n          ELSE '[]'\n        END\n      ) AS filter_values\n      WHERE filter_values.value = ${bound}\n    )\n  )`;\n}\n//#endregion\n//#region src/runtime/queries/brains/index.ts\nfunction notDeletedBrain() {\n\treturn isNull$1(brains.deletedAt);\n}\nfunction notDeletedBrainDocument() {\n\treturn isNull$1(brainDocuments.deletedAt);\n}\nasync function selectBrainById(id) {\n\treturn (await getDb().select().from(brains).where(orgScopedAnd(brains, eq$1(brains.id, id), notDeletedBrain())).limit(1))[0];\n}\nasync function selectBrainByIdIncludingDeleted(id) {\n\treturn (await getDb().select().from(brains).where(orgScopedAnd(brains, eq$1(brains.id, id))).limit(1))[0];\n}\n/** Slugs are unique per organization; excludes Brains mid-delete. */\nasync function selectActiveBrainBySlug(slug) {\n\treturn (await getDb().select().from(brains).where(orgScopedAnd(brains, eq$1(brains.slug, slug), notDeletedBrain(), ne$1(brains.status, \"deleting\"))).limit(1))[0];\n}\n/**\n* Resolves a Brain by slug if the project holds a grant with at least the\n* requested access. `write` requires an explicit write grant; qualified\n* filter references authorize against the base Brain's grant (the caller\n* resolves the filter separately).\n*/\nasync function selectBrainAvailableToProject(slug, projectId, access = \"read\") {\n\treturn (await getDb().select().from(brains).where(orgScopedAnd(brains, eq$1(brains.slug, slug), notDeletedBrain(), ne$1(brains.status, \"deleting\"), inArray$1(brains.id, grantedBrainIdsSubquery(projectId, access)))).limit(1))[0];\n}\nasync function selectDeletingBrainAvailableToProject(id, slug, projectId) {\n\treturn (await getDb().select().from(brains).where(orgScopedAnd(brains, eq$1(brains.id, id), eq$1(brains.slug, slug), eq$1(brains.status, \"deleting\"), isNotNull(brains.deletedAt), inArray$1(brains.id, grantedBrainIdsSubquery(projectId, \"write\")))).limit(1))[0];\n}\nfunction grantedBrainIdsSubquery(projectId, access) {\n\treturn getDb().select({ brainId: brainGrants.brainId }).from(brainGrants).where(orgScopedAnd(brainGrants, eq$1(brainGrants.projectId, projectId), ...access === \"write\" ? [eq$1(brainGrants.access, \"write\")] : []));\n}\n/** Every Brain the project can read, ordered by slug. */\nasync function listBrainsForProject(projectId) {\n\treturn getDb().select().from(brains).where(orgScopedAnd(brains, notDeletedBrain(), inArray$1(brains.id, grantedBrainIdsSubquery(projectId, \"read\")))).orderBy(asc(brains.slug));\n}\nasync function updateBrain(input) {\n\treturn (await getDb().update(brains).set({\n\t\t...input.slug !== void 0 ? { slug: input.slug } : {},\n\t\t...input.name !== void 0 ? { name: input.name } : {},\n\t\t...input.description !== void 0 ? { description: input.description } : {},\n\t\t...input.indexConfig !== void 0 ? { indexConfig: input.indexConfig } : {},\n\t\tupdatedAt: input.now\n\t}).where(orgScopedAnd(brains, eq$1(brains.id, input.id), notDeletedBrain())).returning())[0];\n}\nasync function compareAndSetBrainStatus(input) {\n\treturn (await getDb().update(brains).set({\n\t\tstatus: input.nextStatus,\n\t\tupdatedAt: input.now\n\t}).where(orgScopedAnd(brains, eq$1(brains.id, input.id), inArray$1(brains.status, input.expectedStatuses), notDeletedBrain())).returning())[0];\n}\nasync function claimBrainRebuild(input) {\n\treturn (await getDb().update(brains).set({\n\t\tstatus: \"rebuilding\",\n\t\tpendingGeneration: input.pendingGeneration,\n\t\tpendingIndexConfig: input.pendingIndexConfig,\n\t\tpendingVectorDimensions: null,\n\t\tupdatedAt: input.now\n\t}).where(orgScopedAnd(brains, eq$1(brains.id, input.id), inArray$1(brains.status, [\"active\", \"rebuild_failed\"]), eq$1(brains.activeGeneration, input.expectedGeneration), eq$1(brains.mutationEpoch, input.expectedMutationEpoch), isNull$1(brains.pendingGeneration), notDeletedBrain())).returning())[0];\n}\nasync function claimBrainMutation(input) {\n\treturn (await getDb().update(brains).set({\n\t\tmutationEpoch: sql$1`${brains.mutationEpoch} + 1`,\n\t\tupdatedAt: input.now\n\t}).where(orgScopedAnd(brains, eq$1(brains.id, input.id), eq$1(brains.status, \"active\"), eq$1(brains.mutationEpoch, input.expectedMutationEpoch), notDeletedBrain())).returning())[0];\n}\nasync function abortBrainRebuild(input) {\n\treturn (await getDb().update(brains).set({\n\t\tstatus: \"rebuild_failed\",\n\t\tpendingGeneration: null,\n\t\tpendingIndexConfig: null,\n\t\tpendingVectorDimensions: null,\n\t\tupdatedAt: input.now\n\t}).where(orgScopedAnd(brains, eq$1(brains.id, input.id), eq$1(brains.status, \"rebuilding\"), eq$1(brains.pendingGeneration, input.pendingGeneration), notDeletedBrain())).returning())[0];\n}\n/** Rebuild cut-over: swaps the served namespace generation exactly once. */\nasync function compareAndSetBrainActiveGeneration(input) {\n\treturn (await getDb().update(brains).set({\n\t\tactiveGeneration: input.nextGeneration,\n\t\t...input.indexConfig !== void 0 ? { indexConfig: input.indexConfig } : {},\n\t\tactiveVectorDimensions: sql$1`${brains.pendingVectorDimensions}`,\n\t\tpendingGeneration: null,\n\t\tpendingIndexConfig: null,\n\t\tpendingVectorDimensions: null,\n\t\tupdatedAt: input.now\n\t}).where(orgScopedAnd(brains, eq$1(brains.id, input.id), eq$1(brains.activeGeneration, input.expectedGeneration), eq$1(brains.pendingGeneration, input.nextGeneration), eq$1(brains.status, \"rebuilding\"), notDeletedBrain())).returning())[0];\n}\n/**\n* Records the vector dimension observed for a generation exactly once (CAS on\n* null). Callers that lose the race must re-read the Brain and reject writes\n* whose dimension disagrees with the recorded value.\n*/\nasync function initializeBrainVectorDimensions(input) {\n\tconst db = getDb();\n\tconst active = await db.update(brains).set({\n\t\tactiveVectorDimensions: input.dimensions,\n\t\tupdatedAt: input.now\n\t}).where(orgScopedAnd(brains, eq$1(brains.id, input.id), eq$1(brains.activeGeneration, input.generation), isNull$1(brains.activeVectorDimensions), notDeletedBrain())).returning();\n\tif (active[0]) return active[0];\n\treturn (await db.update(brains).set({\n\t\tpendingVectorDimensions: input.dimensions,\n\t\tupdatedAt: input.now\n\t}).where(orgScopedAnd(brains, eq$1(brains.id, input.id), eq$1(brains.pendingGeneration, input.generation), isNull$1(brains.pendingVectorDimensions), notDeletedBrain())).returning())[0];\n}\nvar BrainRebuildCommitConflict = class extends Error {};\nfunction currentRebuildVersionsQuery(tx, input) {\n\treturn tx.select({ id: brainDocumentVersions.id }).from(brainDocuments).innerJoin(brainDocumentVersions, eq$1(brainDocumentVersions.id, brainDocuments.currentVersionId)).where(orgScopedAnd(brainDocuments, eq$1(brainDocuments.brainId, input.id), notDeletedBrainDocument(), eq$1(brainDocumentVersions.brainId, input.id), eq$1(brainDocumentVersions.status, \"ready\")));\n}\nfunction updateRebuildVersionQuery(tx, input, version) {\n\tconst currentVersionIds = tx.select({ id: brainDocuments.currentVersionId }).from(brainDocuments).where(orgScopedAnd(brainDocuments, eq$1(brainDocuments.brainId, input.id), eq$1(brainDocuments.currentVersionId, version.id), notDeletedBrainDocument()));\n\treturn tx.update(brainDocumentVersions).set({\n\t\tcanonicalObjectKey: version.canonicalObjectKey,\n\t\tcanonicalByteCount: version.canonicalByteCount,\n\t\tdetectedFormat: version.detectedFormat,\n\t\textractorVersion: version.extractorVersion,\n\t\tchunkerVersion: version.chunkerVersion,\n\t\tindexVersion: version.indexVersion,\n\t\tindexGeneration: version.indexGeneration,\n\t\tchunkCount: version.chunkCount,\n\t\tupdatedAt: input.now\n\t}).where(orgScopedAnd(brainDocumentVersions, eq$1(brainDocumentVersions.id, version.id), eq$1(brainDocumentVersions.brainId, input.id), eq$1(brainDocumentVersions.status, \"ready\"), inArray$1(brainDocumentVersions.id, currentVersionIds))).returning({ id: brainDocumentVersions.id });\n}\nfunction cutOverRebuiltBrainQuery(tx, input) {\n\treturn tx.update(brains).set({\n\t\tactiveGeneration: input.nextGeneration,\n\t\tindexConfig: input.indexConfig,\n\t\tstatus: \"active\",\n\t\tactiveVectorDimensions: sql$1`${brains.pendingVectorDimensions}`,\n\t\tpendingGeneration: null,\n\t\tpendingIndexConfig: null,\n\t\tpendingVectorDimensions: null,\n\t\tupdatedAt: input.now\n\t}).where(orgScopedAnd(brains, eq$1(brains.id, input.id), eq$1(brains.status, \"rebuilding\"), eq$1(brains.mutationEpoch, input.expectedMutationEpoch), eq$1(brains.activeGeneration, input.expectedGeneration), eq$1(brains.pendingGeneration, input.nextGeneration), eq$1(brains.pendingIndexConfig, input.indexConfig), notDeletedBrain())).returning({ id: brains.id });\n}\nfunction sqliteRows(query) {\n\treturn query.all();\n}\nfunction stagedVersionsAreCurrent(rows, input) {\n\tconst stagedIds = new Set(input.versions.map((version) => version.id));\n\treturn rows.length === stagedIds.size && rows.every((row) => stagedIds.has(row.id));\n}\n/**\n* Installs parser/chunker provenance only when every staged version is still\n* the live ready version and the Brain rebuild fence still matches.\n*/\nasync function commitBrainRebuild(input) {\n\tif (new Set(input.versions.map((version) => version.id)).size !== input.versions.length || input.versions.some((version) => version.indexGeneration !== input.nextGeneration)) return false;\n\tconst db = getDb();\n\tif (getDatabaseHandle().dialect === \"sqlite\") {\n\t\tconst transaction = db.transaction.bind(db);\n\t\ttry {\n\t\t\treturn transaction((tx) => {\n\t\t\t\tif (!stagedVersionsAreCurrent(sqliteRows(currentRebuildVersionsQuery(tx, input)), input)) throw new BrainRebuildCommitConflict();\n\t\t\t\tfor (const version of input.versions) if (sqliteRows(updateRebuildVersionQuery(tx, input, version)).length !== 1) throw new BrainRebuildCommitConflict();\n\t\t\t\tif (sqliteRows(cutOverRebuiltBrainQuery(tx, input)).length !== 1) throw new BrainRebuildCommitConflict();\n\t\t\t\treturn true;\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (error instanceof BrainRebuildCommitConflict) return false;\n\t\t\tthrow error;\n\t\t}\n\t}\n\tif (!stagedVersionsAreCurrent(await currentRebuildVersionsQuery(db, input), input)) return false;\n\tfor (const version of input.versions) if ((await updateRebuildVersionQuery(db, input, version)).length !== 1) return false;\n\treturn (await cutOverRebuiltBrainQuery(db, input)).length === 1;\n}\nasync function softDeleteBrain(id, now) {\n\treturn (await getDb().update(brains).set({\n\t\tstatus: \"deleting\",\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(orgScopedAnd(brains, eq$1(brains.id, id), notDeletedBrain())).returning())[0];\n}\n/** Compensates a failed delete-job enqueue so the Brain remains manageable. */\nasync function restoreSoftDeletedBrain(input) {\n\treturn (await getDb().update(brains).set({\n\t\tstatus: input.status,\n\t\tdeletedAt: null,\n\t\tupdatedAt: input.now\n\t}).where(orgScopedAnd(brains, eq$1(brains.id, input.id), eq$1(brains.status, \"deleting\"))).returning())[0];\n}\nasync function listDeletingBrains() {\n\treturn getDb().select().from(brains).where(orgScopedAnd(brains, eq$1(brains.status, \"deleting\")));\n}\n/** Final cleanup after the index namespace is dropped: removes all tenant rows. */\nasync function hardDeleteBrainTenantRows(brainId) {\n\tconst db = getDb();\n\tawait db.delete(brainDocumentWriteEvents).where(orgScopedAnd(brainDocumentWriteEvents, eq$1(brainDocumentWriteEvents.brainId, brainId)));\n\tawait db.update(brainDocuments).set({ currentVersionId: null }).where(orgScopedAnd(brainDocuments, eq$1(brainDocuments.brainId, brainId)));\n\tawait db.delete(brainDocumentVersions).where(orgScopedAnd(brainDocumentVersions, eq$1(brainDocumentVersions.brainId, brainId)));\n\tawait db.delete(brainDocuments).where(orgScopedAnd(brainDocuments, eq$1(brainDocuments.brainId, brainId)));\n\tawait db.delete(brainGrants).where(orgScopedAnd(brainGrants, eq$1(brainGrants.brainId, brainId)));\n\tawait db.delete(brainFilters).where(orgScopedAnd(brainFilters, eq$1(brainFilters.brainId, brainId)));\n\tawait db.delete(brainMembers).where(orgScopedAnd(brainMembers, eq$1(brainMembers.brainId, brainId)));\n\tawait db.delete(brains).where(orgScopedAnd(brains, eq$1(brains.id, brainId)));\n}\n/** Retains the deleted Brain tombstone while removing tenant content in FK-safe order. */\nasync function completeBrainDeletion(input) {\n\tconst db = getDb();\n\tconst complete = async (tx) => {\n\t\tif (!(await tx.select().from(brains).where(orgScopedAnd(brains, eq$1(brains.id, input.brainId), eq$1(brains.status, \"deleting\"), isNotNull(brains.deletedAt))).limit(1))[0]) return false;\n\t\tawait tx.delete(brainDocumentWriteEvents).where(orgScopedAnd(brainDocumentWriteEvents, eq$1(brainDocumentWriteEvents.brainId, input.brainId)));\n\t\tawait tx.update(brainDocuments).set({ currentVersionId: null }).where(orgScopedAnd(brainDocuments, eq$1(brainDocuments.brainId, input.brainId)));\n\t\tawait tx.delete(brainDocumentVersions).where(orgScopedAnd(brainDocumentVersions, eq$1(brainDocumentVersions.brainId, input.brainId)));\n\t\tawait tx.delete(brainDocuments).where(orgScopedAnd(brainDocuments, eq$1(brainDocuments.brainId, input.brainId)));\n\t\tawait tx.delete(brainGrants).where(orgScopedAnd(brainGrants, eq$1(brainGrants.brainId, input.brainId)));\n\t\tawait tx.delete(brainFilters).where(orgScopedAnd(brainFilters, eq$1(brainFilters.brainId, input.brainId)));\n\t\tawait tx.delete(brainMembers).where(orgScopedAnd(brainMembers, eq$1(brainMembers.brainId, input.brainId)));\n\t\tawait tx.update(brains).set({\n\t\t\tstatus: \"deleted\",\n\t\t\tupdatedAt: input.now\n\t\t}).where(orgScopedAnd(brains, eq$1(brains.id, input.brainId)));\n\t\treturn true;\n\t};\n\tif (getDatabaseHandle().dialect === \"sqlite\") return complete(db);\n\treturn db.transaction(complete);\n}\nasync function listBrainGrants(brainId) {\n\treturn getDb().select().from(brainGrants).where(orgScopedAnd(brainGrants, eq$1(brainGrants.brainId, brainId))).orderBy(asc(brainGrants.createdAt), asc(brainGrants.id));\n}\n/** Project-grant counts for a batch of Brains. */\nasync function countBrainProjectsByBrainIds(brainIds) {\n\tconst counts = new Map(brainIds.map((brainId) => [brainId, 0]));\n\tif (brainIds.length === 0) return counts;\n\tconst rows = await getDb().select({\n\t\tbrainId: brainGrants.brainId,\n\t\tvalue: count$1()\n\t}).from(brainGrants).where(orgScopedAnd(brainGrants, inArray$1(brainGrants.brainId, brainIds))).groupBy(brainGrants.brainId);\n\tfor (const row of rows) counts.set(row.brainId, row.value);\n\treturn counts;\n}\n/** Upserts on (brainId, projectId): re-granting the same project updates `access`. */\nasync function upsertBrainGrant(input) {\n\tconst db = getDb();\n\tconst existing = await db.select().from(brainGrants).where(orgScopedAnd(brainGrants, eq$1(brainGrants.brainId, input.brainId), eq$1(brainGrants.projectId, input.projectId))).limit(1);\n\tif (existing[0]) {\n\t\tif (existing[0].access === input.access) return existing[0];\n\t\tconst updated = (await db.update(brainGrants).set({ access: input.access }).where(orgScopedAnd(brainGrants, eq$1(brainGrants.id, existing[0].id))).returning())[0];\n\t\tif (!updated) throw new Error(\"Failed to update brain grant\");\n\t\treturn updated;\n\t}\n\tawait db.insert(brainGrants).values({\n\t\tid: input.id,\n\t\torganizationId: organizationScopeId(),\n\t\tbrainId: input.brainId,\n\t\tprojectId: input.projectId,\n\t\taccess: input.access,\n\t\tcreatedByUserId: input.createdByUserId,\n\t\tcreatedAt: input.now\n\t});\n\tconst grant = (await db.select().from(brainGrants).where(orgScopedAnd(brainGrants, eq$1(brainGrants.id, input.id))).limit(1))[0];\n\tif (!grant) throw new Error(\"Failed to create brain grant\");\n\treturn grant;\n}\n/** Grants are unique per (brainId, projectId), so the project is the removal key. */\nasync function removeBrainGrant(brainId, projectId) {\n\treturn (await getDb().delete(brainGrants).where(orgScopedAnd(brainGrants, eq$1(brainGrants.brainId, brainId), eq$1(brainGrants.projectId, projectId))).returning({ id: brainGrants.id })).length > 0;\n}\nvar BrainDocumentWriteIdempotencyConflictError = class extends Error {\n\tconstructor() {\n\t\tsuper(\"Brain document write idempotency key was reused with a different request\");\n\t\tthis.name = \"BrainDocumentWriteIdempotencyConflictError\";\n\t}\n};\nvar BrainDocumentRevisionConflictError = class extends Error {\n\tconstructor() {\n\t\tsuper(\"Brain document revision was reused with different content\");\n\t\tthis.name = \"BrainDocumentRevisionConflictError\";\n\t}\n};\nasync function selectBrainDocumentWriteEventById(id) {\n\treturn (await getDb().select().from(brainDocumentWriteEvents).where(orgScopedAnd(brainDocumentWriteEvents, eq$1(brainDocumentWriteEvents.id, id))).limit(1))[0];\n}\nasync function selectBrainDocumentWriteEventByIdentity(brainId, clientIdempotencyId) {\n\treturn (await getDb().select().from(brainDocumentWriteEvents).where(orgScopedAnd(brainDocumentWriteEvents, eq$1(brainDocumentWriteEvents.brainId, brainId), eq$1(brainDocumentWriteEvents.clientIdempotencyId, clientIdempotencyId))).limit(1))[0];\n}\n/**\n* Creates one retained event per logical write identity. Retries reselect the\n* existing immutable request; mismatched fingerprints are rejected.\n*/\nasync function beginBrainDocumentWriteEvent(input) {\n\tconst db = getDb();\n\tconst provisionerFields = input.provisioner.kind === \"workflow\" ? {\n\t\tprovisionerKind: input.provisioner.kind,\n\t\tprovisionerProjectId: input.provisioner.projectId,\n\t\tprovisionerWorkflowRunId: input.provisioner.workflowRunId,\n\t\tprovisionerWorkflowSlug: input.provisioner.workflowSlug,\n\t\tprovisionerCorrelationId: input.provisioner.correlationId,\n\t\tprovisionerManualUserId: null\n\t} : {\n\t\tprovisionerKind: input.provisioner.kind,\n\t\tprovisionerProjectId: null,\n\t\tprovisionerWorkflowRunId: null,\n\t\tprovisionerWorkflowSlug: null,\n\t\tprovisionerCorrelationId: null,\n\t\tprovisionerManualUserId: input.provisioner.userId\n\t};\n\tawait db.insert(brainDocumentWriteEvents).values({\n\t\tid: input.id,\n\t\torganizationId: organizationScopeId(),\n\t\tbrainId: input.brainId,\n\t\tdocumentRowId: null,\n\t\tdocumentId: input.documentId,\n\t\tclientIdempotencyId: input.clientIdempotencyId,\n\t\trequestFingerprint: input.requestFingerprint,\n\t\t...provisionerFields,\n\t\tversionId: null,\n\t\tinputKind: input.inputKind,\n\t\toutcome: null,\n\t\tfailureCode: null,\n\t\tfailureMessage: null,\n\t\tsubmittedAt: input.now,\n\t\tcontentReceivedAt: null,\n\t\tcompletedAt: null\n\t}).onConflictDoNothing({ target: [brainDocumentWriteEvents.brainId, brainDocumentWriteEvents.clientIdempotencyId] });\n\tconst event = await selectBrainDocumentWriteEventByIdentity(input.brainId, input.clientIdempotencyId);\n\tif (!event) throw new Error(\"Failed to begin Brain document write event\");\n\tif (event.requestFingerprint !== input.requestFingerprint) throw new BrainDocumentWriteIdempotencyConflictError();\n\treturn event;\n}\n/**\n* Links preparation results without overwriting prior linkage. This repairs a\n* begin that committed before preparation or attachment was interrupted.\n*/\nasync function attachBrainDocumentWriteEvent(input) {\n\tconst db = getDb();\n\tconst event = await selectBrainDocumentWriteEventById(input.eventId);\n\tif (!event) throw new Error(\"Brain document write event not found\");\n\tconst document = await selectBrainDocumentByRowId(input.documentRowId);\n\tif (!document || document.brainId !== event.brainId || document.documentId !== event.documentId) throw new Error(\"Brain document write event does not match the prepared document\");\n\tif (event.documentRowId !== null && event.documentRowId !== input.documentRowId) throw new Error(\"Brain document write event is already attached to another document\");\n\tif (event.versionId !== null && event.versionId !== input.versionId) throw new Error(\"Brain document write event is already attached to another version\");\n\tif (event.outcome === \"unchanged\" && input.versionId !== null) throw new Error(\"An unchanged Brain document write cannot attach a version\");\n\tif (input.versionId !== null && event.versionId === null) {\n\t\tconst version = await selectBrainDocumentVersionById(input.versionId);\n\t\tif (!version || version.brainId !== event.brainId || version.documentRowId !== input.documentRowId) throw new Error(\"Brain document write event does not match the prepared version\");\n\t}\n\tif (event.documentRowId === input.documentRowId && (input.versionId === null || event.versionId === input.versionId)) return event;\n\tconst rows = await db.update(brainDocumentWriteEvents).set({\n\t\tdocumentRowId: input.documentRowId,\n\t\t...input.versionId !== null ? { versionId: input.versionId } : {}\n\t}).where(orgScopedAnd(brainDocumentWriteEvents, eq$1(brainDocumentWriteEvents.id, input.eventId), event.documentRowId === null ? isNull$1(brainDocumentWriteEvents.documentRowId) : eq$1(brainDocumentWriteEvents.documentRowId, event.documentRowId), ...input.versionId !== null && event.versionId === null ? [isNull$1(brainDocumentWriteEvents.versionId)] : [])).returning();\n\tif (rows[0]) return rows[0];\n\tconst concurrent = await selectBrainDocumentWriteEventById(input.eventId);\n\tif (concurrent?.documentRowId === input.documentRowId && (input.versionId === null || concurrent.versionId === input.versionId)) return concurrent;\n\tthrow new Error(\"Brain document write event attachment conflicted\");\n}\n/** Records durable receipt once; retries preserve the first timestamp. */\nasync function markBrainDocumentWriteContentReceived(input) {\n\treturn (await getDb().update(brainDocumentWriteEvents).set({ contentReceivedAt: input.now }).where(orgScopedAnd(brainDocumentWriteEvents, eq$1(brainDocumentWriteEvents.id, input.eventId), isNull$1(brainDocumentWriteEvents.contentReceivedAt))).returning())[0] ?? selectBrainDocumentWriteEventById(input.eventId);\n}\n/**\n* Compare-and-set terminal settlement. A settled event is immutable and is\n* returned unchanged on any later delivery.\n*/\nasync function settleBrainDocumentWriteEvent(input) {\n\tif (input.outcome !== \"failed\" && (input.failureCode != null || input.failureMessage != null)) throw new Error(\"Failure details are only valid for failed Brain document writes\");\n\tconst existing = await selectBrainDocumentWriteEventById(input.eventId);\n\tif (!existing || existing.outcome !== null) return existing;\n\treturn (await getDb().update(brainDocumentWriteEvents).set({\n\t\toutcome: input.outcome,\n\t\tmetadataUpdated: input.metadataUpdated ? sql$1`true` : sql$1`false`,\n\t\tfailureCode: input.outcome === \"failed\" ? input.failureCode ?? null : null,\n\t\tfailureMessage: input.outcome === \"failed\" ? input.failureMessage ?? null : null,\n\t\tcompletedAt: input.now\n\t}).where(orgScopedAnd(brainDocumentWriteEvents, eq$1(brainDocumentWriteEvents.id, input.eventId), isNull$1(brainDocumentWriteEvents.outcome))).returning())[0] ?? selectBrainDocumentWriteEventById(input.eventId);\n}\n/** Batch lookup used to enrich documents by currentVersionId, never latest attempt. */\nasync function selectBrainDocumentWriteEventsByVersionIds(versionIds) {\n\tif (versionIds.length === 0) return [];\n\treturn getDb().select().from(brainDocumentWriteEvents).where(orgScopedAnd(brainDocumentWriteEvents, inArray$1(brainDocumentWriteEvents.versionId, versionIds)));\n}\n/**\n* Lists retained accepted attempts newest-first after confirming that the\n* Brain and logical document are currently visible.\n*/\nasync function listBrainDocumentWriteEvents(input) {\n\tconst brain = await selectBrainById(input.brainId);\n\tconst document = await selectBrainDocumentByKey(input.brainId, input.documentId);\n\tif (!brain || !document) return;\n\tconst conditions = [eq$1(brainDocumentWriteEvents.brainId, input.brainId), eq$1(brainDocumentWriteEvents.documentRowId, document.id)];\n\tif (input.cursor !== void 0) {\n\t\tconst decoded = decodeCreatedAtIdCursor(input.cursor);\n\t\tif (!decoded) throw new Error(\"Invalid cursor\");\n\t\tconditions.push(or$1(lt$1(brainDocumentWriteEvents.submittedAt, decoded.createdAt), and$1(eq$1(brainDocumentWriteEvents.submittedAt, decoded.createdAt), lt$1(brainDocumentWriteEvents.id, decoded.id))));\n\t}\n\tconst rows = await getDb().select().from(brainDocumentWriteEvents).where(orgScopedAnd(brainDocumentWriteEvents, ...conditions)).orderBy(desc$1(brainDocumentWriteEvents.submittedAt), desc$1(brainDocumentWriteEvents.id)).limit(input.limit + 1);\n\tconst hasMore = rows.length > input.limit;\n\tconst writes = hasMore ? rows.slice(0, input.limit) : rows;\n\tconst last = writes[writes.length - 1];\n\treturn {\n\t\twrites,\n\t\tnextCursor: hasMore && last ? encodeCreatedAtIdCursor({\n\t\t\tcreatedAt: last.submittedAt,\n\t\t\tid: last.id\n\t\t}) : null\n\t};\n}\nasync function selectBrainDocumentByKeyIncludingDeleted(brainId, documentId) {\n\treturn (await getDb().select().from(brainDocuments).where(orgScopedAnd(brainDocuments, eq$1(brainDocuments.brainId, brainId), eq$1(brainDocuments.documentId, documentId))).limit(1))[0];\n}\nasync function selectBrainDocumentByKey(brainId, documentId) {\n\tconst document = await selectBrainDocumentByKeyIncludingDeleted(brainId, documentId);\n\treturn document && document.deletedAt === null ? document : void 0;\n}\n/** By internal row id, including soft-deleted rows (ingest/delete jobs run async). */\nasync function selectBrainDocumentByRowId(id) {\n\treturn (await getDb().select().from(brainDocuments).where(orgScopedAnd(brainDocuments, eq$1(brainDocuments.id, id))).limit(1))[0];\n}\nasync function selectBrainDocumentVersionByIdempotency(documentRowId, clientIdempotencyId) {\n\treturn (await getDb().select().from(brainDocumentVersions).where(orgScopedAnd(brainDocumentVersions, eq$1(brainDocumentVersions.documentRowId, documentRowId), eq$1(brainDocumentVersions.clientIdempotencyId, clientIdempotencyId))).limit(1))[0];\n}\n/** Creates the document row if missing; concurrent first puts settle via ON CONFLICT + reselect. */\nasync function ensureBrainDocumentRow(input) {\n\tconst db = getDb();\n\tconst existing = await selectBrainDocumentByKeyIncludingDeleted(input.brainId, input.documentId);\n\tif (existing) return existing;\n\tawait db.insert(brainDocuments).values({\n\t\tid: crypto.randomUUID(),\n\t\torganizationId: organizationScopeId(),\n\t\tbrainId: input.brainId,\n\t\tdocumentId: input.documentId,\n\t\ttitle: input.title,\n\t\tsource: input.source,\n\t\tmetadata: input.metadata,\n\t\tuserRevision: input.userRevision,\n\t\tlatestRevision: 0,\n\t\tmetadataRevision: 0,\n\t\tdeletionEpoch: 0,\n\t\tcurrentVersionId: null,\n\t\tcreatedAt: input.now,\n\t\tupdatedAt: input.now,\n\t\tdeletedAt: null\n\t}).onConflictDoNothing({ target: [brainDocuments.brainId, brainDocuments.documentId] });\n\tconst document = await selectBrainDocumentByKeyIncludingDeleted(input.brainId, input.documentId);\n\tif (!document) throw new Error(\"Failed to create brain document\");\n\treturn document;\n}\n/**\n* Allocates the next candidate revision without mutating committed fields.\n* Reviving a tombstone also clears its old current pointer.\n*/\nasync function allocateBrainDocumentRevision(input) {\n\tconst document = (await getDb().update(brainDocuments).set({\n\t\tlatestRevision: sql$1`${brainDocuments.latestRevision} + 1`,\n\t\tcurrentVersionId: sql$1`CASE WHEN ${brainDocuments.deletedAt} IS NOT NULL THEN NULL ELSE ${brainDocuments.currentVersionId} END`,\n\t\tdeletedAt: null,\n\t\tupdatedAt: input.now\n\t}).where(orgScopedAnd(brainDocuments, eq$1(brainDocuments.id, input.documentRowId))).returning())[0];\n\tif (!document) throw new Error(\"Failed to update brain document\");\n\treturn document;\n}\nasync function insertBrainDocumentVersion(values) {\n\tawait getDb().insert(brainDocumentVersions).values(values).onConflictDoNothing({ target: [brainDocumentVersions.documentRowId, brainDocumentVersions.clientIdempotencyId] });\n\tconst existing = await selectBrainDocumentVersionByIdempotency(values.documentRowId, values.clientIdempotencyId);\n\tif (existing) return existing;\n\tconst version = await selectBrainDocumentVersionById(values.id);\n\tif (!version) throw new Error(\"Failed to create brain document version\");\n\treturn version;\n}\nfunction stableJson(value) {\n\tif (value === void 0) return \"null\";\n\tif (value === null || typeof value !== \"object\") return JSON.stringify(value);\n\tif (Array.isArray(value)) return `[${value.map(stableJson).join(\",\")}]`;\n\tconst record = value;\n\treturn `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${stableJson(record[key])}`).join(\",\")}}`;\n}\nfunction indexingFingerprint(input) {\n\treturn createHash(\"sha256\").update(stableJson({\n\t\tversion: 2,\n\t\tcontentSha256: input.contentSha256,\n\t\tcontentType: input.contentType,\n\t\tinputKind: input.inputKind,\n\t\ttitle: input.title,\n\t\tsource: input.source,\n\t\tembeddingContext: input.embeddingContext ?? null,\n\t\tchunkingOverride: input.chunkingOverride ?? null\n\t})).digest(\"hex\");\n}\nfunction versionIndexingFingerprint(version) {\n\tif (version.indexingFingerprint) return version.indexingFingerprint;\n\tif (!version.actualSha256 || !version.contentType) return null;\n\treturn indexingFingerprint({\n\t\tcontentSha256: version.actualSha256,\n\t\tcontentType: version.contentType,\n\t\tinputKind: version.inputKind,\n\t\ttitle: version.title,\n\t\tsource: version.source,\n\t\tembeddingContext: version.embeddingContext,\n\t\tchunkingOverride: version.chunkingOverride\n\t});\n}\n/**\n* Document put: creates or revives the logical row and stages an immutable\n* candidate unless the current indexing fingerprint is unchanged.\n*/\nasync function prepareBrainDocumentPut(input) {\n\tconst db = getDb();\n\tlet document = await ensureBrainDocumentRow({\n\t\tbrainId: input.brainId,\n\t\tdocumentId: input.documentId,\n\t\ttitle: input.title,\n\t\tsource: input.source,\n\t\tmetadata: input.metadata ?? null,\n\t\tuserRevision: input.userRevision ?? null,\n\t\tnow: input.now\n\t});\n\tconst existingVersion = await selectBrainDocumentVersionByIdempotency(document.id, input.clientIdempotencyId);\n\tif (existingVersion) {\n\t\tif (input.writeEventId) await attachBrainDocumentWriteEvent({\n\t\t\teventId: input.writeEventId,\n\t\t\tdocumentRowId: document.id,\n\t\t\tversionId: existingVersion.id\n\t\t});\n\t\treturn {\n\t\t\toutcome: \"queued\",\n\t\t\tdocument,\n\t\t\tversion: existingVersion,\n\t\t\tmetadataUpdated: false\n\t\t};\n\t}\n\tconst currentVersion = document.deletedAt === null && document.currentVersionId ? await selectBrainDocumentVersionById(document.currentVersionId) : void 0;\n\tconst hasLiveReadyVersion = currentVersion?.status === \"ready\";\n\tconst nextIndexingFingerprint = indexingFingerprint(input);\n\tif (hasLiveReadyVersion && input.userRevision != null && document.userRevision != null && input.userRevision === document.userRevision && currentVersion?.actualSha256 != null && currentVersion.actualSha256 !== input.contentSha256) throw new BrainDocumentRevisionConflictError();\n\tif (hasLiveReadyVersion && versionIndexingFingerprint(currentVersion) === nextIndexingFingerprint) {\n\t\tconst metadataChanged = input.metadata !== void 0 && stableJson(input.metadata ?? null) !== stableJson(document.metadata ?? null);\n\t\tconst revisionChanged = (input.userRevision ?? null) !== (document.userRevision ?? null);\n\t\tif (metadataChanged || revisionChanged) document = (await db.update(brainDocuments).set({\n\t\t\t...input.metadata !== void 0 ? { metadata: input.metadata } : {},\n\t\t\tuserRevision: input.userRevision ?? document.userRevision,\n\t\t\t...metadataChanged ? {\n\t\t\t\tlatestRevision: sql$1`${brainDocuments.latestRevision} + 1`,\n\t\t\t\tmetadataRevision: sql$1`${brainDocuments.latestRevision} + 1`\n\t\t\t} : {},\n\t\t\tupdatedAt: input.now\n\t\t}).where(orgScopedAnd(brainDocuments, eq$1(brainDocuments.id, document.id))).returning())[0] ?? document;\n\t\tif (input.writeEventId) {\n\t\t\tawait attachBrainDocumentWriteEvent({\n\t\t\t\teventId: input.writeEventId,\n\t\t\t\tdocumentRowId: document.id,\n\t\t\t\tversionId: null\n\t\t\t});\n\t\t\tawait settleBrainDocumentWriteEvent({\n\t\t\t\teventId: input.writeEventId,\n\t\t\t\toutcome: \"unchanged\",\n\t\t\t\tmetadataUpdated: metadataChanged,\n\t\t\t\tnow: input.now\n\t\t\t});\n\t\t}\n\t\treturn {\n\t\t\toutcome: \"unchanged\",\n\t\t\tdocument,\n\t\t\tversion: null,\n\t\t\tmetadataUpdated: metadataChanged\n\t\t};\n\t}\n\tdocument = await allocateBrainDocumentRevision({\n\t\tdocumentRowId: document.id,\n\t\tnow: input.now\n\t});\n\tconst version = await insertBrainDocumentVersion({\n\t\tid: crypto.randomUUID(),\n\t\torganizationId: organizationScopeId(),\n\t\tbrainId: input.brainId,\n\t\tdocumentRowId: document.id,\n\t\trevision: document.latestRevision,\n\t\tdeletionEpoch: document.deletionEpoch,\n\t\tclientIdempotencyId: input.clientIdempotencyId,\n\t\ttitle: input.title,\n\t\tsource: input.source,\n\t\tmetadata: input.metadata === void 0 ? document.metadata : input.metadata,\n\t\tuserRevision: input.userRevision ?? null,\n\t\tindexingFingerprint: nextIndexingFingerprint,\n\t\tinputKind: input.inputKind,\n\t\tstatus: \"pending_ingest\",\n\t\tdeclaredSha256: null,\n\t\tactualSha256: input.contentSha256,\n\t\tcontentType: input.contentType,\n\t\trawObjectKey: input.rawObjectKey,\n\t\trawByteCount: input.rawByteCount,\n\t\tembeddingContext: input.embeddingContext ?? null,\n\t\tchunkingOverride: input.chunkingOverride ?? null,\n\t\tcreatedAt: input.now,\n\t\tupdatedAt: input.now\n\t});\n\tif (input.writeEventId) await attachBrainDocumentWriteEvent({\n\t\teventId: input.writeEventId,\n\t\tdocumentRowId: document.id,\n\t\tversionId: version.id\n\t});\n\treturn {\n\t\toutcome: \"queued\",\n\t\tdocument,\n\t\tversion,\n\t\tmetadataUpdated: input.metadata !== void 0\n\t};\n}\n/**\n* File upload staging (binary formats): creates the document + a\n* `pending_upload` version for the bounded presigned POST flow; `finalize`\n* verifies storage, enqueues ingestion, then CASes it to `queued`. Idempotent\n* on `(document, clientIdempotencyId)`.\n*/\nasync function prepareBrainUploadVersion(input) {\n\tlet document = await ensureBrainDocumentRow({\n\t\tbrainId: input.brainId,\n\t\tdocumentId: input.documentId,\n\t\ttitle: input.title,\n\t\tsource: input.source,\n\t\tmetadata: input.metadata ?? null,\n\t\tuserRevision: null,\n\t\tnow: input.now\n\t});\n\tconst existingVersion = await selectBrainDocumentVersionByIdempotency(document.id, input.clientIdempotencyId);\n\tif (existingVersion) {\n\t\tif (input.writeEventId) await attachBrainDocumentWriteEvent({\n\t\t\teventId: input.writeEventId,\n\t\t\tdocumentRowId: document.id,\n\t\t\tversionId: existingVersion.id\n\t\t});\n\t\treturn {\n\t\t\tdocument,\n\t\t\tversion: existingVersion\n\t\t};\n\t}\n\tdocument = await allocateBrainDocumentRevision({\n\t\tdocumentRowId: document.id,\n\t\tnow: input.now\n\t});\n\tconst contentSha256 = input.actualSha256 ?? input.declaredSha256;\n\tif (!contentSha256) throw new Error(\"Brain file uploads require a sha256 digest\");\n\tconst version = await insertBrainDocumentVersion({\n\t\tid: input.versionId,\n\t\torganizationId: organizationScopeId(),\n\t\tbrainId: input.brainId,\n\t\tdocumentRowId: document.id,\n\t\trevision: document.latestRevision,\n\t\tdeletionEpoch: document.deletionEpoch,\n\t\tclientIdempotencyId: input.clientIdempotencyId,\n\t\ttitle: input.title,\n\t\tsource: input.source,\n\t\tmetadata: input.metadata === void 0 ? document.metadata : input.metadata,\n\t\tuserRevision: null,\n\t\tindexingFingerprint: indexingFingerprint({\n\t\t\tcontentSha256,\n\t\t\tcontentType: input.contentType,\n\t\t\tinputKind: \"file\",\n\t\t\ttitle: input.title,\n\t\t\tsource: input.source\n\t\t}),\n\t\tinputKind: \"file\",\n\t\tstatus: \"pending_upload\",\n\t\tdeclaredSha256: input.declaredSha256 ?? null,\n\t\tactualSha256: input.actualSha256 ?? null,\n\t\tcontentType: input.contentType,\n\t\trawObjectKey: input.rawObjectKey,\n\t\trawByteCount: input.rawByteCount,\n\t\tcreatedAt: input.now,\n\t\tupdatedAt: input.now\n\t});\n\tif (input.writeEventId) await attachBrainDocumentWriteEvent({\n\t\teventId: input.writeEventId,\n\t\tdocumentRowId: document.id,\n\t\tversionId: version.id\n\t});\n\treturn {\n\t\tdocument,\n\t\tversion\n\t};\n}\nasync function selectBrainDocumentVersionById(versionId) {\n\treturn (await getDb().select().from(brainDocumentVersions).where(orgScopedAnd(brainDocumentVersions, eq$1(brainDocumentVersions.id, versionId))).limit(1))[0];\n}\nasync function listPendingBrainDocumentVersions(brainId) {\n\treturn getDb().select().from(brainDocumentVersions).where(orgScopedAnd(brainDocumentVersions, eq$1(brainDocumentVersions.brainId, brainId), inArray$1(brainDocumentVersions.status, [\n\t\t\"pending_upload\",\n\t\t\"pending_ingest\",\n\t\t\"queued\"\n\t]))).orderBy(asc(brainDocumentVersions.createdAt));\n}\nasync function claimBrainDocumentVersionForIngestion(input) {\n\treturn (await getDb().update(brainDocumentVersions).set({\n\t\tstatus: \"processing\",\n\t\tleaseToken: input.leaseToken,\n\t\tleaseExpiresAt: input.leaseExpiresAt,\n\t\tupdatedAt: input.now\n\t}).where(orgScopedAnd(brainDocumentVersions, eq$1(brainDocumentVersions.id, input.id), or$1(inArray$1(brainDocumentVersions.status, [\n\t\t\"pending_upload\",\n\t\t\"pending_ingest\",\n\t\t\"queued\"\n\t]), and$1(eq$1(brainDocumentVersions.status, \"processing\"), or$1(isNull$1(brainDocumentVersions.leaseExpiresAt), lte$1(brainDocumentVersions.leaseExpiresAt, input.now)))))).returning())[0];\n}\nasync function releaseBrainDocumentVersionLease(input) {\n\treturn (await getDb().update(brainDocumentVersions).set({\n\t\tstatus: \"queued\",\n\t\tleaseToken: null,\n\t\tleaseExpiresAt: null,\n\t\tupdatedAt: input.now\n\t}).where(orgScopedAnd(brainDocumentVersions, eq$1(brainDocumentVersions.id, input.id), eq$1(brainDocumentVersions.status, \"processing\"), eq$1(brainDocumentVersions.leaseToken, input.leaseToken))).returning({ id: brainDocumentVersions.id })).length > 0;\n}\nasync function renewBrainDocumentVersionLease(input) {\n\treturn (await getDb().update(brainDocumentVersions).set({\n\t\tleaseExpiresAt: input.leaseExpiresAt,\n\t\tupdatedAt: input.now\n\t}).where(orgScopedAnd(brainDocumentVersions, eq$1(brainDocumentVersions.id, input.id), eq$1(brainDocumentVersions.status, \"processing\"), eq$1(brainDocumentVersions.leaseToken, input.leaseToken), gt$1(brainDocumentVersions.leaseExpiresAt, input.now))).returning({ id: brainDocumentVersions.id })).length > 0;\n}\nasync function compareAndSetBrainDocumentVersionStatus(input) {\n\treturn (await getDb().update(brainDocumentVersions).set({\n\t\tstatus: input.nextStatus,\n\t\t...input.nextStatus === \"processing\" ? {} : {\n\t\t\tleaseToken: null,\n\t\t\tleaseExpiresAt: null\n\t\t},\n\t\tupdatedAt: input.now,\n\t\t...input.actualSha256 !== void 0 ? { actualSha256: input.actualSha256 } : {},\n\t\t...input.rawObjectKey !== void 0 ? { rawObjectKey: input.rawObjectKey } : {},\n\t\t...input.detectedFormat !== void 0 ? { detectedFormat: input.detectedFormat } : {},\n\t\t...input.canonicalObjectKey !== void 0 ? { canonicalObjectKey: input.canonicalObjectKey } : {},\n\t\t...input.canonicalByteCount !== void 0 ? { canonicalByteCount: input.canonicalByteCount } : {},\n\t\t...input.rawByteCount !== void 0 ? { rawByteCount: input.rawByteCount } : {},\n\t\t...input.extractorVersion !== void 0 ? { extractorVersion: input.extractorVersion } : {},\n\t\t...input.chunkerVersion !== void 0 ? { chunkerVersion: input.chunkerVersion } : {},\n\t\t...input.indexVersion !== void 0 ? { indexVersion: input.indexVersion } : {},\n\t\t...input.indexGeneration !== void 0 ? { indexGeneration: input.indexGeneration } : {},\n\t\t...input.chunkCount !== void 0 ? { chunkCount: input.chunkCount } : {},\n\t\t...input.failureCode !== void 0 ? { failureCode: input.failureCode } : {},\n\t\t...input.failureMessage !== void 0 ? { failureMessage: input.failureMessage } : {}\n\t}).where(orgScopedAnd(brainDocumentVersions, eq$1(brainDocumentVersions.id, input.id), inArray$1(brainDocumentVersions.status, input.expectedStatuses), ...input.expectedLeaseToken ? [eq$1(brainDocumentVersions.leaseToken, input.expectedLeaseToken)] : [])).returning())[0];\n}\nasync function commitBrainDocumentVersionPromotion(input) {\n\tconst db = getDb();\n\tconst commit = async (tx) => {\n\t\tconst version = (await tx.select().from(brainDocumentVersions).where(orgScopedAnd(brainDocumentVersions, eq$1(brainDocumentVersions.id, input.versionId), eq$1(brainDocumentVersions.status, \"processing\"), eq$1(brainDocumentVersions.leaseToken, input.leaseToken), gt$1(brainDocumentVersions.leaseExpiresAt, input.now))).limit(1))[0];\n\t\tif (!version) return void 0;\n\t\tif (!(await tx.update(brainDocumentVersions).set({\n\t\t\tstatus: \"ready\",\n\t\t\tleaseToken: null,\n\t\t\tleaseExpiresAt: null,\n\t\t\tactualSha256: input.actualSha256,\n\t\t\trawObjectKey: input.rawObjectKey,\n\t\t\tdetectedFormat: input.detectedFormat,\n\t\t\tcanonicalObjectKey: input.canonicalObjectKey,\n\t\t\tcanonicalByteCount: input.canonicalByteCount,\n\t\t\trawByteCount: input.rawByteCount,\n\t\t\textractorVersion: input.extractorVersion,\n\t\t\tchunkerVersion: input.chunkerVersion,\n\t\t\tindexVersion: input.indexVersion,\n\t\t\tindexGeneration: input.indexGeneration,\n\t\t\tchunkCount: input.chunkCount,\n\t\t\tfailureCode: null,\n\t\t\tfailureMessage: null,\n\t\t\tupdatedAt: input.now\n\t\t}).where(orgScopedAnd(brainDocumentVersions, eq$1(brainDocumentVersions.id, version.id), eq$1(brainDocumentVersions.status, \"processing\"), eq$1(brainDocumentVersions.leaseToken, input.leaseToken))).returning({ id: brainDocumentVersions.id }))[0]) return void 0;\n\t\tif (!(await tx.update(brainDocuments).set({\n\t\t\tcurrentVersionId: version.id,\n\t\t\ttitle: version.title,\n\t\t\tsource: version.source,\n\t\t\tuserRevision: version.userRevision,\n\t\t\tupdatedAt: input.now\n\t\t}).where(orgScopedAnd(brainDocuments, eq$1(brainDocuments.id, version.documentRowId), isNull$1(brainDocuments.deletedAt), eq$1(brainDocuments.deletionEpoch, version.deletionEpoch), sql$1`NOT EXISTS (\n            SELECT 1\n            FROM brain_document_versions current_version\n            WHERE current_version.id = ${brainDocuments.currentVersionId}\n              AND current_version.revision >= ${version.revision}\n          )`)).returning({ id: brainDocuments.id }))[0]) return void 0;\n\t\tawait tx.update(brainDocuments).set({\n\t\t\tmetadata: version.metadata,\n\t\t\tmetadataRevision: version.revision\n\t\t}).where(orgScopedAnd(brainDocuments, eq$1(brainDocuments.id, version.documentRowId), eq$1(brainDocuments.currentVersionId, version.id), lte$1(brainDocuments.metadataRevision, version.revision)));\n\t\tconst document = (await tx.select().from(brainDocuments).where(orgScopedAnd(brainDocuments, eq$1(brainDocuments.id, version.documentRowId))).limit(1))[0];\n\t\tif (!document) return void 0;\n\t\treturn {\n\t\t\tdocument,\n\t\t\tprunedVersions: await tx.select().from(brainDocumentVersions).where(orgScopedAnd(brainDocumentVersions, eq$1(brainDocumentVersions.documentRowId, document.id), lt$1(brainDocumentVersions.revision, version.revision), inArray$1(brainDocumentVersions.status, [\"ready\", \"failed\"])))\n\t\t};\n\t};\n\tif (getDatabaseHandle().dialect === \"sqlite\") return commit(db);\n\tconst committed = rowsFromResult(await db.execute(sql$1`\n    WITH candidate AS (\n      SELECT\n        version.id,\n        version.document_row_id,\n        version.revision,\n        version.deletion_epoch,\n        version.title,\n        version.source,\n        version.metadata,\n        version.user_revision\n      FROM brain_document_versions version\n      INNER JOIN brains brain ON brain.id = version.brain_id\n      WHERE version.organization_id = ${organizationScopeId()}\n        AND version.id = ${input.versionId}\n        AND version.status = 'processing'\n        AND version.lease_token = ${input.leaseToken}\n        AND version.lease_expires_at > ${input.now}\n        AND brain.organization_id = ${organizationScopeId()}\n        AND brain.status = 'active'\n        AND brain.active_generation = ${input.indexGeneration}\n      FOR UPDATE OF version\n    ),\n    promoted AS (\n      UPDATE brain_documents document\n      SET\n        current_version_id = candidate.id,\n        title = candidate.title,\n        source = candidate.source,\n        user_revision = candidate.user_revision,\n        metadata = CASE\n          WHEN document.metadata_revision <= candidate.revision THEN candidate.metadata\n          ELSE document.metadata\n        END,\n        metadata_revision = GREATEST(document.metadata_revision, candidate.revision),\n        updated_at = ${input.now}\n      FROM candidate\n      WHERE document.organization_id = ${organizationScopeId()}\n        AND document.id = candidate.document_row_id\n        AND document.deleted_at IS NULL\n        AND document.deletion_epoch = candidate.deletion_epoch\n        AND NOT EXISTS (\n          SELECT 1\n          FROM brain_document_versions current_version\n          WHERE current_version.id = document.current_version_id\n            AND current_version.revision >= candidate.revision\n        )\n      RETURNING document.id, document.current_version_id\n    ),\n    ready AS (\n      UPDATE brain_document_versions version\n      SET\n        status = 'ready',\n        lease_token = NULL,\n        lease_expires_at = NULL,\n        actual_sha256 = ${input.actualSha256},\n        raw_object_key = ${input.rawObjectKey},\n        detected_format = ${input.detectedFormat},\n        canonical_object_key = ${input.canonicalObjectKey},\n        canonical_byte_count = ${input.canonicalByteCount},\n        raw_byte_count = ${input.rawByteCount},\n        extractor_version = ${input.extractorVersion},\n        chunker_version = ${input.chunkerVersion},\n        index_version = ${input.indexVersion},\n        index_generation = ${input.indexGeneration},\n        chunk_count = ${input.chunkCount},\n        failure_code = NULL,\n        failure_message = NULL,\n        updated_at = ${input.now}\n      FROM promoted\n      WHERE version.organization_id = ${organizationScopeId()}\n        AND version.id = promoted.current_version_id\n        AND version.status = 'processing'\n        AND version.lease_token = ${input.leaseToken}\n      RETURNING promoted.id AS \"documentId\", version.revision\n    )\n    SELECT \"documentId\" FROM ready\n  `))[0];\n\tif (!committed) return void 0;\n\tconst document = (await db.select().from(brainDocuments).where(orgScopedAnd(brainDocuments, eq$1(brainDocuments.id, committed.documentId))).limit(1))[0];\n\tif (!document) return void 0;\n\treturn {\n\t\tdocument,\n\t\tprunedVersions: await db.select().from(brainDocumentVersions).where(orgScopedAnd(brainDocumentVersions, eq$1(brainDocumentVersions.documentRowId, document.id), lt$1(brainDocumentVersions.revision, committed.revision), inArray$1(brainDocumentVersions.status, [\"ready\", \"failed\"])))\n\t};\n}\n/**\n* Atomically points the document at a newly `ready` version. Promotion is\n* monotonic by revision: the pointer only moves forward, so a stale\n* lower-revision promote no-ops even after a concurrent higher-revision\n* promote landed. After a successful promote, superseded terminal rows are\n* returned for deterministic asynchronous cleanup.\n*/\nasync function promoteBrainDocumentVersion(input) {\n\tconst db = getDb();\n\tconst version = await selectBrainDocumentVersionById(input.versionId);\n\tif (!version || version.status !== \"ready\") return;\n\tconst currentDocument = await selectBrainDocumentByRowId(version.documentRowId);\n\tif (currentDocument?.currentVersionId === version.id) return {\n\t\tdocument: currentDocument,\n\t\tprunedVersions: await db.select().from(brainDocumentVersions).where(orgScopedAnd(brainDocumentVersions, eq$1(brainDocumentVersions.documentRowId, currentDocument.id), lt$1(brainDocumentVersions.revision, version.revision), inArray$1(brainDocumentVersions.status, [\"ready\", \"failed\"])))\n\t};\n\tif (!(await db.update(brainDocuments).set({\n\t\tcurrentVersionId: version.id,\n\t\ttitle: version.title,\n\t\tsource: version.source,\n\t\tuserRevision: version.userRevision,\n\t\tupdatedAt: input.now\n\t}).where(orgScopedAnd(brainDocuments, eq$1(brainDocuments.id, version.documentRowId), isNull$1(brainDocuments.deletedAt), eq$1(brainDocuments.deletionEpoch, version.deletionEpoch), sql$1`NOT EXISTS (\n          SELECT 1\n          FROM brain_document_versions current_version\n          WHERE current_version.id = ${brainDocuments.currentVersionId}\n            AND current_version.revision >= ${version.revision}\n        )`)).returning({ id: brainDocuments.id }))[0]) return void 0;\n\tawait db.update(brainDocuments).set({\n\t\tmetadata: version.metadata,\n\t\tmetadataRevision: version.revision\n\t}).where(orgScopedAnd(brainDocuments, eq$1(brainDocuments.id, version.documentRowId), eq$1(brainDocuments.currentVersionId, version.id), lte$1(brainDocuments.metadataRevision, version.revision)));\n\tconst document = (await db.select().from(brainDocuments).where(orgScopedAnd(brainDocuments, eq$1(brainDocuments.id, version.documentRowId))).limit(1))[0];\n\tif (!document) return void 0;\n\treturn {\n\t\tdocument,\n\t\tprunedVersions: await db.select().from(brainDocumentVersions).where(orgScopedAnd(brainDocumentVersions, eq$1(brainDocumentVersions.documentRowId, document.id), lt$1(brainDocumentVersions.revision, version.revision), inArray$1(brainDocumentVersions.status, [\"ready\", \"failed\"])))\n\t};\n}\n/**\n* Lists live documents with their current-version state and provenance,\n* ordered by `documentId` (unique per Brain) for stable cursor pagination.\n* `prefix` narrows by documentId prefix — the ETL diffing primitive. `search`,\n* `sources`, `provisionerKinds`, and `filter` (a persisted Brain filter\n* expression) are cursor-safe table controls; they AND together.\n*/\nasync function listBrainDocuments(input) {\n\tconst db = getDb();\n\tconst conditions = [eq$1(brainDocuments.brainId, input.brainId), notDeletedBrainDocument()];\n\tif (input.prefix !== void 0) conditions.push(sql$1`${brainDocuments.documentId} LIKE ${`${escapeLikePattern(input.prefix)}%`} ESCAPE '\\\\'`);\n\tif (input.search !== void 0) {\n\t\tconst pattern = `%${escapeLikePattern(input.search.toLowerCase())}%`;\n\t\tconditions.push(or$1(sql$1`LOWER(${brainDocuments.title}) LIKE ${pattern} ESCAPE '\\\\'`, sql$1`LOWER(${brainDocuments.documentId}) LIKE ${pattern} ESCAPE '\\\\'`));\n\t}\n\tif (input.sources !== void 0 && input.sources.length > 0) conditions.push(inArray$1(brainDocuments.source, input.sources));\n\tif (input.provisionerKinds !== void 0 && input.provisionerKinds.length > 0) conditions.push(inArray$1(brainDocumentWriteEvents.provisionerKind, input.provisionerKinds));\n\tif (input.filter !== void 0) {\n\t\tconst compiled = compileBrainFilterExpressionSql(input.filter, getDatabaseHandle().dialect === \"sqlite\" ? \"sqlite\" : \"pg\");\n\t\tif (compiled) conditions.push(compiled);\n\t}\n\tif (input.cursor !== void 0) conditions.push(gt$1(brainDocuments.documentId, input.cursor));\n\tconst rows = await db.select({\n\t\tdocument: brainDocuments,\n\t\tcurrentStatus: brainDocumentVersions.status,\n\t\tcurrentFailureCode: brainDocumentVersions.failureCode,\n\t\tcurrentFailureMessage: brainDocumentVersions.failureMessage,\n\t\tcurrentSha256: brainDocumentVersions.actualSha256,\n\t\tcurrentByteSize: brainDocumentVersions.rawByteCount,\n\t\tcurrentChunkCount: brainDocumentVersions.chunkCount,\n\t\tcurrentContentType: brainDocumentVersions.contentType,\n\t\tcurrentDetectedFormat: brainDocumentVersions.detectedFormat,\n\t\tcurrentWriteEvent: brainDocumentWriteEvents\n\t}).from(brainDocuments).leftJoin(brainDocumentVersions, eq$1(brainDocumentVersions.id, brainDocuments.currentVersionId)).leftJoin(brainDocumentWriteEvents, eq$1(brainDocumentWriteEvents.versionId, brainDocuments.currentVersionId)).where(orgScopedAnd(brainDocuments, ...conditions)).orderBy(asc(brainDocuments.documentId)).limit(input.limit + 1);\n\tconst page = rows.slice(0, input.limit);\n\tconst latestByDocument = /* @__PURE__ */ new Map();\n\tif (page.length > 0) {\n\t\tconst latestVersions = await db.select().from(brainDocumentVersions).where(orgScopedAnd(brainDocumentVersions, inArray$1(brainDocumentVersions.documentRowId, page.map((row) => row.document.id)))).orderBy(asc(brainDocumentVersions.documentRowId), desc$1(brainDocumentVersions.revision));\n\t\tfor (const version of latestVersions) if (!latestByDocument.has(version.documentRowId)) latestByDocument.set(version.documentRowId, version);\n\t}\n\tconst nextCursor = rows.length > input.limit ? page[page.length - 1]?.document.documentId ?? null : null;\n\treturn {\n\t\tdocuments: page.map((row) => ({\n\t\t\t...row.document,\n\t\t\tlatestStatus: latestByDocument.get(row.document.id)?.status ?? null,\n\t\t\tlatestFailureCode: latestByDocument.get(row.document.id)?.failureCode ?? null,\n\t\t\tlatestFailureMessage: latestByDocument.get(row.document.id)?.failureMessage ?? null,\n\t\t\tcurrentStatus: row.currentStatus,\n\t\t\tcurrentFailureCode: row.currentFailureCode,\n\t\t\tcurrentFailureMessage: row.currentFailureMessage,\n\t\t\tcurrentSha256: row.currentSha256,\n\t\t\tcurrentByteSize: row.currentByteSize,\n\t\t\tcurrentChunkCount: row.currentChunkCount,\n\t\t\tcurrentContentType: row.currentContentType,\n\t\t\tcurrentDetectedFormat: row.currentDetectedFormat,\n\t\t\tcurrentWriteEvent: row.currentWriteEvent\n\t\t})),\n\t\tnextCursor\n\t};\n}\n/** Single-document variant of the list row for the detail side panel. */\nasync function selectBrainDocumentDetail(brainId, documentId) {\n\tconst { documents } = await listBrainDocuments({\n\t\tbrainId,\n\t\tprefix: documentId,\n\t\tlimit: 1\n\t});\n\tconst document = documents[0];\n\treturn document?.documentId === documentId ? document : void 0;\n}\nfunction escapeLikePattern(value) {\n\treturn value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll(\"%\", \"\\\\%\").replaceAll(\"_\", \"\\\\_\");\n}\n/** Full metadata replacement without touching content or embeddings (ACL churn path). */\nasync function updateBrainDocumentMetadata(input) {\n\treturn (await getDb().update(brainDocuments).set({\n\t\tmetadata: input.metadata,\n\t\tlatestRevision: sql$1`${brainDocuments.latestRevision} + 1`,\n\t\tmetadataRevision: sql$1`${brainDocuments.latestRevision} + 1`,\n\t\tupdatedAt: input.now\n\t}).where(orgScopedAnd(brainDocuments, eq$1(brainDocuments.brainId, input.brainId), eq$1(brainDocuments.documentId, input.documentId), notDeletedBrainDocument())).returning())[0];\n}\n/**\n* Idempotently tombstones logical documents. Clearing the current pointer in\n* the same update prevents version cleanup from creating dangling references.\n*/\nasync function softDeleteBrainDocuments(input) {\n\tconst db = getDb();\n\tif (input.documentIds.length === 0) return [];\n\tconst documents = await db.update(brainDocuments).set({\n\t\tdeletedAt: input.now,\n\t\tcurrentVersionId: null,\n\t\tdeletionEpoch: sql$1`CASE WHEN ${brainDocuments.deletedAt} IS NULL THEN ${brainDocuments.deletionEpoch} + 1 ELSE ${brainDocuments.deletionEpoch} END`,\n\t\tlatestRevision: sql$1`CASE WHEN ${brainDocuments.deletedAt} IS NULL THEN ${brainDocuments.latestRevision} + 1 ELSE ${brainDocuments.latestRevision} END`,\n\t\tupdatedAt: input.now\n\t}).where(orgScopedAnd(brainDocuments, eq$1(brainDocuments.brainId, input.brainId), inArray$1(brainDocuments.documentId, input.documentIds))).returning();\n\tfor (const document of documents) {\n\t\tconst invalidated = await db.update(brainDocumentVersions).set({\n\t\t\tstatus: \"failed\",\n\t\t\tleaseToken: null,\n\t\t\tleaseExpiresAt: null,\n\t\t\tfailureMessage: \"Document was deleted before ingestion completed\",\n\t\t\tupdatedAt: input.now\n\t\t}).where(orgScopedAnd(brainDocumentVersions, eq$1(brainDocumentVersions.documentRowId, document.id), lt$1(brainDocumentVersions.deletionEpoch, document.deletionEpoch), inArray$1(brainDocumentVersions.status, [\n\t\t\t\"pending_upload\",\n\t\t\t\"pending_ingest\",\n\t\t\t\"queued\",\n\t\t\t\"processing\"\n\t\t]))).returning({ id: brainDocumentVersions.id });\n\t\tif (invalidated.length > 0) await db.update(brainDocumentWriteEvents).set({\n\t\t\toutcome: \"failed\",\n\t\t\tfailureMessage: \"Document was deleted before ingestion completed\",\n\t\t\tcompletedAt: input.now\n\t\t}).where(orgScopedAnd(brainDocumentWriteEvents, inArray$1(brainDocumentWriteEvents.versionId, invalidated.map((version) => version.id)), isNull$1(brainDocumentWriteEvents.outcome)));\n\t}\n\treturn documents;\n}\n/** Exact pre-delete versions captured for revival-safe external cleanup. */\nasync function listBrainDocumentVersionsBeforeDeletionEpoch(input) {\n\treturn getDb().select().from(brainDocumentVersions).where(orgScopedAnd(brainDocumentVersions, eq$1(brainDocumentVersions.documentRowId, input.documentRowId), lt$1(brainDocumentVersions.deletionEpoch, input.deletionEpoch)));\n}\nasync function countBrainDocuments(brainId) {\n\tconst db = getDb();\n\tconst totals = await db.select({ value: count$1() }).from(brainDocuments).where(orgScopedAnd(brainDocuments, eq$1(brainDocuments.brainId, brainId), notDeletedBrainDocument()));\n\tconst ready = await db.select({ value: count$1() }).from(brainDocuments).innerJoin(brainDocumentVersions, eq$1(brainDocumentVersions.id, brainDocuments.currentVersionId)).where(orgScopedAnd(brainDocuments, eq$1(brainDocuments.brainId, brainId), notDeletedBrainDocument(), eq$1(brainDocumentVersions.status, \"ready\")));\n\treturn {\n\t\ttotal: totals[0]?.value ?? 0,\n\t\tready: ready[0]?.value ?? 0\n\t};\n}\n/** Live document counts and distinct sources for a batch of Brains. */\nasync function summarizeBrainDocumentsByBrainIds(brainIds) {\n\tconst summaries = new Map(brainIds.map((brainId) => [brainId, {\n\t\tdocumentCount: 0,\n\t\tsources: []\n\t}]));\n\tif (brainIds.length === 0) return summaries;\n\tconst rows = await getDb().select({\n\t\tbrainId: brainDocuments.brainId,\n\t\tsource: brainDocuments.source,\n\t\tvalue: count$1()\n\t}).from(brainDocuments).where(orgScopedAnd(brainDocuments, inArray$1(brainDocuments.brainId, brainIds), notDeletedBrainDocument())).groupBy(brainDocuments.brainId, brainDocuments.source);\n\tfor (const row of rows) {\n\t\tconst summary = summaries.get(row.brainId);\n\t\tif (!summary) continue;\n\t\tsummary.documentCount += row.value;\n\t\tsummary.sources.push(row.source);\n\t}\n\tfor (const summary of summaries.values()) summary.sources.sort();\n\treturn summaries;\n}\n/** Live ready versions of a Brain — the rebuild worklist. */\nasync function listCurrentBrainDocumentVersionsForRebuild(brainId) {\n\treturn (await getDb().select({ version: brainDocumentVersions }).from(brainDocuments).innerJoin(brainDocumentVersions, eq$1(brainDocumentVersions.id, brainDocuments.currentVersionId)).where(orgScopedAnd(brainDocuments, eq$1(brainDocuments.brainId, brainId), notDeletedBrainDocument(), eq$1(brainDocumentVersions.status, \"ready\"))).orderBy(asc(brainDocuments.documentId))).map((row) => row.version);\n}\n/** Removes all staging rows of a deleted document. */\nasync function deleteBrainDocumentVersionsForDocument(documentRowId) {\n\treturn getDb().delete(brainDocumentVersions).where(orgScopedAnd(brainDocumentVersions, eq$1(brainDocumentVersions.documentRowId, documentRowId), sql$1`NOT EXISTS (\n          SELECT 1\n          FROM brain_documents document\n          WHERE document.current_version_id = ${brainDocumentVersions.id}\n        )`)).returning();\n}\n/** Removes one aborted staging row after its index write has been compensated. */\nasync function deleteBrainDocumentVersionById(versionId) {\n\treturn (await getDb().delete(brainDocumentVersions).where(orgScopedAnd(brainDocumentVersions, eq$1(brainDocumentVersions.id, versionId), sql$1`NOT EXISTS (\n          SELECT 1\n          FROM brain_documents document\n          WHERE document.current_version_id = ${brainDocumentVersions.id}\n        )`)).returning())[0];\n}\n/** Finds an existing ready version with identical content to reuse its cached objects. */\nasync function findReadyVersionBySha(sha256) {\n\treturn (await getDb().select().from(brainDocumentVersions).where(orgScopedAnd(brainDocumentVersions, eq$1(brainDocumentVersions.actualSha256, sha256), eq$1(brainDocumentVersions.status, \"ready\"))).limit(1))[0];\n}\n//#endregion\n//#region src/runtime/queries/brains/filters.ts\nvar BrainFilterSlugConflictError = class extends Error {\n\tconstructor() {\n\t\tsuper(\"A filter with this slug already exists on the Brain\");\n\t\tthis.name = \"BrainFilterSlugConflictError\";\n\t}\n};\nasync function selectBrainFilterById(brainId, filterId) {\n\treturn (await getDb().select().from(brainFilters).where(orgScopedAnd(brainFilters, eq$1(brainFilters.id, filterId), eq$1(brainFilters.brainId, brainId))).limit(1))[0];\n}\nasync function selectBrainFilterBySlug(brainId, slug) {\n\treturn (await getDb().select().from(brainFilters).where(orgScopedAnd(brainFilters, eq$1(brainFilters.brainId, brainId), eq$1(brainFilters.slug, slug))).limit(1))[0];\n}\nasync function listBrainFilters(brainId) {\n\treturn getDb().select().from(brainFilters).where(orgScopedAnd(brainFilters, eq$1(brainFilters.brainId, brainId))).orderBy(asc(brainFilters.slug));\n}\nasync function createBrainFilter(input) {\n\tawait getDb().insert(brainFilters).values({\n\t\tid: input.id,\n\t\torganizationId: organizationScopeId(),\n\t\tbrainId: input.brainId,\n\t\tslug: input.slug,\n\t\tname: input.name,\n\t\tdescription: input.description,\n\t\tfilter: input.filter,\n\t\tcreatedByUserId: input.createdByUserId,\n\t\tcreatedAt: input.now,\n\t\tupdatedAt: input.now\n\t}).onConflictDoNothing({ target: [brainFilters.brainId, brainFilters.slug] });\n\tconst filter = await selectBrainFilterBySlug(input.brainId, input.slug);\n\tif (!filter) throw new Error(\"Failed to create brain filter\");\n\tif (filter.id !== input.id) throw new BrainFilterSlugConflictError();\n\treturn filter;\n}\nasync function updateBrainFilter(input) {\n\treturn (await getDb().update(brainFilters).set({\n\t\t...input.name !== void 0 ? { name: input.name } : {},\n\t\t...input.description !== void 0 ? { description: input.description } : {},\n\t\t...input.filter !== void 0 ? { filter: input.filter } : {},\n\t\tupdatedAt: input.now\n\t}).where(orgScopedAnd(brainFilters, eq$1(brainFilters.id, input.filterId), eq$1(brainFilters.brainId, input.brainId))).returning())[0];\n}\nasync function deleteBrainFilter(brainId, filterId) {\n\treturn (await getDb().delete(brainFilters).where(orgScopedAnd(brainFilters, eq$1(brainFilters.id, filterId), eq$1(brainFilters.brainId, brainId))).returning({ id: brainFilters.id })).length > 0;\n}\n/** Removes all filters of a Brain (deletion cleanup). */\nasync function deleteBrainFilters(brainId) {\n\tawait getDb().delete(brainFilters).where(orgScopedAnd(brainFilters, eq$1(brainFilters.brainId, brainId)));\n}\n/** Filter counts for the Brain list column, one query for the whole page. */\nasync function countBrainFiltersByBrainIds(brainIds) {\n\tconst counts = /* @__PURE__ */ new Map();\n\tif (brainIds.length === 0) return counts;\n\tconst rows = await getDb().select({\n\t\tbrainId: brainFilters.brainId,\n\t\tvalue: count$1()\n\t}).from(brainFilters).where(orgScopedAnd(brainFilters, inArray$1(brainFilters.brainId, brainIds))).groupBy(brainFilters.brainId);\n\tfor (const row of rows) counts.set(row.brainId, row.value);\n\treturn counts;\n}\n//#endregion\n//#region src/runtime/runs/source.ts\nfunction runSource(kind, id) {\n\treturn {\n\t\tkind,\n\t\tid: id ?? null\n\t};\n}\nfunction runSourceFromWorkflowRunMetadata(metadata) {\n\tif (metadata && typeof metadata === \"object\" && \"runId\" in metadata) {\n\t\tconst runId = metadata.runId;\n\t\tif (typeof runId === \"string\") return runSource(\"workflow\", runId);\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 runSourceFromWorkflowRunMetadata(span.metadata) ?? 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\": return runSourceFromWorkflowRunMetadata(span.metadata);\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/runtime/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\tcredentialContext: input.credentialContext ?? 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 markWorkflowRunWaitingChildren(id) {\n\tawait setWorkflowRunStatusRow(id, \"waiting_children\");\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 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/runtime/history/cancel.ts\nconst CANCELABLE_STATUSES = new Set([\n\t\"pending\",\n\t\"running\",\n\t\"sleeping\",\n\t\"waiting_hook\",\n\t\"waiting_children\"\n]);\nfunction isCancelableWorkflowStatus(status) {\n\treturn CANCELABLE_STATUSES.has(status);\n}\nfunction isCancelableAgentStatus(status, canceledAt) {\n\treturn !canceledAt && status !== \"completed\" && status !== \"failed\" && status !== \"canceled\";\n}\n/**\n* Lists active descendants in depth-first order. Source linkage covers agent\n* tools and subagents; `parentWorkflowRunId` covers workflow composition.\n*/\nasync function collectChildRunCancelTargets(kind, id) {\n\tconst seen = /* @__PURE__ */ new Set();\n\tconst targets = [];\n\tconst visit = async (parentKind, parentId) => {\n\t\tconst sourceKind = parentKind === \"workflow\" ? \"workflow\" : \"agent\";\n\t\tconst [sourcedWorkflows, composedWorkflows, agents] = await Promise.all([\n\t\t\tlistWorkflowRunsBySourceIds({\n\t\t\t\tsourceKind,\n\t\t\t\tsourceIds: [parentId]\n\t\t\t}),\n\t\t\tparentKind === \"workflow\" ? listWorkflowRunsByParentRunIds([parentId]) : Promise.resolve(/* @__PURE__ */ new Map()),\n\t\t\tlistAgentSessionsBySourceIds({\n\t\t\t\tsourceKind,\n\t\t\t\tsourceIds: [parentId]\n\t\t\t})\n\t\t]);\n\t\tconst workflows = [...sourcedWorkflows.get(parentId) ?? [], ...composedWorkflows.get(parentId) ?? []];\n\t\tfor (const run of workflows) {\n\t\t\tconst key = `workflow:${run.id}`;\n\t\t\tif (!seen.has(key) && isCancelableWorkflowStatus(run.status)) {\n\t\t\t\tseen.add(key);\n\t\t\t\ttargets.push({\n\t\t\t\t\tkind: \"workflow\",\n\t\t\t\t\tid: run.id\n\t\t\t\t});\n\t\t\t\tawait visit(\"workflow\", run.id);\n\t\t\t}\n\t\t}\n\t\tfor (const session of agents.get(parentId) ?? []) {\n\t\t\tconst key = `agent:${session.id}`;\n\t\t\tif (!seen.has(key) && isCancelableAgentStatus(session.status, session.canceledAt)) {\n\t\t\t\tseen.add(key);\n\t\t\t\ttargets.push({\n\t\t\t\t\tkind: \"agent\",\n\t\t\t\t\tid: session.id\n\t\t\t\t});\n\t\t\t\tawait visit(\"agent\", session.id);\n\t\t\t}\n\t\t}\n\t};\n\tawait visit(kind, id);\n\treturn targets;\n}\nasync function cancelChildren(kind, id) {\n\tconst children = await collectChildRunCancelTargets(kind, id);\n\tawait Promise.all(children.map(async (child) => {\n\t\tif (child.kind === \"workflow\") await finalizeCanceledWorkflowRun(child.id);\n\t\telse await cancelAgentSessionRow(child.id, /* @__PURE__ */ new Date());\n\t}));\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 cancelChildren(\"workflow\", runId);\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 cancelChildren(\"agent\", sessionId);\n\tawait cancelAgentSessionRow(sessionId, /* @__PURE__ */ new Date());\n\treturn findHistoryRunCore(sessionId);\n}\n//#endregion\n//#region src/runtime/map-pool.ts\n/**\n* Run `worker` over `items` with at most `concurrency` in flight.\n* Soft-delete / post-pass work should stay outside this helper.\n*/\nasync function mapPool(items, concurrency, worker) {\n\tif (items.length === 0) return [];\n\tconst limit = Math.max(1, Math.min(concurrency, items.length));\n\tconst results = new Array(items.length);\n\tlet nextIndex = 0;\n\tawait Promise.all(Array.from({ length: limit }, async () => {\n\t\twhile (true) {\n\t\t\tconst index = nextIndex;\n\t\t\tnextIndex += 1;\n\t\t\tif (index >= items.length) return;\n\t\t\tresults[index] = await worker(items[index], index);\n\t\t}\n\t}));\n\treturn results;\n}\n//#endregion\n//#region src/runtime/agents/sync.ts\nconst SYNC_CONCURRENCY$2 = 8;\nfunction agentMetadata(record) {\n\treturn {\n\t\tname: record.name ?? null,\n\t\tdescription: record.description ?? null,\n\t\t...record.sandboxMode !== void 0 ? { sandboxMode: record.sandboxMode } : {},\n\t\ttoolCount: record.toolCount ?? null,\n\t\tcredentialCount: record.credentialCount ?? null,\n\t\tappSlugs: record.appSlugs ?? null,\n\t\t...record.brainSlugs !== void 0 ? { brainSlugs: record.brainSlugs } : {}\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\tconst entries = await mapPool(records, SYNC_CONCURRENCY$2, async (record) => {\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\treturn {\n\t\t\t\troute: record.route,\n\t\t\t\tentry: {\n\t\t\t\t\tid: existing.id,\n\t\t\t\t\tslug: record.slug\n\t\t\t\t}\n\t\t\t};\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\treturn {\n\t\t\troute: record.route,\n\t\t\tentry: {\n\t\t\t\tid,\n\t\t\t\tslug: record.slug\n\t\t\t}\n\t\t};\n\t});\n\tfor (const { route, entry } of entries) byRoute.set(route, entry);\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/runtime/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}\n/** Message events with seq — for model-context rebuild without a full event-log scan. */\nasync function listMessageEventRecords(sessionId, afterSeq) {\n\treturn (await listMessageEventsForSession(sessionId, MESSAGE_EVENT_TYPE, afterSeq)).map((row) => ({\n\t\tseq: row.seq,\n\t\tpayload: row.payload\n\t}));\n}\n/** Compaction events with seq — indexed by event type, not a full session scan. */\nasync function listContextCompactedEventRecords(sessionId) {\n\treturn (await listMessageEventsForSession(sessionId, CONTEXT_COMPACTED_EVENT_TYPE)).map((row) => ({\n\t\tseq: row.seq,\n\t\tpayload: row.payload\n\t}));\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}\n/** The highest-seq event of one of the given types — tail lookup, no full-log scan. */\nasync function latestSessionEventByTypes(sessionId, eventTypes) {\n\tconst row = await selectLatestAgentEventByTypes(sessionId, eventTypes);\n\tif (!row) return;\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\n\t};\n}\nasync function hasSessionEventAfterSeq(sessionId, eventType, afterSeq) {\n\treturn hasAgentEventAfterSeq(sessionId, eventType, afterSeq);\n}\n/** Explicit status writes: running at prompt start, completed on clean end. */\nasync function setSessionStatus(sessionId, status) {\n\tawait updateAgentSessionStatus(sessionId, status);\n}\n//#endregion\n//#region src/runtime/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* Best-effort message from a failed agent session's terminal span. Used by\n* parent waiters (queued subagents) so the parent sees the real failure text\n* instead of a generic \"Child agent prompt failed\".\n*/\nasync function readAgentSessionErrorMessage(sessionId) {\n\tconst span = await selectLatestAgentSessionSpanByRefId(sessionId);\n\tif (!span || span.status !== \"error\" || span.error == null) return null;\n\tconst payload = span.error;\n\tif (typeof payload === \"object\" && \"message\" in payload) {\n\t\tconst message = payload.message;\n\t\tif (typeof message === \"string\" && message.length > 0) return message;\n\t}\n\tif (typeof payload === \"string\" && payload.length > 0) return payload;\n\treturn null;\n}\n/**\n* Mark an agent session as failed: sets the explicit `status` column (skipped\n* when the session was canceled — cancellation wins) and closes or inserts its\n* terminal `agent_session` trace span, which legacy rows derive status from.\n*\n* Overwrites an `ok` span when a soft/late failure corrects a false completion\n* (so the UI still gets an error message). Leaves an existing `error` span alone\n* so the first failure wins.\n*/\nasync function failAgentSession(sessionId, error) {\n\tconst serializedError = serializeSpanError(error);\n\tconst finishedAt = /* @__PURE__ */ new Date();\n\tawait updateAgentSessionStatus(sessionId, \"failed\");\n\tconst span = await selectLatestAgentSessionSpanByRefId(sessionId);\n\tif (span) {\n\t\tif (span.status === \"error\") 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/runtime/skills/sync.ts\nconst SYNC_CONCURRENCY$1 = 8;\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\tconst entries = await mapPool(records, SYNC_CONCURRENCY$1, async (record) => {\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\treturn {\n\t\t\t\tslug: record.slug,\n\t\t\t\tentry: {\n\t\t\t\t\tid: existing.id,\n\t\t\t\t\tslug: record.slug\n\t\t\t\t}\n\t\t\t};\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\treturn {\n\t\t\tslug: record.slug,\n\t\t\tentry: {\n\t\t\t\tid,\n\t\t\t\tslug: record.slug\n\t\t\t}\n\t\t};\n\t});\n\tfor (const { slug, entry } of entries) bySlug.set(slug, entry);\n\tif (slugs.length === 0) await softDeleteAllSkills(now);\n\telse await softDeleteSkillsNotInSlugs(slugs, now);\n\treturn bySlug;\n}\n//#endregion\n//#region src/runtime/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*\n* Bump `overviewPromptVersion` when the overview job's prompt inputs change in a way\n* that should invalidate cached markdown (e.g. adding timezone to the LLM prompt).\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\toverviewPromptVersion: 1,\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, options) {\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\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\tdisabledAt: null,\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\tif (schedule && (source.kind === \"cron\" || source.kind === \"poll\")) {\n\t\t\tconst initialNextRunAt = options?.resolveInitialNextRunAt?.(schedule, source.kind, now, source.timezone) ?? now;\n\t\t\tconst executable = await listExecutableAttachmentsByTriggerIds([triggerId]);\n\t\t\tawait upsertTriggerScheduleFields({\n\t\t\t\ttriggerSlug: group.triggerSlug,\n\t\t\t\tschedule,\n\t\t\t\tnextRunAt: existingTrigger?.nextRunAt ?? initialNextRunAt,\n\t\t\t\tenabled: executable.length > 0,\n\t\t\t\tupdatedAt: now\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/runtime/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/runtime/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 = input.id && input.id.length > 0 ? input.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/runtime/triggers/assignments.ts\nfunction triggerStatusFromRow(row, attachments) {\n\tif (row.deletedAt) return \"disabled\";\n\tconst lifecycleStatus = row.lifecycle?.status;\n\tif (lifecycleStatus === \"disabled\" || lifecycleStatus === \"completed\") return \"disabled\";\n\tif (attachments !== void 0) {\n\t\tif (!attachments.some((attachment) => triggerAttachmentStatusFromRow(attachment) === \"active\")) return \"disabled\";\n\t}\n\tif (row.kind === \"cron\" || row.kind === \"poll\") return row.enabled === 1 ? \"active\" : \"disabled\";\n\treturn \"active\";\n}\nfunction assignmentFromRow(row, trigger, target) {\n\treturn {\n\t\tkind: target.kind,\n\t\tid: target.id,\n\t\tslug: target.slug,\n\t\tname: target.name,\n\t\tattachmentId: row.id,\n\t\tattachmentSlug: row.slug,\n\t\tstatus: triggerAttachmentStatusFromRow(row),\n\t\tdisabledAt: row.disabledAt ? row.disabledAt.toISOString() : null\n\t};\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(assignmentFromRow(row, trigger, {\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(assignmentFromRow(row, trigger, {\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/runtime/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() ?? row.workflowSlug,\n\t\t\t\tattachmentId: row.id,\n\t\t\t\tattachmentSlug: row.slug,\n\t\t\t\tstatus: triggerAttachmentStatusFromRow(row),\n\t\t\t\tdisabledAt: row.disabledAt ? row.disabledAt.toISOString() : null\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() ?? row.agentSlug,\n\t\t\t\tattachmentId: row.id,\n\t\t\t\tattachmentSlug: row.slug,\n\t\t\t\tstatus: triggerAttachmentStatusFromRow(row),\n\t\t\t\tdisabledAt: row.disabledAt ? row.disabledAt.toISOString() : null\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\tconst name = titleCaseResourceName(trigger.slug, trigger.name);\n\treturn {\n\t\tid: trigger.id,\n\t\tslug: trigger.slug,\n\t\tname,\n\t\tdescription: trigger.description?.trim() || name,\n\t\ttype: trigger.kind,\n\t\tstatus: triggerStatusFromRow(trigger, attachments),\n\t\tprojectId: trigger.projectId,\n\t\tschedule: trigger.schedule,\n\t\ttimezone: triggerTimezoneFromConfig(trigger.config ?? null) ?? null,\n\t\tnextRunAt: trigger.nextRunAt ? trigger.nextRunAt.toISOString() : null,\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, options) {\n\tconst triggers = await listActiveTriggersByProjectIds(projectIds, { limit: options?.limit ?? 200 });\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 getWorkspaceTriggerById(triggerId, [projectId]);\n}\n/**\n* Single workspace trigger by id. Optionally restrict to `projectIds` (caller access set).\n* Loads attachments / fire stats / assignment refs for that trigger only.\n*/\nasync function getWorkspaceTriggerById(triggerId, projectIds) {\n\tif (projectIds !== void 0 && projectIds.length === 0) return null;\n\tconst trigger = await selectActiveTriggerById(triggerId);\n\tif (!trigger) return null;\n\tif (projectIds !== void 0 && !projectIds.includes(trigger.projectId)) return null;\n\tconst [attachments, lastFiredAt, fireCount] = await Promise.all([\n\t\tlistAttachmentsByTriggerIds([trigger.id]),\n\t\tselectTriggerLastFiredAtByTriggerIds([trigger.id]),\n\t\tselectTriggerFireCountByTriggerIds([trigger.id])\n\t]);\n\tconst { workflows, agents } = await buildResourceMaps([trigger.projectId]);\n\treturn buildRecord(trigger, attachments, workflows, agents, lastFiredAt, fireCount);\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\toutcome: options.outcome\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/runtime/triggers/set-attachment-enabled.ts\nasync function syncTriggerScheduleForAttachments(trigger, now) {\n\tif (trigger.kind !== \"cron\" && trigger.kind !== \"poll\") return;\n\tconst executable = await listExecutableAttachmentsByTriggerIds([trigger.id]);\n\tawait setTriggerScheduleEnabled(trigger.slug, executable.length > 0, now);\n}\nasync function setTriggerAttachmentEnabledState(options) {\n\tconst trigger = await selectTriggerById(options.triggerId);\n\tif (!trigger || trigger.deletedAt !== null) return null;\n\tconst attachment = await selectTriggerAttachmentById(options.attachmentId);\n\tif (!attachment || attachment.deletedAt !== null || attachment.triggerId !== trigger.id) return null;\n\tconst now = /* @__PURE__ */ new Date();\n\tif (isTriggerAttachmentExecutable(attachment) === options.enabled) return {\n\t\ttrigger,\n\t\tattachmentId: attachment.id\n\t};\n\tawait setTriggerAttachmentEnabled(attachment.id, options.enabled, now);\n\tawait syncTriggerScheduleForAttachments(trigger, now);\n\treturn {\n\t\ttrigger: await selectTriggerById(trigger.id) ?? trigger,\n\t\tattachmentId: attachment.id\n\t};\n}\n/** Count executable (non-deleted, non-disabled) attachments for a trigger. */\nasync function countExecutableAttachments(triggerId) {\n\treturn (await listExecutableAttachmentsByTriggerIds([triggerId])).length;\n}\n//#endregion\n//#region src/runtime/triggers/stored-source-from-row.ts\nfunction storedTriggerSourceFromRow(row) {\n\tconst slug = row.slug;\n\tconst meta = {\n\t\tname: row.name,\n\t\tdescription: row.description\n\t};\n\tif (row.kind === \"webhook\") {\n\t\tconst config = row.config ?? {};\n\t\treturn {\n\t\t\t...meta,\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\") {\n\t\tconst config = row.config ?? null;\n\t\treturn {\n\t\t\t...meta,\n\t\t\tkind: \"cron\",\n\t\t\tslug,\n\t\t\tschedule: row.schedule ?? \"\",\n\t\t\t...config?.timezone ? { timezone: config.timezone } : {},\n\t\t\t...config?.payload !== void 0 ? { payload: config.payload } : {}\n\t\t};\n\t}\n\tconst config = row.config ?? {};\n\treturn {\n\t\t...meta,\n\t\tkind: \"poll\",\n\t\tslug,\n\t\tschedule: row.schedule ?? \"\",\n\t\t...config.timezone ? { timezone: config.timezone } : {},\n\t\t...config.code ? { code: config.code } : {},\n\t\t...config.id ? { id: config.id } : {}\n\t};\n}\n//#endregion\n//#region src/runtime/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,\n\t\t\tdescription: input.description,\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,\n\t\t\tdescription: input.description,\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/runtime/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 triggerTimezone(source) {\n\treturn triggerTimezoneFromSource(source) ?? null;\n}\nfunction triggerEndpoint(source) {\n\tif (source.kind === \"webhook\") return source.endpoint;\n\treturn null;\n}\nfunction agentTriggerStatus(row, attachment) {\n\tif (row.origin === \"ephemeral\") {\n\t\tconst lifecycleStatus = row.lifecycle?.status;\n\t\tif (lifecycleStatus === \"disabled\" || lifecycleStatus === \"completed\") return lifecycleStatus;\n\t}\n\tif (triggerAttachmentStatusFromRow(attachment) === \"disabled\") return \"disabled\";\n\treturn row.lifecycle?.status ?? \"active\";\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\ttimezone: triggerTimezone(source),\n\t\tnextRunAt: row.nextRunAt ? row.nextRunAt.toISOString() : null,\n\t\tendpoint: triggerEndpoint(source),\n\t\torigin: row.origin,\n\t\tprompt: attachment.prompt ?? null,\n\t\tstatus: agentTriggerStatus(row, attachment),\n\t\texecutionCount: row.lifecycle?.executionCount ?? 0,\n\t\tuntil: row.lifecycle?.until ?? null,\n\t\tattachmentId: attachment.id,\n\t\tattachmentSlug: attachment.slug\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/runtime/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/runtime/workflows/sync.ts\n/** Bound parallel upserts so cold boot doesn't open a DB stampede. */\nconst SYNC_CONCURRENCY = 8;\nfunction workflowMetadata(record) {\n\treturn {\n\t\tname: record.name,\n\t\tdescription: record.description,\n\t\trequestSchema: record.requestSchema\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\tconst entries = await mapPool(records, SYNC_CONCURRENCY, async (record) => {\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\treturn {\n\t\t\t\tslug: record.slug,\n\t\t\t\tentry: {\n\t\t\t\t\tid: existing.id,\n\t\t\t\t\tslug: record.slug,\n\t\t\t\t\tsubscribable: record.subscribable\n\t\t\t\t}\n\t\t\t};\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\treturn {\n\t\t\tslug: record.slug,\n\t\t\tentry: {\n\t\t\t\tid,\n\t\t\t\tslug: record.slug,\n\t\t\t\tsubscribable: record.subscribable\n\t\t\t}\n\t\t};\n\t});\n\tfor (const { slug, entry } of entries) bySlug.set(slug, entry);\n\tif (slugs.length === 0) await softDeleteAllWorkflows(now);\n\telse await softDeleteWorkflowsNotInSlugs(slugs, now);\n\treturn bySlug;\n}\n//#endregion\n//#region src/runtime/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/runtime/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/runtime/workflows/hook-store.ts\nfunction hookSummaryFromRow(row) {\n\treturn {\n\t\ttoken: row.token,\n\t\tcorrelationId: row.correlationId,\n\t\tstatus: row.status,\n\t\tcreatedAt: row.createdAt\n\t};\n}\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\tschema: row.schema,\n\t\t\t\tpayload: row.payload\n\t\t\t};\n\t\t},\n\t\tasync listByRun(runId, options) {\n\t\t\treturn (await listWorkflowHooksByRun(runId, options)).map(hookSummaryFromRow);\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/runtime/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\toutcome: options.outcome\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/runtime/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/runtime/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/runtime/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/runtime/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 previousConnectionId = existing.connectionId;\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\treturn {\n\t\tinstanceId: existing.id,\n\t\tcreated: false,\n\t\tpreviousConnectionId\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 created = !existing;\n\tconst instanceId = existing?.id ?? crypto.randomUUID();\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: instanceId,\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\treturn {\n\t\tinstanceId,\n\t\tcreated,\n\t\tpreviousConnectionId: null\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) return runWithProjectScope(existing.scopeId, reconnect);\n\t\treturn reconnect();\n\t}\n\tconst { scopeType, scopeId, ...scopeOptions } = options;\n\tif (scopeType === \"project\") return runWithProjectScope(scopeId, () => ensureKeystrokeInstanceForScope({\n\t\t...scopeOptions,\n\t\tscopeType,\n\t\tscopeId\n\t}));\n\treturn ensureKeystrokeInstanceForScope({\n\t\t...scopeOptions,\n\t\tscopeType,\n\t\tscopeId\n\t});\n}\n//#endregion\n//#region src/runtime/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\tparent: input.parent ?? 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\t...row.parent ? { parent: row.parent } : {},\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\t...row.parent ? { parent: row.parent } : {},\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 { BrainDocumentRevisionConflictError, BrainDocumentWriteIdempotencyConflictError, BrainFilterSlugConflictError, BrainLastOwnerError, DEFAULT_DATABASE_URL, DEFAULT_LIST_LIMIT, DEFAULT_PG_POOL_MAX, DEFAULT_PROJECT_ID, EPHEMERAL_TRIGGER_MODULE_FILE, GatewayChannelConflictError, MESSAGE_EVENT_TYPE, SKIPPED_WEBHOOK_TRIGGER_RUN_RETENTION_MS, abortBrainRebuild, acquireProjectDatabasePool, adaptPgMigrationsForSearchPath, addAgentSessionDuration, addBrainMember, appendEvent, assertPgIdent, attachBrainDocumentWriteEvent, beginBrainDocumentWriteEvent, buildAgentSessionDetail, buildHistoryAgentSessionDetail, buildHistoryWorkflowRunDetail, buildPostgresUrl, buildTriggerRunDetail, buildWorkflowRunDetail, cancelAgentSession, cancelWorkflowRun, claimBrainDocumentVersionForIngestion, claimBrainMutation, claimBrainRebuild, claimDueTriggers, claimDueTriggersForOrg, claimNextJob, clearAgentSessionCancellation, clearCredentialInstanceDefaults, closeAllProjectDatabasePools, closeDatabase, collectChildRunCancelTargets, commitBrainDocumentVersionPromotion, commitBrainRebuild, compareAndSetBrainActiveGeneration, compareAndSetBrainDocumentVersionStatus, compareAndSetBrainStatus, compileBrainFilterExpressionSql, completeBrainDeletion, completeWorkflowRun, countBrainDocuments, countBrainFiltersByBrainIds, countBrainProjectsByBrainIds, countExecutableAttachments, countMessageEvents, createAgentAttachmentExecution, createAttachmentExecution, createBrainFilter, createBrainWithOwner, createClaimScopedHandle, createConnection, createDatabaseEventLog, createDatabaseHookStore, createDatabaseTracingSink, createOrgScopedHandle, createOrganizationClaim, createPendingAttachmentExecution, createPendingWorkflowRun, createPgConnection, createPostgresCancelChannel, createPublicScopedHandle, createPublicScopedPool, createSession, createSqliteConnection, createWorkflowRun, decodeCreatedAtIdCursor, decryptCredentialPayload, deleteBrainDocumentVersionById, deleteBrainDocumentVersionsForDocument, deleteBrainFilter, deleteBrainFilters, deleteBrainMembers, deleteCredentialAssignmentById, deleteCredentialInstanceById, deleteEphemeralTrigger, deleteWorkflowSubscriptionById, disableAllTriggerSchedules, disableTriggerSchedulesNotInSlugs, encodeCreatedAtIdCursor, encryptCredentialPayload, enqueueJob, ensureKeystrokeCredentialInstance, ensureOAuthCredentialInstance, explainMissingWorkflowRun, failAgentSession, failWorkflowRun, finalizeCanceledWorkflowRun, findHistoryRunCore, findReadyVersionBySha, gatewayAttachmentKeyForChannel, getActiveGatewayAttachmentByChannel, getActiveOrgGatewayAttachmentByChannel, getActiveOrgGatewayAttachmentByTeamAndChannel, getAgentByRoute, getBoundProjectScopeId, getDatabaseHandle, getGatewayAttachmentBySlug, getJobByRunId, getOrCreateGatewayThreadSession, getProjectScopeId, getServerTenantScopeId, getSession, getTraceForAgentSession, getTraceForTriggerRun, getTraceForWorkflowRun, getTriggerAttachmentBySlug, getTriggerRunForAgentSession, getWorkflowSubscription, getWorkspaceTrigger, getWorkspaceTriggerById, hardDeleteBrainTenantRows, hasSessionEventAfterSeq, inferDialect, initDatabase, initializeBrainVectorDimensions, insertWorkflowSubscription, isDatabaseInitialized, isEphemeralTriggerActive, latestSessionEventByTypes, listActiveAgents, listActiveGatewayAttachments, listActiveGatewayAttachmentsByAgentSlug, listActiveGatewayAttachmentsByPlatform, listActiveOrgGatewayBindingsByPlatform, listActiveSkills, listActiveTriggerAttachments, listActiveWorkflows, listAgentSessionsBySourceIds, listAgentSessionsPaginated, listAgentTriggers, listAllCredentialInstances, listAttachmentsByTriggerIds, listBrainDocumentVersionsBeforeDeletionEpoch, listBrainDocumentWriteEvents, listBrainDocuments, listBrainFilters, listBrainGrants, listBrainMembers, listBrainSlugsWhereUserIsSoleOwner, listBrainsForMember, listBrainsForProject, listChildDispatchedEvents, listContextCompactedEventRecords, listCredentialAssignmentsByTarget, listCredentialInstancesByConnectionId, listCredentialInstancesByScope, listCredentialInstancesForAssignment, listCurrentBrainDocumentVersionsForRebuild, listDeletingBrains, listEnabledScheduledTriggers, listEnabledWorkflowSubscriptionsByWorkflowSlug, listExecutableAttachmentsByTriggerIds, listHistoryRuns, listMessageEventRecords, listMessageEvents, listPendingBrainDocumentVersions, listRecentResourceActivity, listRecentWorkflowStepConsumers, listReplayEvents, listSessionEvents, listStepCompletedEvents, listTriggerRunsPaginated, listTriggersByIds, listWorkflowRunsByParentRunIds, listWorkflowRunsBySourceIds, listWorkflowRunsByWorkflowSlug, listWorkflowRunsPaginated, listWorkflowSubscriptionsByWorkflowSlug, listWorkspaceTriggerRunRows, listWorkspaceTriggers, loadMigrations, markAttachmentExecutionRunning, markBrainDocumentWriteContentReceived, markJobComplete, markJobFailed, markWorkflowRunRunning, markWorkflowRunSleeping, markWorkflowRunWaitingChildren, markWorkflowRunWaitingHook, migratePgDatabase, nextSeq, normalizeStoredTriggerSource, parsePostgresUrl, prepareBrainDocumentPut, prepareBrainUploadVersion, primarySearchPathSchema, promoteBrainDocumentVersion, pruneSkippedWebhookTriggerRuns, qualifyConnectionUser, quotePgIdent, readAgentSessionErrorMessage, recordEphemeralTriggerExecution, recordTriggerFire, releaseBrainDocumentVersionLease, releaseProjectDatabasePool, removeBrainGrant, removeBrainMember, renewBrainDocumentVersionLease, requeueExpiredLeases, resolveAgentProjectId, resolveDatabaseUrlFromEnv, resolveMigrationsFolder, resolveMigrationsSchema, resolvePgPoolMax, resolvePostgresConfigFromEnv, resolvePostgresUrlFromEnv, resolveProjectDatabaseUrlFromEnv, resolveRunSourceFromTraceContext, resolveSearchPath, resolveSqlitePath, resolveTriggerAssignments, resolveWorkflowRunProjectId, restoreSoftDeletedBrain, runMigrations, runSource, runWithProjectDatabase, runWithProjectScope, runWithTenantScope, scheduleJobRetry, selectActiveAgentById, selectActiveAgentsByIds, selectActiveBrainBySlug, selectActiveEphemeralCronAttachmentSlugs, selectActiveEphemeralScheduledAttachmentSlugs, selectActiveEphemeralScheduledTriggerSlugs, selectActiveSkillById, selectActiveSkillsByIds, selectActiveSkillsBySlugs, selectActiveTriggerById, selectActiveWorkflowById, selectActiveWorkflowBySlug, selectActiveWorkflowsByIds, selectAgentBySlug, selectAgentLastRunAtByIds, selectAgentSessionById, selectBrainAvailableToProject, selectBrainById, selectBrainByIdIncludingDeleted, selectBrainDocumentByKey, selectBrainDocumentByKeyIncludingDeleted, selectBrainDocumentByRowId, selectBrainDocumentDetail, selectBrainDocumentVersionById, selectBrainDocumentWriteEventById, selectBrainDocumentWriteEventByIdentity, selectBrainDocumentWriteEventsByVersionIds, selectBrainFilterById, selectBrainFilterBySlug, selectBrainMember, selectCredentialAssignmentById, selectCredentialInstanceById, selectCredentialInstancesByAppSlug, selectCredentialInstancesByIds, selectCredentialInstancesForScope, selectCredentialInstancesForScopes, selectDeletingBrainAvailableToProject, selectDisabledAttachmentSlugs, selectEphemeralTriggerAttachments, selectEphemeralTriggerAttachmentsByAgentSlug, selectGatewayThreadSessionByThreadId, selectProjectResourceCounts, selectTriggerAttachmentsByAgentSlug, selectTriggerById, selectTriggerBySlug, selectWebhookTriggerAttachments, selectWebhookTriggers, selectWorkflowCanvasAnnotations, selectWorkflowLastRunAtByIds, selectWorkflowOverview, selectWorkflowRunById, selectWorkflowRunForWorkflow, selectWorkflowRunInputValues, selectWorkflowSubscriptionById, selectWorkflowSubscriptionByWorkflowAndUser, setCredentialInstanceValue, setSessionStatus, setSessionTitle, setTriggerAttachmentEnabled, setTriggerAttachmentEnabledState, setTriggerOverviewGenerating, setTriggerScheduleEnabled, setWorkflowCanvasAnnotationsGenerating, setWorkflowOverviewGenerating, settleBrainDocumentWriteEvent, softDeleteBrain, softDeleteBrainDocuments, softDeleteGatewayAttachmentByChannel, softDeleteGatewayAttachmentsForAgentPlatformTeam, sourceFromSpan, storedTriggerSourceFromRow, storedTriggerSourceFromTrigger, storedTriggerSourceSlug, summarizeBrainDocumentsByBrainIds, syncAgentRegistry, syncSkillRegistry, syncTriggerAttachmentRegistry, syncWorkflowRegistry, touchCredentialInstanceLastUsed, touchResourceActivity, touchSession, triggerAttachmentStatusFromRow, triggerScheduleFromSource, triggerSourceGroupKeyFromSource, triggerStatusFromRow, triggerTimezoneFromConfig, triggerTimezoneFromSource, updateBrain, updateBrainDocumentMetadata, updateBrainFilter, updateBrainMemberRole, updateTriggerOverview, updateTriggerState, updateWorkflowCanvasAnnotations, updateWorkflowOverview, updateWorkflowRunInputValues, updateWorkflowSubscriptionById, upsertBrainGrant, upsertCredentialAssignment, upsertCredentialInstance, upsertEphemeralTrigger, upsertGatewayAttachmentByChannel, upsertTriggerScheduleFields, verifyOrganizationClaim };\n\n//# sourceMappingURL=index.mjs.map","//#region src/map-in-batches.ts\n/** Default concurrency for parallel blob downloads and file writes. */\nconst DEFAULT_PARALLEL_BATCH_SIZE = 8;\n/** Run `fn` over `items` in parallel batches of `batchSize`. */\nasync function mapInParallelBatches(items, batchSize, fn) {\n\tif (batchSize < 1) throw new Error(\"batchSize must be at least 1\");\n\tconst results = [];\n\tfor (let index = 0; index < items.length; index += batchSize) {\n\t\tconst batch = items.slice(index, index + batchSize);\n\t\tresults.push(...await Promise.all(batch.map(fn)));\n\t}\n\treturn results;\n}\n//#endregion\nexport { DEFAULT_PARALLEL_BATCH_SIZE, mapInParallelBatches };\n\n//# sourceMappingURL=map-in-batches.mjs.map","import { existsSync, readFileSync, readdirSync, statSync } from \"node:fs\";\nimport { join, relative } from \"node:path\";\nimport { ProjectArtifactIndexSchema } from \"@keystrokehq/shared\";\nimport { createHash } from \"node:crypto\";\n//#region src/assert-module-blob-hash.ts\n/** Lowercase hex sha256 of raw bytes. */\nfunction sha256Hex(bytes) {\n\treturn createHash(\"sha256\").update(bytes).digest(\"hex\");\n}\n/**\n* Assert a content-addressed module blob matches its declared size and SHA-256 hash.\n* Returns a Buffer copy suitable for disk write / JSON parse.\n*/\nfunction assertModuleBlobMatchesHash(input) {\n\tif (input.bytes.byteLength !== input.expectedSize) throw new Error(`Module blob size mismatch for ${input.path}: expected ${input.expectedSize}, got ${input.bytes.byteLength}`);\n\tconst actual = sha256Hex(input.bytes);\n\tconst expected = input.expectedHash.toLowerCase();\n\tif (actual !== expected) throw new Error(`Module blob hash mismatch for ${input.path}: expected ${expected}, got ${actual}`);\n\treturn Buffer.from(input.bytes);\n}\n//#endregion\n//#region src/collect-artifact-modules.ts\nfunction toPosix(path) {\n\treturn path.replace(/\\\\/g, \"/\");\n}\nfunction walkFiles(dir) {\n\tif (!existsSync(dir) || !statSync(dir).isDirectory()) return [];\n\tconst out = [];\n\tfor (const name of readdirSync(dir)) {\n\t\tif (name === \".\" || name === \"..\") continue;\n\t\tconst abs = join(dir, name);\n\t\tconst st = statSync(abs);\n\t\tif (st.isDirectory()) out.push(...walkFiles(abs));\n\t\telse if (st.isFile() && !name.endsWith(\".map\")) out.push(abs);\n\t}\n\treturn out;\n}\n/**\n* Collect every file under `dist/` (except sourcemaps) for modular deploy upload.\n* Paths in the index are relative to `dist/` (e.g. `workflows/c.mjs`).\n*/\nfunction collectArtifactModules(projectRoot, outDir = \"dist\") {\n\tconst distRoot = join(projectRoot, outDir);\n\tif (!existsSync(distRoot) || !statSync(distRoot).isDirectory()) throw new Error(`Missing ${outDir}/ — run keystroke build before deploy`);\n\tconst files = walkFiles(distRoot);\n\tif (files.length === 0) throw new Error(`${outDir}/ is empty — run keystroke build before deploy`);\n\tconst collected = [];\n\tfor (const absolutePath of files) {\n\t\tconst bytes = readFileSync(absolutePath);\n\t\tconst path = toPosix(relative(distRoot, absolutePath));\n\t\tcollected.push({\n\t\t\tpath,\n\t\t\thash: sha256Hex(bytes),\n\t\t\tsize: bytes.byteLength,\n\t\t\tabsolutePath,\n\t\t\tbytes\n\t\t});\n\t}\n\tcollected.sort((a, b) => a.path.localeCompare(b.path));\n\treturn collected;\n}\n/** Build the Zod-validated artifact index (no bytes) from collected modules. */\nfunction artifactIndexFromModules(modules) {\n\treturn ProjectArtifactIndexSchema.parse({\n\t\tversion: 1,\n\t\tfiles: modules.map(({ path, hash, size }) => ({\n\t\t\tpath,\n\t\t\thash,\n\t\t\tsize\n\t\t}))\n\t});\n}\n/** Unique blob refs for presign (deduped by hash). */\nfunction moduleBlobRefsFromModules(modules) {\n\tconst byHash = /* @__PURE__ */ new Map();\n\tfor (const mod of modules) {\n\t\tconst existing = byHash.get(mod.hash);\n\t\tif (existing === void 0) byHash.set(mod.hash, mod.size);\n\t\telse if (existing !== mod.size) throw new Error(`Module blob size mismatch for hash ${mod.hash}`);\n\t}\n\treturn [...byHash.entries()].map(([hash, size]) => ({\n\t\thash,\n\t\tsize\n\t})).sort((a, b) => a.hash.localeCompare(b.hash));\n}\n//#endregion\nexport { sha256Hex as a, assertModuleBlobMatchesHash as i, collectArtifactModules as n, moduleBlobRefsFromModules as r, artifactIndexFromModules as t };\n\n//# sourceMappingURL=collect-artifact-modules-CApdro3d.mjs.map","import { $ as cancelProjectDeploy, $r as oauthConnections, $t as buildOrgRedisUrl, Ar as projectAgentSessionSandboxesSqlite, At as checkOrganizationSlugAvailability, Br as platformAgentSessionsSqlite, Bt as eq$1, Cr as organizationBilling, Ct as selectUserOrganizations, Dn as runMigrations, Dr as publishedForms, Dt as updateOrganizationSlug, En as encryptCredentialPayload, Er as projectUsers, Et as updateOrganizationName, Fn as scopeClient, Fr as platformAgentProjectSnapshots, Ft as checkProjectSlugAvailability, G as DEFAULT_STANDALONE_PROJECT_SLUG, Gr as projectStatuses, Gt as lt$1, H as DEFAULT_STANDALONE_ORGANIZATION_NAME, Hr as projectRepositoriesSqlite, Ht as inArray$1, In as createConnection, Ir as platformAgentProjectSnapshotsSqlite, It as and$1, J as ensureDefaultProject, Jr as organizationInvitationStatuses, Jt as or$1, K as ensureDefaultOrganization, Kr as projects, Kt as max$1, Ln as createSqliteConnection, Lr as platformAgentEvents, Lt as asc, Mn as connectWithRetry, Mr as projectAgentEnvImagesSqlite, Mt as buildDefaultOrgProjectName, Nn as connectWithRetryCallback, Nr as platformAgentProjectSnapshotBuildStatuses, Nt as ensureDefaultOrgProjectInTransaction, On as resolveMigrationsFolder, Or as publishedFormsSqlite, Ot as organizationRowToSidebarBranding, Pn as runScopedQuery, Pr as platformAgentProjectSnapshotRecoveryStates, Pt as ProjectSlugTakenError, Q as abortStagedProjectDeploy, Qr as oauthPendingStates, Qt as isSqliteDialect, Rn as createPgConnection, Rr as platformAgentEventsSqlite, Rt as count$1, Sr as billingEvents, St as selectUserOrganizationMembership, Tn as decryptCredentialPayload, Tr as secretValues, Tt as updateOrganizationFailed, U as DEFAULT_STANDALONE_ORGANIZATION_SLUG, Ur as projectArtifactStatuses, Ut as isNotNull, V as DEFAULT_STANDALONE_ORGANIZATION_ID, Vn as createPgDb, Vr as projectRepositories, Vt as gt$1, W as DEFAULT_STANDALONE_PROJECT_NAME, Wr as projectArtifacts, Wt as isNull$1, X as runWithStandaloneScope, Xr as organizationUserRoles, Xt as getDb, Y as isStandaloneMode, Yr as organizationInvitations, Yt as sql$1, Z as PROJECT_DEPLOY_LEASE_TTL_MS, Zr as organizationUsers, Zt as getSqliteDb, _i as inferDialect, _r as managedServiceCredentials, _t as resolveNewOrganizationIdentity, ai as authApiKeys, an as orgDbRoleName, at as selectProjectById, br as billingLedger, bt as selectOrganizationBySlug, ci as getOrganizationScopeId, cn as orgRedisUsername, ct as selectProjectsByOrganizationId, di as resolvePlatformDatabaseUrl, dt as updateProjectFailed, ei as oauthApps, en as deprovisionOrgRedis, et as countActiveProjectsForOrganization, fi as resolvePlatformPostgresConfig, ft as updateProjectForOrganization, gi as qualifyConnectionUser, gt as isOrganizationStorageBucketInUse, hi as parsePostgresUrl, ht as createOrganizationForUser, ii as organizationsSqlite, in as provisionOrgDatabase, it as releaseProjectDeployLease, jr as projectAgentEnvImages, jt as addUserToDefaultOrgProjectInTransaction, kr as projectAgentSessionSandboxes, kt as updateOrganizationSidebarBranding, li as requireOrganizationScopeId, lt as tryAcquireProjectDeployLease, mi as buildPostgresUrl, mt as OrganizationSlugTakenError, ni as apps, nn as provisionOrgRedis, nt as deleteProjectForOrganization, oi as authApiKeysSqlite, on as orgDbSchemaName, ot as selectProjectForOrganization, pi as resolveTenantDatabaseUrl, pt as updateProjectSettings, q as ensureDefaultOrganizationAndProject, qr as projectsSqlite, qt as ne$1, ri as organizations, rn as deprovisionOrgDatabase, rt as refreshProjectDeployLease, s as listBrainSlugsWhereUserIsSoleOwner, si as bindOrganizationScope, sn as orgRedisQueueSegment, st as selectProjectForOrganizationBySlug, t as sanitizeMessagePayloadContext, ti as templates, tn as orgRedisAclSetUserArgs, tt as createProjectForOrganization, ui as runWithOrganizationScope, ut as updateProjectActive, vi as DEFAULT_PLATFORM_DATABASE_URL, vr as managedServiceCredentialsSqlite, vt as selectActiveOrganizationIds, wr as organizationBillingSqlite, wt as updateOrganizationActive, xr as billingWallet, xt as selectUserOrganization, yr as usageEvents, yt as selectOrganizationById, zn as resolveSearchPath, zr as platformAgentSessions, zt as desc$1 } from \"./sanitize-message-JfOafIe_.mjs\";\nimport { S as setDatabaseHandle, _ as users, x as isDatabaseInitialized, y as getDatabaseHandle } from \"./mcp-oauth-SRTcHMWZ.mjs\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { and, desc, eq, gt, gte, inArray, isNull, like, lte, max, ne, notInArray, sql } from \"drizzle-orm\";\nimport { log } from \"@keystrokehq/telemetry\";\nimport { join, relative } from \"node:path\";\nimport { createHash, randomBytes, timingSafeEqual } from \"node:crypto\";\nimport { AppSlugSchema, DEFAULT_PLAN_KEY, TemplateManifestSchema, parsePlatformAgentTranscript, qualifyOrgSlug, slugifyAppName } from \"@keystrokehq/shared\";\nimport { containerPresignEndpointFromEnv, createContainerPresignStorage, createStorage, orgAgentBucketName } from \"@keystrokehq/storage\";\nimport { readFile, readdir, stat } from \"node:fs/promises\";\n//#region src/client/close.ts\nasync function closeDatabase() {\n\tif (!isDatabaseInitialized()) return;\n\tawait getDatabaseHandle().close();\n\tsetDatabaseHandle(void 0);\n}\n/** Single multi-statement round trip: BEGIN + SET LOCAL search_path. */\nconst PUBLIC_SCOPE_BEGIN = `BEGIN; SET LOCAL search_path TO public`;\nfunction beginPublicScope(query) {\n\treturn query(PUBLIC_SCOPE_BEGIN);\n}\nfunction createPublicScopedClient(client, release) {\n\treturn scopeClient(client, beginPublicScope, release);\n}\nfunction createPublicScopedPool(pool) {\n\tconst scopedPool = Object.create(pool);\n\tscopedPool.query = ((...args) => runScopedQuery(pool, beginPublicScope, args));\n\tscopedPool.connect = ((callback) => {\n\t\tif (callback) {\n\t\t\tconnectWithRetryCallback(pool, (error, client) => {\n\t\t\t\tif (error || !client) {\n\t\t\t\t\tcallback(error ?? /* @__PURE__ */ new Error(\"failed to connect\"), client, () => void 0);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst scoped = createPublicScopedClient(client);\n\t\t\t\tcallback(null, scoped.client, scoped.release);\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\treturn connectWithRetry(pool).then((client) => createPublicScopedClient(client).client);\n\t});\n\treturn scopedPool;\n}\n//#endregion\n//#region src/tenant-claim/upsert-secret.ts\n/** Upsert the HMAC secret used by `keystroke.current_organization_id()`. */\nasync function upsertOrganizationClaimSecret(pool, secret = process.env.DATABASE_RLS_CLAIM_SECRET ?? \"\") {\n\tconst trimmed = secret.trim();\n\tif (!trimmed) throw new Error(\"DATABASE_RLS_CLAIM_SECRET is required to configure claim verification\");\n\tawait pool.query(`INSERT INTO keystroke_private.claim_secret (singleton, secret, updated_at)\n     VALUES (true, $1, now())\n     ON CONFLICT (singleton) DO UPDATE\n     SET secret = EXCLUDED.secret, updated_at = now()`, [trimmed]);\n}\n//#endregion\n//#region src/client/init.ts\nfunction resolveUrl(url) {\n\treturn url ?? resolvePlatformDatabaseUrl();\n}\nfunction wrapPlatformPostgresHandle(base) {\n\tconst pool = createPublicScopedPool(base.pool);\n\treturn {\n\t\tdialect: \"postgres\",\n\t\tdb: createPgDb(pool),\n\t\tpool,\n\t\tsearchPath: \"public\",\n\t\tclose: base.close\n\t};\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 base = createConnection({\n\t\turl,\n\t\tdialect,\n\t\tmax: options.max,\n\t\tsearchPath\n\t});\n\tconst next = base.dialect === \"postgres\" ? wrapPlatformPostgresHandle(base) : base;\n\tsetDatabaseHandle(next);\n\tif (options.migrate ?? true) await runMigrations(next, resolveMigrationsFolder(dialect, options.migrationsFolder));\n\tif (next.dialect === \"postgres\" && process.env.DATABASE_RLS_CLAIM_SECRET?.trim()) await upsertOrganizationClaimSecret(next.pool);\n}\n//#endregion\n//#region src/tenant-claim/ensure-runtime-role.ts\n/** Shared login for claim-scoped tenant SQL. Must not be superuser / BYPASSRLS / table owner. */\nconst TENANT_RUNTIME_ROLE = \"keystroke_runtime\";\nconst TENANT_TABLES = [\n\t\"agent_events\",\n\t\"agent_sessions\",\n\t\"agents\",\n\t\"credential_assignments\",\n\t\"credential_instances\",\n\t\"gateway_attachments\",\n\t\"gateway_thread_sessions\",\n\t\"jobs\",\n\t\"resource_activity\",\n\t\"skills\",\n\t\"trace_logs\",\n\t\"trace_spans\",\n\t\"trigger_attachments\",\n\t\"trigger_runs\",\n\t\"triggers\",\n\t\"workflow_events\",\n\t\"workflow_hooks\",\n\t\"workflow_runs\",\n\t\"workflow_subscriptions\",\n\t\"workflows\"\n];\nfunction quoteLiteral(value) {\n\treturn `'${value.replace(/'/g, \"''\")}'`;\n}\n/**\n* Create (or reset) the unprivileged runtime role used by claim-scoped pools.\n* Superusers bypass RLS even with FORCE — tenant traffic must authenticate as this role.\n*/\nasync function ensureTenantRuntimeRole(pool, password) {\n\tif (!password.trim()) throw new Error(\"Tenant runtime role password is required\");\n\tconst quotedPassword = quoteLiteral(password);\n\tawait pool.query(`\n    DO $role$\n    BEGIN\n      CREATE ROLE ${TENANT_RUNTIME_ROLE} WITH LOGIN PASSWORD ${quotedPassword}\n        NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS;\n    EXCEPTION\n      WHEN duplicate_object THEN\n        ALTER ROLE ${TENANT_RUNTIME_ROLE} WITH LOGIN PASSWORD ${quotedPassword}\n          NOSUPERUSER NOBYPASSRLS;\n    END\n    $role$;\n  `);\n\tawait pool.query(`GRANT USAGE ON SCHEMA public TO ${TENANT_RUNTIME_ROLE}`);\n\tawait pool.query(`GRANT USAGE ON SCHEMA keystroke TO ${TENANT_RUNTIME_ROLE}`);\n\tawait pool.query(`GRANT SELECT, INSERT, UPDATE, DELETE ON ${TENANT_TABLES.map((t) => `public.${t}`).join(\", \")} TO ${TENANT_RUNTIME_ROLE}`);\n}\n/** Rewrite a postgres URL to authenticate as the tenant runtime role. */\nfunction buildTenantRuntimeDatabaseUrl(adminUrl, password) {\n\treturn buildPostgresUrl({\n\t\t...parsePostgresUrl(adminUrl),\n\t\tuser: TENANT_RUNTIME_ROLE,\n\t\tpassword\n\t});\n}\n//#endregion\n//#region src/queries/billing/index.ts\n/**\n* Platform billing authority: `organization_billing` (Stripe/plan),\n* `billing_wallet` / `billing_ledger` / `usage_events`, plus `billing_events`\n* (best-effort webhook audit). Grant idempotency is `billing_ledger`\n* `(organization_id, idempotency_key)`.\n*/\n/** Must match `@keystroke-cloud/billing` `WELCOME_CREDIT_IDEMPOTENCY_PREFIX`. */\nconst WELCOME_CREDIT_IDEMPOTENCY_PREFIX = \"promo:welcome:\";\n/**\n* Postgres uses a real transaction and row locks. SQLite is only used for local\n* dev/tests here; better-sqlite3 does not support async transaction callbacks.\n*/\nasync function withBillingTx(fn) {\n\tconst db = getDb();\n\tif (getDatabaseHandle().dialect === \"postgres\") return db.transaction(fn);\n\treturn fn(db);\n}\nfunction balancesOf(wallet, deltaPlan, deltaPrepaid) {\n\treturn {\n\t\tplanCreditMicroCredits: wallet.planCreditMicroCredits + deltaPlan,\n\t\tprepaidCreditMicroCredits: wallet.prepaidCreditMicroCredits + deltaPrepaid\n\t};\n}\nfunction storedJson(value) {\n\tif (value == null) return null;\n\treturn getDatabaseHandle().dialect === \"sqlite\" ? JSON.stringify(value) : value;\n}\nasync function lockWallet(tx, organizationId) {\n\tawait tx.insert(billingWallet).values({\n\t\torganizationId,\n\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t}).onConflictDoNothing();\n\tconst query = tx.select().from(billingWallet).where(eq(billingWallet.organizationId, organizationId));\n\tconst wallet = (getDatabaseHandle().dialect === \"postgres\" ? await query.for(\"update\") : await query)[0];\n\tif (!wallet) throw new Error(`billing wallet missing for organization ${organizationId}`);\n\treturn wallet;\n}\nfunction splitDebit(wallet, chargeMicroCredits) {\n\tconst fromPlan = Math.min(Math.max(wallet.planCreditMicroCredits, 0), chargeMicroCredits);\n\treturn {\n\t\tplanCreditMicroCredits: fromPlan,\n\t\tprepaidCreditMicroCredits: chargeMicroCredits - fromPlan\n\t};\n}\nasync function getOrCreateBillingWallet(organizationId) {\n\tconst db = getDb();\n\tawait db.insert(billingWallet).values({\n\t\torganizationId,\n\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t}).onConflictDoNothing();\n\tconst row = (await db.select().from(billingWallet).where(eq(billingWallet.organizationId, organizationId)).limit(1))[0];\n\tif (!row) throw new Error(`billing wallet missing for organization ${organizationId}`);\n\treturn row;\n}\nasync function getBillingWallet(organizationId) {\n\treturn (await getDb().select().from(billingWallet).where(eq(billingWallet.organizationId, organizationId)).limit(1))[0];\n}\nasync function applyLedgerCredit(input) {\n\treturn withBillingTx(async (tx) => {\n\t\tconst wallet = await lockWallet(tx, input.organizationId);\n\t\tconst planDelta = input.planDeltaMicroCredits ?? 0;\n\t\tconst prepaidDelta = input.prepaidDeltaMicroCredits ?? 0;\n\t\tconst createdAt = input.createdAt ?? /* @__PURE__ */ new Date();\n\t\tconst ledgerEntryId = (await tx.insert(billingLedger).values({\n\t\t\tid: crypto.randomUUID(),\n\t\t\torganizationId: input.organizationId,\n\t\t\tentryType: input.entryType,\n\t\t\tplanDeltaMicroCredits: planDelta,\n\t\t\tprepaidDeltaMicroCredits: prepaidDelta,\n\t\t\tsource: input.source,\n\t\t\tidempotencyKey: input.idempotencyKey,\n\t\t\trunId: input.runId ?? null,\n\t\t\tprojectId: input.projectId ?? null,\n\t\t\tproviderReference: input.providerReference ?? null,\n\t\t\tmetadata: storedJson(input.metadata),\n\t\t\tcreatedAt\n\t\t}).onConflictDoNothing().returning({ id: billingLedger.id }))[0]?.id ?? null;\n\t\tif (!ledgerEntryId) return {\n\t\t\tapplied: false,\n\t\t\tledgerEntryId: null,\n\t\t\tbalances: balancesOf(wallet, 0, 0)\n\t\t};\n\t\tawait tx.update(billingWallet).set({\n\t\t\tplanCreditMicroCredits: wallet.planCreditMicroCredits + planDelta,\n\t\t\tprepaidCreditMicroCredits: wallet.prepaidCreditMicroCredits + prepaidDelta,\n\t\t\t...input.periodStart === void 0 ? {} : { periodStart: input.periodStart },\n\t\t\t...input.periodEnd === void 0 ? {} : { periodEnd: input.periodEnd },\n\t\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t\t}).where(eq(billingWallet.organizationId, input.organizationId));\n\t\tif ((input.entryType === \"grant_prepaid\" || input.entryType === \"grant_promo\") && prepaidDelta > 0) await clearCreditAlertFlagsTx(tx, input.organizationId);\n\t\treturn {\n\t\t\tapplied: true,\n\t\t\tledgerEntryId,\n\t\t\tbalances: balancesOf(wallet, planDelta, prepaidDelta)\n\t\t};\n\t});\n}\nasync function applyLedgerDebit(input) {\n\tif (input.chargeMicroCredits < 0) throw new Error(\"chargeMicroCredits must be >= 0; use applyLedgerCredit for credits\");\n\treturn withBillingTx(async (tx) => {\n\t\tconst wallet = await lockWallet(tx, input.organizationId);\n\t\tconst split = splitDebit(wallet, input.chargeMicroCredits);\n\t\tconst createdAt = input.createdAt ?? /* @__PURE__ */ new Date();\n\t\tconst ledgerEntryId = (await tx.insert(billingLedger).values({\n\t\t\tid: crypto.randomUUID(),\n\t\t\torganizationId: input.organizationId,\n\t\t\tentryType: \"debit\",\n\t\t\tplanDeltaMicroCredits: -split.planCreditMicroCredits,\n\t\t\tprepaidDeltaMicroCredits: -split.prepaidCreditMicroCredits,\n\t\t\tsource: input.source,\n\t\t\tidempotencyKey: input.idempotencyKey,\n\t\t\trunId: input.runId ?? null,\n\t\t\tprojectId: input.projectId ?? null,\n\t\t\tproviderReference: input.providerReference ?? null,\n\t\t\tmetadata: storedJson(input.metadata),\n\t\t\tcreatedAt\n\t\t}).onConflictDoNothing().returning({ id: billingLedger.id }))[0]?.id ?? null;\n\t\tif (!ledgerEntryId) return {\n\t\t\tapplied: false,\n\t\t\tledgerEntryId: null,\n\t\t\tfromPlanMicroCredits: 0,\n\t\t\tfromPrepaidMicroCredits: 0,\n\t\t\tbalances: balancesOf(wallet, 0, 0)\n\t\t};\n\t\tif (input.chargeMicroCredits > 0) await tx.update(billingWallet).set({\n\t\t\tplanCreditMicroCredits: wallet.planCreditMicroCredits - split.planCreditMicroCredits,\n\t\t\tprepaidCreditMicroCredits: wallet.prepaidCreditMicroCredits - split.prepaidCreditMicroCredits,\n\t\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t\t}).where(eq(billingWallet.organizationId, input.organizationId));\n\t\treturn {\n\t\t\tapplied: true,\n\t\t\tledgerEntryId,\n\t\t\tfromPlanMicroCredits: split.planCreditMicroCredits,\n\t\t\tfromPrepaidMicroCredits: split.prepaidCreditMicroCredits,\n\t\t\tbalances: balancesOf(wallet, -split.planCreditMicroCredits, -split.prepaidCreditMicroCredits)\n\t\t};\n\t});\n}\n/**\n* Plan period reset in one wallet-locked transaction: expire any positive\n* plan leftover (debt carries into the new period), grant the new monthly\n* amount, and advance the period. Idempotent on the grant key — a duplicate\n* grant applies nothing, including the expiry, and the expire delta is read\n* under the lock so concurrent debits cannot leave residual plan credit.\n*/\nasync function resetWalletPlanPeriod(input) {\n\treturn withBillingTx(async (tx) => {\n\t\tconst wallet = await lockWallet(tx, input.organizationId);\n\t\tconst createdAt = input.createdAt ?? /* @__PURE__ */ new Date();\n\t\tif (!(await tx.insert(billingLedger).values({\n\t\t\tid: crypto.randomUUID(),\n\t\t\torganizationId: input.organizationId,\n\t\t\tentryType: \"grant_plan\",\n\t\t\tplanDeltaMicroCredits: input.grantMicroCredits,\n\t\t\tprepaidDeltaMicroCredits: 0,\n\t\t\tsource: input.source,\n\t\t\tidempotencyKey: input.idempotencyKey,\n\t\t\tproviderReference: input.providerReference ?? null,\n\t\t\tmetadata: storedJson(input.metadata),\n\t\t\tcreatedAt\n\t\t}).onConflictDoNothing().returning({ id: billingLedger.id }))[0]) return {\n\t\t\tapplied: false,\n\t\t\tbalances: balancesOf(wallet, 0, 0)\n\t\t};\n\t\tconst expireDelta = -Math.max(wallet.planCreditMicroCredits, 0);\n\t\tif (expireDelta !== 0) await tx.insert(billingLedger).values({\n\t\t\tid: crypto.randomUUID(),\n\t\t\torganizationId: input.organizationId,\n\t\t\tentryType: \"expire_plan\",\n\t\t\tplanDeltaMicroCredits: expireDelta,\n\t\t\tprepaidDeltaMicroCredits: 0,\n\t\t\tsource: input.source,\n\t\t\tidempotencyKey: `expire:${input.idempotencyKey}`,\n\t\t\tproviderReference: input.providerReference ?? null,\n\t\t\tmetadata: storedJson(input.metadata),\n\t\t\tcreatedAt\n\t\t});\n\t\tconst planDelta = expireDelta + input.grantMicroCredits;\n\t\tawait tx.update(billingWallet).set({\n\t\t\tplanCreditMicroCredits: wallet.planCreditMicroCredits + planDelta,\n\t\t\tperiodStart: input.periodStart,\n\t\t\tperiodEnd: input.periodEnd,\n\t\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t\t}).where(eq(billingWallet.organizationId, input.organizationId));\n\t\tawait clearCreditAlertFlagsTx(tx, input.organizationId);\n\t\treturn {\n\t\t\tapplied: true,\n\t\t\tbalances: balancesOf(wallet, planDelta, 0)\n\t\t};\n\t});\n}\n/**\n* Read-or-create the org's billing row. New rows default to\n* {@link DEFAULT_PLAN_KEY}; pass `defaults.planKey` to override on first\n* creation only. An existing row is returned untouched.\n*/\nasync function getOrCreateOrganizationBilling(organizationId, defaults) {\n\tconst db = getDb();\n\tconst existing = (await db.select().from(organizationBilling).where(eq(organizationBilling.organizationId, organizationId)).limit(1))[0];\n\tif (existing) return existing;\n\tconst now = /* @__PURE__ */ new Date();\n\tconst values = {\n\t\torganizationId,\n\t\tplanKey: defaults?.planKey ?? DEFAULT_PLAN_KEY,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t};\n\tif (isSqliteDialect()) await getSqliteDb().insert(organizationBillingSqlite).values(values).onConflictDoNothing();\n\telse {\n\t\tconst inserted = (await db.insert(organizationBilling).values(values).onConflictDoNothing().returning())[0];\n\t\tif (inserted) return inserted;\n\t}\n\tconst row = (await db.select().from(organizationBilling).where(eq(organizationBilling.organizationId, organizationId)).limit(1))[0];\n\tif (!row) throw new Error(`organization_billing row missing for organization ${organizationId}`);\n\treturn row;\n}\nasync function selectOrganizationBillingByStripeCustomerId(stripeCustomerId) {\n\treturn (await getDb().select().from(organizationBilling).where(eq(organizationBilling.stripeCustomerId, stripeCustomerId)).limit(1))[0];\n}\nasync function updateOrganizationBilling(organizationId, values) {\n\tconst row = (await getDb().update(organizationBilling).set({\n\t\t...values,\n\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t}).where(eq(organizationBilling.organizationId, organizationId)).returning())[0];\n\tif (!row) throw new Error(`organization_billing row missing for organization ${organizationId}`);\n\treturn row;\n}\n/**\n* Atomically claim the auto-top-up in-flight slot: set the marker only when no\n* intent is pending (`WHERE auto_topup_pending_intent_id IS NULL`). Concurrent\n* top-up triggers race here and exactly one wins; the losers no-op.\n*/\nasync function claimAutoTopupPendingIntent(organizationId, claimId) {\n\treturn (await getDb().update(organizationBilling).set({\n\t\tautoTopupPendingIntentId: claimId,\n\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t}).where(and(eq(organizationBilling.organizationId, organizationId), isNull(organizationBilling.autoTopupPendingIntentId))).returning({ organizationId: organizationBilling.organizationId })).length > 0;\n}\n/**\n* Clear the auto-top-up in-flight marker only if it still matches the given\n* claim — a newer claim is never clobbered by a stale webhook.\n*/\nasync function clearAutoTopupPendingIntent(organizationId, claimId) {\n\tawait getDb().update(organizationBilling).set({\n\t\tautoTopupPendingIntentId: null,\n\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t}).where(and(eq(organizationBilling.organizationId, organizationId), eq(organizationBilling.autoTopupPendingIntentId, claimId)));\n}\nasync function clearCreditAlertFlagsTx(tx, organizationId) {\n\tawait tx.update(organizationBilling).set({\n\t\tcreditWarningSentAt: null,\n\t\tcreditExhaustedSentAt: null,\n\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t}).where(eq(organizationBilling.organizationId, organizationId));\n}\n/** Reset warning + exhausted email dedupe after a plan refill or prepaid top-up. */\nasync function clearCreditAlertFlags(organizationId) {\n\tawait clearCreditAlertFlagsTx(getDb(), organizationId);\n}\n/**\n* Claim the credit-warning email slot. Concurrent callers race; only one wins.\n* Returns false when already claimed this cycle.\n*/\nasync function claimCreditWarningSent(organizationId, sentAt = /* @__PURE__ */ new Date()) {\n\treturn (await getDb().update(organizationBilling).set({\n\t\tcreditWarningSentAt: sentAt,\n\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t}).where(and(eq(organizationBilling.organizationId, organizationId), isNull(organizationBilling.creditWarningSentAt))).returning({ organizationId: organizationBilling.organizationId })).length > 0;\n}\n/**\n* Claim the credit-exhausted email slot. Concurrent callers race; only one wins.\n* Returns false when already claimed this cycle.\n*/\nasync function claimCreditExhaustedSent(organizationId, sentAt = /* @__PURE__ */ new Date()) {\n\treturn (await getDb().update(organizationBilling).set({\n\t\tcreditExhaustedSentAt: sentAt,\n\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t}).where(and(eq(organizationBilling.organizationId, organizationId), isNull(organizationBilling.creditExhaustedSentAt))).returning({ organizationId: organizationBilling.organizationId })).length > 0;\n}\n/**\n* Newest audit-event timestamp for the org across the given types, or null.\n* Powers the billing page's failed-payment notice (failure newer than the\n* latest success).\n*/\nasync function selectLatestBillingEventAt(organizationId, types) {\n\treturn (await getDb().select({ createdAt: billingEvents.createdAt }).from(billingEvents).where(and(eq(billingEvents.organizationId, organizationId), inArray(billingEvents.type, types))).orderBy(desc(billingEvents.createdAt)).limit(1))[0]?.createdAt ?? null;\n}\n/** Best-effort audit insert; duplicate Stripe event ids no-op. */\nasync function insertBillingEvent(values) {\n\tawait getDb().insert(billingEvents).values({\n\t\tid: crypto.randomUUID(),\n\t\tstripeEventId: values.stripeEventId,\n\t\torganizationId: values.organizationId,\n\t\ttype: values.type,\n\t\tstatus: values.status,\n\t\tamountMicroCredits: values.amountMicroCredits ?? null,\n\t\tcreditsGrantedMicroCredits: values.creditsGrantedMicroCredits ?? null,\n\t\tbucket: values.bucket ?? null,\n\t\tstripeObjectId: values.stripeObjectId ?? null,\n\t\tmetadata: storedJson(values.metadata),\n\t\tcreatedAt: /* @__PURE__ */ new Date()\n\t}).onConflictDoNothing();\n}\nfunction usageEventKey(event) {\n\treturn `${event.source}\\0${event.sourceEventId}`;\n}\n/** First occurrence of each `(source, sourceEventId)` wins within a batch. */\nfunction normalizeUsageEvents(events) {\n\tconst byKey = /* @__PURE__ */ new Map();\n\tfor (const event of events) {\n\t\tconst key = usageEventKey(event);\n\t\tif (!byKey.has(key)) byKey.set(key, {\n\t\t\t...event,\n\t\t\tkey\n\t\t});\n\t}\n\treturn [...byKey.values()];\n}\n/**\n* Insert priced usage events and settle their total as one wallet debit,\n* atomically. Idempotency is the `(organizationId, source, sourceEventId)`\n* unique index — first write wins, a replay (e.g. a retried dispatch fee or a\n* same-day storage re-sample) is a `duplicate` no-op regardless of payload,\n* matching the old org-DB `(entryType, reference)` semantics.\n*/\nasync function insertUsageEventsAndSettle(organizationId, events) {\n\tconst normalized = normalizeUsageEvents(events);\n\treturn withBillingTx(async (tx) => {\n\t\tconst wallet = await lockWallet(tx, organizationId);\n\t\tconst acceptedAt = /* @__PURE__ */ new Date();\n\t\tconst inserted = normalized.length === 0 ? [] : await tx.insert(usageEvents).values(normalized.map((event) => ({\n\t\t\tid: crypto.randomUUID(),\n\t\t\torganizationId,\n\t\t\tprojectId: event.projectId ?? null,\n\t\t\trunId: event.runId ?? null,\n\t\t\trunKind: event.runKind ?? null,\n\t\t\tsource: event.source,\n\t\t\tsourceEventId: event.sourceEventId,\n\t\t\tmeterKey: event.meterKey,\n\t\t\tquantity: event.quantity,\n\t\t\tunit: event.unit,\n\t\t\tproviderCostUsd: event.providerCostUsd ?? null,\n\t\t\tkeySource: event.keySource ?? null,\n\t\t\tpriceVersion: event.priceVersion,\n\t\t\tchargeMicroCredits: event.chargeMicroCredits,\n\t\t\tsettledLedgerId: null,\n\t\t\toccurredAt: event.occurredAt,\n\t\t\tacceptedAt,\n\t\t\tmetadata: storedJson(event.metadata)\n\t\t}))).onConflictDoNothing().returning({\n\t\t\tid: usageEvents.id,\n\t\t\tsource: usageEvents.source,\n\t\t\tsourceEventId: usageEvents.sourceEventId,\n\t\t\trunId: usageEvents.runId,\n\t\t\tprojectId: usageEvents.projectId,\n\t\t\tchargeMicroCredits: usageEvents.chargeMicroCredits,\n\t\t\toccurredAt: usageEvents.occurredAt\n\t\t});\n\t\tconst insertedKeys = new Set(inserted.map((event) => usageEventKey(event)));\n\t\tconst duplicateCount = normalized.length - insertedKeys.size;\n\t\tconst chargeable = inserted.filter((event) => event.chargeMicroCredits > 0);\n\t\tconst totalChargeMicroCredits = chargeable.reduce((total, event) => total + event.chargeMicroCredits, 0);\n\t\tif (totalChargeMicroCredits === 0) return {\n\t\t\tinserted: inserted.length,\n\t\t\tduplicate: duplicateCount,\n\t\t\tsettledLedgerId: null,\n\t\t\tchargeMicroCredits: 0,\n\t\t\tbalances: balancesOf(wallet, 0, 0)\n\t\t};\n\t\tconst split = splitDebit(wallet, totalChargeMicroCredits);\n\t\tconst ledgerEntryId = crypto.randomUUID();\n\t\tawait tx.insert(billingLedger).values({\n\t\t\tid: ledgerEntryId,\n\t\t\torganizationId,\n\t\t\tentryType: \"debit\",\n\t\t\tplanDeltaMicroCredits: -split.planCreditMicroCredits,\n\t\t\tprepaidDeltaMicroCredits: -split.prepaidCreditMicroCredits,\n\t\t\tsource: \"usage_events\",\n\t\t\tidempotencyKey: `usage_settle:${chargeable.map((event) => event.id).sort().join(\",\")}`,\n\t\t\trunId: chargeable.length === 1 ? chargeable[0]?.runId ?? null : null,\n\t\t\tprojectId: chargeable.length === 1 ? chargeable[0]?.projectId ?? null : null,\n\t\t\tproviderReference: null,\n\t\t\tmetadata: storedJson({\n\t\t\t\tusageEventIds: chargeable.map((event) => event.id),\n\t\t\t\teventCount: chargeable.length,\n\t\t\t\tsplit: {\n\t\t\t\t\tfromPlan: split.planCreditMicroCredits,\n\t\t\t\t\tfromPrepaid: split.prepaidCreditMicroCredits\n\t\t\t\t}\n\t\t\t}),\n\t\t\tcreatedAt: acceptedAt\n\t\t});\n\t\tawait tx.update(billingWallet).set({\n\t\t\tplanCreditMicroCredits: wallet.planCreditMicroCredits - split.planCreditMicroCredits,\n\t\t\tprepaidCreditMicroCredits: wallet.prepaidCreditMicroCredits - split.prepaidCreditMicroCredits,\n\t\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t\t}).where(eq(billingWallet.organizationId, organizationId));\n\t\tawait tx.update(usageEvents).set({ settledLedgerId: ledgerEntryId }).where(inArray(usageEvents.id, chargeable.map((event) => event.id)));\n\t\treturn {\n\t\t\tinserted: inserted.length,\n\t\t\tduplicate: duplicateCount,\n\t\t\tsettledLedgerId: ledgerEntryId,\n\t\t\tchargeMicroCredits: totalChargeMicroCredits,\n\t\t\tbalances: balancesOf(wallet, -split.planCreditMicroCredits, -split.prepaidCreditMicroCredits)\n\t\t};\n\t});\n}\nasync function listUsageEventsForRuns(input) {\n\tif (input.runIds.length === 0) return [];\n\tconst conditions = [eq(usageEvents.organizationId, input.organizationId), inArray(usageEvents.runId, input.runIds)];\n\tif (input.runKind) conditions.push(eq(usageEvents.runKind, input.runKind));\n\treturn getDb().select().from(usageEvents).where(and(...conditions)).orderBy(desc(usageEvents.occurredAt), desc(usageEvents.id)).limit(input.limit ?? 100);\n}\n/**\n* Per-run usage rollup for the history list: one row per distinct\n* (run, meter, label) instead of raw events. The detail view loads full rows\n* via {@link listUsageEventsForRuns} only when a run is opened.\n*/\nasync function summarizeUsageForRuns(input) {\n\tif (input.runIds.length === 0) return [];\n\tconst sqlite = getDatabaseHandle().dialect === \"sqlite\";\n\tconst model = sqlite ? sql`json_extract(json_extract(${usageEvents.metadata}, '$'), '$.model')` : sql`${usageEvents.metadata}->>'model'`;\n\tconst legacyLabel = sqlite ? sql`json_extract(json_extract(${usageEvents.metadata}, '$'), '$.legacy.label')` : sql`${usageEvents.metadata}->'legacy'->>'label'`;\n\tconst legacyKind = sqlite ? sql`json_extract(json_extract(${usageEvents.metadata}, '$'), '$.legacy.kind')` : sql`${usageEvents.metadata}->'legacy'->>'kind'`;\n\treturn (await getDb().select({\n\t\trunId: usageEvents.runId,\n\t\tmeterKey: usageEvents.meterKey,\n\t\tmodel,\n\t\tlegacyLabel,\n\t\tlegacyKind,\n\t\tchargeMicroCredits: sql`coalesce(sum(${usageEvents.chargeMicroCredits}), 0)`.mapWith(Number)\n\t}).from(usageEvents).where(and(eq(usageEvents.organizationId, input.organizationId), inArray(usageEvents.runId, input.runIds))).groupBy(usageEvents.runId, usageEvents.meterKey, model, legacyLabel, legacyKind)).filter((row) => row.runId !== null);\n}\nasync function summarizeUsageByMeter(input) {\n\tconst conditions = [eq(usageEvents.organizationId, input.organizationId)];\n\tif (input.since) conditions.push(gte(usageEvents.occurredAt, input.since));\n\tif (input.until) conditions.push(lte(usageEvents.occurredAt, input.until));\n\treturn getDb().select({\n\t\tmeterKey: usageEvents.meterKey,\n\t\tquantity: sql`coalesce(sum(${usageEvents.quantity}), 0)`.mapWith(Number),\n\t\tchargeMicroCredits: sql`coalesce(sum(${usageEvents.chargeMicroCredits}), 0)`.mapWith(Number),\n\t\tunchargedProviderCostUsd: sql`coalesce(sum(\n        case when ${usageEvents.chargeMicroCredits} = 0 then ${usageEvents.providerCostUsd} else 0 end\n      ), 0)`.mapWith(Number)\n\t}).from(usageEvents).where(and(...conditions)).groupBy(usageEvents.meterKey);\n}\nasync function listBillingLedgerEntries(input) {\n\tconst db = getDb();\n\tconst conditions = [eq(billingLedger.organizationId, input.organizationId)];\n\tif (input.excludeEntryTypes && input.excludeEntryTypes.length > 0) conditions.push(notInArray(billingLedger.entryType, input.excludeEntryTypes));\n\treturn db.select().from(billingLedger).where(and(...conditions)).orderBy(desc(billingLedger.createdAt), desc(billingLedger.id)).limit(input.limit ?? 50);\n}\nasync function reconcileWalletAgainstLedger(organizationId) {\n\tconst row = (await getDb().select({\n\t\tplanLedgerMicroCredits: sql`(\n        select coalesce(sum(${billingLedger.planDeltaMicroCredits}), 0)\n        from ${billingLedger}\n        where ${billingLedger.organizationId} = ${billingWallet.organizationId}\n      )`.mapWith(Number),\n\t\tprepaidLedgerMicroCredits: sql`(\n        select coalesce(sum(${billingLedger.prepaidDeltaMicroCredits}), 0)\n        from ${billingLedger}\n        where ${billingLedger.organizationId} = ${billingWallet.organizationId}\n      )`.mapWith(Number),\n\t\twalletPlanMicroCredits: billingWallet.planCreditMicroCredits,\n\t\twalletPrepaidMicroCredits: billingWallet.prepaidCreditMicroCredits\n\t}).from(billingWallet).where(eq(billingWallet.organizationId, organizationId)).limit(1))[0];\n\tif (!row) return;\n\treturn {\n\t\t...row,\n\t\tbalanced: row.planLedgerMicroCredits === row.walletPlanMicroCredits && row.prepaidLedgerMicroCredits === row.walletPrepaidMicroCredits\n\t};\n}\nasync function listActiveOrganizationOwners(db, organizationId) {\n\treturn db.select({ userId: organizationUsers.userId }).from(organizationUsers).where(and(eq(organizationUsers.organizationId, organizationId), eq(organizationUsers.role, \"owner\"), eq(organizationUsers.status, \"active\"), isNull(organizationUsers.deletedAt)));\n}\n/**\n* True when `userId` is an active owner of some other org that already received\n* welcome credits (`promo:welcome:%`). Used so a user gets the $20 promo once;\n* invitees who later create their own org still qualify.\n*/\nasync function userOwnsOtherOrgWithWelcomeCredits(userId, excludeOrganizationId) {\n\treturn (await getDb().select({ organizationId: billingLedger.organizationId }).from(billingLedger).innerJoin(organizationUsers, eq(organizationUsers.organizationId, billingLedger.organizationId)).where(and(eq(organizationUsers.userId, userId), eq(organizationUsers.role, \"owner\"), eq(organizationUsers.status, \"active\"), isNull(organizationUsers.deletedAt), ne(billingLedger.organizationId, excludeOrganizationId), like(billingLedger.idempotencyKey, `${WELCOME_CREDIT_IDEMPOTENCY_PREFIX}%`))).limit(1)).length > 0;\n}\n/**\n* Welcome credits for this org: grant when no active owner has already claimed\n* welcome on another owned org. Orgs with no owners (standalone default) still\n* qualify so local/dev bootstrap keeps working.\n*/\nasync function organizationQualifiesForWelcomeCredits(organizationId) {\n\tconst owners = await listActiveOrganizationOwners(getDb(), organizationId);\n\tif (owners.length === 0) return true;\n\tfor (const owner of owners) if (await userOwnsOtherOrgWithWelcomeCredits(owner.userId, organizationId)) return false;\n\treturn true;\n}\n/**\n* Atomically claim welcome credits for an organization when eligible.\n*\n* On Postgres, takes per-owner transaction advisory locks (sorted) so concurrent\n* bootstraps for orgs sharing an owner serialize: only the first grant wins.\n* SQLite (unit tests / local) has no advisory locks; callers are single-threaded.\n*/\nasync function grantWelcomeCreditsIfEligible(input) {\n\treturn withBillingTx(async (tx) => {\n\t\tconst owners = await listActiveOrganizationOwners(tx, input.organizationId);\n\t\tif (getDatabaseHandle().dialect === \"postgres\" && owners.length > 0) {\n\t\t\tconst ownerIds = [...new Set(owners.map((owner) => owner.userId))].sort();\n\t\t\tfor (const userId of ownerIds) await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtext(${`welcome-credits:${userId}`}))`);\n\t\t}\n\t\tfor (const owner of owners) if (await userOwnsOtherOrgWithWelcomeCredits(owner.userId, input.organizationId)) return { applied: false };\n\t\tconst wallet = await lockWallet(tx, input.organizationId);\n\t\tconst prepaidDelta = input.prepaidDeltaMicroCredits;\n\t\tconst createdAt = input.createdAt ?? /* @__PURE__ */ new Date();\n\t\tif (!(await tx.insert(billingLedger).values({\n\t\t\tid: crypto.randomUUID(),\n\t\t\torganizationId: input.organizationId,\n\t\t\tentryType: \"grant_prepaid\",\n\t\t\tplanDeltaMicroCredits: 0,\n\t\t\tprepaidDeltaMicroCredits: prepaidDelta,\n\t\t\tsource: \"promo\",\n\t\t\tidempotencyKey: input.idempotencyKey,\n\t\t\trunId: null,\n\t\t\tprojectId: null,\n\t\t\tproviderReference: null,\n\t\t\tmetadata: storedJson({ label: \"Welcome credits\" }),\n\t\t\tcreatedAt\n\t\t}).onConflictDoNothing().returning({ id: billingLedger.id }))[0]?.id) return { applied: false };\n\t\tawait tx.update(billingWallet).set({\n\t\t\tprepaidCreditMicroCredits: wallet.prepaidCreditMicroCredits + prepaidDelta,\n\t\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t\t}).where(eq(billingWallet.organizationId, input.organizationId));\n\t\treturn { applied: true };\n\t});\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 listApiKeysByConfigReferenceIds(configId, referenceIds) {\n\tif (referenceIds.length === 0) return [];\n\treturn getDb().select().from(authApiKeys).where(and$1(eq$1(authApiKeys.configId, configId), inArray$1(authApiKeys.referenceId, referenceIds)));\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/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/list-cursor.ts\nfunction encodeCreatedAtIdCursor(cursor) {\n\treturn Buffer.from(JSON.stringify({\n\t\tcreatedAt: cursor.createdAt.toISOString(),\n\t\tid: cursor.id\n\t})).toString(\"base64url\");\n}\nfunction decodeCreatedAtIdCursor(value) {\n\ttry {\n\t\tconst parsed = JSON.parse(Buffer.from(value, \"base64url\").toString(\"utf8\"));\n\t\tif (typeof parsed.createdAt !== \"string\" || typeof parsed.id !== \"string\") return null;\n\t\tconst createdAt = new Date(parsed.createdAt);\n\t\tif (Number.isNaN(createdAt.getTime())) return null;\n\t\treturn {\n\t\t\tcreatedAt,\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/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/** Removal would orphan Brains: add another Brain owner first, then retry. */\nvar LastBrainOwnerMemberError = class extends OrganizationMemberMutationError {\n\tbrainSlugs;\n\tconstructor(brainSlugs) {\n\t\tsuper(\"last_brain_owner\", `Member is the last owner of Brain(s): ${brainSlugs.join(\", \")}. Add another owner first.`);\n\t\tthis.brainSlugs = brainSlugs;\n\t}\n};\n//#endregion\n//#region src/queries/members/index.ts\nconst INVITATION_TTL_MS = 336 * 60 * 60 * 1e3;\n/** Active (non-deleted) members in the org — used for group analytics. */\nasync function countActiveMembersForOrganization(organizationId) {\n\tconst rows = await getDb().select({ total: count$1() }).from(organizationUsers).where(and$1(eq$1(organizationUsers.organizationId, organizationId), eq$1(organizationUsers.status, \"active\"), isNull$1(organizationUsers.deletedAt)));\n\treturn Number(rows[0]?.total ?? 0);\n}\n/**\n* Active owner/admin emails for billing alerts. Send-path only — not on the\n* settle/gate hot path.\n*/\nasync function listActiveOwnerAdminEmails(organizationId) {\n\tconst rows = await getDb().select({ email: users.email }).from(organizationUsers).innerJoin(users, eq$1(organizationUsers.userId, users.id)).where(and$1(eq$1(organizationUsers.organizationId, organizationId), eq$1(organizationUsers.status, \"active\"), isNull$1(organizationUsers.deletedAt), inArray$1(organizationUsers.role, [\"owner\", \"admin\"])));\n\tconst emails = [];\n\tconst seen = /* @__PURE__ */ new Set();\n\tfor (const row of rows) {\n\t\tconst email = row.email.trim();\n\t\tif (!email) continue;\n\t\tconst key = email.toLowerCase();\n\t\tif (seen.has(key)) continue;\n\t\tseen.add(key);\n\t\temails.push(email);\n\t}\n\treturn emails;\n}\nasync function selectOrganizationMembers(organizationId, options) {\n\tconst db = getDb();\n\tconst limit = options?.limit ?? 200;\n\tconst conditions = [eq$1(organizationUsers.organizationId, organizationId), isNull$1(organizationUsers.deletedAt)];\n\tif (options?.cursor) {\n\t\tconst decoded = decodeCreatedAtIdCursor(options.cursor);\n\t\tif (!decoded) throw new Error(\"Invalid cursor\");\n\t\tconditions.push(or$1(lt$1(organizationUsers.createdAt, decoded.createdAt), and$1(eq$1(organizationUsers.createdAt, decoded.createdAt), lt$1(users.id, decoded.id))));\n\t}\n\tconst rows = await db.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(...conditions)).orderBy(desc$1(organizationUsers.createdAt), desc$1(users.id)).limit(limit + 1);\n\tconst hasMore = rows.length > limit;\n\tconst items = hasMore ? rows.slice(0, limit) : rows;\n\tconst last = items[items.length - 1];\n\treturn {\n\t\titems,\n\t\tnextCursor: hasMore && last ? encodeCreatedAtIdCursor({\n\t\t\tcreatedAt: last.createdAt,\n\t\t\tid: last.id\n\t\t}) : null\n\t};\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 hasOrganizationMembership(organizationId, userId) {\n\tconst membership = await selectOrganizationMembership(organizationId, userId);\n\treturn membership?.status === \"active\" || membership?.status === \"invited\";\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((page) => page.items.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\tif (membership.status === \"active\") {\n\t\tconst soleOwnedBrainSlugs = await listBrainSlugsWhereUserIsSoleOwner(organizationId, userId);\n\t\tif (soleOwnedBrainSlugs.length > 0) throw new LastBrainOwnerMemberError(soleOwnedBrainSlugs);\n\t}\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$1(isNull$1(organizationInvitations.expiresAt), gt$1(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 addUserToDefaultOrgProjectInTransaction(tx, invitation.organizationId, userId);\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-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/project-repositories/index.ts\n/** Lifecycle statuses that may transition to `ready` for an active repository. */\nconst READYABLE_LIFECYCLE_STATUSES = [\"provisioning\", \"failed\"];\n/** Lifecycle statuses that may transition to `failed` while still desired-active. */\nconst ACTIVE_FAILABLE_LIFECYCLE_STATUSES = [\"provisioning\", \"failed\"];\n/** Lifecycle statuses that may transition to `failed` while deleting. */\nconst DELETE_FAILABLE_LIFECYCLE_STATUSES = [\"deleting\", \"failed\"];\nasync function selectProjectRepositoryByProjectId(projectId) {\n\tif (isSqliteDialect()) return getSqliteDb().select().from(projectRepositoriesSqlite).where(eq(projectRepositoriesSqlite.projectId, projectId)).limit(1).get();\n\treturn (await getDb().select().from(projectRepositories).where(eq(projectRepositories.projectId, projectId)).limit(1))[0];\n}\n/**\n* Idempotent insert for projects that predate managed Git. Concurrent callers\n* race on the project_id unique index; losers re-select the winner's row.\n*/\nasync function ensureProjectRepositoryRow(input) {\n\tconst existing = await selectProjectRepositoryByProjectId(input.projectId);\n\tif (existing) return existing;\n\tconst now = input.now ?? /* @__PURE__ */ new Date();\n\tconst values = {\n\t\tid: crypto.randomUUID(),\n\t\torganizationId: input.organizationId,\n\t\tprojectId: input.projectId,\n\t\tprovider: input.provider,\n\t\tdefaultBranch: \"main\",\n\t\tlifecycleStatus: \"provisioning\",\n\t\tcontentStatus: \"empty\",\n\t\tdesiredState: \"active\",\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t};\n\tif (isSqliteDialect()) getSqliteDb().insert(projectRepositoriesSqlite).values(values).onConflictDoNothing({ target: projectRepositoriesSqlite.projectId }).run();\n\telse await getDb().insert(projectRepositories).values(values).onConflictDoNothing({ target: projectRepositories.projectId });\n\tconst row = await selectProjectRepositoryByProjectId(input.projectId);\n\tif (!row) throw new Error(`Failed to ensure project repository row for ${input.projectId}`);\n\treturn row;\n}\nasync function markProjectRepositoryReady(input) {\n\tconst now = input.now ?? /* @__PURE__ */ new Date();\n\tconst values = {\n\t\tlifecycleStatus: \"ready\",\n\t\tcontentStatus: input.contentStatus ?? \"empty\",\n\t\texternalRepositoryId: input.externalRepositoryId,\n\t\towner: input.owner,\n\t\tname: input.name,\n\t\tdefaultBranch: input.defaultBranch ?? \"main\",\n\t\tlastErrorCode: null,\n\t\tlastError: null,\n\t\tprovisionedAt: now,\n\t\tupdatedAt: now\n\t};\n\tif (isSqliteDialect()) return getSqliteDb().update(projectRepositoriesSqlite).set(values).where(and(eq(projectRepositoriesSqlite.id, input.id), eq(projectRepositoriesSqlite.desiredState, \"active\"), inArray(projectRepositoriesSqlite.lifecycleStatus, [...READYABLE_LIFECYCLE_STATUSES]))).returning().get();\n\tconst [row] = await getDb().update(projectRepositories).set(values).where(and(eq(projectRepositories.id, input.id), eq(projectRepositories.desiredState, \"active\"), inArray(projectRepositories.lifecycleStatus, [...READYABLE_LIFECYCLE_STATUSES]))).returning();\n\treturn row;\n}\nasync function markProjectRepositoryFailed(input) {\n\tconst now = input.now ?? /* @__PURE__ */ new Date();\n\tconst values = {\n\t\tlifecycleStatus: \"failed\",\n\t\tlastErrorCode: input.lastErrorCode ?? null,\n\t\tlastError: input.lastError ?? null,\n\t\tupdatedAt: now\n\t};\n\tconst allowedLifecycle = input.desiredState === \"active\" ? ACTIVE_FAILABLE_LIFECYCLE_STATUSES : DELETE_FAILABLE_LIFECYCLE_STATUSES;\n\tif (isSqliteDialect()) return getSqliteDb().update(projectRepositoriesSqlite).set(values).where(and(eq(projectRepositoriesSqlite.id, input.id), eq(projectRepositoriesSqlite.desiredState, input.desiredState), inArray(projectRepositoriesSqlite.lifecycleStatus, [...allowedLifecycle]))).returning().get();\n\tconst [row] = await getDb().update(projectRepositories).set(values).where(and(eq(projectRepositories.id, input.id), eq(projectRepositories.desiredState, input.desiredState), inArray(projectRepositories.lifecycleStatus, [...allowedLifecycle]))).returning();\n\treturn row;\n}\nasync function requestProjectRepositoryDeletion(input) {\n\tconst values = {\n\t\tdesiredState: \"deleted\",\n\t\tlifecycleStatus: \"deleting\",\n\t\tupdatedAt: input.now ?? /* @__PURE__ */ new Date()\n\t};\n\tif (isSqliteDialect()) return getSqliteDb().update(projectRepositoriesSqlite).set(values).where(eq(projectRepositoriesSqlite.projectId, input.projectId)).returning().get();\n\tconst [row] = await getDb().update(projectRepositories).set(values).where(eq(projectRepositories.projectId, input.projectId)).returning();\n\treturn row;\n}\nasync function markProjectRepositoryDeleted(input) {\n\tconst now = input.now ?? /* @__PURE__ */ new Date();\n\tconst values = {\n\t\tlifecycleStatus: \"deleted\",\n\t\tdesiredState: \"deleted\",\n\t\tlastErrorCode: null,\n\t\tlastError: null,\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t};\n\tif (isSqliteDialect()) return getSqliteDb().update(projectRepositoriesSqlite).set(values).where(and(eq(projectRepositoriesSqlite.id, input.id), eq(projectRepositoriesSqlite.desiredState, \"deleted\"))).returning().get();\n\tconst [row] = await getDb().update(projectRepositories).set(values).where(and(eq(projectRepositories.id, input.id), eq(projectRepositories.desiredState, \"deleted\"))).returning();\n\treturn row;\n}\nasync function markProjectRepositoryContentStatus(input) {\n\tconst now = input.now ?? /* @__PURE__ */ new Date();\n\tconst values = {\n\t\tcontentStatus: input.contentStatus,\n\t\tupdatedAt: now\n\t};\n\tif (isSqliteDialect()) return getSqliteDb().update(projectRepositoriesSqlite).set(values).where(eq(projectRepositoriesSqlite.id, input.id)).returning().get();\n\tconst [row] = await getDb().update(projectRepositories).set(values).where(eq(projectRepositories.id, input.id)).returning();\n\treturn row;\n}\n/** Idempotent: only sets platform_agent_scaffolded_at when currently null. */\nasync function markProjectRepositoryPlatformAgentScaffolded(input) {\n\tconst now = input.now ?? /* @__PURE__ */ new Date();\n\tconst values = {\n\t\tplatformAgentScaffoldedAt: now,\n\t\tupdatedAt: now\n\t};\n\tif (isSqliteDialect()) return getSqliteDb().update(projectRepositoriesSqlite).set(values).where(and(eq(projectRepositoriesSqlite.projectId, input.projectId), isNull(projectRepositoriesSqlite.platformAgentScaffoldedAt))).returning().get();\n\tconst [row] = await getDb().update(projectRepositories).set(values).where(and(eq(projectRepositories.projectId, input.projectId), isNull(projectRepositories.platformAgentScaffoldedAt))).returning();\n\treturn row;\n}\n//#endregion\n//#region src/queries/project-artifacts/complete-promote.ts\nvar ProjectArtifactSourceManifestConflictError = class extends Error {\n\tcode = \"source_manifest_conflict\";\n\tconstructor() {\n\t\tsuper(\"Artifact source manifest already exists with different content\");\n\t\tthis.name = \"ProjectArtifactSourceManifestConflictError\";\n\t}\n};\n/** Staging lost the deploy lease (reclaimed or stolen) — do not set pending. */\nvar DeployLeaseLostError = class extends Error {\n\tcode = \"deploy_lease_lost\";\n\tconstructor() {\n\t\tsuper(\"Deploy lease is no longer held; cannot stage artifact\");\n\t\tthis.name = \"DeployLeaseLostError\";\n\t}\n};\nfunction manifestFileRefs(manifest) {\n\tif (!manifest || typeof manifest !== \"object\" || !(\"files\" in manifest)) return;\n\tconst files = manifest.files;\n\tif (!Array.isArray(files)) return;\n\tconst refs = [];\n\tfor (const file of files) {\n\t\tif (!file || typeof file !== \"object\") return;\n\t\tconst path = file.path;\n\t\tconst hash = file.hash;\n\t\tif (typeof path !== \"string\" || typeof hash !== \"string\") return;\n\t\trefs.push({\n\t\t\tpath,\n\t\t\thash\n\t\t});\n\t}\n\treturn refs.sort((a, b) => a.path.localeCompare(b.path));\n}\nfunction sourceManifestFilesEqual(existing, next) {\n\tconst existingFiles = manifestFileRefs(existing);\n\tconst nextFiles = manifestFileRefs(next);\n\tif (!existingFiles || !nextFiles || existingFiles.length !== nextFiles.length) return false;\n\treturn existingFiles.every((file, index) => file.path === nextFiles[index]?.path && file.hash === nextFiles[index]?.hash);\n}\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/**\n* Mark artifact ready and stage it as pending only while this artifact still\n* owns `deployLeaseArtifactId`. A reclaimed/expired builder fails without\n* overwriting another deploy's lease or pending pointer.\n*/\nasync function completeProjectArtifactUnderDeployLease(input) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\tconst [existing] = await db.select({\n\t\tartifact: projectArtifacts,\n\t\tproject: projects\n\t}).from(projectArtifacts).innerJoin(projects, eq(projects.id, projectArtifacts.projectId)).where(and(eq(projectArtifacts.id, input.artifactId), eq(projectArtifacts.projectId, input.projectId))).limit(1);\n\tif (existing?.artifact.status === \"ready\" && existing.project.pendingArtifactId === input.artifactId) return existing;\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(and(eq(projects.id, input.projectId), eq(projects.deployLeaseArtifactId, input.artifactId), gt(projects.deployLeaseExpiresAt, now))).returning();\n\t\tif (!project) {\n\t\t\tawait db.update(projectArtifacts).set({\n\t\t\t\tstatus: \"pending\",\n\t\t\t\tmanifestJson: null,\n\t\t\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t\t\t}).where(and(eq(projectArtifacts.id, input.artifactId), eq(projectArtifacts.projectId, input.projectId), eq(projectArtifacts.status, \"ready\")));\n\t\t\tthrow new DeployLeaseLostError();\n\t\t}\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(and(eq(projects.id, input.projectId), eq(projects.deployLeaseArtifactId, input.artifactId), gt(projects.deployLeaseExpiresAt, now))).returning();\n\t\tif (!project) throw new DeployLeaseLostError();\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\tdeployLeaseArtifactId: null,\n\t\t\tdeployLeaseExpiresAt: null,\n\t\t\tupdatedAt: now\n\t\t}).where(and(eq(projects.id, input.projectId), eq(projects.pendingArtifactId, input.artifactId))).returning();\n\t\tif (!updatedProject) throw new Error(\"Artifact is not the pending deploy for this project\");\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\tdeployLeaseArtifactId: null,\n\t\t\tdeployLeaseExpiresAt: null,\n\t\t\tupdatedAt: now\n\t\t}).where(and(eq(projects.id, input.projectId), eq(projects.pendingArtifactId, input.artifactId))).returning();\n\t\tif (!updatedProject) throw new Error(\"Artifact is not the pending deploy for this project\");\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 current = (await db.select({ sourceManifestJson: projectArtifacts.sourceManifestJson }).from(projectArtifacts).where(and(eq(projectArtifacts.id, input.artifactId), eq(projectArtifacts.projectId, input.projectId))).limit(1))[0];\n\tif (!current) throw new Error(\"Artifact not found\");\n\tif (current.sourceManifestJson != null) {\n\t\tif (sourceManifestFilesEqual(current.sourceManifestJson, input.sourceManifestJson)) {\n\t\t\tconst [artifact] = await db.select().from(projectArtifacts).where(and(eq(projectArtifacts.id, input.artifactId), eq(projectArtifacts.projectId, input.projectId))).limit(1);\n\t\t\tif (!artifact) throw new Error(\"Artifact not found\");\n\t\t\treturn artifact;\n\t\t}\n\t\tthrow new ProjectArtifactSourceManifestConflictError();\n\t}\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\nconst GIT_PROVENANCE_KEYS = [\n\t\"sourceRepositoryId\",\n\t\"sourceCommitSha\",\n\t\"baseMainSha\",\n\t\"baseDraftSha\"\n];\nfunction resolveGitProvenance(input) {\n\tif (GIT_PROVENANCE_KEYS.filter((key) => input[key] !== void 0).length === 0) return {\n\t\tsourceRepositoryId: null,\n\t\tsourceCommitSha: null,\n\t\tbaseMainSha: null,\n\t\tbaseDraftSha: null\n\t};\n\tconst missing = GIT_PROVENANCE_KEYS.filter((key) => input[key] === void 0);\n\tif (missing.length > 0) throw new Error(`Missing git provenance fields: ${missing.join(\", \")}`);\n\treturn {\n\t\tsourceRepositoryId: input.sourceRepositoryId,\n\t\tsourceCommitSha: input.sourceCommitSha,\n\t\tbaseMainSha: input.baseMainSha,\n\t\tbaseDraftSha: input.baseDraftSha\n\t};\n}\nasync function insertProjectArtifact(input) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\tconst git = resolveGitProvenance(input);\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\tsourceRepositoryId: git.sourceRepositoryId,\n\t\tsourceCommitSha: git.sourceCommitSha,\n\t\tbaseMainSha: git.baseMainSha,\n\t\tbaseDraftSha: git.baseDraftSha,\n\t\tdeployMode: input.deployMode ?? null,\n\t\tcandidateOps: input.candidateOps ?? null,\n\t\tcandidateRef: input.candidateRef ?? null,\n\t\tcandidateEphemeral: input.candidateEphemeral ?? null,\n\t\tprotocolState: input.protocolState ?? null,\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 updateProjectArtifactCandidate(input) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\tconst [row] = await db.update(projectArtifacts).set({\n\t\tcandidateRef: input.candidateRef,\n\t\tcandidateEphemeral: input.candidateEphemeral,\n\t\tsourceCommitSha: input.sourceCommitSha,\n\t\t...input.protocolState !== void 0 ? { protocolState: input.protocolState } : {},\n\t\tupdatedAt: now\n\t}).where(and(eq(projectArtifacts.id, input.artifactId), eq(projectArtifacts.projectId, input.projectId), ...input.expectedProtocolState ? [eq(projectArtifacts.protocolState, input.expectedProtocolState)] : [])).returning();\n\tif (!row) throw new Error(\"Artifact not found\");\n\treturn row;\n}\nasync function updateProjectArtifactProtocolState(input) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\tconst [row] = await db.update(projectArtifacts).set({\n\t\tprotocolState: input.protocolState,\n\t\tupdatedAt: now\n\t}).where(and(eq(projectArtifacts.id, input.artifactId), eq(projectArtifacts.projectId, input.projectId))).returning();\n\tif (!row) throw new Error(\"Artifact not found\");\n\treturn row;\n}\n/** Compare-and-set a managed deploy protocol transition. */\nasync function transitionProjectArtifactProtocolState(input) {\n\tif (input.from.length === 0) return;\n\tconst [row] = await getDb().update(projectArtifacts).set({\n\t\tprotocolState: input.to,\n\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t}).where(and(eq(projectArtifacts.id, input.artifactId), eq(projectArtifacts.projectId, input.projectId), inArray(projectArtifacts.protocolState, input.from))).returning();\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}\n/** Delete an abandoned transaction only when no project pointer references it. */\nasync function deleteProjectArtifactIfUnreferenced(input) {\n\tconst db = getDb();\n\tconst [project] = await db.select({\n\t\tactiveArtifactId: projects.activeArtifactId,\n\t\tpendingArtifactId: projects.pendingArtifactId,\n\t\tdeployLeaseArtifactId: projects.deployLeaseArtifactId\n\t}).from(projects).where(eq(projects.id, input.projectId)).limit(1);\n\tif (!project || project.activeArtifactId === input.artifactId || project.pendingArtifactId === input.artifactId || project.deployLeaseArtifactId === input.artifactId) return false;\n\treturn (await db.delete(projectArtifacts).where(and(eq(projectArtifacts.id, input.artifactId), eq(projectArtifacts.projectId, input.projectId))).returning({ id: projectArtifacts.id })).length > 0;\n}\n/** Source manifest only — avoids loading the runtime `manifestJson` blob. */\nasync function selectProjectArtifactSourceManifestForProject(artifactId, projectId) {\n\treturn (await getDb().select({ sourceManifestJson: projectArtifacts.sourceManifestJson }).from(projectArtifacts).where(and(eq(projectArtifacts.id, artifactId), eq(projectArtifacts.projectId, projectId))).limit(1))[0];\n}\nconst sourceRevisionColumns = {\n\tartifactId: projectArtifacts.id,\n\tsourceRepositoryId: projectArtifacts.sourceRepositoryId,\n\tsourceCommitSha: projectArtifacts.sourceCommitSha,\n\tsourceManifestJson: projectArtifacts.sourceManifestJson\n};\n/** Source revision fields for a specific artifact in a project. */\nasync function selectProjectArtifactSourceRevisionForProject(artifactId, projectId) {\n\treturn (await getDb().select(sourceRevisionColumns).from(projectArtifacts).where(and(eq(projectArtifacts.id, artifactId), eq(projectArtifacts.projectId, projectId))).limit(1))[0];\n}\n/** Source revision fields for the project's currently active deploy. */\nasync function selectActiveArtifactSourceRevisionForProject(projectId) {\n\treturn (await getDb().select(sourceRevisionColumns).from(projects).innerJoin(projectArtifacts, eq(projects.activeArtifactId, projectArtifacts.id)).where(eq(projects.id, 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/queries/published-forms/index.ts\nfunction createPublishedFormToken() {\n\treturn randomBytes(32).toString(\"base64url\");\n}\nasync function listPublishedFormsForOrganization(organizationId, options) {\n\tif (options?.projectIds !== void 0 && options.projectIds.length === 0) return [];\n\tif (isSqliteDialect()) {\n\t\tconst conditions = [eq$1(publishedFormsSqlite.organizationId, organizationId)];\n\t\tif (options?.projectIds !== void 0) conditions.push(inArray$1(publishedFormsSqlite.projectId, options.projectIds));\n\t\treturn getSqliteDb().select().from(publishedFormsSqlite).where(and$1(...conditions)).orderBy(desc$1(publishedFormsSqlite.updatedAt), desc$1(publishedFormsSqlite.id));\n\t}\n\tconst conditions = [eq$1(publishedForms.organizationId, organizationId)];\n\tif (options?.projectIds !== void 0) conditions.push(inArray$1(publishedForms.projectId, options.projectIds));\n\treturn getDb().select().from(publishedForms).where(and$1(...conditions)).orderBy(desc$1(publishedForms.updatedAt), desc$1(publishedForms.id));\n}\nasync function selectPublishedFormForWorkflow(organizationId, projectId, workflowSlug) {\n\tif (isSqliteDialect()) return (await getSqliteDb().select().from(publishedFormsSqlite).where(and$1(eq$1(publishedFormsSqlite.organizationId, organizationId), eq$1(publishedFormsSqlite.projectId, projectId), eq$1(publishedFormsSqlite.workflowSlug, workflowSlug))).limit(1))[0];\n\treturn (await getDb().select().from(publishedForms).where(and$1(eq$1(publishedForms.organizationId, organizationId), eq$1(publishedForms.projectId, projectId), eq$1(publishedForms.workflowSlug, workflowSlug))).limit(1))[0];\n}\nasync function selectEnabledPublishedFormByToken(token) {\n\tif (isSqliteDialect()) return (await getSqliteDb().select({\n\t\tform: publishedFormsSqlite,\n\t\torganization: {\n\t\t\tid: organizationsSqlite.id,\n\t\t\tname: organizationsSqlite.name,\n\t\t\tcustomLogoEnabled: organizationsSqlite.customLogoEnabled,\n\t\t\tlogoLightUrl: organizationsSqlite.logoLightUrl,\n\t\t\tlogoDarkUrl: organizationsSqlite.logoDarkUrl,\n\t\t\tlogoHeightPx: organizationsSqlite.logoHeightPx\n\t\t},\n\t\tproject: {\n\t\t\tid: projectsSqlite.id,\n\t\t\tname: projectsSqlite.name\n\t\t}\n\t}).from(publishedFormsSqlite).innerJoin(organizationsSqlite, eq$1(publishedFormsSqlite.organizationId, organizationsSqlite.id)).innerJoin(projectsSqlite, eq$1(publishedFormsSqlite.projectId, projectsSqlite.id)).where(and$1(eq$1(publishedFormsSqlite.token, token), eq$1(publishedFormsSqlite.enabled, true), isNull$1(organizationsSqlite.deletedAt), isNull$1(projectsSqlite.deletedAt))).limit(1))[0];\n\treturn (await getDb().select({\n\t\tform: publishedForms,\n\t\torganization: {\n\t\t\tid: organizations.id,\n\t\t\tname: organizations.name,\n\t\t\tcustomLogoEnabled: organizations.customLogoEnabled,\n\t\t\tlogoLightUrl: organizations.logoLightUrl,\n\t\t\tlogoDarkUrl: organizations.logoDarkUrl,\n\t\t\tlogoHeightPx: organizations.logoHeightPx\n\t\t},\n\t\tproject: {\n\t\t\tid: projects.id,\n\t\t\tname: projects.name\n\t\t}\n\t}).from(publishedForms).innerJoin(organizations, eq$1(publishedForms.organizationId, organizations.id)).innerJoin(projects, eq$1(publishedForms.projectId, projects.id)).where(and$1(eq$1(publishedForms.token, token), eq$1(publishedForms.enabled, true), isNull$1(organizations.deletedAt), isNull$1(projects.deletedAt))).limit(1))[0];\n}\nasync function upsertPublishedForm(input) {\n\tconst existing = await selectPublishedFormForWorkflow(input.organizationId, input.projectId, input.workflowSlug);\n\tconst now = /* @__PURE__ */ new Date();\n\tif (existing) {\n\t\tif (isSqliteDialect()) {\n\t\t\tconst [updated] = await getSqliteDb().update(publishedFormsSqlite).set({\n\t\t\t\t...input.enabled !== void 0 ? { enabled: input.enabled } : {},\n\t\t\t\t...input.title !== void 0 ? { title: input.title } : {},\n\t\t\t\t...input.description !== void 0 ? { description: input.description } : {},\n\t\t\t\t...input.fieldConfig !== void 0 ? { fieldConfig: input.fieldConfig } : {},\n\t\t\t\tupdatedAt: now\n\t\t\t}).where(eq$1(publishedFormsSqlite.id, existing.id)).returning();\n\t\t\treturn updated;\n\t\t}\n\t\tconst [updated] = await getDb().update(publishedForms).set({\n\t\t\t...input.enabled !== void 0 ? { enabled: input.enabled } : {},\n\t\t\t...input.title !== void 0 ? { title: input.title } : {},\n\t\t\t...input.description !== void 0 ? { description: input.description } : {},\n\t\t\t...input.fieldConfig !== void 0 ? { fieldConfig: input.fieldConfig } : {},\n\t\t\tupdatedAt: now\n\t\t}).where(eq$1(publishedForms.id, existing.id)).returning();\n\t\treturn updated;\n\t}\n\tif (isSqliteDialect()) {\n\t\tconst [created] = await getSqliteDb().insert(publishedFormsSqlite).values({\n\t\t\tid: crypto.randomUUID(),\n\t\t\torganizationId: input.organizationId,\n\t\t\tprojectId: input.projectId,\n\t\t\tworkflowSlug: input.workflowSlug,\n\t\t\ttoken: createPublishedFormToken(),\n\t\t\tenabled: input.enabled ?? true,\n\t\t\ttitle: input.title ?? null,\n\t\t\tdescription: input.description ?? null,\n\t\t\tfieldConfig: input.fieldConfig ?? {},\n\t\t\tcreatedByUserId: input.createdByUserId,\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now\n\t\t}).returning();\n\t\treturn created;\n\t}\n\tconst [created] = await getDb().insert(publishedForms).values({\n\t\tid: crypto.randomUUID(),\n\t\torganizationId: input.organizationId,\n\t\tprojectId: input.projectId,\n\t\tworkflowSlug: input.workflowSlug,\n\t\ttoken: createPublishedFormToken(),\n\t\tenabled: input.enabled ?? true,\n\t\ttitle: input.title ?? null,\n\t\tdescription: input.description ?? null,\n\t\tfieldConfig: input.fieldConfig ?? {},\n\t\tcreatedByUserId: input.createdByUserId,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t}).returning();\n\treturn created;\n}\nasync function unpublishFormForWorkflow(organizationId, projectId, workflowSlug) {\n\tif (isSqliteDialect()) {\n\t\tconst [updated] = await getSqliteDb().update(publishedFormsSqlite).set({\n\t\t\tenabled: false,\n\t\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t\t}).where(and$1(eq$1(publishedFormsSqlite.organizationId, organizationId), eq$1(publishedFormsSqlite.projectId, projectId), eq$1(publishedFormsSqlite.workflowSlug, workflowSlug))).returning();\n\t\treturn updated;\n\t}\n\tconst [updated] = await getDb().update(publishedForms).set({\n\t\tenabled: false,\n\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t}).where(and$1(eq$1(publishedForms.organizationId, organizationId), eq$1(publishedForms.projectId, projectId), eq$1(publishedForms.workflowSlug, workflowSlug))).returning();\n\treturn updated;\n}\nasync function rotatePublishedFormToken(organizationId, projectId, workflowSlug) {\n\tif (isSqliteDialect()) {\n\t\tconst [updated] = await getSqliteDb().update(publishedFormsSqlite).set({\n\t\t\ttoken: createPublishedFormToken(),\n\t\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t\t}).where(and$1(eq$1(publishedFormsSqlite.organizationId, organizationId), eq$1(publishedFormsSqlite.projectId, projectId), eq$1(publishedFormsSqlite.workflowSlug, workflowSlug))).returning();\n\t\treturn updated;\n\t}\n\tconst [updated] = await getDb().update(publishedForms).set({\n\t\ttoken: createPublishedFormToken(),\n\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t}).where(and$1(eq$1(publishedForms.organizationId, organizationId), eq$1(publishedForms.projectId, projectId), eq$1(publishedForms.workflowSlug, workflowSlug))).returning();\n\treturn updated;\n}\n//#endregion\n//#region src/queries/platform-agent/events.ts\nconst PLATFORM_AGENT_MESSAGE_EVENT_TYPE = \"message\";\nconst PLATFORM_AGENT_CONTEXT_COMPACTED_EVENT_TYPE = \"context_compacted\";\nconst PLATFORM_AGENT_AGENT_START_EVENT_TYPE = \"agent_start\";\nconst PLATFORM_AGENT_AGENT_END_EVENT_TYPE = \"agent_end\";\nasync function maxSeqForSession(sessionId) {\n\tif (isSqliteDialect()) return (await getSqliteDb().select({ value: max$1(platformAgentEventsSqlite.seq) }).from(platformAgentEventsSqlite).where(and$1(eq$1(platformAgentEventsSqlite.sessionId, sessionId), isNull$1(platformAgentEventsSqlite.deletedAt))))[0]?.value ?? 0;\n\treturn (await getDb().select({ value: max$1(platformAgentEvents.seq) }).from(platformAgentEvents).where(and$1(eq$1(platformAgentEvents.sessionId, sessionId), isNull$1(platformAgentEvents.deletedAt))))[0]?.value ?? 0;\n}\n/** Stable primary key for a durable transcript message row (retry-safe). */\nfunction platformAgentMessageEventId(sessionId, messageId) {\n\treturn `pam:${sessionId}:${messageId}`;\n}\n/** Stable primary key for a per-run `agent_start` row (route + worker dedupe). */\nfunction platformAgentStartEventId(sessionId, promptId) {\n\treturn `pas:${sessionId}:${promptId}`;\n}\n/** Stable primary key for a per-run `agent_end` row (terminal finalizer dedupe). */\nfunction platformAgentEndEventId(sessionId, promptId) {\n\treturn `pae:${sessionId}:${promptId}`;\n}\nasync function existingEventSeq(input) {\n\tif (isSqliteDialect()) {\n\t\tconst row = (await getSqliteDb().select({\n\t\t\tseq: platformAgentEventsSqlite.seq,\n\t\t\tsessionId: platformAgentEventsSqlite.sessionId,\n\t\t\teventType: platformAgentEventsSqlite.eventType\n\t\t}).from(platformAgentEventsSqlite).where(eq$1(platformAgentEventsSqlite.id, input.eventId)).limit(1))[0];\n\t\tif (!row || row.sessionId !== input.sessionId || row.eventType !== input.eventType) throw new Error(\"Platform agent event id conflict\");\n\t\treturn row.seq;\n\t}\n\tconst row = (await getDb().select({\n\t\tseq: platformAgentEvents.seq,\n\t\tsessionId: platformAgentEvents.sessionId,\n\t\teventType: platformAgentEvents.eventType\n\t}).from(platformAgentEvents).where(eq$1(platformAgentEvents.id, input.eventId)).limit(1))[0];\n\tif (!row || row.sessionId !== input.sessionId || row.eventType !== input.eventType) throw new Error(\"Platform agent event id conflict\");\n\treturn row.seq;\n}\n/**\n* Append one event. When `eventId` is supplied the insert is idempotent on the\n* primary key — a committed-but-unacked insert returns the existing sequence.\n*/\nasync function appendPlatformAgentEvent(input) {\n\tconst id = input.eventId ?? crypto.randomUUID();\n\tconst seq = await maxSeqForSession(input.sessionId) + 1;\n\tconst values = {\n\t\tid,\n\t\torganizationId: input.organizationId,\n\t\tsessionId: input.sessionId,\n\t\tseq,\n\t\teventType: input.eventType,\n\t\tpayload: input.payload,\n\t\tcreatedAt: /* @__PURE__ */ new Date(),\n\t\tdeletedAt: null\n\t};\n\tif (isSqliteDialect()) {\n\t\tif ((await getSqliteDb().insert(platformAgentEventsSqlite).values(values).onConflictDoNothing({ target: platformAgentEventsSqlite.id }).returning({ id: platformAgentEventsSqlite.id }))[0]) return seq;\n\t\treturn existingEventSeq({\n\t\t\teventId: id,\n\t\t\tsessionId: input.sessionId,\n\t\t\teventType: input.eventType\n\t\t});\n\t}\n\tif ((await getDb().insert(platformAgentEvents).values(values).onConflictDoNothing({ target: platformAgentEvents.id }).returning({ id: platformAgentEvents.id }))[0]) return seq;\n\treturn existingEventSeq({\n\t\teventId: id,\n\t\tsessionId: input.sessionId,\n\t\teventType: input.eventType\n\t});\n}\nasync function listPlatformAgentEvents(sessionId) {\n\tif (isSqliteDialect()) return getSqliteDb().select().from(platformAgentEventsSqlite).where(and$1(eq$1(platformAgentEventsSqlite.sessionId, sessionId), isNull$1(platformAgentEventsSqlite.deletedAt))).orderBy(asc(platformAgentEventsSqlite.seq));\n\treturn getDb().select().from(platformAgentEvents).where(and$1(eq$1(platformAgentEvents.sessionId, sessionId), isNull$1(platformAgentEvents.deletedAt))).orderBy(asc(platformAgentEvents.seq));\n}\nasync function listPlatformAgentEventsByType(sessionId, eventType, afterSeq) {\n\tif (isSqliteDialect()) return await getSqliteDb().select({\n\t\tpayload: platformAgentEventsSqlite.payload,\n\t\tcreatedAt: platformAgentEventsSqlite.createdAt,\n\t\tseq: platformAgentEventsSqlite.seq\n\t}).from(platformAgentEventsSqlite).where(and$1(eq$1(platformAgentEventsSqlite.sessionId, sessionId), eq$1(platformAgentEventsSqlite.eventType, eventType), ...afterSeq === void 0 ? [] : [gt$1(platformAgentEventsSqlite.seq, afterSeq)], isNull$1(platformAgentEventsSqlite.deletedAt))).orderBy(asc(platformAgentEventsSqlite.seq));\n\treturn getDb().select({\n\t\tpayload: platformAgentEvents.payload,\n\t\tcreatedAt: platformAgentEvents.createdAt,\n\t\tseq: platformAgentEvents.seq\n\t}).from(platformAgentEvents).where(and$1(eq$1(platformAgentEvents.sessionId, sessionId), eq$1(platformAgentEvents.eventType, eventType), ...afterSeq === void 0 ? [] : [gt$1(platformAgentEvents.seq, afterSeq)], isNull$1(platformAgentEvents.deletedAt))).orderBy(asc(platformAgentEvents.seq));\n}\n/** Message records with sequence numbers, optionally bounded to the active post-compaction suffix. */\nasync function listPlatformAgentMessageEventRecords(sessionId, afterSeq) {\n\treturn (await listPlatformAgentEventsByType(sessionId, PLATFORM_AGENT_MESSAGE_EVENT_TYPE, afterSeq)).map((row) => ({\n\t\tseq: row.seq,\n\t\tpayload: row.payload\n\t}));\n}\nasync function countPlatformAgentMessageEvents(sessionId) {\n\tif (isSqliteDialect()) {\n\t\tconst rows = await getSqliteDb().select({ count: sql$1`count(*)` }).from(platformAgentEventsSqlite).where(and$1(eq$1(platformAgentEventsSqlite.sessionId, sessionId), eq$1(platformAgentEventsSqlite.eventType, PLATFORM_AGENT_MESSAGE_EVENT_TYPE), isNull$1(platformAgentEventsSqlite.deletedAt)));\n\t\treturn Number(rows[0]?.count ?? 0);\n\t}\n\tconst rows = await getDb().select({ count: sql$1`count(*)` }).from(platformAgentEvents).where(and$1(eq$1(platformAgentEvents.sessionId, sessionId), eq$1(platformAgentEvents.eventType, PLATFORM_AGENT_MESSAGE_EVENT_TYPE), isNull$1(platformAgentEvents.deletedAt)));\n\treturn Number(rows[0]?.count ?? 0);\n}\nasync function countPlatformAgentMessageEventsBySessionIds(sessionIds) {\n\tconst counts = /* @__PURE__ */ new Map();\n\tif (sessionIds.length === 0) return counts;\n\tif (isSqliteDialect()) {\n\t\tconst rows = await getSqliteDb().select({\n\t\t\tsessionId: platformAgentEventsSqlite.sessionId,\n\t\t\tcount: sql$1`count(*)`\n\t\t}).from(platformAgentEventsSqlite).where(and$1(inArray$1(platformAgentEventsSqlite.sessionId, sessionIds), eq$1(platformAgentEventsSqlite.eventType, PLATFORM_AGENT_MESSAGE_EVENT_TYPE), isNull$1(platformAgentEventsSqlite.deletedAt))).groupBy(platformAgentEventsSqlite.sessionId);\n\t\tfor (const row of rows) counts.set(row.sessionId, Number(row.count ?? 0));\n\t\treturn counts;\n\t}\n\tconst rows = await getDb().select({\n\t\tsessionId: platformAgentEvents.sessionId,\n\t\tcount: sql$1`count(*)`\n\t}).from(platformAgentEvents).where(and$1(inArray$1(platformAgentEvents.sessionId, sessionIds), eq$1(platformAgentEvents.eventType, PLATFORM_AGENT_MESSAGE_EVENT_TYPE), isNull$1(platformAgentEvents.deletedAt))).groupBy(platformAgentEvents.sessionId);\n\tfor (const row of rows) counts.set(row.sessionId, Number(row.count ?? 0));\n\treturn counts;\n}\nasync function latestPlatformAgentEventByTypes(sessionId, eventTypes) {\n\tif (eventTypes.length === 0) return;\n\tif (isSqliteDialect()) return (await getSqliteDb().select().from(platformAgentEventsSqlite).where(and$1(eq$1(platformAgentEventsSqlite.sessionId, sessionId), inArray$1(platformAgentEventsSqlite.eventType, eventTypes), isNull$1(platformAgentEventsSqlite.deletedAt))).orderBy(desc$1(platformAgentEventsSqlite.seq)).limit(1))[0];\n\treturn (await getDb().select().from(platformAgentEvents).where(and$1(eq$1(platformAgentEvents.sessionId, sessionId), inArray$1(platformAgentEvents.eventType, eventTypes), isNull$1(platformAgentEvents.deletedAt))).orderBy(desc$1(platformAgentEvents.seq)).limit(1))[0];\n}\nasync function hasPlatformAgentEventAfterSeq(sessionId, eventType, afterSeq) {\n\tif (isSqliteDialect()) return (await getSqliteDb().select({ seq: platformAgentEventsSqlite.seq }).from(platformAgentEventsSqlite).where(and$1(eq$1(platformAgentEventsSqlite.sessionId, sessionId), eq$1(platformAgentEventsSqlite.eventType, eventType), gt$1(platformAgentEventsSqlite.seq, afterSeq), isNull$1(platformAgentEventsSqlite.deletedAt))).limit(1)).length > 0;\n\treturn (await getDb().select({ seq: platformAgentEvents.seq }).from(platformAgentEvents).where(and$1(eq$1(platformAgentEvents.sessionId, sessionId), eq$1(platformAgentEvents.eventType, eventType), gt$1(platformAgentEvents.seq, afterSeq), isNull$1(platformAgentEvents.deletedAt))).limit(1)).length > 0;\n}\nfunction compactionEventFromPlatformAgentRow(event) {\n\tconst payload = typeof event.payload === \"object\" && event.payload !== null ? event.payload : null;\n\tconst checkpoint = payload && typeof payload.checkpoint === \"object\" && payload.checkpoint !== null ? payload.checkpoint : payload;\n\tif (!checkpoint || typeof checkpoint.compactionModel !== \"string\" || typeof checkpoint.sourceModel !== \"string\" || typeof checkpoint.durable !== \"boolean\") return null;\n\treturn {\n\t\tseq: event.seq,\n\t\tcreatedAt: event.createdAt.toISOString(),\n\t\tcompactionModel: checkpoint.compactionModel,\n\t\tsourceModel: checkpoint.sourceModel,\n\t\tdurable: checkpoint.durable,\n\t\t...typeof checkpoint.estimatedBeforeTokens === \"number\" ? { estimatedBeforeTokens: checkpoint.estimatedBeforeTokens } : {},\n\t\t...typeof checkpoint.retainedTailEstimate === \"number\" ? { retainedTailEstimate: checkpoint.retainedTailEstimate } : {}\n\t};\n}\nasync function listPlatformAgentCompactionEvents(sessionId) {\n\treturn (await listPlatformAgentEventsByType(sessionId, PLATFORM_AGENT_CONTEXT_COMPACTED_EVENT_TYPE)).flatMap((row) => {\n\t\tconst event = compactionEventFromPlatformAgentRow(row);\n\t\treturn event ? [event] : [];\n\t});\n}\n/**\n* Map assistant message ids → worked wall-clock ms from matching\n* `agent_start` / `agent_end` pairs (same `promptId`, start seq before end seq).\n*/\nfunction workedMsByAssistantMessageId(starts, ends) {\n\tconst startsByPromptId = /* @__PURE__ */ new Map();\n\tfor (const start of starts) {\n\t\tconst payload = start.payload && typeof start.payload === \"object\" && !Array.isArray(start.payload) ? start.payload : null;\n\t\tconst promptId = typeof payload?.promptId === \"string\" ? payload.promptId : null;\n\t\tif (!promptId) continue;\n\t\tconst list = startsByPromptId.get(promptId) ?? [];\n\t\tlist.push({\n\t\t\tseq: start.seq,\n\t\t\tcreatedAt: start.createdAt\n\t\t});\n\t\tstartsByPromptId.set(promptId, list);\n\t}\n\tconst workedMsByMessageId = /* @__PURE__ */ new Map();\n\tfor (const end of ends) {\n\t\tconst payload = end.payload && typeof end.payload === \"object\" && !Array.isArray(end.payload) ? end.payload : null;\n\t\tconst promptId = typeof payload?.promptId === \"string\" ? payload.promptId : null;\n\t\tif (!promptId) continue;\n\t\tconst candidates = startsByPromptId.get(promptId) ?? [];\n\t\tlet matchedStart = null;\n\t\tfor (const candidate of candidates) {\n\t\t\tif (candidate.seq >= end.seq) continue;\n\t\t\tif (!matchedStart || candidate.seq > matchedStart.seq) matchedStart = candidate;\n\t\t}\n\t\tif (!matchedStart) continue;\n\t\tconst elapsedMs = end.createdAt.getTime() - matchedStart.createdAt.getTime();\n\t\tif (!Number.isFinite(elapsedMs) || elapsedMs < 0) continue;\n\t\tconst messageIds = Array.isArray(payload?.messageIds) ? payload.messageIds : [];\n\t\tfor (const messageId of messageIds) if (typeof messageId === \"string\" && messageId.length > 0) workedMsByMessageId.set(messageId, elapsedMs);\n\t}\n\treturn workedMsByMessageId;\n}\nasync function listPlatformAgentTranscriptMessages(sessionId) {\n\tconst [messageRows, startRows, endRows] = await Promise.all([\n\t\tlistPlatformAgentEventsByType(sessionId, PLATFORM_AGENT_MESSAGE_EVENT_TYPE),\n\t\tlistPlatformAgentEventsByType(sessionId, PLATFORM_AGENT_AGENT_START_EVENT_TYPE),\n\t\tlistPlatformAgentEventsByType(sessionId, PLATFORM_AGENT_AGENT_END_EVENT_TYPE)\n\t]);\n\tconst workedMsByMessageId = workedMsByAssistantMessageId(startRows, endRows);\n\treturn parsePlatformAgentTranscript(messageRows.map((row) => {\n\t\tconst payload = row.payload && typeof row.payload === \"object\" && !Array.isArray(row.payload) ? { ...row.payload } : {};\n\t\tconst id = typeof payload.id === \"string\" ? payload.id : null;\n\t\tconst workedMs = id ? workedMsByMessageId.get(id) : void 0;\n\t\treturn sanitizeMessagePayloadContext({\n\t\t\t...payload,\n\t\t\tcreatedAt: row.createdAt.toISOString(),\n\t\t\t...workedMs !== void 0 ? { workedMs } : {}\n\t\t});\n\t}));\n}\nasync function latestDurablePlatformAgentCompactionCheckpoint(sessionId) {\n\tconst rows = isSqliteDialect() ? await getSqliteDb().select({\n\t\tpayload: platformAgentEventsSqlite.payload,\n\t\tseq: platformAgentEventsSqlite.seq\n\t}).from(platformAgentEventsSqlite).where(and$1(eq$1(platformAgentEventsSqlite.sessionId, sessionId), eq$1(platformAgentEventsSqlite.eventType, PLATFORM_AGENT_CONTEXT_COMPACTED_EVENT_TYPE), sql$1`json_extract(${platformAgentEventsSqlite.payload}, '$.checkpoint.durable') = 1`, isNull$1(platformAgentEventsSqlite.deletedAt))).orderBy(desc$1(platformAgentEventsSqlite.seq)).limit(1) : await getDb().select({\n\t\tpayload: platformAgentEvents.payload,\n\t\tseq: platformAgentEvents.seq\n\t}).from(platformAgentEvents).where(and$1(eq$1(platformAgentEvents.sessionId, sessionId), eq$1(platformAgentEvents.eventType, PLATFORM_AGENT_CONTEXT_COMPACTED_EVENT_TYPE), sql$1`${platformAgentEvents.payload}->'checkpoint'->>'durable' = 'true'`, isNull$1(platformAgentEvents.deletedAt))).orderBy(desc$1(platformAgentEvents.seq)).limit(1);\n\tfor (const row of rows) {\n\t\tconst payload = typeof row.payload === \"object\" && row.payload !== null ? row.payload : null;\n\t\tconst checkpoint = payload && typeof payload.checkpoint === \"object\" && payload.checkpoint !== null ? payload.checkpoint : null;\n\t\tif (checkpoint && checkpoint.durable === true && typeof checkpoint.summary === \"string\" && typeof checkpoint.compactedThroughSeq === \"number\" && typeof checkpoint.compactionModel === \"string\" && typeof checkpoint.sourceModel === \"string\") return {\n\t\t\tseq: row.seq,\n\t\t\tcompactedThroughSeq: checkpoint.compactedThroughSeq,\n\t\t\tsummary: checkpoint.summary,\n\t\t\tcompactionModel: checkpoint.compactionModel,\n\t\t\tsourceModel: checkpoint.sourceModel,\n\t\t\tdurable: true,\n\t\t\t...typeof checkpoint.estimatedBeforeTokens === \"number\" ? { estimatedBeforeTokens: checkpoint.estimatedBeforeTokens } : {},\n\t\t\t...typeof checkpoint.retainedTailEstimate === \"number\" ? { retainedTailEstimate: checkpoint.retainedTailEstimate } : {},\n\t\t\t...typeof checkpoint.promptId === \"string\" ? { promptId: checkpoint.promptId } : {}\n\t\t};\n\t}\n\treturn null;\n}\n//#endregion\n//#region src/queries/platform-agent/index.ts\n/** Stale `building` rows may be reclaimed after this window (install / snapshot timeout). */\nconst PLATFORM_AGENT_SNAPSHOT_BUILD_STALE_MS = 30 * 6e4;\n/** Statuses that may accept a new follow-up run. */\nconst STARTABLE_STATUSES = [\n\t\"completed\",\n\t\"failed\",\n\t\"canceled\"\n];\nconst PLATFORM_AGENT_SESSION_LIST_LIMIT = 100;\nfunction ownerConditions(table, scope) {\n\treturn and$1(eq$1(table.organizationId, scope.organizationId), eq$1(table.projectId, scope.projectId), eq$1(table.userId, scope.userId));\n}\nfunction orgUserConditions(table, scope) {\n\treturn and$1(eq$1(table.organizationId, scope.organizationId), eq$1(table.userId, scope.userId));\n}\n/** Lazy-create: insert already running with the first run id. */\nasync function createRunningPlatformAgentSession(input) {\n\tconst now = /* @__PURE__ */ new Date();\n\tconst values = {\n\t\tid: crypto.randomUUID(),\n\t\torganizationId: input.organizationId,\n\t\tprojectId: input.projectId,\n\t\tuserId: input.userId,\n\t\tstatus: \"running\",\n\t\ttitle: null,\n\t\tmodel: input.model,\n\t\tactiveRunId: input.runId,\n\t\tlastDraftCommitSha: null,\n\t\tsandboxId: null,\n\t\tsandboxLastUsedAt: null,\n\t\tpackageManager: null,\n\t\terror: null,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t};\n\tif (isSqliteDialect()) return (await getSqliteDb().insert(platformAgentSessionsSqlite).values(values).returning())[0];\n\treturn (await getDb().insert(platformAgentSessions).values(values).returning())[0];\n}\nasync function selectPlatformAgentSessionForOwner(scope, sessionId) {\n\tif (isSqliteDialect()) return (await getSqliteDb().select().from(platformAgentSessionsSqlite).where(and$1(ownerConditions(platformAgentSessionsSqlite, scope), eq$1(platformAgentSessionsSqlite.id, sessionId))).limit(1))[0];\n\treturn (await getDb().select().from(platformAgentSessions).where(and$1(ownerConditions(platformAgentSessions, scope), eq$1(platformAgentSessions.id, sessionId))).limit(1))[0];\n}\nasync function selectPlatformAgentSessionForOrgUser(scope, sessionId) {\n\tif (isSqliteDialect()) return (await getSqliteDb().select().from(platformAgentSessionsSqlite).where(and$1(orgUserConditions(platformAgentSessionsSqlite, scope), eq$1(platformAgentSessionsSqlite.id, sessionId))).limit(1))[0];\n\treturn (await getDb().select().from(platformAgentSessions).where(and$1(orgUserConditions(platformAgentSessions, scope), eq$1(platformAgentSessions.id, sessionId))).limit(1))[0];\n}\n/** Reconnect lookup — ownership-scoped session with current active run. */\nasync function selectPlatformAgentSessionForReconnect(scope, sessionId) {\n\treturn selectPlatformAgentSessionForOwner(scope, sessionId);\n}\nasync function listPlatformAgentSessionsForOwner(scope, options) {\n\tconst limit = options?.limit ?? 50;\n\tif (isSqliteDialect()) return getSqliteDb().select().from(platformAgentSessionsSqlite).where(ownerConditions(platformAgentSessionsSqlite, scope)).orderBy(desc$1(platformAgentSessionsSqlite.updatedAt), desc$1(platformAgentSessionsSqlite.id)).limit(limit);\n\treturn getDb().select().from(platformAgentSessions).where(ownerConditions(platformAgentSessions, scope)).orderBy(desc$1(platformAgentSessions.updatedAt), desc$1(platformAgentSessions.id)).limit(limit);\n}\nasync function listPlatformAgentSessionsForOrgUser(scope, options) {\n\tconst limit = options?.limit ?? 100;\n\tif (isSqliteDialect()) return getSqliteDb().select().from(platformAgentSessionsSqlite).where(orgUserConditions(platformAgentSessionsSqlite, scope)).orderBy(desc$1(platformAgentSessionsSqlite.updatedAt), desc$1(platformAgentSessionsSqlite.id)).limit(limit);\n\treturn getDb().select().from(platformAgentSessions).where(orgUserConditions(platformAgentSessions, scope)).orderBy(desc$1(platformAgentSessions.updatedAt), desc$1(platformAgentSessions.id)).limit(limit);\n}\n/**\n* Start a follow-up run only when the session is not currently running.\n* Compare-and-set: status in startable set AND activeRunId IS NULL.\n* Persists the selected model only when the CAS succeeds.\n*/\nasync function tryStartPlatformAgentRun(scope, sessionId, runId, model) {\n\tconst patch = {\n\t\tstatus: \"running\",\n\t\tactiveRunId: runId,\n\t\terror: null,\n\t\tupdatedAt: /* @__PURE__ */ new Date(),\n\t\t...model !== void 0 ? { model } : {}\n\t};\n\tif (isSqliteDialect()) {\n\t\tconst session = (await getSqliteDb().update(platformAgentSessionsSqlite).set(patch).where(and$1(ownerConditions(platformAgentSessionsSqlite, scope), eq$1(platformAgentSessionsSqlite.id, sessionId), isNull$1(platformAgentSessionsSqlite.activeRunId), inArray$1(platformAgentSessionsSqlite.status, STARTABLE_STATUSES))).returning())[0];\n\t\tif (!session) return { started: false };\n\t\treturn {\n\t\t\tstarted: true,\n\t\t\tsession\n\t\t};\n\t}\n\tconst session = (await getDb().update(platformAgentSessions).set(patch).where(and$1(ownerConditions(platformAgentSessions, scope), eq$1(platformAgentSessions.id, sessionId), isNull$1(platformAgentSessions.activeRunId), inArray$1(platformAgentSessions.status, STARTABLE_STATUSES))).returning())[0];\n\tif (!session) return { started: false };\n\treturn {\n\t\tstarted: true,\n\t\tsession\n\t};\n}\nasync function finishPlatformAgentRun(scope, sessionId, runId, status, error) {\n\tconst now = /* @__PURE__ */ new Date();\n\tif (isSqliteDialect()) return (await getSqliteDb().update(platformAgentSessionsSqlite).set({\n\t\tstatus,\n\t\tactiveRunId: null,\n\t\terror,\n\t\tupdatedAt: now\n\t}).where(and$1(ownerConditions(platformAgentSessionsSqlite, scope), eq$1(platformAgentSessionsSqlite.id, sessionId), eq$1(platformAgentSessionsSqlite.activeRunId, runId), eq$1(platformAgentSessionsSqlite.status, \"running\"))).returning())[0];\n\treturn (await getDb().update(platformAgentSessions).set({\n\t\tstatus,\n\t\tactiveRunId: null,\n\t\terror,\n\t\tupdatedAt: now\n\t}).where(and$1(ownerConditions(platformAgentSessions, scope), eq$1(platformAgentSessions.id, sessionId), eq$1(platformAgentSessions.activeRunId, runId), eq$1(platformAgentSessions.status, \"running\"))).returning())[0];\n}\n/**\n* Atomically CAS the session to a terminal status and append exactly one\n* `agent_end` for this run. Losing the CAS appends nothing.\n*/\nasync function finalizePlatformAgentRun(scope, sessionId, runId, input) {\n\tconst now = /* @__PURE__ */ new Date();\n\tconst error = input.status === \"failed\" ? input.error ?? \"Platform agent failed\" : null;\n\tconst endId = platformAgentEndEventId(sessionId, runId);\n\tconst endPayload = {\n\t\ttype: PLATFORM_AGENT_AGENT_END_EVENT_TYPE,\n\t\tpromptId: runId,\n\t\tmessageIds: input.messageIds ?? [],\n\t\t...input.diagnostics !== void 0 ? { diagnostics: input.diagnostics } : {}\n\t};\n\tif (isSqliteDialect()) return getSqliteDb().transaction((tx) => {\n\t\tconst session = tx.update(platformAgentSessionsSqlite).set({\n\t\t\tstatus: input.status,\n\t\t\tactiveRunId: null,\n\t\t\terror,\n\t\t\tupdatedAt: now\n\t\t}).where(and$1(ownerConditions(platformAgentSessionsSqlite, scope), eq$1(platformAgentSessionsSqlite.id, sessionId), eq$1(platformAgentSessionsSqlite.activeRunId, runId), eq$1(platformAgentSessionsSqlite.status, \"running\"))).returning().get();\n\t\tif (!session) return { finalized: false };\n\t\tconst maxSeq = tx.select({ value: sql$1`coalesce(max(${platformAgentEventsSqlite.seq}), 0)` }).from(platformAgentEventsSqlite).where(and$1(eq$1(platformAgentEventsSqlite.sessionId, sessionId), isNull$1(platformAgentEventsSqlite.deletedAt))).get()?.value ?? 0;\n\t\ttx.insert(platformAgentEventsSqlite).values({\n\t\t\tid: endId,\n\t\t\torganizationId: scope.organizationId,\n\t\t\tsessionId,\n\t\t\tseq: Number(maxSeq) + 1,\n\t\t\teventType: PLATFORM_AGENT_AGENT_END_EVENT_TYPE,\n\t\t\tpayload: endPayload,\n\t\t\tcreatedAt: now,\n\t\t\tdeletedAt: null\n\t\t}).onConflictDoNothing({ target: platformAgentEventsSqlite.id }).run();\n\t\treturn {\n\t\t\tfinalized: true,\n\t\t\tsession\n\t\t};\n\t});\n\treturn getDb().transaction(async (tx) => {\n\t\tconst session = (await tx.update(platformAgentSessions).set({\n\t\t\tstatus: input.status,\n\t\t\tactiveRunId: null,\n\t\t\terror,\n\t\t\tupdatedAt: now\n\t\t}).where(and$1(ownerConditions(platformAgentSessions, scope), eq$1(platformAgentSessions.id, sessionId), eq$1(platformAgentSessions.activeRunId, runId), eq$1(platformAgentSessions.status, \"running\"))).returning())[0];\n\t\tif (!session) return { finalized: false };\n\t\tconst maxRows = await tx.select({ value: sql$1`coalesce(max(${platformAgentEvents.seq}), 0)` }).from(platformAgentEvents).where(and$1(eq$1(platformAgentEvents.sessionId, sessionId), isNull$1(platformAgentEvents.deletedAt)));\n\t\tconst nextSeq = Number(maxRows[0]?.value ?? 0) + 1;\n\t\tawait tx.insert(platformAgentEvents).values({\n\t\t\tid: endId,\n\t\t\torganizationId: scope.organizationId,\n\t\t\tsessionId,\n\t\t\tseq: nextSeq,\n\t\t\teventType: PLATFORM_AGENT_AGENT_END_EVENT_TYPE,\n\t\t\tpayload: endPayload,\n\t\t\tcreatedAt: now,\n\t\t\tdeletedAt: null\n\t\t}).onConflictDoNothing({ target: platformAgentEvents.id });\n\t\treturn {\n\t\t\tfinalized: true,\n\t\t\tsession\n\t\t};\n\t});\n}\nasync function completePlatformAgentRun(scope, sessionId, runId) {\n\treturn finishPlatformAgentRun(scope, sessionId, runId, \"completed\", null);\n}\nasync function failPlatformAgentRun(scope, sessionId, runId, error) {\n\treturn finishPlatformAgentRun(scope, sessionId, runId, \"failed\", error);\n}\nasync function cancelPlatformAgentRun(scope, sessionId, runId) {\n\treturn finishPlatformAgentRun(scope, sessionId, runId, \"canceled\", null);\n}\nasync function updatePlatformAgentSessionTitle(scope, sessionId, title) {\n\tconst now = /* @__PURE__ */ new Date();\n\tif (isSqliteDialect()) return (await getSqliteDb().update(platformAgentSessionsSqlite).set({\n\t\ttitle,\n\t\tupdatedAt: now\n\t}).where(and$1(ownerConditions(platformAgentSessionsSqlite, scope), eq$1(platformAgentSessionsSqlite.id, sessionId))).returning())[0];\n\treturn (await getDb().update(platformAgentSessions).set({\n\t\ttitle,\n\t\tupdatedAt: now\n\t}).where(and$1(ownerConditions(platformAgentSessions, scope), eq$1(platformAgentSessions.id, sessionId))).returning())[0];\n}\nasync function updatePlatformAgentLastDraftCommitSha(scope, sessionId, lastDraftCommitSha) {\n\tconst now = /* @__PURE__ */ new Date();\n\tif (isSqliteDialect()) return (await getSqliteDb().update(platformAgentSessionsSqlite).set({\n\t\tlastDraftCommitSha,\n\t\tupdatedAt: now\n\t}).where(and$1(ownerConditions(platformAgentSessionsSqlite, scope), eq$1(platformAgentSessionsSqlite.id, sessionId))).returning())[0];\n\treturn (await getDb().update(platformAgentSessions).set({\n\t\tlastDraftCommitSha,\n\t\tupdatedAt: now\n\t}).where(and$1(ownerConditions(platformAgentSessions, scope), eq$1(platformAgentSessions.id, sessionId))).returning())[0];\n}\nasync function setPlatformAgentSessionSandbox(scope, sessionId, sandboxId) {\n\tconst now = /* @__PURE__ */ new Date();\n\tif (isSqliteDialect()) return (await getSqliteDb().update(platformAgentSessionsSqlite).set({\n\t\tsandboxId,\n\t\tsandboxLastUsedAt: now,\n\t\tupdatedAt: now\n\t}).where(and$1(ownerConditions(platformAgentSessionsSqlite, scope), eq$1(platformAgentSessionsSqlite.id, sessionId))).returning())[0];\n\treturn (await getDb().update(platformAgentSessions).set({\n\t\tsandboxId,\n\t\tsandboxLastUsedAt: now,\n\t\tupdatedAt: now\n\t}).where(and$1(ownerConditions(platformAgentSessions, scope), eq$1(platformAgentSessions.id, sessionId))).returning())[0];\n}\nasync function touchPlatformAgentSessionSandbox(scope, sessionId) {\n\tconst now = /* @__PURE__ */ new Date();\n\tif (isSqliteDialect()) return (await getSqliteDb().update(platformAgentSessionsSqlite).set({\n\t\tsandboxLastUsedAt: now,\n\t\tupdatedAt: now\n\t}).where(and$1(ownerConditions(platformAgentSessionsSqlite, scope), eq$1(platformAgentSessionsSqlite.id, sessionId), isNotNull(platformAgentSessionsSqlite.sandboxId))).returning())[0];\n\treturn (await getDb().update(platformAgentSessions).set({\n\t\tsandboxLastUsedAt: now,\n\t\tupdatedAt: now\n\t}).where(and$1(ownerConditions(platformAgentSessions, scope), eq$1(platformAgentSessions.id, sessionId), isNotNull(platformAgentSessions.sandboxId))).returning())[0];\n}\nasync function clearPlatformAgentSessionSandbox(scope, sessionId, options) {\n\tconst patch = {\n\t\tsandboxId: null,\n\t\tsandboxLastUsedAt: null,\n\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t};\n\tif (isSqliteDialect()) {\n\t\tconst conditions = [ownerConditions(platformAgentSessionsSqlite, scope), eq$1(platformAgentSessionsSqlite.id, sessionId)];\n\t\tif (options?.expectedSandboxId !== void 0) conditions.push(eq$1(platformAgentSessionsSqlite.sandboxId, options.expectedSandboxId));\n\t\treturn (await getSqliteDb().update(platformAgentSessionsSqlite).set(patch).where(and$1(...conditions)).returning())[0];\n\t}\n\tconst conditions = [ownerConditions(platformAgentSessions, scope), eq$1(platformAgentSessions.id, sessionId)];\n\tif (options?.expectedSandboxId !== void 0) conditions.push(eq$1(platformAgentSessions.sandboxId, options.expectedSandboxId));\n\treturn (await getDb().update(platformAgentSessions).set(patch).where(and$1(...conditions)).returning())[0];\n}\n/**\n* Atomically detach a session sandbox for post-run snapshot capture.\n* Requires matching sandbox id and no active run — winners clear the DB pointer\n* before snapshotting so a new prompt cannot race the same sandbox.\n*/\nasync function detachPlatformAgentSessionSandboxForSnapshot(scope, sessionId, expectedSandboxId) {\n\tconst patch = {\n\t\tsandboxId: null,\n\t\tsandboxLastUsedAt: null,\n\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t};\n\tif (isSqliteDialect()) {\n\t\tconst session = (await getSqliteDb().update(platformAgentSessionsSqlite).set(patch).where(and$1(ownerConditions(platformAgentSessionsSqlite, scope), eq$1(platformAgentSessionsSqlite.id, sessionId), eq$1(platformAgentSessionsSqlite.sandboxId, expectedSandboxId), isNull$1(platformAgentSessionsSqlite.activeRunId))).returning())[0];\n\t\tif (!session) return { detached: false };\n\t\treturn {\n\t\t\tdetached: true,\n\t\t\tsession\n\t\t};\n\t}\n\tconst session = (await getDb().update(platformAgentSessions).set(patch).where(and$1(ownerConditions(platformAgentSessions, scope), eq$1(platformAgentSessions.id, sessionId), eq$1(platformAgentSessions.sandboxId, expectedSandboxId), isNull$1(platformAgentSessions.activeRunId))).returning())[0];\n\tif (!session) return { detached: false };\n\treturn {\n\t\tdetached: true,\n\t\tsession\n\t};\n}\nasync function setPlatformAgentSessionPackageManager(scope, sessionId, packageManager) {\n\tconst patch = {\n\t\tpackageManager,\n\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t};\n\tif (isSqliteDialect()) return (await getSqliteDb().update(platformAgentSessionsSqlite).set(patch).where(and$1(ownerConditions(platformAgentSessionsSqlite, scope), eq$1(platformAgentSessionsSqlite.id, sessionId))).returning())[0];\n\treturn (await getDb().update(platformAgentSessions).set(patch).where(and$1(ownerConditions(platformAgentSessions, scope), eq$1(platformAgentSessions.id, sessionId))).returning())[0];\n}\n/**\n* Platform-wide idle sandbox lookup for maintenance — not ownership-scoped.\n*/\nasync function listIdlePlatformAgentSessionSandboxes(idleBefore, options) {\n\tconst limit = options?.limit ?? 100;\n\tif (isSqliteDialect()) return getSqliteDb().select().from(platformAgentSessionsSqlite).where(and$1(isNotNull(platformAgentSessionsSqlite.sandboxId), lt$1(platformAgentSessionsSqlite.sandboxLastUsedAt, idleBefore))).orderBy(asc(platformAgentSessionsSqlite.sandboxLastUsedAt)).limit(limit);\n\treturn getDb().select().from(platformAgentSessions).where(and$1(isNotNull(platformAgentSessions.sandboxId), lt$1(platformAgentSessions.sandboxLastUsedAt, idleBefore))).orderBy(asc(platformAgentSessions.sandboxLastUsedAt)).limit(limit);\n}\nasync function selectPlatformAgentProjectSnapshot(projectId) {\n\tif (isSqliteDialect()) return (await getSqliteDb().select().from(platformAgentProjectSnapshotsSqlite).where(eq$1(platformAgentProjectSnapshotsSqlite.projectId, projectId)).limit(1))[0];\n\treturn (await getDb().select().from(platformAgentProjectSnapshots).where(eq$1(platformAgentProjectSnapshots.projectId, projectId)).limit(1))[0];\n}\nfunction snapshotBuildingReclaimCondition(table, staleBefore) {\n\treturn or$1(ne$1(table.buildStatus, \"building\"), isNull$1(table.buildStartedAt), lt$1(table.buildStartedAt, staleBefore));\n}\n/**\n* Compare-and-set to `building` when no row exists or the current build is not recent.\n* Coalesces concurrent snapshot builders.\n*/\nasync function upsertPlatformAgentProjectSnapshotBuilding(projectId) {\n\tconst now = /* @__PURE__ */ new Date();\n\tconst staleBefore = new Date(now.getTime() - PLATFORM_AGENT_SNAPSHOT_BUILD_STALE_MS);\n\tconst buildingValues = {\n\t\tprojectId,\n\t\tmodalImageId: null,\n\t\tdepsFingerprint: null,\n\t\theadSha: null,\n\t\tpackageManager: null,\n\t\tcliVersion: null,\n\t\tsyncReady: false,\n\t\tcaptureGeneration: 0,\n\t\tbuildStatus: \"building\",\n\t\tbuildStartedAt: now,\n\t\tlastError: null,\n\t\tupdatedAt: now,\n\t\tcreatedAt: now\n\t};\n\tconst buildingPatch = {\n\t\tbuildStatus: \"building\",\n\t\tbuildStartedAt: now,\n\t\tlastError: null,\n\t\tupdatedAt: now\n\t};\n\tif (isSqliteDialect()) {\n\t\tconst inserted = await getSqliteDb().insert(platformAgentProjectSnapshotsSqlite).values(buildingValues).onConflictDoNothing().returning();\n\t\tif (inserted[0]) return {\n\t\t\tacquired: true,\n\t\t\tsnapshot: inserted[0]\n\t\t};\n\t\tconst updated = await getSqliteDb().update(platformAgentProjectSnapshotsSqlite).set(buildingPatch).where(and$1(eq$1(platformAgentProjectSnapshotsSqlite.projectId, projectId), snapshotBuildingReclaimCondition(platformAgentProjectSnapshotsSqlite, staleBefore))).returning();\n\t\tif (updated[0]) return {\n\t\t\tacquired: true,\n\t\t\tsnapshot: updated[0]\n\t\t};\n\t\treturn {\n\t\t\tacquired: false,\n\t\t\tsnapshot: await selectPlatformAgentProjectSnapshot(projectId)\n\t\t};\n\t}\n\tconst inserted = await getDb().insert(platformAgentProjectSnapshots).values(buildingValues).onConflictDoNothing().returning();\n\tif (inserted[0]) return {\n\t\tacquired: true,\n\t\tsnapshot: inserted[0]\n\t};\n\tconst updated = await getDb().update(platformAgentProjectSnapshots).set(buildingPatch).where(and$1(eq$1(platformAgentProjectSnapshots.projectId, projectId), snapshotBuildingReclaimCondition(platformAgentProjectSnapshots, staleBefore))).returning();\n\tif (updated[0]) return {\n\t\tacquired: true,\n\t\tsnapshot: updated[0]\n\t};\n\treturn {\n\t\tacquired: false,\n\t\tsnapshot: await selectPlatformAgentProjectSnapshot(projectId)\n\t};\n}\nasync function completePlatformAgentProjectSnapshot(projectId, input) {\n\tconst now = /* @__PURE__ */ new Date();\n\tconst patch = {\n\t\tmodalImageId: input.modalImageId,\n\t\tdepsFingerprint: input.depsFingerprint,\n\t\theadSha: input.headSha,\n\t\tpackageManager: input.packageManager,\n\t\tcliVersion: input.cliVersion ?? null,\n\t\tsyncReady: input.syncReady,\n\t\tbuildStatus: \"ready\",\n\t\tbuildStartedAt: null,\n\t\tlastError: null,\n\t\tupdatedAt: now\n\t};\n\tif (isSqliteDialect()) {\n\t\tconst conditions = [eq$1(platformAgentProjectSnapshotsSqlite.projectId, projectId), eq$1(platformAgentProjectSnapshotsSqlite.buildStatus, \"building\")];\n\t\tif (input.previousImageId !== void 0) conditions.push(input.previousImageId === null ? isNull$1(platformAgentProjectSnapshotsSqlite.modalImageId) : eq$1(platformAgentProjectSnapshotsSqlite.modalImageId, input.previousImageId));\n\t\treturn (await getSqliteDb().update(platformAgentProjectSnapshotsSqlite).set(patch).where(and$1(...conditions)).returning())[0];\n\t}\n\tconst conditions = [eq$1(platformAgentProjectSnapshots.projectId, projectId), eq$1(platformAgentProjectSnapshots.buildStatus, \"building\")];\n\tif (input.previousImageId !== void 0) conditions.push(input.previousImageId === null ? isNull$1(platformAgentProjectSnapshots.modalImageId) : eq$1(platformAgentProjectSnapshots.modalImageId, input.previousImageId));\n\treturn (await getDb().update(platformAgentProjectSnapshots).set(patch).where(and$1(...conditions)).returning())[0];\n}\nasync function failPlatformAgentProjectSnapshot(projectId, error) {\n\tconst patch = {\n\t\tbuildStatus: \"failed\",\n\t\tlastError: error,\n\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t};\n\tif (isSqliteDialect()) return (await getSqliteDb().update(platformAgentProjectSnapshotsSqlite).set(patch).where(and$1(eq$1(platformAgentProjectSnapshotsSqlite.projectId, projectId), eq$1(platformAgentProjectSnapshotsSqlite.buildStatus, \"building\"))).returning())[0];\n\treturn (await getDb().update(platformAgentProjectSnapshots).set(patch).where(and$1(eq$1(platformAgentProjectSnapshots.projectId, projectId), eq$1(platformAgentProjectSnapshots.buildStatus, \"building\"))).returning())[0];\n}\n/**\n* Claim the next capture generation while leaving the prior ready image usable.\n* Concurrent grace shutdowns each get a unique generation; only the matching\n* generation may replace the project image.\n*/\nasync function claimPlatformAgentProjectSnapshotCaptureGeneration(projectId) {\n\tconst now = /* @__PURE__ */ new Date();\n\tif (isSqliteDialect()) {\n\t\tif (!await selectPlatformAgentProjectSnapshot(projectId)) {\n\t\t\tconst inserted = await getSqliteDb().insert(platformAgentProjectSnapshotsSqlite).values({\n\t\t\t\tprojectId,\n\t\t\t\tmodalImageId: null,\n\t\t\t\tdepsFingerprint: null,\n\t\t\t\theadSha: null,\n\t\t\t\tpackageManager: null,\n\t\t\t\tcliVersion: null,\n\t\t\t\tsyncReady: false,\n\t\t\t\tcaptureGeneration: 1,\n\t\t\t\tbuildStatus: \"ready\",\n\t\t\t\tbuildStartedAt: null,\n\t\t\t\tlastError: null,\n\t\t\t\tupdatedAt: now,\n\t\t\t\tcreatedAt: now\n\t\t\t}).onConflictDoNothing().returning();\n\t\t\tif (inserted[0]) return {\n\t\t\t\tgeneration: 1,\n\t\t\t\tsnapshot: inserted[0]\n\t\t\t};\n\t\t}\n\t\tconst snapshot = (await getSqliteDb().update(platformAgentProjectSnapshotsSqlite).set({\n\t\t\tcaptureGeneration: sql$1`${platformAgentProjectSnapshotsSqlite.captureGeneration} + 1`,\n\t\t\tupdatedAt: now\n\t\t}).where(eq$1(platformAgentProjectSnapshotsSqlite.projectId, projectId)).returning())[0] ?? await selectPlatformAgentProjectSnapshot(projectId);\n\t\tif (!snapshot) throw new Error(\"Failed to claim platform agent snapshot capture generation\");\n\t\treturn {\n\t\t\tgeneration: snapshot.captureGeneration,\n\t\t\tsnapshot\n\t\t};\n\t}\n\tif (!await selectPlatformAgentProjectSnapshot(projectId)) {\n\t\tconst inserted = await getDb().insert(platformAgentProjectSnapshots).values({\n\t\t\tprojectId,\n\t\t\tmodalImageId: null,\n\t\t\tdepsFingerprint: null,\n\t\t\theadSha: null,\n\t\t\tpackageManager: null,\n\t\t\tcliVersion: null,\n\t\t\tsyncReady: false,\n\t\t\tcaptureGeneration: 1,\n\t\t\tbuildStatus: \"ready\",\n\t\t\tbuildStartedAt: null,\n\t\t\tlastError: null,\n\t\t\tupdatedAt: now,\n\t\t\tcreatedAt: now\n\t\t}).onConflictDoNothing().returning();\n\t\tif (inserted[0]) return {\n\t\t\tgeneration: 1,\n\t\t\tsnapshot: inserted[0]\n\t\t};\n\t}\n\tconst snapshot = (await getDb().update(platformAgentProjectSnapshots).set({\n\t\tcaptureGeneration: sql$1`${platformAgentProjectSnapshots.captureGeneration} + 1`,\n\t\tupdatedAt: now\n\t}).where(eq$1(platformAgentProjectSnapshots.projectId, projectId)).returning())[0] ?? await selectPlatformAgentProjectSnapshot(projectId);\n\tif (!snapshot) throw new Error(\"Failed to claim platform agent snapshot capture generation\");\n\treturn {\n\t\tgeneration: snapshot.captureGeneration,\n\t\tsnapshot\n\t};\n}\n/**\n* Replace project snapshot image when the capture generation still matches.\n* Losers should delete their candidate Modal image.\n*/\nasync function replacePlatformAgentProjectSnapshotImage(projectId, input) {\n\tconst existing = await selectPlatformAgentProjectSnapshot(projectId);\n\tconst previousImageId = existing?.modalImageId ?? null;\n\tconst now = /* @__PURE__ */ new Date();\n\tconst recoveryPatch = input.recovery === void 0 ? {} : {\n\t\trecoveryState: input.recovery.state,\n\t\trecoveryClaimantRunId: null,\n\t\trecoveryClaimedAt: null\n\t};\n\tconst values = {\n\t\tprojectId,\n\t\tmodalImageId: input.modalImageId,\n\t\tdepsFingerprint: input.depsFingerprint,\n\t\theadSha: input.headSha,\n\t\tpackageManager: input.packageManager,\n\t\tcliVersion: input.cliVersion ?? null,\n\t\tsyncReady: input.syncReady,\n\t\tcaptureGeneration: input.captureGeneration,\n\t\trecoveryState: input.recovery?.state ?? null,\n\t\trecoveryClaimantRunId: null,\n\t\trecoveryClaimedAt: null,\n\t\tbuildStatus: \"ready\",\n\t\tbuildStartedAt: null,\n\t\tlastError: null,\n\t\tupdatedAt: now,\n\t\tcreatedAt: existing?.createdAt ?? now\n\t};\n\tconst patch = {\n\t\tmodalImageId: input.modalImageId,\n\t\tdepsFingerprint: input.depsFingerprint,\n\t\theadSha: input.headSha,\n\t\tpackageManager: input.packageManager,\n\t\tcliVersion: input.cliVersion ?? null,\n\t\tsyncReady: input.syncReady,\n\t\t...recoveryPatch,\n\t\tbuildStatus: \"ready\",\n\t\tbuildStartedAt: null,\n\t\tlastError: null,\n\t\tupdatedAt: now\n\t};\n\tif (isSqliteDialect()) {\n\t\tif (!existing) {\n\t\t\tconst inserted = await getSqliteDb().insert(platformAgentProjectSnapshotsSqlite).values(values).onConflictDoNothing().returning();\n\t\t\tif (inserted[0]) return {\n\t\t\t\treplaced: true,\n\t\t\t\tsnapshot: inserted[0],\n\t\t\t\tpreviousImageId: null\n\t\t\t};\n\t\t}\n\t\tconst snapshot = (await getSqliteDb().update(platformAgentProjectSnapshotsSqlite).set(patch).where(and$1(eq$1(platformAgentProjectSnapshotsSqlite.projectId, projectId), eq$1(platformAgentProjectSnapshotsSqlite.captureGeneration, input.captureGeneration))).returning())[0];\n\t\tif (!snapshot) return {\n\t\t\treplaced: false,\n\t\t\tsnapshot: await selectPlatformAgentProjectSnapshot(projectId)\n\t\t};\n\t\treturn {\n\t\t\treplaced: true,\n\t\t\tsnapshot,\n\t\t\tpreviousImageId\n\t\t};\n\t}\n\tif (!existing) {\n\t\tconst inserted = await getDb().insert(platformAgentProjectSnapshots).values(values).onConflictDoNothing().returning();\n\t\tif (inserted[0]) return {\n\t\t\treplaced: true,\n\t\t\tsnapshot: inserted[0],\n\t\t\tpreviousImageId: null\n\t\t};\n\t}\n\tconst snapshot = (await getDb().update(platformAgentProjectSnapshots).set(patch).where(and$1(eq$1(platformAgentProjectSnapshots.projectId, projectId), eq$1(platformAgentProjectSnapshots.captureGeneration, input.captureGeneration))).returning())[0];\n\tif (!snapshot) return {\n\t\treplaced: false,\n\t\tsnapshot: await selectPlatformAgentProjectSnapshot(projectId)\n\t};\n\treturn {\n\t\treplaced: true,\n\t\tsnapshot,\n\t\tpreviousImageId\n\t};\n}\n/**\n* Clear the project recovery marker after verified clean publish.\n* Any successful clean publish may clear — there is no exclusive claimant.\n*/\nasync function clearPlatformAgentProjectSnapshotRecovery(projectId) {\n\tconst patch = {\n\t\trecoveryState: null,\n\t\trecoveryClaimantRunId: null,\n\t\trecoveryClaimedAt: null,\n\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t};\n\tif (isSqliteDialect()) return (await getSqliteDb().update(platformAgentProjectSnapshotsSqlite).set(patch).where(eq$1(platformAgentProjectSnapshotsSqlite.projectId, projectId)).returning())[0];\n\treturn (await getDb().update(platformAgentProjectSnapshots).set(patch).where(eq$1(platformAgentProjectSnapshots.projectId, projectId)).returning())[0];\n}\n/** Exported for tests — statuses that may accept a new run. */\nconst PLATFORM_AGENT_IDLE_STATUSES = STARTABLE_STATUSES;\nconst PLATFORM_AGENT_STARTABLE_STATUSES = STARTABLE_STATUSES;\n//#endregion\n//#region src/queries/project-agent-session-sandboxes.ts\nfunction scopeMatch(table, scope) {\n\treturn and$1(eq$1(table.sessionId, scope.sessionId), eq$1(table.organizationId, scope.organizationId), eq$1(table.projectId, scope.projectId), eq$1(table.agentId, scope.agentId));\n}\nasync function selectProjectAgentSessionSandbox(sessionId) {\n\tif (isSqliteDialect()) return (await getSqliteDb().select().from(projectAgentSessionSandboxesSqlite).where(eq$1(projectAgentSessionSandboxesSqlite.sessionId, sessionId)).limit(1))[0];\n\treturn (await getDb().select().from(projectAgentSessionSandboxes).where(eq$1(projectAgentSessionSandboxes.sessionId, sessionId)).limit(1))[0];\n}\n/** Lookup by full org/project/agent/session scope (not session id alone). */\nasync function selectProjectAgentSessionSandboxByScope(scope) {\n\tif (isSqliteDialect()) return (await getSqliteDb().select().from(projectAgentSessionSandboxesSqlite).where(scopeMatch(projectAgentSessionSandboxesSqlite, scope)).limit(1))[0];\n\treturn (await getDb().select().from(projectAgentSessionSandboxes).where(scopeMatch(projectAgentSessionSandboxes, scope)).limit(1))[0];\n}\n/** Upsert live sandbox pointer and touch last-used. */\nasync function setProjectAgentSessionSandbox(scope, sandboxId) {\n\tconst now = /* @__PURE__ */ new Date();\n\tif (isSqliteDialect()) {\n\t\tif (await selectProjectAgentSessionSandbox(scope.sessionId)) return (await getSqliteDb().update(projectAgentSessionSandboxesSqlite).set({\n\t\t\tsandboxId,\n\t\t\tsandboxLastUsedAt: now,\n\t\t\tupdatedAt: now,\n\t\t\torganizationId: scope.organizationId,\n\t\t\tprojectId: scope.projectId,\n\t\t\tagentId: scope.agentId\n\t\t}).where(eq$1(projectAgentSessionSandboxesSqlite.sessionId, scope.sessionId)).returning())[0];\n\t\treturn (await getSqliteDb().insert(projectAgentSessionSandboxesSqlite).values({\n\t\t\tsessionId: scope.sessionId,\n\t\t\torganizationId: scope.organizationId,\n\t\t\tprojectId: scope.projectId,\n\t\t\tagentId: scope.agentId,\n\t\t\tsandboxId,\n\t\t\tsandboxLastUsedAt: now,\n\t\t\tmodalImageId: null,\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now\n\t\t}).returning())[0];\n\t}\n\treturn (await getDb().insert(projectAgentSessionSandboxes).values({\n\t\tsessionId: scope.sessionId,\n\t\torganizationId: scope.organizationId,\n\t\tprojectId: scope.projectId,\n\t\tagentId: scope.agentId,\n\t\tsandboxId,\n\t\tsandboxLastUsedAt: now,\n\t\tmodalImageId: null,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t}).onConflictDoUpdate({\n\t\ttarget: projectAgentSessionSandboxes.sessionId,\n\t\tset: {\n\t\t\tsandboxId,\n\t\t\tsandboxLastUsedAt: now,\n\t\t\tupdatedAt: now,\n\t\t\torganizationId: scope.organizationId,\n\t\t\tprojectId: scope.projectId,\n\t\t\tagentId: scope.agentId\n\t\t}\n\t}).returning())[0];\n}\nasync function touchProjectAgentSessionSandbox(scope) {\n\tconst now = /* @__PURE__ */ new Date();\n\tif (isSqliteDialect()) return (await getSqliteDb().update(projectAgentSessionSandboxesSqlite).set({\n\t\tsandboxLastUsedAt: now,\n\t\tupdatedAt: now\n\t}).where(and$1(scopeMatch(projectAgentSessionSandboxesSqlite, scope), isNotNull(projectAgentSessionSandboxesSqlite.sandboxId))).returning())[0];\n\treturn (await getDb().update(projectAgentSessionSandboxes).set({\n\t\tsandboxLastUsedAt: now,\n\t\tupdatedAt: now\n\t}).where(and$1(scopeMatch(projectAgentSessionSandboxes, scope), isNotNull(projectAgentSessionSandboxes.sandboxId))).returning())[0];\n}\nasync function clearProjectAgentSessionSandbox(scope, options) {\n\tconst patch = {\n\t\tsandboxId: null,\n\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t};\n\tif (isSqliteDialect()) {\n\t\tconst conditions = [scopeMatch(projectAgentSessionSandboxesSqlite, scope)];\n\t\tif (options?.expectedSandboxId !== void 0) conditions.push(eq$1(projectAgentSessionSandboxesSqlite.sandboxId, options.expectedSandboxId));\n\t\treturn (await getSqliteDb().update(projectAgentSessionSandboxesSqlite).set(patch).where(and$1(...conditions)).returning())[0];\n\t}\n\tconst conditions = [scopeMatch(projectAgentSessionSandboxes, scope)];\n\tif (options?.expectedSandboxId !== void 0) conditions.push(eq$1(projectAgentSessionSandboxes.sandboxId, options.expectedSandboxId));\n\treturn (await getDb().update(projectAgentSessionSandboxes).set(patch).where(and$1(...conditions)).returning())[0];\n}\n/**\n* Atomically clear the live sandbox id before snapshot so a concurrent create\n* cannot race the same sandbox. Keeps `modal_image_id` and last-used.\n*\n* When `expectedLastUsedAt` is provided, detach only succeeds if last-used still\n* matches (BullMQ grace CAS against a follow-up create/touch on another machine).\n*/\nasync function detachProjectAgentSessionSandboxForSnapshot(scope, expectedSandboxId, options) {\n\tconst patch = {\n\t\tsandboxId: null,\n\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t};\n\tconst lastUsedMatch = (table) => {\n\t\tif (options === void 0 || !(\"expectedLastUsedAt\" in options)) return;\n\t\tif (options.expectedLastUsedAt == null) return isNull$1(table.sandboxLastUsedAt);\n\t\treturn eq$1(table.sandboxLastUsedAt, options.expectedLastUsedAt);\n\t};\n\tif (isSqliteDialect()) {\n\t\tconst lastUsed = lastUsedMatch(projectAgentSessionSandboxesSqlite);\n\t\tconst row = (await getSqliteDb().update(projectAgentSessionSandboxesSqlite).set(patch).where(and$1(scopeMatch(projectAgentSessionSandboxesSqlite, scope), eq$1(projectAgentSessionSandboxesSqlite.sandboxId, expectedSandboxId), ...lastUsed ? [lastUsed] : [])).returning())[0];\n\t\tif (!row) return { detached: false };\n\t\treturn {\n\t\t\tdetached: true,\n\t\t\trow\n\t\t};\n\t}\n\tconst lastUsed = lastUsedMatch(projectAgentSessionSandboxes);\n\tconst row = (await getDb().update(projectAgentSessionSandboxes).set(patch).where(and$1(scopeMatch(projectAgentSessionSandboxes, scope), eq$1(projectAgentSessionSandboxes.sandboxId, expectedSandboxId), ...lastUsed ? [lastUsed] : [])).returning())[0];\n\tif (!row) return { detached: false };\n\treturn {\n\t\tdetached: true,\n\t\trow\n\t};\n}\n/** Persist a new session filesystem Image id; returns the previous id (if any). */\nasync function replaceProjectAgentSessionModalImage(scope, modalImageId) {\n\tconst now = /* @__PURE__ */ new Date();\n\tconst existing = await selectProjectAgentSessionSandbox(scope.sessionId);\n\tconst previousImageId = existing?.modalImageId ?? null;\n\tif (isSqliteDialect()) {\n\t\tif (existing) return {\n\t\t\tpreviousImageId,\n\t\t\trow: (await getSqliteDb().update(projectAgentSessionSandboxesSqlite).set({\n\t\t\t\tmodalImageId,\n\t\t\t\tsandboxLastUsedAt: existing.sandboxLastUsedAt ?? now,\n\t\t\t\tupdatedAt: now\n\t\t\t}).where(eq$1(projectAgentSessionSandboxesSqlite.sessionId, scope.sessionId)).returning())[0]\n\t\t};\n\t\treturn {\n\t\t\tpreviousImageId: null,\n\t\t\trow: (await getSqliteDb().insert(projectAgentSessionSandboxesSqlite).values({\n\t\t\t\tsessionId: scope.sessionId,\n\t\t\t\torganizationId: scope.organizationId,\n\t\t\t\tprojectId: scope.projectId,\n\t\t\t\tagentId: scope.agentId,\n\t\t\t\tsandboxId: null,\n\t\t\t\tsandboxLastUsedAt: now,\n\t\t\t\tmodalImageId,\n\t\t\t\tcreatedAt: now,\n\t\t\t\tupdatedAt: now\n\t\t\t}).returning())[0]\n\t\t};\n\t}\n\tif (existing) return {\n\t\tpreviousImageId,\n\t\trow: (await getDb().update(projectAgentSessionSandboxes).set({\n\t\t\tmodalImageId,\n\t\t\tsandboxLastUsedAt: existing.sandboxLastUsedAt ?? now,\n\t\t\tupdatedAt: now\n\t\t}).where(eq$1(projectAgentSessionSandboxes.sessionId, scope.sessionId)).returning())[0]\n\t};\n\treturn {\n\t\tpreviousImageId: null,\n\t\trow: (await getDb().insert(projectAgentSessionSandboxes).values({\n\t\t\tsessionId: scope.sessionId,\n\t\t\torganizationId: scope.organizationId,\n\t\t\tprojectId: scope.projectId,\n\t\t\tagentId: scope.agentId,\n\t\t\tsandboxId: null,\n\t\t\tsandboxLastUsedAt: now,\n\t\t\tmodalImageId,\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now\n\t\t}).returning())[0]\n\t};\n}\nasync function clearProjectAgentSessionModalImage(scope, options) {\n\tconst patch = {\n\t\tmodalImageId: null,\n\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t};\n\tif (isSqliteDialect()) {\n\t\tconst conditions = [scopeMatch(projectAgentSessionSandboxesSqlite, scope)];\n\t\tif (options?.expectedImageId !== void 0) conditions.push(eq$1(projectAgentSessionSandboxesSqlite.modalImageId, options.expectedImageId));\n\t\treturn (await getSqliteDb().update(projectAgentSessionSandboxesSqlite).set(patch).where(and$1(...conditions)).returning())[0];\n\t}\n\tconst conditions = [scopeMatch(projectAgentSessionSandboxes, scope)];\n\tif (options?.expectedImageId !== void 0) conditions.push(eq$1(projectAgentSessionSandboxes.modalImageId, options.expectedImageId));\n\treturn (await getDb().update(projectAgentSessionSandboxes).set(patch).where(and$1(...conditions)).returning())[0];\n}\n/** Idle live sandboxes for maintenance terminate. */\nasync function listIdleProjectAgentSessionSandboxes(idleBefore, options) {\n\tconst limit = options?.limit ?? 100;\n\tif (isSqliteDialect()) return getSqliteDb().select().from(projectAgentSessionSandboxesSqlite).where(and$1(isNotNull(projectAgentSessionSandboxesSqlite.sandboxId), lt$1(projectAgentSessionSandboxesSqlite.sandboxLastUsedAt, idleBefore))).orderBy(asc(projectAgentSessionSandboxesSqlite.sandboxLastUsedAt)).limit(limit);\n\treturn getDb().select().from(projectAgentSessionSandboxes).where(and$1(isNotNull(projectAgentSessionSandboxes.sandboxId), lt$1(projectAgentSessionSandboxes.sandboxLastUsedAt, idleBefore))).orderBy(asc(projectAgentSessionSandboxes.sandboxLastUsedAt)).limit(limit);\n}\n/** Idle session Images (no requirement that sandbox is cleared). */\nasync function listIdleProjectAgentSessionImages(idleBefore, options) {\n\tconst limit = options?.limit ?? 100;\n\tif (isSqliteDialect()) return getSqliteDb().select().from(projectAgentSessionSandboxesSqlite).where(and$1(isNotNull(projectAgentSessionSandboxesSqlite.modalImageId), lt$1(projectAgentSessionSandboxesSqlite.sandboxLastUsedAt, idleBefore))).orderBy(asc(projectAgentSessionSandboxesSqlite.sandboxLastUsedAt)).limit(limit);\n\treturn getDb().select().from(projectAgentSessionSandboxes).where(and$1(isNotNull(projectAgentSessionSandboxes.modalImageId), lt$1(projectAgentSessionSandboxes.sandboxLastUsedAt, idleBefore))).orderBy(asc(projectAgentSessionSandboxes.sandboxLastUsedAt)).limit(limit);\n}\n//#endregion\n//#region src/queries/project-agent-env-images.ts\n/** Stale `building` rows may be reclaimed after this window. */\nconst PROJECT_AGENT_ENV_IMAGE_BUILD_STALE_MS = 1800 * 1e3;\nasync function selectProjectAgentEnvImageByOrgHash(organizationId, setupHash) {\n\tif (isSqliteDialect()) return (await getSqliteDb().select().from(projectAgentEnvImagesSqlite).where(and$1(eq$1(projectAgentEnvImagesSqlite.organizationId, organizationId), eq$1(projectAgentEnvImagesSqlite.setupHash, setupHash))).limit(1))[0];\n\treturn (await getDb().select().from(projectAgentEnvImages).where(and$1(eq$1(projectAgentEnvImages.organizationId, organizationId), eq$1(projectAgentEnvImages.setupHash, setupHash))).limit(1))[0];\n}\n/** Ready env Image id for cold boot, or null when missing / not ready. */\nasync function selectReadyProjectAgentEnvImageId(organizationId, setupHash) {\n\tconst row = await selectProjectAgentEnvImageByOrgHash(organizationId, setupHash);\n\tif (!row || row.buildStatus !== \"ready\") return null;\n\treturn row.modalImageId?.trim() || null;\n}\n/**\n* Claim (or create) a building row for this org+hash.\n* Returns acquired=false when another builder already holds a fresh lease.\n*/\nasync function claimProjectAgentEnvImageBuild(input) {\n\tconst now = /* @__PURE__ */ new Date();\n\tconst staleBefore = new Date(now.getTime() - PROJECT_AGENT_ENV_IMAGE_BUILD_STALE_MS);\n\tconst id = crypto.randomUUID();\n\tif (isSqliteDialect()) {\n\t\tconst existing = await selectProjectAgentEnvImageByOrgHash(input.organizationId, input.setupHash);\n\t\tif (!existing) return {\n\t\t\tacquired: true,\n\t\t\trow: (await getSqliteDb().insert(projectAgentEnvImagesSqlite).values({\n\t\t\t\tid,\n\t\t\t\torganizationId: input.organizationId,\n\t\t\t\tsetupHash: input.setupHash,\n\t\t\t\tbaseImageName: input.baseImageName,\n\t\t\t\tsetupCommands: input.setupCommandsJson,\n\t\t\t\tmodalImageId: null,\n\t\t\t\tbuildStatus: \"building\",\n\t\t\t\tbuildStartedAt: now,\n\t\t\t\tlastError: null,\n\t\t\t\tcreatedAt: now,\n\t\t\t\tupdatedAt: now\n\t\t\t}).returning())[0]\n\t\t};\n\t\tif (existing.buildStatus === \"building\" && existing.buildStartedAt && existing.buildStartedAt > staleBefore) return {\n\t\t\tacquired: false,\n\t\t\trow: existing\n\t\t};\n\t\tif (existing.buildStatus === \"ready\" && existing.modalImageId?.trim()) return {\n\t\t\tacquired: false,\n\t\t\trow: existing\n\t\t};\n\t\tconst rows = await getSqliteDb().update(projectAgentEnvImagesSqlite).set({\n\t\t\tbaseImageName: input.baseImageName,\n\t\t\tsetupCommands: input.setupCommandsJson,\n\t\t\tbuildStatus: \"building\",\n\t\t\tbuildStartedAt: now,\n\t\t\tlastError: null,\n\t\t\tupdatedAt: now\n\t\t}).where(and$1(eq$1(projectAgentEnvImagesSqlite.organizationId, input.organizationId), eq$1(projectAgentEnvImagesSqlite.setupHash, input.setupHash), or$1(inArray$1(projectAgentEnvImagesSqlite.buildStatus, [\"idle\", \"failed\"]), and$1(eq$1(projectAgentEnvImagesSqlite.buildStatus, \"building\"), or$1(isNull$1(projectAgentEnvImagesSqlite.buildStartedAt), lt$1(projectAgentEnvImagesSqlite.buildStartedAt, staleBefore))), and$1(eq$1(projectAgentEnvImagesSqlite.buildStatus, \"ready\"), or$1(isNull$1(projectAgentEnvImagesSqlite.modalImageId), eq$1(projectAgentEnvImagesSqlite.modalImageId, \"\")))))).returning();\n\t\tif (rows[0]) return {\n\t\t\tacquired: true,\n\t\t\trow: rows[0]\n\t\t};\n\t\treturn {\n\t\t\tacquired: false,\n\t\t\trow: await selectProjectAgentEnvImageByOrgHash(input.organizationId, input.setupHash)\n\t\t};\n\t}\n\tconst inserted = await getDb().insert(projectAgentEnvImages).values({\n\t\tid,\n\t\torganizationId: input.organizationId,\n\t\tsetupHash: input.setupHash,\n\t\tbaseImageName: input.baseImageName,\n\t\tsetupCommands: input.setupCommandsJson,\n\t\tmodalImageId: null,\n\t\tbuildStatus: \"building\",\n\t\tbuildStartedAt: now,\n\t\tlastError: null,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t}).onConflictDoNothing().returning();\n\tif (inserted[0]) return {\n\t\tacquired: true,\n\t\trow: inserted[0]\n\t};\n\tconst updated = await getDb().update(projectAgentEnvImages).set({\n\t\tbaseImageName: input.baseImageName,\n\t\tsetupCommands: input.setupCommandsJson,\n\t\tbuildStatus: \"building\",\n\t\tbuildStartedAt: now,\n\t\tlastError: null,\n\t\tupdatedAt: now\n\t}).where(and$1(eq$1(projectAgentEnvImages.organizationId, input.organizationId), eq$1(projectAgentEnvImages.setupHash, input.setupHash), or$1(inArray$1(projectAgentEnvImages.buildStatus, [\"idle\", \"failed\"]), and$1(eq$1(projectAgentEnvImages.buildStatus, \"building\"), or$1(isNull$1(projectAgentEnvImages.buildStartedAt), lt$1(projectAgentEnvImages.buildStartedAt, staleBefore))), and$1(eq$1(projectAgentEnvImages.buildStatus, \"ready\"), or$1(isNull$1(projectAgentEnvImages.modalImageId), eq$1(projectAgentEnvImages.modalImageId, \"\")))))).returning();\n\tif (updated[0]) return {\n\t\tacquired: true,\n\t\trow: updated[0]\n\t};\n\treturn {\n\t\tacquired: false,\n\t\trow: await selectProjectAgentEnvImageByOrgHash(input.organizationId, input.setupHash)\n\t};\n}\nasync function completeProjectAgentEnvImageBuild(input) {\n\tconst now = /* @__PURE__ */ new Date();\n\tconst patch = {\n\t\tmodalImageId: input.modalImageId,\n\t\tbuildStatus: \"ready\",\n\t\tbuildStartedAt: null,\n\t\tlastError: null,\n\t\tupdatedAt: now\n\t};\n\tif (isSqliteDialect()) return (await getSqliteDb().update(projectAgentEnvImagesSqlite).set(patch).where(and$1(eq$1(projectAgentEnvImagesSqlite.organizationId, input.organizationId), eq$1(projectAgentEnvImagesSqlite.setupHash, input.setupHash), eq$1(projectAgentEnvImagesSqlite.buildStatus, \"building\"), eq$1(projectAgentEnvImagesSqlite.buildStartedAt, input.expectedBuildStartedAt))).returning())[0];\n\treturn (await getDb().update(projectAgentEnvImages).set(patch).where(and$1(eq$1(projectAgentEnvImages.organizationId, input.organizationId), eq$1(projectAgentEnvImages.setupHash, input.setupHash), eq$1(projectAgentEnvImages.buildStatus, \"building\"), eq$1(projectAgentEnvImages.buildStartedAt, input.expectedBuildStartedAt))).returning())[0];\n}\nasync function failProjectAgentEnvImageBuild(input) {\n\tconst now = /* @__PURE__ */ new Date();\n\tconst patch = {\n\t\tbuildStatus: \"failed\",\n\t\tlastError: input.error,\n\t\tupdatedAt: now\n\t};\n\tif (isSqliteDialect()) return (await getSqliteDb().update(projectAgentEnvImagesSqlite).set(patch).where(and$1(eq$1(projectAgentEnvImagesSqlite.organizationId, input.organizationId), eq$1(projectAgentEnvImagesSqlite.setupHash, input.setupHash), eq$1(projectAgentEnvImagesSqlite.buildStatus, \"building\"), eq$1(projectAgentEnvImagesSqlite.buildStartedAt, input.expectedBuildStartedAt))).returning())[0];\n\treturn (await getDb().update(projectAgentEnvImages).set(patch).where(and$1(eq$1(projectAgentEnvImages.organizationId, input.organizationId), eq$1(projectAgentEnvImages.setupHash, input.setupHash), eq$1(projectAgentEnvImages.buildStatus, \"building\"), eq$1(projectAgentEnvImages.buildStartedAt, input.expectedBuildStartedAt))).returning())[0];\n}\n/**\n* Mark a ready env Image failed and clear its Modal id so the next claim/enqueue\n* can rebuild (legacy snapshots that die when a Volume mounts over `/workspace/agent`).\n*/\nasync function invalidateReadyProjectAgentEnvImage(input) {\n\tconst now = /* @__PURE__ */ new Date();\n\tconst patch = {\n\t\tbuildStatus: \"failed\",\n\t\tmodalImageId: null,\n\t\tlastError: input.error,\n\t\tupdatedAt: now\n\t};\n\tif (isSqliteDialect()) return (await getSqliteDb().update(projectAgentEnvImagesSqlite).set(patch).where(and$1(eq$1(projectAgentEnvImagesSqlite.organizationId, input.organizationId), eq$1(projectAgentEnvImagesSqlite.setupHash, input.setupHash), eq$1(projectAgentEnvImagesSqlite.buildStatus, \"ready\"), eq$1(projectAgentEnvImagesSqlite.modalImageId, input.modalImageId))).returning())[0];\n\treturn (await getDb().update(projectAgentEnvImages).set(patch).where(and$1(eq$1(projectAgentEnvImages.organizationId, input.organizationId), eq$1(projectAgentEnvImages.setupHash, input.setupHash), eq$1(projectAgentEnvImages.buildStatus, \"ready\"), eq$1(projectAgentEnvImages.modalImageId, input.modalImageId))).returning())[0];\n}\n//#endregion\n//#region src/queries/managed-service-credentials/index.ts\nasync function insertManagedServiceCredential(values) {\n\tif (isSqliteDialect()) {\n\t\tawait getSqliteDb().insert(managedServiceCredentialsSqlite).values(values);\n\t\treturn;\n\t}\n\tawait getDb().insert(managedServiceCredentials).values(values);\n}\nasync function updateManagedServiceCredentialValue(id, values) {\n\tif (isSqliteDialect()) {\n\t\tawait getSqliteDb().update(managedServiceCredentialsSqlite).set(values).where(eq$1(managedServiceCredentialsSqlite.id, id));\n\t\treturn;\n\t}\n\tawait getDb().update(managedServiceCredentials).set(values).where(eq$1(managedServiceCredentials.id, id));\n}\nasync function listManagedServiceCredentialsForOrganization(organizationId, kind) {\n\tconst db = getDb();\n\tconst conditions = kind ? and$1(eq$1(managedServiceCredentials.organizationId, organizationId), eq$1(managedServiceCredentials.kind, kind)) : eq$1(managedServiceCredentials.organizationId, organizationId);\n\treturn db.select().from(managedServiceCredentials).where(conditions);\n}\nasync function getManagedServiceCredential(organizationId, kind, provider) {\n\treturn (await getDb().select().from(managedServiceCredentials).where(and$1(eq$1(managedServiceCredentials.organizationId, organizationId), eq$1(managedServiceCredentials.kind, kind), eq$1(managedServiceCredentials.provider, provider))).limit(1))[0];\n}\nasync function selectManagedServiceCredentialById(id) {\n\treturn (await getDb().select().from(managedServiceCredentials).where(eq$1(managedServiceCredentials.id, id)).limit(1))[0];\n}\nasync function deleteManagedServiceCredential(id) {\n\tif (isSqliteDialect()) {\n\t\tawait getSqliteDb().delete(managedServiceCredentialsSqlite).where(eq$1(managedServiceCredentialsSqlite.id, id));\n\t\treturn;\n\t}\n\tawait getDb().delete(managedServiceCredentials).where(eq$1(managedServiceCredentials.id, id));\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(secret);\n}\nfunction decryptApiKeySecret(ciphertext) {\n\treturn decryptCredentialPayload(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\nfunction toWebhookApiKeyViews(rows) {\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 listWebhookApiKeys() {\n\treturn toWebhookApiKeyViews(await listApiKeysByConfigId(WEBHOOK_API_KEY_CONFIG_ID));\n}\nasync function listWebhookApiKeysForProject(projectId) {\n\treturn toWebhookApiKeyViews(await listApiKeysByConfigReferenceId(WEBHOOK_API_KEY_CONFIG_ID, projectId));\n}\n/** Webhook keys for the given projects only (decrypts only those rows). */\nasync function listWebhookApiKeysForProjects(projectIds) {\n\tif (projectIds.length === 0) return [];\n\treturn toWebhookApiKeyViews(await listApiKeysByConfigReferenceIds(WEBHOOK_API_KEY_CONFIG_ID, projectIds));\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}\n/** Returns an existing org-platform key secret or creates one when missing. */\nasync function ensureOrgPlatformApiKey(input) {\n\tconst row = await selectApiKeyByConfigName(ORG_PLATFORM_API_KEY_CONFIG_ID, input.name);\n\tif (row?.keyCiphertext && isActiveApiKey(row)) {\n\t\tif (parseOrgPlatformApiKeyMetadata(row.metadata)?.organizationId === input.organizationId) return decryptApiKeySecret(row.keyCiphertext);\n\t}\n\treturn (await createOrgPlatformApiKey(input)).secret;\n}\nfunction mcpProjectApiKeyName(organizationId, projectSlug) {\n\treturn `mcp:${organizationId}:${projectSlug}`;\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\n/**\n* Org DB connection options for tenant scope.\n*\n* Postgres: shared platform `DATABASE_URL` + signed organization claim (RLS).\n* Sqlite: per-org file path (standalone).\n*/\nfunction resolveOrgProjectDatabaseOptions(organization, env = process.env) {\n\tconst platformUrl = resolvePlatformDatabaseUrl(env);\n\tif (inferDialect(platformUrl) === \"postgres\") return {\n\t\turl: platformUrl,\n\t\torganizationId: organization.id\n\t};\n\treturn { url: organization.dbSchema.startsWith(\"file:\") ? organization.dbSchema : `file:${organization.dbSchema}` };\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, env = process.env) {\n\tconst platformUrl = resolvePlatformDatabaseUrl(env);\n\tif (inferDialect(platformUrl) === \"sqlite\") return organization.dbSchema.startsWith(\"file:\") ? organization.dbSchema : `file:${organization.dbSchema}`;\n\treturn platformUrl;\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: platform.user,\n\t\tpassword: platform.password,\n\t\tsearchPath: \"public\"\n\t};\n}\n//#endregion\n//#region src/project-database/ensure-pgboss-grants.ts\n/**\n* Historical: granted every org login role access to `pgboss`.\n* Org roles are retired (public + RLS); the platform DB role owns pg-boss.\n*/\nasync function ensureOrgPgBossGrants() {}\n/** @deprecated Use {@link ensureOrgPgBossGrants}. */\nconst ensureProjectPgBossGrants = ensureOrgPgBossGrants;\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(organization.storageAccessKeyIdCiphertext),\n\t\tsecretAccessKey: decryptCredentialPayload(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/org-redis/runtime-env.ts\n/**\n* Per-org Redis env for org machines. Uses the restricted ACL connection string\n* when provisioned; otherwise falls back to the platform admin URL (pre-backfill).\n*/\nfunction orgSchedulerRuntimeEnv(organization, platformEnv = process.env) {\n\tconst orgUrl = organization.redisUrlCiphertext?.trim();\n\tif (orgUrl) {\n\t\tconst result = { REDIS_URL: decryptCredentialPayload(orgUrl) };\n\t\tconst prefix = platformEnv.KEYSTROKE_QUEUE_PREFIX?.trim();\n\t\tif (prefix) result.KEYSTROKE_QUEUE_PREFIX = prefix;\n\t\treturn result;\n\t}\n\tconst adminUrl = platformEnv.UPSTASH_REDIS_URL?.trim() || platformEnv.REDIS_URL?.trim() || void 0;\n\tif (!adminUrl) return {};\n\tconst fallback = { REDIS_URL: adminUrl };\n\tconst prefix = platformEnv.KEYSTROKE_QUEUE_PREFIX?.trim();\n\tif (prefix) fallback.KEYSTROKE_QUEUE_PREFIX = prefix;\n\treturn fallback;\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}\n/** Org-scoped list of every OAuth app (used by Composio → native dual-read). */\nasync function listOAuthApps() {\n\treturn getDb().select().from(oauthApps).where(eqOrganizationScope(oauthApps));\n}\n/** Org-scoped list of oauth apps whose slug starts with `prefix` (e.g. `slack-app:`). */\nasync function listOAuthAppsBySlugPrefix(prefix) {\n\treturn getDb().select().from(oauthApps).where(scopedAnd(oauthApps, sql$1`${oauthApps.slug} like ${`${prefix}%`}`));\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}\nasync function updateOAuthAppMetadataBySlug(slug, metadata) {\n\tawait getDb().update(oauthApps).set({\n\t\tmetadata,\n\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t}).where(scopedAnd(oauthApps, eq$1(oauthApps.slug, slug)));\n}\n/** Hard-delete an org-scoped OAuth app (connections cascade via FK). */\nasync function deleteOAuthAppBySlug(slug) {\n\tif (!await selectOAuthAppBySlug(slug)) return false;\n\tawait getDb().delete(oauthApps).where(scopedAnd(oauthApps, eq$1(oauthApps.slug, slug)));\n\treturn true;\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/**\n* Org-unscoped lookup by Slack `api_app_id` stored in `metadata.slackAppId`.\n* Used by webhook routing to find the custom app (and its org) before scope is known.\n*\n* ponytail: unindexed jsonb filter; fine at current custom-app scale. Add a generated\n* column + index if webhook routing latency becomes an issue.\n*/\nasync function listOAuthAppsBySlackAppIdGlobal(slackAppId) {\n\treturn getDb().select().from(oauthApps).where(sql$1`${oauthApps.metadata}->>'slackAppId' = ${slackAppId}`);\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-pending-states/index.ts\n/**\n* ponytail: opportunistic prune on write — upgrade to a scheduled job if abandoned\n* pending-state volume grows beyond what insert-path cleanup can keep up with.\n*/\nasync function putOAuthPendingState(input) {\n\tconst now = /* @__PURE__ */ new Date();\n\tconst db = getDb();\n\tawait db.insert(oauthPendingStates).values({\n\t\t...input,\n\t\tcreatedAt: now\n\t}).onConflictDoUpdate({\n\t\ttarget: oauthPendingStates.id,\n\t\tset: {\n\t\t\tpayloadCiphertext: input.payloadCiphertext,\n\t\t\texpiresAt: input.expiresAt,\n\t\t\tcreatedAt: now\n\t\t}\n\t});\n\tawait db.delete(oauthPendingStates).where(lt$1(oauthPendingStates.expiresAt, now));\n}\nasync function takeOAuthPendingState(id) {\n\tconst row = (await getDb().delete(oauthPendingStates).where(eq$1(oauthPendingStates.id, id)).returning())[0];\n\tif (!row || row.expiresAt.getTime() < Date.now()) return;\n\treturn row.payloadCiphertext;\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(options.clientId),\n\t\tclientSecretCiphertext: encryptCredentialPayload(options.clientSecret),\n\t\tsigningSecretCiphertext: options.signingSecret ? encryptCredentialPayload(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(row.clientIdCiphertext),\n\t\tclientSecret: decryptCredentialPayload(row.clientSecretCiphertext),\n\t\tsigningSecret: row.signingSecretCiphertext ? decryptCredentialPayload(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(row.accessTokenCiphertext),\n\t\trefreshToken: row.refreshTokenCiphertext ? decryptCredentialPayload(row.refreshTokenCiphertext) : null,\n\t\taccessTokenExpiresAt: row.accessTokenExpiresAt ?? null,\n\t\tgrantedScopes: row.grantedScopes ?? null,\n\t\tmetadata: row.metadata ?? null,\n\t\tupdatedAt: row.updatedAt\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}\n/** All org-scoped OAuth connections (every oauth app). Used by Composio dual-read. */\nasync function listDecryptedOAuthConnections() {\n\tconst apps = await listOAuthApps();\n\tconst connections = [];\n\tfor (const app of apps) {\n\t\tconst rows = await listOAuthConnectionsByAppId(app.id);\n\t\tfor (const row of rows) try {\n\t\t\tconnections.push(decryptOAuthConnectionRow(row));\n\t\t} catch {}\n\t}\n\treturn connections;\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(options.accessToken),\n\t\trefreshTokenCiphertext: options.refreshToken ? encryptCredentialPayload(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/mcp-refresh.ts\nvar McpOAuthTokenError = class extends Error {\n\tdiagnostics;\n\tconstructor(message, diagnostics) {\n\t\tsuper(message);\n\t\tthis.diagnostics = diagnostics;\n\t\tthis.name = \"McpOAuthTokenError\";\n\t}\n};\nfunction assertHttps(value, label) {\n\ttry {\n\t\tif (new URL(value).protocol === \"https:\") return;\n\t} catch {}\n\tthrow new McpOAuthTokenError(`${label} must use HTTPS`, { phase: \"token_refresh\" });\n}\nfunction oauthErrorCode(body) {\n\ttry {\n\t\tconst parsed = JSON.parse(body);\n\t\treturn typeof parsed.error === \"string\" && parsed.error.trim() ? parsed.error.trim() : void 0;\n\t} catch {\n\t\treturn;\n\t}\n}\nasync function refreshMcpOAuthToken(params) {\n\tconst tokenEndpoint = params.tokenEndpoint?.trim();\n\tif (!tokenEndpoint) throw new Error(\"MCP OAuth refresh requires tokenEndpoint in app metadata\");\n\tassertHttps(tokenEndpoint, \"MCP OAuth token endpoint\");\n\tconst body = new URLSearchParams({\n\t\tgrant_type: \"refresh_token\",\n\t\trefresh_token: params.refreshToken\n\t});\n\tif (params.resource) {\n\t\tassertHttps(params.resource, \"MCP OAuth resource\");\n\t\tbody.set(\"resource\", params.resource);\n\t}\n\tconst headers = new Headers({\n\t\t\"Content-Type\": \"application/x-www-form-urlencoded\",\n\t\tAccept: \"application/json\"\n\t});\n\tconst authMethod = params.tokenEndpointAuthMethod ?? (params.clientSecret ? \"client_secret_basic\" : \"none\");\n\tif (authMethod === \"client_secret_basic\") {\n\t\tif (!params.clientSecret) throw new McpOAuthTokenError(\"MCP OAuth refresh client authentication is invalid\", { phase: \"token_refresh\" });\n\t\theaders.set(\"Authorization\", `Basic ${Buffer.from(`${params.clientId}:${params.clientSecret}`).toString(\"base64\")}`);\n\t} else {\n\t\tbody.set(\"client_id\", params.clientId);\n\t\tif (authMethod === \"client_secret_post\") {\n\t\t\tif (!params.clientSecret) throw new McpOAuthTokenError(\"MCP OAuth refresh client authentication is invalid\", { phase: \"token_refresh\" });\n\t\t\tbody.set(\"client_secret\", params.clientSecret);\n\t\t}\n\t}\n\tconst response = await fetch(tokenEndpoint, {\n\t\tmethod: \"POST\",\n\t\theaders,\n\t\tbody\n\t});\n\tif (!response.ok) {\n\t\tconst code = oauthErrorCode(await response.text().catch(() => \"\"));\n\t\tthrow new McpOAuthTokenError(`MCP OAuth refresh failed (HTTP ${response.status}${code ? `, ${code}` : \"\"})`, {\n\t\t\tphase: \"token_refresh\",\n\t\t\thttpStatus: response.status,\n\t\t\t...code ? { oauthError: code } : {}\n\t\t});\n\t}\n\tconst payload = await response.json().catch(() => null);\n\tif (!payload || typeof payload.access_token !== \"string\" || !payload.access_token || typeof payload.token_type !== \"string\" || payload.token_type.toLowerCase() !== \"bearer\" || payload.refresh_token !== void 0 && typeof payload.refresh_token !== \"string\" || payload.expires_in !== void 0 && (typeof payload.expires_in !== \"number\" || payload.expires_in <= 0)) throw new McpOAuthTokenError(\"MCP OAuth refresh returned an invalid token response\", {\n\t\tphase: \"token_refresh\",\n\t\thttpStatus: response.status\n\t});\n\treturn {\n\t\taccessToken: payload.access_token,\n\t\trefreshToken: payload.refresh_token,\n\t\taccessTokenExpiresAt: typeof payload.expires_in === \"number\" ? new Date(Date.now() + payload.expires_in * 1e3) : void 0\n\t};\n}\nfunction readMcpTokenEndpoint(metadata) {\n\treturn metadata?.tokenEndpoint?.trim() || void 0;\n}\n//#endregion\n//#region src/oauth/refresh-token.ts\nconst TOKEN_EXPIRY_BUFFER_MS = 6e4;\nfunction oauthClientSecretForRefresh(app) {\n\tif (app.metadata?.tokenEndpointAuthMethod === \"none\") return \"\";\n\treturn app.clientSecret?.trim() ?? \"\";\n}\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) {\n\t\tif (!connection.accessTokenExpiresAt) return connection.accessToken;\n\t\tthrow new Error(`OAuth connection \"${connection.id}\" is missing a refresh token.`);\n\t}\n\tconst refresh = tokenRefresh?.get(app.slug) ?? (app.provider === \"mcp\" ? refreshMcpOAuthToken : void 0);\n\tif (!refresh) throw new Error(`OAuth refresh is not registered for app \"${app.slug}\".`);\n\tlet refreshed;\n\ttry {\n\t\trefreshed = await refresh({\n\t\t\tclientId: app.clientId,\n\t\t\tclientSecret: oauthClientSecretForRefresh(app),\n\t\t\trefreshToken: connection.refreshToken,\n\t\t\ttokenEndpoint: readMcpTokenEndpoint(app.metadata),\n\t\t\tresource: app.metadata?.resource,\n\t\t\ttokenEndpointAuthMethod: app.metadata?.tokenEndpointAuthMethod\n\t\t});\n\t} catch (error) {\n\t\tlog.error(\"mcp.oauth.connect.failed\", {\n\t\t\tapp_slug: app.slug,\n\t\t\tconnection_id: connection.id,\n\t\t\tfailure_phase: \"token_refresh\",\n\t\t\terror_name: error instanceof Error ? error.name : \"UnknownError\",\n\t\t\terror_message: error instanceof McpOAuthTokenError ? error.message : \"MCP OAuth token refresh failed\",\n\t\t\t...error instanceof McpOAuthTokenError ? {\n\t\t\t\t...error.diagnostics.httpStatus ? { provider_http_status: error.diagnostics.httpStatus } : {},\n\t\t\t\t...error.diagnostics.oauthError ? { oauth_error: error.diagnostics.oauthError } : {}\n\t\t\t} : {}\n\t\t});\n\t\tthrow error;\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/** Decrypt a signing secret from an oauth_apps row (null when unset). */\nfunction decryptOAuthAppSigningSecret(app) {\n\tif (!app.signingSecretCiphertext) return null;\n\treturn decryptCredentialPayload(app.signingSecretCiphertext);\n}\n/**\n* Signing secret for inbound webhooks before org scope is known.\n* `SLACK_SIGNING_SECRET` env override applies only to the managed Keystroke app (`slack`).\n*/\nasync function getOAuthAppSigningSecretBySlugGlobal(appSlug) {\n\tif (appSlug === \"slack\") {\n\t\tconst fromEnv = process.env.SLACK_SIGNING_SECRET?.trim();\n\t\tif (fromEnv) return fromEnv;\n\t}\n\tconst apps = await listOAuthAppsBySlugUnscoped(appSlug);\n\tfor (const app of apps) {\n\t\tconst secret = decryptOAuthAppSigningSecret(app);\n\t\tif (secret) return secret;\n\t}\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/**\n* Bot token for a team from any org's connection (same Slack app + team → same token).\n* Safe to call before organization scope is set (e.g. platform Slack gateway).\n*/\nasync function getGlobalOAuthAccessTokenByAppSlugAndExternalId(appSlug, externalId) {\n\tconst first = (await selectOAuthInstallationsByAppSlugAndExternalId(appSlug, externalId))[0];\n\tif (!first) return null;\n\tconst connection = await runWithOrganizationScope(first.organizationId, () => selectOAuthConnectionById(first.connectionId));\n\tif (!connection) return null;\n\treturn decryptCredentialPayload(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$1(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: values.logo ?? null,\n\t\tauthKind: values.authKind,\n\t\toauthScopes: values.oauthScopes ?? [],\n\t\tcredentialFields: values.credentialFields ?? {},\n\t\tcredentialScheme: values.credentialScheme ?? null,\n\t\turl: values.url ?? null,\n\t\tsource: values.source,\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\tcredentialFields: values.credentialFields ?? {},\n\t\tcredentialScheme: values.credentialScheme ?? null,\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\t...values,\n\t\tcredentialFields: values.credentialFields ?? {},\n\t\tcredentialScheme: values.credentialScheme ?? null,\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/** Hard-delete an org-owned app. Returns the deleted row, or undefined if missing/not owned. */\nasync function deleteOrgApp(organizationId, slug) {\n\tif (!await selectOrgAppBySlug(organizationId, slug)) return;\n\treturn (await getDb().delete(apps).where(and$1(eq$1(apps.slug, slug), eq$1(apps.organizationId, organizationId))).returning())[0];\n}\n//#endregion\n//#region src/queries/templates/index.ts\nasync function listTemplates(kind) {\n\treturn getDb().select({\n\t\tslug: templates.slug,\n\t\tkind: templates.kind,\n\t\ttitle: templates.title,\n\t\tdescription: templates.description,\n\t\ttags: templates.tags,\n\t\trequiredApps: templates.requiredApps,\n\t\tupdatedAt: templates.updatedAt\n\t}).from(templates).where(kind ? eq$1(templates.kind, kind) : void 0).orderBy(templates.slug);\n}\nasync function selectTemplateBySlug(slug) {\n\treturn (await getDb().select().from(templates).where(eq$1(templates.slug, slug)).limit(1))[0];\n}\nasync function upsertTemplate(values) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\tif (await selectTemplateBySlug(values.slug)) return (await db.update(templates).set({\n\t\tkind: values.kind,\n\t\ttitle: values.title,\n\t\tdescription: values.description,\n\t\ttags: values.tags,\n\t\trequiredApps: values.requiredApps,\n\t\tfiles: values.files,\n\t\tupdatedAt: now\n\t}).where(eq$1(templates.slug, values.slug)).returning())[0];\n\treturn (await db.insert(templates).values({\n\t\tid: crypto.randomUUID(),\n\t\tslug: values.slug,\n\t\tkind: values.kind,\n\t\ttitle: values.title,\n\t\tdescription: values.description,\n\t\ttags: values.tags,\n\t\trequiredApps: values.requiredApps,\n\t\tfiles: values.files,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t}).returning())[0];\n}\nasync function upsertTemplatesFromSeed(entries) {\n\tfor (const entry of entries) await upsertTemplate({\n\t\tslug: entry.slug,\n\t\tkind: entry.kind,\n\t\ttitle: entry.title,\n\t\tdescription: entry.description,\n\t\ttags: entry.tags,\n\t\trequiredApps: entry.requiredApps,\n\t\tfiles: entry.files\n\t});\n}\n//#endregion\n//#region src/templates/official-seed.generated.ts\nconst OFFICIAL_TEMPLATE_SEED = [\n\t{\n\t\t\"slug\": \"github-ci-debugger\",\n\t\t\"kind\": \"both\",\n\t\t\"title\": \"GitHub CI Debugger\",\n\t\t\"description\": \"On CI failure: fetch logs, classify the failure, notify Slack for Triage/Skip, then run a debugger agent that posts root-cause findings in-thread.\",\n\t\t\"tags\": [\n\t\t\t\"github\",\n\t\t\t\"ci\",\n\t\t\t\"slack\",\n\t\t\t\"debugging\"\n\t\t],\n\t\t\"requiredApps\": [\"github\", \"slackbot\"],\n\t\t\"files\": {\n\t\t\t\"src/agents/ci-failure-debugger.ts\": \"import { defineAgent } from \\\"@keystrokehq/keystroke/agent\\\";\\nimport {\\n  githubDownloadJobLogsForAWorkflowRun,\\n  githubDownloadWorkflowRunLogs,\\n  githubGetACommit,\\n  githubGetAPullRequest,\\n  githubGetAWorkflow,\\n  githubGetAWorkflowRun,\\n  githubGetRawRepositoryContent,\\n  githubGetRepositoryContent,\\n  githubGetWorkflowRunJob,\\n  githubListJobsForAWorkflowRun,\\n  githubListPullRequestsAssociatedWithACommit,\\n  githubListPullRequestsFiles,\\n  githubListRepositoryWorkflows,\\n  githubListWorkflowRunArtifacts,\\n} from \\\"@keystrokehq/github/actions\\\";\\nimport { slackbotSendMessage } from \\\"@keystrokehq/slackbot/actions\\\";\\n\\n/** Replace with your GitHub owner/repo before deploying. */\\nconst REPO_OWNER = \\\"REPLACE_ME\\\";\\nconst REPO_NAME = \\\"REPLACE_ME\\\";\\nconst SLACK_CHANNEL = \\\"REPLACE_ME\\\";\\n\\nexport default defineAgent({\\n  slug: \\\"ci-failure-debugger\\\",\\n  name: \\\"CI Failure Debugger\\\",\\n  description: `Investigates GitHub Actions CI failures for ${REPO_OWNER}/${REPO_NAME} and posts root-cause findings to Slack.`,\\n  systemPrompt: `You debug GitHub Actions CI failures for the ${REPO_OWNER}/${REPO_NAME} repository.\\n\\nYour job:\\n1. Investigate the failure using GitHub tools — pull full job logs, inspect workflow runs, read source files at the failing commit, and check related PRs when useful.\\n2. Identify the root cause and a concrete recommended fix (file paths, commands, or config changes when possible).\\n3. Post your findings to Slack in the #${SLACK_CHANNEL} thread you are given. Always reply in-thread using thread_ts from the prompt — never start a new top-level message.\\n\\nSlack message format (markdown_text):\\n- Start with a short headline (e.g. \\\":mag: CI debug findings\\\")\\n- *Root cause:* one clear paragraph\\n- *Recommended fix:* numbered steps or bullet list\\n- *Evidence:* key log lines, file paths, and GitHub links when relevant\\n- Keep it scannable; avoid dumping entire logs into Slack\\n\\nRepository context:\\n- Organization: ${REPO_OWNER}\\n- Repo: ${REPO_NAME}\\n- CI workflows live under .github/workflows/\\n\\nBe thorough but concise. Use tools before guessing. If the initial logs are enough, say so; otherwise fetch more context from GitHub.\\nOnce you post to slack you are done. Just respond \\\"Sent findings to slack\\\" nothing else.`,\\n  model: \\\"zai/glm-5.2\\\",\\n  tools: [\\n    githubGetAWorkflowRun,\\n    githubGetAWorkflow,\\n    githubListJobsForAWorkflowRun,\\n    githubGetWorkflowRunJob,\\n    githubDownloadJobLogsForAWorkflowRun,\\n    githubDownloadWorkflowRunLogs,\\n    githubListWorkflowRunArtifacts,\\n    githubListRepositoryWorkflows,\\n    githubGetRepositoryContent,\\n    githubGetRawRepositoryContent,\\n    githubGetACommit,\\n    githubListPullRequestsAssociatedWithACommit,\\n    githubGetAPullRequest,\\n    githubListPullRequestsFiles,\\n    slackbotSendMessage,\\n  ],\\n});\\n\",\n\t\t\t\"src/lib/ci-debug.ts\": \"export type CiDebugPromptInput = {\\n  owner: string;\\n  repo: string;\\n  runId: number;\\n  workflowName: string;\\n  runUrl: string;\\n  headSha: string;\\n  commitMessage?: string;\\n  triage: \\\"simple\\\" | \\\"advanced\\\";\\n  summary: string;\\n  failedJobIds: number[];\\n  failedJobNames: string[];\\n  logs: string;\\n  slackChannel: string;\\n  slackThreadTs: string;\\n  reviewer?: string;\\n};\\n\\nexport function buildCiDebugPrompt(input: CiDebugPromptInput): string {\\n  const failedJobs =\\n    input.failedJobIds.length > 0\\n      ? input.failedJobIds\\n          .map((id, index) => `• ${input.failedJobNames[index] ?? \\\"unknown\\\"} (job id ${id})`)\\n          .join(\\\"\\\\n\\\")\\n      : \\\"• (none listed)\\\";\\n\\n  return [\\n    \\\"Debug this CI failure and post your findings to Slack.\\\",\\n    \\\"\\\",\\n    `Repository: ${input.owner}/${input.repo}`,\\n    `Workflow: ${input.workflowName}`,\\n    `Workflow run id: ${input.runId}`,\\n    `Run URL: ${input.runUrl}`,\\n    `Commit: ${input.headSha}`,\\n    input.commitMessage ? `Commit message: ${input.commitMessage}` : null,\\n    \\\"\\\",\\n    `Initial triage: ${input.triage}`,\\n    `Initial summary: ${input.summary}`,\\n    input.reviewer ? `Requested by: ${input.reviewer}` : null,\\n    \\\"\\\",\\n    \\\"Failed jobs:\\\",\\n    failedJobs,\\n    \\\"\\\",\\n    \\\"Slack reply target:\\\",\\n    `• channel: ${input.slackChannel}`,\\n    `• thread_ts: ${input.slackThreadTs}`,\\n    \\\"\\\",\\n    \\\"Use slackbot-send-message with channel and thread_ts to reply in the existing #ci-cd thread.\\\",\\n    \\\"\\\",\\n    \\\"Failed job logs (tail):\\\",\\n    input.logs,\\n  ]\\n    .filter(Boolean)\\n    .join(\\\"\\\\n\\\");\\n}\\n\",\n\t\t\t\"src/lib/ci-logs.ts\": \"const ANSI_REGEX = /\\\\x1b\\\\[[0-9;]*m/g;\\n\\nexport type JobLogEntry = {\\n  jobName: string;\\n  jobId: number;\\n  details: string;\\n};\\n\\nexport function stripAnsi(text: string): string {\\n  return text.replace(ANSI_REGEX, \\\"\\\");\\n}\\n\\nexport function tailLogLines(text: string, maxLines = 120): string {\\n  const lines = stripAnsi(text).split(\\\"\\\\n\\\");\\n  if (lines.length <= maxLines) {\\n    return lines.join(\\\"\\\\n\\\");\\n  }\\n  return lines.slice(-maxLines).join(\\\"\\\\n\\\");\\n}\\n\\nexport function mergeJobLogs(entries: JobLogEntry[], maxChars = 14_000): string {\\n  if (entries.length === 0) {\\n    return \\\"(no job logs available)\\\";\\n  }\\n\\n  const sections = entries.map(\\n    (entry) => `=== Job: ${entry.jobName} (id ${entry.jobId}) ===\\\\n${tailLogLines(entry.details)}`,\\n  );\\n  const merged = sections.join(\\\"\\\\n\\\\n\\\");\\n\\n  if (merged.length <= maxChars) {\\n    return merged;\\n  }\\n\\n  const tail = merged.slice(-maxChars);\\n  return `[logs truncated; showing last ${maxChars} chars]\\\\n${tail}`;\\n}\\n\",\n\t\t\t\"src/lib/ci-slack.ts\": \"export type CiApprovalMessageInput = {\\n  owner: string;\\n  repo: string;\\n  workflowName: string;\\n  runUrl: string;\\n  headSha: string;\\n  triage: \\\"simple\\\" | \\\"advanced\\\";\\n  summary: string;\\n  failedJobNames: string[];\\n};\\n\\nexport function formatCiApprovalBody(input: CiApprovalMessageInput): string {\\n  const repoLabel = `${input.owner}/${input.repo}`;\\n  const jobs =\\n    input.failedJobNames.length > 0\\n      ? input.failedJobNames.map((name) => `• ${name}`).join(\\\"\\\\n\\\")\\n      : \\\"• (no failed jobs listed)\\\";\\n\\n  return [\\n    `:x: *CI failed* — \\\\`${repoLabel}\\\\``,\\n    `*Workflow:* ${input.workflowName}`,\\n    `*Commit:* \\\\`${input.headSha.slice(0, 7)}\\\\``,\\n    `*Run:* ${input.runUrl}`,\\n    `*Failed jobs:*`,\\n    jobs,\\n    \\\"\\\",\\n    `*LLM triage:* ${input.triage}`,\\n    `*Summary:* ${input.summary}`,\\n  ].join(\\\"\\\\n\\\");\\n}\\n\\ntype SlackBlock = Record<string, unknown>;\\n\\nexport type CiHookActionId = \\\"triage\\\" | \\\"skip\\\";\\n\\n/** Build a GET resume URL with hook payload fields as query params. */\\nexport function buildHookResumeUrl(\\n  resumeUrl: string,\\n  payload: { actionId: CiHookActionId },\\n): string {\\n  const base = resumeUrl.split(\\\"?\\\")[0] ?? resumeUrl;\\n  const url = new URL(base);\\n  for (const [key, value] of Object.entries(payload)) {\\n    url.searchParams.set(key, value);\\n  }\\n  return url.toString();\\n}\\n\\nexport function buildCiApprovalBlocks(input: {\\n  title: string;\\n  body: string;\\n  resumeUrl: string;\\n}): SlackBlock[] {\\n  return [\\n    {\\n      type: \\\"header\\\",\\n      text: { type: \\\"plain_text\\\", text: input.title, emoji: true },\\n    },\\n    {\\n      type: \\\"section\\\",\\n      text: { type: \\\"mrkdwn\\\", text: input.body },\\n    },\\n    {\\n      type: \\\"actions\\\",\\n      elements: [\\n        {\\n          type: \\\"button\\\",\\n          text: { type: \\\"plain_text\\\", text: \\\"Triage\\\", emoji: true },\\n          style: \\\"primary\\\",\\n          url: buildHookResumeUrl(input.resumeUrl, { actionId: \\\"triage\\\" }),\\n        },\\n        {\\n          type: \\\"button\\\",\\n          text: { type: \\\"plain_text\\\", text: \\\"Skip\\\", emoji: true },\\n          url: buildHookResumeUrl(input.resumeUrl, { actionId: \\\"skip\\\" }),\\n        },\\n      ],\\n    },\\n  ];\\n}\\n\",\n\t\t\t\"src/triggers/github-ci-failure.ts\": \"import { defineWebhookSource } from \\\"@keystrokehq/keystroke/trigger\\\";\\nimport { z } from \\\"zod\\\";\\nimport ciFailureTriage from \\\"../workflows/ci-failure-triage\\\";\\n\\n/** Replace with your GitHub owner/repo before deploying. */\\nconst REPO_FULL_NAME = \\\"REPLACE_ME/REPLACE_ME\\\" as const;\\n\\nconst githubCiFailurePayload = z\\n  .object({\\n    action: z.literal(\\\"completed\\\"),\\n    workflow_run: z\\n      .object({\\n        id: z.number(),\\n        name: z.string().nullable().optional(),\\n        head_branch: z.string().nullable().optional(),\\n        head_sha: z.string(),\\n        conclusion: z.literal(\\\"failure\\\"),\\n        html_url: z.string(),\\n        head_commit: z\\n          .object({\\n            message: z.string().nullable().optional(),\\n          })\\n          .loose()\\n          .nullable()\\n          .optional(),\\n      })\\n      .loose(),\\n    repository: z\\n      .object({\\n        name: z.string(),\\n        full_name: z.literal(REPO_FULL_NAME),\\n        owner: z\\n          .object({\\n            login: z.string(),\\n          })\\n          .loose(),\\n      })\\n      .loose(),\\n  })\\n  .loose();\\n\\nexport default defineWebhookSource({\\n  slug: \\\"github-ci-failure\\\",\\n  name: \\\"GitHub CI Failure\\\",\\n  description:\\n    \\\"Webhook for failed GitHub Actions runs on REPLACE_ME/REPLACE_ME; starts the CI failure triage workflow.\\\",\\n  endpoint: \\\"github-ci-failure\\\",\\n  payload: githubCiFailurePayload,\\n}).attach({\\n  workflow: ciFailureTriage,\\n  transform: (payload) => ({\\n    owner: payload.repository.owner.login,\\n    repo: payload.repository.name,\\n    runId: payload.workflow_run.id,\\n    headSha: payload.workflow_run.head_sha,\\n    workflowName: payload.workflow_run.name ?? \\\"unknown workflow\\\",\\n    runUrl: payload.workflow_run.html_url,\\n    commitMessage: payload.workflow_run.head_commit?.message ?? undefined,\\n  }),\\n});\\n\",\n\t\t\t\"src/workflows/ci-failure-triage.ts\": \"import { defineWorkflow, promptLlm } from \\\"@keystrokehq/keystroke/workflow\\\";\\nimport {\\n  githubDownloadJobLogsForAWorkflowRun,\\n  githubListJobsForAWorkflowRun,\\n} from \\\"@keystrokehq/github/actions\\\";\\nimport { slackbotSendMessage } from \\\"@keystrokehq/slackbot/actions\\\";\\nimport { z } from \\\"zod\\\";\\nimport ciFailureDebugger from \\\"../agents/ci-failure-debugger\\\";\\nimport { buildCiDebugPrompt } from \\\"../lib/ci-debug\\\";\\nimport { mergeJobLogs, type JobLogEntry } from \\\"../lib/ci-logs\\\";\\nimport { buildCiApprovalBlocks, formatCiApprovalBody } from \\\"../lib/ci-slack\\\";\\n\\nconst CLASSIFY_MODEL = \\\"google/gemini-3.5-flash\\\";\\nconst MAX_FAILED_JOBS = 5;\\nconst CI_CHANNEL = \\\"ci-cd\\\";\\n\\n/** Catalog `.run()` output is typed as `unknown` (integration helpers use bare `z.ZodType`). */\\ntype WorkflowJob = { id: number; name: string; conclusion?: string | null };\\ntype JobsResult = { jobs: WorkflowJob[] };\\ntype JobLogs = { details: string };\\ntype SlackSendResult = { ok?: boolean | null; ts?: string | null; error?: string | null };\\n\\nconst workflowInput = z.object({\\n  owner: z.string(),\\n  repo: z.string(),\\n  runId: z.number(),\\n  headSha: z.string(),\\n  workflowName: z.string(),\\n  runUrl: z.string(),\\n  commitMessage: z.string().optional(),\\n});\\n\\nconst classifySchema = z.object({\\n  triage: z.enum([\\\"simple\\\", \\\"advanced\\\"]),\\n  summary: z.string(),\\n});\\n\\nconst hookPayloadSchema = z.object({\\n  type: z.literal(\\\"action\\\").optional(),\\n  actionId: z.enum([\\\"triage\\\", \\\"skip\\\"]),\\n  user: z\\n    .object({\\n      id: z.string(),\\n      name: z.string().optional(),\\n    })\\n    .optional(),\\n});\\n\\nfunction buildClassifyPrompt(input: {\\n  owner: string;\\n  repo: string;\\n  workflowName: string;\\n  runUrl: string;\\n  headSha: string;\\n  commitMessage?: string;\\n  logs: string;\\n}): string {\\n  return [\\n    \\\"Classify this GitHub Actions CI failure.\\\",\\n    \\\"Return triage: simple when the fix is obvious from logs alone (lint/type error with file:line, missing env, lockfile drift).\\\",\\n    \\\"Return triage: advanced when source inspection, flaky infra, or deeper debugging is needed.\\\",\\n    \\\"Return summary: a concise 1-3 sentence summary of the failure.\\\",\\n    'Return your response in the exact JSON format: { \\\"triage\\\": \\\"simple\\\" | \\\"advanced\\\", \\\"summary\\\": \\\"string\\\" }',\\n    \\\"\\\",\\n    `Repository: ${input.owner}/${input.repo}`,\\n    `Workflow: ${input.workflowName}`,\\n    `Run: ${input.runUrl}`,\\n    `Commit: ${input.headSha}`,\\n    input.commitMessage ? `Commit message: ${input.commitMessage}` : null,\\n    \\\"\\\",\\n    \\\"Failed job logs (tail):\\\",\\n    input.logs,\\n  ]\\n    .filter(Boolean)\\n    .join(\\\"\\\\n\\\");\\n}\\n\\nexport default defineWorkflow({\\n  slug: \\\"ci-failure-triage\\\",\\n  name: \\\"CI Failure Triage\\\",\\n  description:\\n    \\\"On CI failure: fetch failed job logs, classify with an LLM, notify #ci-cd, and wait for Triage or Skip.\\\",\\n  input: workflowInput,\\n  output: z.object({\\n    decision: z.enum([\\\"triage\\\", \\\"skip\\\"]),\\n    triage: z.enum([\\\"simple\\\", \\\"advanced\\\"]),\\n    summary: z.string(),\\n    runUrl: z.string(),\\n    slackTs: z.string(),\\n    reviewer: z.string().optional(),\\n    debugSessionId: z.string().optional(),\\n  }),\\n  async run(input, ctx) {\\n    const jobsResult = (await githubListJobsForAWorkflowRun.run({\\n      owner: input.owner,\\n      repo: input.repo,\\n      run_id: input.runId,\\n      filter: \\\"latest\\\",\\n    })) as JobsResult;\\n\\n    const failedJobs = jobsResult.jobs.filter((job) => job.conclusion === \\\"failure\\\");\\n\\n    const logEntries: JobLogEntry[] = [];\\n    for (const job of failedJobs.slice(0, MAX_FAILED_JOBS)) {\\n      const logs = (await githubDownloadJobLogsForAWorkflowRun.run({\\n        owner: input.owner,\\n        repo: input.repo,\\n        job_id: job.id,\\n      })) as JobLogs;\\n      logEntries.push({\\n        jobName: job.name,\\n        jobId: job.id,\\n        details: logs.details,\\n      });\\n    }\\n\\n    const mergedLogs = mergeJobLogs(logEntries);\\n\\n    const classification = await promptLlm(buildClassifyPrompt({ ...input, logs: mergedLogs }), {\\n      model: CLASSIFY_MODEL,\\n      system:\\n        \\\"You triage CI failures for an engineering team. Respond with JSON only via the schema.\\\",\\n      outputSchema: classifySchema,\\n    });\\n\\n    const approvalBody = formatCiApprovalBody({\\n      owner: input.owner,\\n      repo: input.repo,\\n      workflowName: input.workflowName,\\n      runUrl: input.runUrl,\\n      headSha: input.headSha,\\n      triage: classification.triage,\\n      summary: classification.summary,\\n      failedJobNames: failedJobs.map((job) => job.name),\\n    });\\n    const approvalTitle = `CI failure: ${input.workflowName}`;\\n\\n    const approval = ctx.hook({ schema: hookPayloadSchema });\\n\\n    const slackMessage = (await slackbotSendMessage.run({\\n      channel: CI_CHANNEL,\\n      fallback_text: `${approvalTitle} — ${classification.summary}`,\\n      blocks: buildCiApprovalBlocks({\\n        title: approvalTitle,\\n        body: approvalBody,\\n        resumeUrl: approval.resumeUrl,\\n      }),\\n    })) as SlackSendResult;\\n\\n    if (!slackMessage.ok || !slackMessage.ts) {\\n      throw new Error(slackMessage.error ?? \\\"slackbot-send-message failed without a timestamp\\\");\\n    }\\n\\n    const clicked = await approval;\\n    const decision = clicked.actionId;\\n    const reviewer = clicked.user?.name ?? clicked.user?.id;\\n\\n    if (decision === \\\"skip\\\") {\\n      return {\\n        decision,\\n        triage: classification.triage,\\n        summary: classification.summary,\\n        runUrl: input.runUrl,\\n        slackTs: slackMessage.ts,\\n        reviewer,\\n      };\\n    }\\n\\n    const debugResult = await ciFailureDebugger.prompt({\\n      message: buildCiDebugPrompt({\\n        owner: input.owner,\\n        repo: input.repo,\\n        runId: input.runId,\\n        workflowName: input.workflowName,\\n        runUrl: input.runUrl,\\n        headSha: input.headSha,\\n        commitMessage: input.commitMessage,\\n        triage: classification.triage,\\n        summary: classification.summary,\\n        failedJobIds: failedJobs.map((job) => job.id),\\n        failedJobNames: failedJobs.map((job) => job.name),\\n        logs: mergedLogs,\\n        slackChannel: CI_CHANNEL,\\n        slackThreadTs: slackMessage.ts,\\n        reviewer,\\n      }),\\n    });\\n\\n    if (debugResult.error) {\\n      throw new Error(`CI debug agent failed: ${debugResult.error}`);\\n    }\\n\\n    return {\\n      decision,\\n      triage: classification.triage,\\n      summary: classification.summary,\\n      runUrl: input.runUrl,\\n      slackTs: slackMessage.ts,\\n      reviewer,\\n      debugSessionId: debugResult.sessionId,\\n    };\\n  },\\n});\\n\"\n\t\t}\n\t},\n\t{\n\t\t\"slug\": \"meeting-recap\",\n\t\t\"kind\": \"agent\",\n\t\t\"title\": \"Meeting Recap\",\n\t\t\"description\": \"Poll Granola for newly ended meetings, create Linear follow-ups, and DM Slack recaps to attendees.\",\n\t\t\"tags\": [\n\t\t\t\"granola\",\n\t\t\t\"linear\",\n\t\t\t\"slack\",\n\t\t\t\"meetings\"\n\t\t],\n\t\t\"requiredApps\": [\n\t\t\t\"granola_mcp\",\n\t\t\t\"linear\",\n\t\t\t\"slackbot\"\n\t\t],\n\t\t\"files\": {\n\t\t\t\"src/agents/meeting-recap.ts\": \"import { defineAgent } from \\\"@keystrokehq/keystroke/agent\\\";\\nimport {\\n  granolaMcpGetMeetingTranscript,\\n  granolaMcpGetMeetings,\\n} from \\\"@keystrokehq/granola_mcp/actions\\\";\\nimport {\\n  linearCreateLinearIssue,\\n  linearGetIssueDefaults,\\n  linearListLinearTeams,\\n  linearSearchIssues,\\n} from \\\"@keystrokehq/linear/actions\\\";\\nimport {\\n  slackbotFindUserByEmailAddress,\\n  slackbotOpenDm,\\n  slackbotSendMessage,\\n} from \\\"@keystrokehq/slackbot/actions\\\";\\nimport { MEETING_RECAP_LINEAR_TEAM_KEY, formatMeetingRecapMessage } from \\\"../lib/meeting-recap\\\";\\n\\nexport default defineAgent({\\n  slug: \\\"meeting-recap\\\",\\n  name: \\\"Meeting Recap\\\",\\n  description:\\n    \\\"Turns Granola meeting transcripts into Linear follow-ups and sends Slack recaps to attendees.\\\",\\n  systemPrompt: `You turn newly ended Granola meetings into follow-up work and attendee recaps.\\n\\nEach run may include one or more meetings. Process every meeting in the prompt before finishing.\\n\\nGranola:\\n- Use granola-mcp-get-meetings for summary, attendees, and metadata.\\n- Use granola-mcp-get-meeting-transcript for the verbatim transcript when you need exact commitments or wording.\\n- Do not invent meeting content.\\n\\nAction items:\\n- Extract specific, actionable follow-ups with clear owners when mentioned.\\n- Prefer tasks that start with a verb and include enough context to act without re-reading the transcript.\\n- Skip vague discussion points that are not commitments.\\n\\nLinear (team ${MEETING_RECAP_LINEAR_TEAM_KEY}):\\n- Resolve the team id with linear-list-linear-teams.\\n- Call linear-get-issue-defaults for that team before creating issues.\\n- Search with linear-search-issues before creating duplicates.\\n- Create issues with linear-create-linear-issue.\\n- Put meeting title and Granola note id in the issue description.\\n- Assign with assignee_id: \\\"me\\\" only when no better owner is known from the meeting.\\n\\nSlack delivery:\\n- Send each attendee a DM with their own recap (same content for all attendees is fine).\\n- Find users with slackbot-find-user-by-email-address, open DM with slackbot-open-dm, then slackbot-send-message.\\n- Use markdown_text with this structure:\\n\\n${formatMeetingRecapMessage({\\n  title: \\\"{meeting title}\\\",\\n  summary: \\\"2-4 bullet summary of decisions and context.\\\",\\n  actionItems: [\\n    {\\n      title: \\\"Example follow-up\\\",\\n      linearIssue: \\\"ENG-123\\\",\\n      assignee: \\\"Name\\\",\\n    },\\n  ],\\n  attendeeEmails: [\\\"person@company.com\\\"],\\n})}\\n\\nKeep each recap under ~45 lines. Preserve Linear issue identifiers in the action-items section.\\nIf an attendee is not in Slack, note that in your final completion summary and continue with the others.\\nAfter all meetings are handled, reply with a short completion summary listing meetings processed, Linear issues created, and any delivery failures.`,\\n  model: \\\"xai/grok-4.3\\\",\\n  tools: [\\n    granolaMcpGetMeetings,\\n    granolaMcpGetMeetingTranscript,\\n    linearListLinearTeams,\\n    linearGetIssueDefaults,\\n    linearSearchIssues,\\n    linearCreateLinearIssue,\\n    slackbotFindUserByEmailAddress,\\n    slackbotOpenDm,\\n    slackbotSendMessage,\\n  ],\\n});\\n\",\n\t\t\t\"src/lib/meeting-recap.ts\": \"/** Local timezone for working-hours checks and meeting windows. */\\nexport const MEETING_RECAP_TIMEZONE = \\\"America/New_York\\\";\\n\\n/**\\n * Weekdays every 30 minutes from 9am–5pm Eastern.\\n * Keystroke schedules run in UTC; 13:00–21:00 UTC ≈ 9am–5pm ET during EDT\\n * (same convention as morning-briefing).\\n */\\nexport const MEETING_RECAP_POLL_SCHEDULE = \\\"*/30 13-21 * * 1-5\\\";\\n\\nexport const MEETING_RECAP_WORK_START_HOUR = 9;\\nexport const MEETING_RECAP_WORK_END_HOUR = 17;\\n\\n/** Linear team key used when creating follow-up issues. Replace before deploying. */\\nexport const MEETING_RECAP_LINEAR_TEAM_KEY = \\\"REPLACE_ME\\\";\\n\\nexport type GranolaMeetingSummary = {\\n  id: string;\\n  title: string;\\n  endTime?: string;\\n  startTime?: string;\\n  updatedAt?: string;\\n  attendeeEmails: string[];\\n};\\n\\nexport type MeetingRecapPollPayload = {\\n  meetings: GranolaMeetingSummary[];\\n};\\n\\nexport type MeetingRecapPollState = {\\n  /** Local date key (YYYY-MM-DD) for the processedMeetingIds bucket. */\\n  cursorDate?: string;\\n  processedMeetingIds: string[];\\n};\\n\\nconst WEEKDAY_FORMATTER = new Intl.DateTimeFormat(\\\"en-US\\\", {\\n  timeZone: MEETING_RECAP_TIMEZONE,\\n  weekday: \\\"short\\\",\\n});\\n\\nexport function getLocalDateKey(date: Date, timeZone = MEETING_RECAP_TIMEZONE): string {\\n  return new Intl.DateTimeFormat(\\\"en-CA\\\", {\\n    timeZone,\\n    year: \\\"numeric\\\",\\n    month: \\\"2-digit\\\",\\n    day: \\\"2-digit\\\",\\n  }).format(date);\\n}\\n\\n/** Reset processed ids when the local day rolls over. */\\nexport function normalizePollState(\\n  state: MeetingRecapPollState | undefined,\\n  now: Date,\\n  timeZone = MEETING_RECAP_TIMEZONE,\\n): MeetingRecapPollState {\\n  const cursorDate = getLocalDateKey(now, timeZone);\\n  if (!state || state.cursorDate !== cursorDate) {\\n    return { cursorDate, processedMeetingIds: [] };\\n  }\\n\\n  return state;\\n}\\n\\nexport function nextPollState(\\n  state: MeetingRecapPollState,\\n  newMeetingIds: string[],\\n): MeetingRecapPollState {\\n  const processedMeetingIds = [...state.processedMeetingIds];\\n  for (const id of newMeetingIds) {\\n    if (!processedMeetingIds.includes(id)) {\\n      processedMeetingIds.push(id);\\n    }\\n  }\\n\\n  return {\\n    cursorDate: state.cursorDate,\\n    processedMeetingIds,\\n  };\\n}\\n\\nexport function isWeekdayInTimezone(date: Date, timeZone = MEETING_RECAP_TIMEZONE): boolean {\\n  const weekday = new Intl.DateTimeFormat(\\\"en-US\\\", {\\n    timeZone,\\n    weekday: \\\"short\\\",\\n  }).format(date);\\n  return weekday !== \\\"Sat\\\" && weekday !== \\\"Sun\\\";\\n}\\n\\nexport function getLocalHourInTimezone(date: Date, timeZone = MEETING_RECAP_TIMEZONE): number {\\n  return Number(\\n    new Intl.DateTimeFormat(\\\"en-US\\\", {\\n      timeZone,\\n      hour: \\\"numeric\\\",\\n      hour12: false,\\n    }).format(date),\\n  );\\n}\\n\\nexport function isWithinWorkingHours(date: Date, timeZone = MEETING_RECAP_TIMEZONE): boolean {\\n  if (!isWeekdayInTimezone(date, timeZone)) {\\n    return false;\\n  }\\n\\n  const hour = getLocalHourInTimezone(date, timeZone);\\n  return hour >= MEETING_RECAP_WORK_START_HOUR && hour < MEETING_RECAP_WORK_END_HOUR;\\n}\\n\\nexport function getTodayRangeIso(\\n  date: Date,\\n  timeZone = MEETING_RECAP_TIMEZONE,\\n): { start: string; end: string } {\\n  const dateKey = getLocalDateKey(date, timeZone);\\n\\n  return {\\n    start: `${dateKey}T00:00:00`,\\n    end: `${dateKey}T23:59:59`,\\n  };\\n}\\n\\nfunction asRecord(value: unknown): Record<string, unknown> | null {\\n  return value !== null && typeof value === \\\"object\\\" ? (value as Record<string, unknown>) : null;\\n}\\n\\nfunction readString(value: unknown): string | undefined {\\n  return typeof value === \\\"string\\\" && value.length > 0 ? value : undefined;\\n}\\n\\nfunction readEmail(value: unknown): string | undefined {\\n  const email = readString(value);\\n  if (!email || !email.includes(\\\"@\\\")) {\\n    return undefined;\\n  }\\n  return email.toLowerCase();\\n}\\n\\nfunction collectAttendeeEmails(value: unknown, emails: Set<string>): void {\\n  if (Array.isArray(value)) {\\n    for (const item of value) {\\n      collectAttendeeEmails(item, emails);\\n    }\\n    return;\\n  }\\n\\n  const record = asRecord(value);\\n  if (!record) {\\n    return;\\n  }\\n\\n  const directEmail =\\n    readEmail(record.email) ?? readEmail(record.email_address) ?? readEmail(record.emailAddress);\\n  if (directEmail) {\\n    emails.add(directEmail);\\n  }\\n\\n  for (const key of [\\\"attendees\\\", \\\"participants\\\", \\\"users\\\", \\\"people\\\"]) {\\n    if (key in record) {\\n      collectAttendeeEmails(record[key], emails);\\n    }\\n  }\\n}\\n\\nfunction readMeetingEndTime(record: Record<string, unknown>): string | undefined {\\n  const direct =\\n    readString(record.end_time) ??\\n    readString(record.endTime) ??\\n    readString(record.ended_at) ??\\n    readString(record.endedAt) ??\\n    readString(record.date);\\n\\n  if (direct) {\\n    return direct;\\n  }\\n\\n  const calendarEvent = asRecord(record.calendar_event) ?? asRecord(record.event);\\n  if (!calendarEvent) {\\n    return undefined;\\n  }\\n\\n  return (\\n    readString(calendarEvent.end_time) ??\\n    readString(calendarEvent.endTime) ??\\n    readString(calendarEvent.end)\\n  );\\n}\\n\\nfunction readMeetingId(record: Record<string, unknown>): string | undefined {\\n  return (\\n    readString(record.id) ??\\n    readString(record.meeting_id) ??\\n    readString(record.meetingId) ??\\n    readString(record.note_id) ??\\n    readString(record.noteId)\\n  );\\n}\\n\\nfunction readMeetingTitle(record: Record<string, unknown>): string {\\n  return (\\n    readString(record.title) ??\\n    readString(record.name) ??\\n    readString(record.subject) ??\\n    \\\"Untitled meeting\\\"\\n  );\\n}\\n\\nexport function parseGranolaMeeting(record: unknown): GranolaMeetingSummary | null {\\n  const value = asRecord(record);\\n  if (!value) {\\n    return null;\\n  }\\n\\n  const id = readMeetingId(value);\\n  if (!id) {\\n    return null;\\n  }\\n\\n  const attendeeEmails = new Set<string>();\\n  collectAttendeeEmails(value.attendees, attendeeEmails);\\n  collectAttendeeEmails(value.participants, attendeeEmails);\\n  collectAttendeeEmails(value, attendeeEmails);\\n\\n  const owner = asRecord(value.owner);\\n  const ownerEmail = owner ? readEmail(owner.email) : undefined;\\n  if (ownerEmail) {\\n    attendeeEmails.add(ownerEmail);\\n  }\\n\\n  return {\\n    id,\\n    title: readMeetingTitle(value),\\n    endTime: readMeetingEndTime(value),\\n    startTime:\\n      readString(value.start_time) ?? readString(value.startTime) ?? readString(value.started_at),\\n    updatedAt: readString(value.updated_at) ?? readString(value.updatedAt),\\n    attendeeEmails: [...attendeeEmails],\\n  };\\n}\\n\\nexport function parseGranolaMeetings(payload: unknown): GranolaMeetingSummary[] {\\n  const unwrapped = unwrapGranolaMcpPayload(payload);\\n  if (Array.isArray(unwrapped)) {\\n    return unwrapped.flatMap((item) => {\\n      if (isGranolaMeetingSummary(item)) {\\n        return [item];\\n      }\\n      const parsed = parseGranolaMeeting(item);\\n      return parsed ? [parsed] : [];\\n    });\\n  }\\n\\n  const record = asRecord(unwrapped);\\n  if (!record) {\\n    return [];\\n  }\\n\\n  for (const key of [\\\"meetings\\\", \\\"notes\\\", \\\"items\\\", \\\"results\\\", \\\"documents\\\"]) {\\n    if (Array.isArray(record[key])) {\\n      return parseGranolaMeetings(record[key]);\\n    }\\n  }\\n\\n  const result = asRecord(record.result);\\n  if (result && Array.isArray(result.meetings)) {\\n    return parseGranolaMeetings(result.meetings);\\n  }\\n\\n  const single = parseGranolaMeeting(record);\\n  return single ? [single] : [];\\n}\\n\\nfunction isGranolaMeetingSummary(value: unknown): value is GranolaMeetingSummary {\\n  const record = asRecord(value);\\n  return (\\n    !!record &&\\n    typeof record.id === \\\"string\\\" &&\\n    typeof record.title === \\\"string\\\" &&\\n    Array.isArray(record.attendeeEmails)\\n  );\\n}\\n\\nfunction parseGranolaMcpXmlMeetings(text: string): GranolaMeetingSummary[] {\\n  if (!text.includes(\\\"<meeting\\\")) {\\n    return [];\\n  }\\n\\n  const meetings: GranolaMeetingSummary[] = [];\\n  const meetingPattern = /<meeting\\\\s+([^>]+)>([\\\\s\\\\S]*?)<\\\\/meeting>/g;\\n\\n  for (const match of text.matchAll(meetingPattern)) {\\n    const attrs = match[1] ?? \\\"\\\";\\n    const body = match[2] ?? \\\"\\\";\\n    const id = attrs.match(/\\\\bid=\\\"([^\\\"]+)\\\"/)?.[1];\\n    if (!id) {\\n      continue;\\n    }\\n\\n    const title = attrs.match(/\\\\btitle=\\\"([^\\\"]*)\\\"/)?.[1] ?? \\\"Untitled meeting\\\";\\n    const date = attrs.match(/\\\\bdate=\\\"([^\\\"]*)\\\"/)?.[1];\\n    const attendeeEmails = [...body.matchAll(/<([A-Z0-9._%+-]+@[A-Z0-9.-]+\\\\.[A-Z]{2,})>/gi)]\\n      .map((emailMatch) => emailMatch[1]?.toLowerCase() ?? \\\"\\\")\\n      .filter(Boolean);\\n\\n    meetings.push({\\n      id,\\n      title,\\n      endTime: date,\\n      attendeeEmails: [...new Set(attendeeEmails)],\\n    });\\n  }\\n\\n  return meetings;\\n}\\n\\nfunction unwrapGranolaMcpPayload(payload: unknown): unknown {\\n  const record = asRecord(payload);\\n  if (!record) {\\n    return payload;\\n  }\\n\\n  const data = record.data;\\n  if (!Array.isArray(data)) {\\n    return payload;\\n  }\\n\\n  for (const item of data) {\\n    const entry = asRecord(item);\\n    const text = entry ? readString(entry.text) : undefined;\\n    if (!text) {\\n      continue;\\n    }\\n\\n    if (\\n      text.startsWith(\\\"MCP error\\\") ||\\n      text.startsWith(\\\"Unauthorized:\\\") ||\\n      text.startsWith(\\\"Error:\\\")\\n    ) {\\n      throw new Error(text);\\n    }\\n\\n    if (text.includes(\\\"<meeting\\\")) {\\n      return parseGranolaMcpXmlMeetings(text);\\n    }\\n\\n    try {\\n      return JSON.parse(text);\\n    } catch {\\n      // Some MCP responses return plain text summaries instead of JSON.\\n    }\\n  }\\n\\n  return payload;\\n}\\n\\nexport function isMeetingOnDate(\\n  meeting: GranolaMeetingSummary,\\n  date: Date,\\n  timeZone = MEETING_RECAP_TIMEZONE,\\n): boolean {\\n  const targetDate = getLocalDateKey(date, timeZone);\\n  const timestamp = meeting.endTime ?? meeting.startTime ?? meeting.updatedAt;\\n  if (!timestamp) {\\n    return true;\\n  }\\n\\n  const parsed = new Date(timestamp);\\n  if (Number.isNaN(parsed.getTime())) {\\n    return true;\\n  }\\n\\n  return getLocalDateKey(parsed, timeZone) === targetDate;\\n}\\n\\nexport function filterMeetingsForDate(\\n  meetings: GranolaMeetingSummary[],\\n  date: Date,\\n  timeZone = MEETING_RECAP_TIMEZONE,\\n): GranolaMeetingSummary[] {\\n  return meetings.filter((meeting) => isMeetingOnDate(meeting, date, timeZone));\\n}\\n\\nexport function isMeetingEnded(meeting: GranolaMeetingSummary, now: Date): boolean {\\n  if (!meeting.endTime) {\\n    return true;\\n  }\\n\\n  const end = new Date(meeting.endTime);\\n  return !Number.isNaN(end.getTime()) && end.getTime() <= now.getTime();\\n}\\n\\nexport function findNewEndedMeetings(input: {\\n  meetings: GranolaMeetingSummary[];\\n  processedMeetingIds: string[];\\n  now: Date;\\n}): GranolaMeetingSummary[] {\\n  const processed = new Set(input.processedMeetingIds);\\n  return input.meetings.filter(\\n    (meeting) => !processed.has(meeting.id) && isMeetingEnded(meeting, input.now),\\n  );\\n}\\n\\nexport type MeetingRecapSlackInput = {\\n  title: string;\\n  summary: string;\\n  actionItems: Array<{ title: string; linearIssue?: string; assignee?: string }>;\\n  attendeeEmails: string[];\\n};\\n\\nexport function formatMeetingRecapMessage(input: MeetingRecapSlackInput): string {\\n  const actionLines =\\n    input.actionItems.length > 0\\n      ? input.actionItems\\n          .map((item) => {\\n            const issue = item.linearIssue ? ` → ${item.linearIssue}` : \\\"\\\";\\n            const assignee = item.assignee ? ` (${item.assignee})` : \\\"\\\";\\n            return `• ${item.title}${assignee}${issue}`;\\n          })\\n          .join(\\\"\\\\n\\\")\\n      : \\\"• No action items identified.\\\";\\n\\n  const attendeeLines =\\n    input.attendeeEmails.length > 0\\n      ? input.attendeeEmails.map((email) => `• ${email}`).join(\\\"\\\\n\\\")\\n      : \\\"• Attendees unavailable.\\\";\\n\\n  return [\\n    `:clipboard: *Meeting recap — ${input.title}*`,\\n    \\\"\\\",\\n    \\\"*Summary*\\\",\\n    input.summary,\\n    \\\"\\\",\\n    \\\"*Action items*\\\",\\n    actionLines,\\n    \\\"\\\",\\n    \\\"*Attendees*\\\",\\n    attendeeLines,\\n  ].join(\\\"\\\\n\\\");\\n}\\n\\nexport function buildMeetingRecapAgentPrompt(payload: MeetingRecapPollPayload): string {\\n  const meetingLines = payload.meetings\\n    .map((meeting) => {\\n      const attendees =\\n        meeting.attendeeEmails.length > 0 ? meeting.attendeeEmails.join(\\\", \\\") : \\\"unknown\\\";\\n      return `- ${meeting.title} (id: ${meeting.id}, attendees: ${attendees})`;\\n    })\\n    .join(\\\"\\\\n\\\");\\n\\n  return [\\n    \\\"Process the newly ended Granola meetings below.\\\",\\n    \\\"For each meeting:\\\",\\n    \\\"1. Fetch meeting details and transcript from Granola.\\\",\\n    \\\"2. Extract concrete action items with owners when possible.\\\",\\n    \\\"3. Create Linear follow-up issues on team REPLACE_ME (search first to avoid duplicates).\\\",\\n    \\\"4. DM every attendee a recap in Slack using their work email.\\\",\\n    \\\"\\\",\\n    \\\"Meetings to process:\\\",\\n    meetingLines,\\n    \\\"\\\",\\n    `Today is ${WEEKDAY_FORMATTER.format(new Date())}, ${new Date().toLocaleDateString(\\\"en-US\\\", { timeZone: MEETING_RECAP_TIMEZONE })}.`,\\n    \\\"After all recaps are sent, reply with a short completion summary.\\\",\\n  ].join(\\\"\\\\n\\\");\\n}\\n\",\n\t\t\t\"src/triggers/meeting-recap.ts\": \"import { granolaMcpListMeetings } from \\\"@keystrokehq/granola_mcp/actions\\\";\\nimport { definePollSource } from \\\"@keystrokehq/keystroke/trigger\\\";\\nimport { z } from \\\"zod\\\";\\nimport meetingRecap from \\\"../agents/meeting-recap\\\";\\nimport {\\n  MEETING_RECAP_POLL_SCHEDULE,\\n  buildMeetingRecapAgentPrompt,\\n  filterMeetingsForDate,\\n  findNewEndedMeetings,\\n  normalizePollState,\\n  nextPollState,\\n  parseGranolaMeetings,\\n  type MeetingRecapPollPayload,\\n  type MeetingRecapPollState,\\n} from \\\"../lib/meeting-recap\\\";\\n\\nconst pollStateSchema = z.object({\\n  cursorDate: z.string().optional(),\\n  processedMeetingIds: z.array(z.string()).default([]),\\n});\\n\\nexport default definePollSource<MeetingRecapPollPayload, MeetingRecapPollState>({\\n  slug: \\\"meeting-recap\\\",\\n  name: \\\"Meeting Recap\\\",\\n  description:\\n    \\\"Weekdays during working hours: poll Granola for newly ended meetings and run the recap agent.\\\",\\n  schedule: MEETING_RECAP_POLL_SCHEDULE,\\n  state: pollStateSchema,\\n  async run(ctx) {\\n    const now = new Date();\\n    const previousState = ctx?.state;\\n    const state = normalizePollState(previousState, now);\\n    const listed = await granolaMcpListMeetings.run({\\n      time_range: \\\"this_week\\\",\\n    });\\n\\n    const meetings = filterMeetingsForDate(parseGranolaMeetings(listed), now);\\n    const newMeetings = findNewEndedMeetings({\\n      meetings,\\n      processedMeetingIds: state.processedMeetingIds,\\n      now,\\n    });\\n\\n    if (newMeetings.length === 0) {\\n      if (previousState?.cursorDate !== state.cursorDate) {\\n        ctx?.setState(state);\\n      }\\n      return { meetings: [] };\\n    }\\n\\n    ctx?.setState(\\n      nextPollState(\\n        state,\\n        newMeetings.map((meeting) => meeting.id),\\n      ),\\n    );\\n\\n    return { meetings: newMeetings };\\n  },\\n})\\n  .filter((payload): payload is MeetingRecapPollPayload => {\\n    return \\\"meetings\\\" in payload && payload.meetings.length > 0;\\n  })\\n  .attach({\\n    agent: meetingRecap,\\n    prompt: (payload) => {\\n      if (\\n        !payload ||\\n        typeof payload !== \\\"object\\\" ||\\n        !(\\\"meetings\\\" in payload) ||\\n        !Array.isArray(payload.meetings)\\n      ) {\\n        throw new Error(\\\"Meeting recap poll payload is missing meetings.\\\");\\n      }\\n\\n      return buildMeetingRecapAgentPrompt(payload as MeetingRecapPollPayload);\\n    },\\n  });\\n\"\n\t\t}\n\t},\n\t{\n\t\t\"slug\": \"personal-assistant\",\n\t\t\"kind\": \"agent\",\n\t\t\"title\": \"Personal Assistant\",\n\t\t\"description\": \"A personal assistant for inbox triage, calendar management, drafting, and day planning.\",\n\t\t\"tags\": [\n\t\t\t\"gmail\",\n\t\t\t\"calendar\",\n\t\t\t\"productivity\",\n\t\t\t\"assistant\"\n\t\t],\n\t\t\"requiredApps\": [\"gmail\", \"googlecalendar\"],\n\t\t\"files\": { \"src/agents/personal-assistant.ts\": \"import { defineAgent } from \\\"@keystrokehq/keystroke/agent\\\";\\nimport {\\n  gmailAddLabelToEmail,\\n  gmailCreateEmailDraft,\\n  gmailCreateLabel,\\n  gmailFetchEmails,\\n  gmailFetchMessageByMessageId,\\n  gmailListLabels,\\n  gmailModifyThreadLabels,\\n  gmailReplyToThread,\\n  gmailSendEmail,\\n} from \\\"@keystrokehq/gmail/actions\\\";\\nimport {\\n  googlecalendarCreateEvent,\\n  googlecalendarEventsGet,\\n  googlecalendarEventsList,\\n  googlecalendarFindEvent,\\n  googlecalendarFindFreeSlots,\\n  googlecalendarListCalendars,\\n  googlecalendarPatchEvent,\\n} from \\\"@keystrokehq/googlecalendar/actions\\\";\\n\\nexport default defineAgent({\\n  slug: \\\"personal-assistant\\\",\\n  name: \\\"Personal Assistant\\\",\\n  description:\\n    \\\"A personal assistant for inbox triage, calendar management, drafting, and day planning.\\\",\\n  systemPrompt: `You are a personal assistant. Be concise, proactive, and practical.\\nPrefer short replies unless the user asks for more detail.\\n\\nHelp with:\\n- Inbox triage: scan mail, summarize threads, flag what needs a reply, draft or send responses\\n- Calendar: check the schedule, find free time, create or update events, and propose meeting times\\n- Day planning: turn priorities into a simple plan that fits around existing calendar commitments\\n- Follow-ups: remind the user what is outstanding and draft the next message when useful\\n- Light research and writing: short briefs, talking points, and polished drafts when asked\\n\\nGmail:\\n- Use fetch emails to scan the inbox; use fetch message by message ID for full content.\\n- Use send email or reply to thread to compose and send; confirm to/cc/subject/body before sending.\\n- Use create email draft when the user wants a draft instead of sending.\\n- Use list labels to resolve label IDs; use create label for new labels; use add label to email or modify thread labels to apply them.\\n- Summarize clearly: subject, sender, date, and key points.\\n\\nCalendar:\\n- Use list calendars to see available calendars and resolve calendar IDs.\\n- Use list events or find event to read upcoming or matching events; use get event for full details.\\n- Use find free slots when asked for availability before scheduling.\\n- Use create event to add events; include attendees to invite people and confirm title, time, timezone, and guest list before creating.\\n- Use patch event to update existing events or add attendees.\\n\\nPrivacy:\\n- Treat email and calendar contents as private.\\n- Never share other people's private email or calendar details beyond what the user needs.\\n- Confirm before sending email or creating/updating calendar events that invite others.`,\\n  model: \\\"anthropic/claude-sonnet-5\\\",\\n  tools: [\\n    gmailFetchEmails,\\n    gmailFetchMessageByMessageId,\\n    gmailSendEmail,\\n    gmailReplyToThread,\\n    gmailCreateEmailDraft,\\n    gmailListLabels,\\n    gmailCreateLabel,\\n    gmailAddLabelToEmail,\\n    gmailModifyThreadLabels,\\n    googlecalendarEventsList,\\n    googlecalendarEventsGet,\\n    googlecalendarFindEvent,\\n    googlecalendarFindFreeSlots,\\n    googlecalendarListCalendars,\\n    googlecalendarCreateEvent,\\n    googlecalendarPatchEvent,\\n  ],\\n});\\n\" }\n\t},\n\t{\n\t\t\"slug\": \"secretary\",\n\t\t\"kind\": \"both\",\n\t\t\"title\": \"Secretary\",\n\t\t\"description\": \"Inbox triage, digests, follow-up reminders, and meeting prep — with a secretary agent that manages Gmail, Calendar, Meet transcripts, and Slack.\",\n\t\t\"tags\": [\n\t\t\t\"gmail\",\n\t\t\t\"calendar\",\n\t\t\t\"slack\",\n\t\t\t\"meetings\",\n\t\t\t\"inbox\",\n\t\t\t\"assistant\"\n\t\t],\n\t\t\"requiredApps\": [\n\t\t\t\"gmail\",\n\t\t\t\"googlecalendar\",\n\t\t\t\"googlemeet\",\n\t\t\t\"slackbot\"\n\t\t],\n\t\t\"files\": {\n\t\t\t\"src/agents/sheila.ts\": \"import { defineAgent } from \\\"@keystrokehq/keystroke/agent\\\";\\nimport { defineSandbox } from \\\"@keystrokehq/keystroke/sandbox\\\";\\nimport {\\n  gmailFetchEmails,\\n  gmailFetchMessageByMessageId,\\n  gmailFetchMessageByThreadId,\\n  gmailListThreads,\\n  gmailListLabels,\\n  gmailSendEmail,\\n  gmailReplyToThread,\\n  gmailForwardMessage,\\n  gmailCreateEmailDraft,\\n  gmailSendDraft,\\n  gmailUpdateDraft,\\n  gmailDeleteDraft,\\n  gmailMoveToTrash,\\n  gmailMoveThreadToTrash,\\n  gmailAddLabelToEmail,\\n  gmailModifyThreadLabels,\\n  gmailBatchModifyMessages,\\n  gmailCreateLabel,\\n  gmailCreateFilter,\\n  gmailGetProfile,\\n} from \\\"@keystrokehq/gmail/actions\\\";\\nimport {\\n  googlecalendarEventsList,\\n  googlecalendarEventsListAllCalendars,\\n  googlecalendarEventsGet,\\n  googlecalendarFindEvent,\\n  googlecalendarCreateEvent,\\n  googlecalendarQuickAdd,\\n  googlecalendarPatchEvent,\\n  googlecalendarUpdateEvent,\\n  googlecalendarDeleteEvent,\\n  googlecalendarFindFreeSlots,\\n  googlecalendarListCalendars,\\n  googlecalendarGetCalendar,\\n  googlecalendarGetCurrentDateTime,\\n  googlecalendarSettingsList,\\n} from \\\"@keystrokehq/googlecalendar/actions\\\";\\nimport {\\n  googlemeetListConferenceRecords,\\n  googlemeetGetConferenceRecordByName,\\n  googlemeetGetTranscriptsByConferenceRecordId,\\n  googlemeetGetTranscript,\\n  googlemeetListTranscriptEntries,\\n  googlemeetListParticipants,\\n} from \\\"@keystrokehq/googlemeet/actions\\\";\\nimport {\\n  slackbotSearchMessages,\\n  slackbotSearchAll,\\n  slackbotFetchConversationHistory,\\n  slackbotFetchMessageThreadFromAConversation,\\n  slackbotFindChannels,\\n  slackbotFindUserByEmailAddress,\\n  slackbotListAllChannels,\\n  slackbotListAllUsers,\\n  slackbotSendMessage,\\n  slackbotRetrieveDetailedUserInformation,\\n} from \\\"@keystrokehq/slackbot/actions\\\";\\nimport {\\n  FOLLOWUP_LABEL_PREFIX,\\n  OWNER_FIRST_NAME,\\n  OWNER_NAME,\\n  SHEILA_CHANNEL,\\n  TIMEZONE,\\n} from \\\"../lib/config\\\";\\n\\nexport default defineAgent({\\n  slug: \\\"sheila\\\",\\n  name: \\\"Sheila\\\",\\n  description:\\n    \\\"Personal secretary. Manages Gmail, Google Calendar, Meet transcripts, and Slack — reads, drafts, sends, files, schedules, briefs before meetings, and posts prep notes to Slack.\\\",\\n  model: \\\"anthropic/claude-sonnet-5\\\",\\n  thinkingLevel: \\\"medium\\\",\\n  skills: [\\\"sheila\\\"],\\n  sandbox: defineSandbox({ files: \\\"sheila\\\" }),\\n  systemPrompt: `You are Sheila, ${OWNER_NAME}'s personal secretary. You act on their behalf at all times.\\n\\nYour job:\\n- Keep their Gmail inbox clean: read, triage, file, archive, label, draft, and send mail as they ask.\\n- Manage their Google Calendar: check availability, create/move/update/cancel events, find free slots, and protect their time.\\n- Prepare meeting briefs: research attendees, past conversations, transcripts, and Slack context, then post a concise briefing to Slack.\\n- Be concise and proactive. Summarize, don't dump. When something is ambiguous or consequential (sending to a new recipient, cancelling a meeting, replying on their behalf), confirm before acting.\\n\\nHow you represent ${OWNER_FIRST_NAME}:\\n- You are emailing and scheduling AS ${OWNER_FIRST_NAME} — never as \\\"Sheila\\\" or as an assistant. Use their voice, first person.\\n- Never send anything that could embarrass them: no off-brand tone, no commitments they didn't authorize, no opinions attributed to them, no sensitive contents forwarded to the wrong people. When in doubt, draft and ask.\\n- Tie your hands by default: prefer drafting over sending; prefer proposing a slot over booking it; prefer labeling/archiving over deleting (trash is recoverable, permanent delete is not — never use permanent delete without explicit confirmation).\\n- Privacy: never expose message contents, calendar details, or contacts beyond what they asked for, and never to channels or recipients that aren't part of the task.\\n- Be honest about limits. If a tool fails or data is missing, say so — don't pretend an action succeeded.\\n\\nMeeting briefs:\\n- When preparing a briefing, gather context in this order: (1) calendar event details + attendees, (2) past email threads with attendees (gmailFetchEmails with from: queries), (3) Google Meet transcripts from prior calls (googlemeetListConferenceRecords, then get transcripts), (4) Slack messages mentioning the attendee or topic (slackbotSearchMessages), (5) web research on the company/person if it's a first meeting.\\n- Google Meet sends a post-call email with the recording/transcript. Use gmailFetchEmails with a query like \\\"from:meetings-mailer@google.com in:inbox\\\" to find these and link them to past events.\\n- Keep the briefing short: who, what they care about, last interaction summary, open follow-ups, and any relevant Slack context. Bullet points, not paragraphs.\\n- Post briefings to the #${SHEILA_CHANNEL} Slack channel using slackbotSendMessage with channel \\\"${SHEILA_CHANNEL}\\\".\\n\\nPractical defaults:\\n- Timezone: assume ${TIMEZONE} unless a calendar or ${OWNER_FIRST_NAME} says otherwise; confirm times in that zone.\\n- Use gmailFetchEmails/gmailListThreads to survey the inbox before acting; hydrate specific messages with gmailFetchMessageByMessageId/ByThreadId.\\n- Resolve label IDs via gmailListLabels before applying labels (display names won't work).\\n- For scheduling, call googlecalendarGetCurrentDateTime first to ground relative terms like \\\"tomorrow\\\", then googlecalendarFindFreeSlots / googlecalendarEventsList to find conflicts before creating.\\n- Reply in threads with gmailReplyToThread (don't set a subject). New mail uses gmailSendEmail.\\n- For Slack, use slackbotSearchMessages to find relevant messages across the workspace, slackbotFindChannels to locate channels, slackbotFetchConversationHistory to read a channel's messages.\\n\\nReply the way a trusted, sharp chief of staff would: short, clear, and action-oriented.\\n\\nEmail follow-up reminders:\\n- When asked to remind about an email, tag it with a Gmail label naming the due date.\\n- Label format: \\\"${FOLLOWUP_LABEL_PREFIX}YYYY-MM-DD\\\" (defaults to 8am local) or \\\"${FOLLOWUP_LABEL_PREFIX}YYYY-MM-DD-HHMM\\\" for a specific time (24h, ${TIMEZONE}).\\n- Steps: (1) resolve or create the label with gmailCreateLabel, (2) apply it to the email with gmailAddLabelToEmail.\\n- A poll trigger checks every 15 min for due labels and posts reminders to #${SHEILA_CHANNEL} automatically. You don't need to schedule anything else.\\n- If they say \\\"in 2 days\\\" without a time, use the date 2 days from now at 8am: ${FOLLOWUP_LABEL_PREFIX}2026-07-17.\\n- If they say \\\"tomorrow at 3pm\\\": ${FOLLOWUP_LABEL_PREFIX}2026-07-16-1500.\\n- Remove the follow-up label if asked to cancel a reminder. Use gmailAddLabelToEmail with remove_label_ids.\\n\\nTriage configuration:\\n- Your triage rules and vendor list live at /workspace/agent/triage-config.md.\\n- To modify them (add/remove vendors, change rules), edit the file and save a copy to /workspace/agent/.triage/config.md so changes persist across sessions.\\n- The inbox-triage workflow reads .triage/config.md first, then falls back to triage-config.md.`,\\n  tools: [\\n    gmailGetProfile,\\n    gmailFetchEmails,\\n    gmailFetchMessageByMessageId,\\n    gmailFetchMessageByThreadId,\\n    gmailListThreads,\\n    gmailListLabels,\\n    gmailSendEmail,\\n    gmailReplyToThread,\\n    gmailForwardMessage,\\n    gmailCreateEmailDraft,\\n    gmailSendDraft,\\n    gmailUpdateDraft,\\n    gmailDeleteDraft,\\n    gmailMoveToTrash,\\n    gmailMoveThreadToTrash,\\n    gmailAddLabelToEmail,\\n    gmailModifyThreadLabels,\\n    gmailBatchModifyMessages,\\n    gmailCreateLabel,\\n    gmailCreateFilter,\\n    googlecalendarGetCurrentDateTime,\\n    googlecalendarSettingsList,\\n    googlecalendarListCalendars,\\n    googlecalendarGetCalendar,\\n    googlecalendarEventsList,\\n    googlecalendarEventsListAllCalendars,\\n    googlecalendarEventsGet,\\n    googlecalendarFindEvent,\\n    googlecalendarFindFreeSlots,\\n    googlecalendarCreateEvent,\\n    googlecalendarQuickAdd,\\n    googlecalendarPatchEvent,\\n    googlecalendarUpdateEvent,\\n    googlecalendarDeleteEvent,\\n    googlemeetListConferenceRecords,\\n    googlemeetGetConferenceRecordByName,\\n    googlemeetGetTranscriptsByConferenceRecordId,\\n    googlemeetGetTranscript,\\n    googlemeetListTranscriptEntries,\\n    googlemeetListParticipants,\\n    slackbotSearchMessages,\\n    slackbotSearchAll,\\n    slackbotFetchConversationHistory,\\n    slackbotFetchMessageThreadFromAConversation,\\n    slackbotFindChannels,\\n    slackbotFindUserByEmailAddress,\\n    slackbotListAllChannels,\\n    slackbotListAllUsers,\\n    slackbotSendMessage,\\n    slackbotRetrieveDetailedUserInformation,\\n  ],\\n});\\n\",\n\t\t\t\"src/files/sheila/triage-config.md\": \"# Triage Configuration\\n\\nSheila maintains this file. To modify the vendor list or rules, update this file and save a copy to `/workspace/agent/.triage/config.md` so changes persist across sessions.\\n\\nEdit the buckets below for your company, domains, and vendors before relying on automated triage.\\n\\n## Archive silently (spam / marketing)\\n\\n- Marketing emails, newsletters, promotional content, webinar announcements\\n- Cold sales outreach from tools/services you don't use\\n- Automated notifications that aren't actionable (social digests, app updates, product announcements from non-vendors)\\n- Receipts, order confirmations, shipping notifications\\n- Job board alerts, recruiter blasts, cold outreach platforms\\n- Vendor newsletters and routine product updates — archive these unless they're a failure/alert\\n\\n## Urgent (post to #sheila immediately)\\n\\n- Inbound investor interest (if relevant)\\n- Failed deploys, CI failures, build breaks\\n- Usage spikes, quota warnings, rate limit alerts\\n- Billing issues, payment failures, invoice problems\\n- Security alerts, unauthorized access warnings\\n- Vendor alerts from companies on your vendor list (ONLY if failure/alert/warning, not routine updates)\\n- Internal team emails that need a response\\n\\n## Digest (collect for 9am/12pm/5pm/8pm summary)\\n\\n- Product interest or demo requests\\n- Support requests from users\\n- General company inquiries\\n- Partnership inquiries\\n- Emails from known contacts (people you've corresponded with before)\\n- Non-urgent vendor emails (product updates, changelogs, routine notifications)\\n\\n## Leave in inbox (you should see yourself)\\n\\n- Personal emails from friends/family\\n- Anything ambiguous that doesn't clearly fit another bucket\\n- Emails that seem sensitive or need personal judgment\\n\\n## Contact categories\\n\\n- investor: VCs, angels, anyone expressing investment interest\\n- customer_prospect: People using or evaluating your product\\n- partner: Integration partners, service providers\\n- vendor: Companies whose tools you use (see vendor list below)\\n- internal: Your team (match INTERNAL_DOMAINS in config)\\n- personal: Friends, family, non-work contacts\\n\\n## Vendor list\\n\\nCompanies whose tools/services you use. Treat failure/alert/billing emails as urgent. Archive newsletters and routine updates to the digest bucket.\\n\\n1. (add your vendors here)\\n\\n## Draft reply guidelines\\n\\nWrite in the owner's voice: terse, professional, direct, a little fun. No preamble. Lead with the point. Short sentences. No corporate speak (\\\"per my last email,\\\" \\\"circling back\\\"). No \\\"very,\\\" \\\"really,\\\" \\\"super.\\\" One exclamation mark max, only when genuine. For formal external emails, use standard capitalization; for casual/internal, lowercase is fine.\\n\\n## How to modify this file\\n\\nWhen asked to add or remove a vendor, change a rule, or adjust categories:\\n1. Edit this file in place with your changes\\n2. Save a copy to /workspace/agent/.triage/config.md (this path persists across sessions since it's not overwritten by deployment materialization)\\n3. Confirm the change\\n\\nThe inbox-triage workflow embeds default rules; keep this file in sync when you change policy.\\n\",\n\t\t\t\"src/lib/config.ts\": \"/**\\n * Personalize these before deploying.\\n * Slack accepts a channel name (e.g. \\\"sheila\\\") or a channel ID (e.g. \\\"C0123…\\\").\\n */\\nexport const OWNER_NAME = \\\"Your Name\\\";\\nexport const OWNER_FIRST_NAME = \\\"you\\\";\\nexport const COMPANY_NAME = \\\"Your Company\\\";\\n/** Internal email domains used in triage (e.g. [\\\"@acme.com\\\"]). */\\nexport const INTERNAL_DOMAINS = [\\\"@example.com\\\"];\\n/** Slack channel where Sheila posts briefs, digests, and urgent mail. */\\nexport const SHEILA_CHANNEL = \\\"sheila\\\";\\nexport const TIMEZONE = \\\"America/Denver\\\";\\n/** Default due time for follow-up labels without an HHMM suffix (24h, local to TIMEZONE offset below). */\\nexport const FOLLOWUP_DEFAULT_HOUR = \\\"0800\\\";\\n/**\\n * Fixed offset used when parsing follow-up label due times.\\n * Update if TIMEZONE is not Mountain Time (e.g. \\\"-05:00\\\" for Eastern).\\n */\\nexport const FOLLOWUP_TZ_OFFSET = \\\"-06:00\\\";\\n\\n/** Gmail label display names — resolved to IDs at runtime (never hardcode Label_N). */\\nexport const LABEL_PENDING_DIGEST = \\\"sheila/pending-digest\\\";\\nexport const LABEL_HANDLED = \\\"sheila/handled\\\";\\nexport const FOLLOWUP_LABEL_PREFIX = \\\"sheila/followup-\\\";\\n\",\n\t\t\t\"src/lib/gmail-labels.ts\": \"import { gmailCreateLabel, gmailListLabels } from \\\"@keystrokehq/gmail/actions\\\";\\n\\ntype Label = { id?: string | null; name?: string | null };\\n\\n/**\\n * Resolve a Gmail label ID by display name, creating the label if missing.\\n */\\nexport async function resolveLabelId(labelName: string): Promise<string> {\\n  const listed = await gmailListLabels.run({});\\n  const labels = (listed as { labels?: Label[] }).labels ?? [];\\n  const existing = labels.find((l) => l.name === labelName && l.id);\\n  if (existing?.id) return existing.id;\\n\\n  const created = await gmailCreateLabel.run({ label_name: labelName });\\n  const id = (created as { id?: string | null }).id;\\n  if (!id) {\\n    throw new Error(`Failed to create Gmail label \\\"${labelName}\\\"`);\\n  }\\n  return id;\\n}\\n\",\n\t\t\t\"src/skills/sheila/SKILL.md\": \"---\\nname: sheila\\ndescription: Use when composing emails, Slack messages, or any written communication on behalf of the owner. Defines voice, tone, and style rules.\\n---\\n\\n# Communication Style\\n\\nWhen writing as the owner — emails, Slack, calendar invites, replies — match the style below. Edit this skill to match their real voice.\\n\\n## Voice\\n\\n- **Direct first.** Lead with the answer or action. No \\\"I hope this finds you well,\\\" no preamble.\\n- **Information-dense.** Every line carries weight. Cut filler words, hedge words, and throat-clearing.\\n- **Short sentences.** One thought per line. Fragments are fine in casual contexts.\\n- **Conversational** in casual contexts (Slack, quick emails). In formal emails to external parties, use standard capitalization and grammar.\\n- **Approachable, not aloof.** Light humor is fine in Slack; keep email mostly clean.\\n- **Confident but honest.** Admit uncertainty fast, then pivot to next steps.\\n\\n## Structure\\n\\n- **Bullet points and numbered lists** for anything with 3+ items. Short bullets, not paragraphs.\\n- **Code blocks** for technical content, not inline prose.\\n- **Bold** for the one thing that matters. Don't bold everything.\\n- **Ask the direct question.** \\\"Does X still use Y?\\\" not \\\"I was wondering if perhaps X might still use Y.\\\"\\n\\n## Tone\\n\\n- **Terse, not cold.**\\n- **Fun, not goofy.** Light and human — never forced.\\n- **Professional but real.** Humility and accountability beat corporate polish.\\n- **Customer-facing:** warm and competent — inviting, not desperate.\\n\\n## What to Avoid\\n\\n- Corporate speak: \\\"per my last email,\\\" \\\"circling back,\\\" \\\"as discussed.\\\"\\n- Over-apologizing. \\\"Sorry\\\" is fine once; don't stack it.\\n- Paragraphs when bullets work.\\n- Hedged opinions: \\\"I think maybe we might want to...\\\" Say \\\"we should...\\\" or \\\"I like...\\\"\\n- Anything that sounds like a brand, not a person.\\n- Intensifiers like \\\"very\\\", \\\"really\\\", \\\"super\\\", \\\"literally\\\" — rare and intentional at most.\\n- Exclamation points liberally. One per message, max, and only when genuine.\\n\\n## Quick Samples\\n\\nRight: \\\"I'll check it out\\\"\\nRight: \\\"Yeah no worries — we're using the HubSpot app and it looks scary, but it's safe\\\"\\nRight: \\\"Give me a few min if you can spare the time\\\"\\n\\nWrong: \\\"I wanted to reach out and see if you had a chance to review...\\\"\\nWrong: \\\"Just following up on this thread to make sure we're aligned!\\\"\\nWrong: \\\"I'm really super excited about this opportunity!!\\\"\\n\\n## Context Switching\\n\\n| Context | Register |\\n| --- | --- |\\n| Slack (internal team) | Casual, emoji ok, fragments |\\n| Slack (customer/partner) | Warmer, standard caps, still terse |\\n| Email (internal) | Quick, direct, minimal formality |\\n| Email (external/customer) | Professional, standard grammar, still concise — no fluff |\\n| Calendar invites | Short title, clear agenda in 2–3 lines max |\\n\\n## Scheduling Links\\n\\nOnly share scheduling links when the owner explicitly asks. Add yours here:\\n\\n- 15-min call: (add your link)\\n- 30-min call: (add your link)\\n\\nNever offer them unprompted.\\n\",\n\t\t\t\"src/triggers/followup-remind-poll.ts\": \"import { definePollSource } from \\\"@keystrokehq/keystroke/trigger\\\";\\nimport { z } from \\\"zod\\\";\\nimport { gmailListLabels, gmailFetchEmails } from \\\"@keystrokehq/gmail/actions\\\";\\nimport followupRemind from \\\"../workflows/followup-remind\\\";\\nimport {\\n  FOLLOWUP_DEFAULT_HOUR,\\n  FOLLOWUP_LABEL_PREFIX,\\n  FOLLOWUP_TZ_OFFSET,\\n  TIMEZONE,\\n} from \\\"../lib/config\\\";\\n\\nexport default definePollSource({\\n  slug: \\\"followup-remind-poll\\\",\\n  name: \\\"Follow-up Reminder Poll\\\",\\n  description: \\\"Checks every 15 min for due Gmail follow-up labels and fires reminder workflow.\\\",\\n  schedule: \\\"*/15 * * * *\\\",\\n  timezone: TIMEZONE,\\n  state: z.object({\\n    firedLabelIds: z.array(z.string()).default([]),\\n  }),\\n  run: async ({ state, setState }) => {\\n    const labelsResult = await gmailListLabels.run({});\\n    type Label = {\\n      id: string | null;\\n      name: string | null;\\n      messagesTotal?: number | null;\\n    };\\n    const allLabels = (labelsResult as { labels?: Label[] }).labels ?? [];\\n\\n    const followupLabels = allLabels.filter(\\n      (l) =>\\n        l.id !== null &&\\n        l.name !== null &&\\n        l.name.startsWith(FOLLOWUP_LABEL_PREFIX) &&\\n        (l.messagesTotal ?? 0) > 0,\\n    );\\n\\n    const alreadyFired = state?.firedLabelIds ?? [];\\n    const now = new Date();\\n\\n    const reminders: Array<{\\n      label_id: string;\\n      label_name: string;\\n      due_datetime: string;\\n      emails: Array<{\\n        message_id: string;\\n        subject: string;\\n        from: string;\\n        gmail_link: string;\\n      }>;\\n    }> = [];\\n\\n    for (const label of followupLabels) {\\n      const labelId = label.id!;\\n      const labelName = label.name!;\\n\\n      if (alreadyFired.includes(labelId)) continue;\\n\\n      const parsed = parseDueDate(labelName);\\n      if (!parsed) continue;\\n\\n      if (parsed.due > now) continue;\\n\\n      const emailsResult = await gmailFetchEmails.run({\\n        label_ids: [labelId],\\n        verbose: false,\\n        max_results: 20,\\n      });\\n\\n      type Msg = {\\n        messageId?: string | null;\\n        subject?: string | null;\\n        sender?: string | null;\\n      };\\n      const messages = (emailsResult as { messages?: Msg[] }).messages ?? [];\\n\\n      const emails = messages\\n        .map((m) => {\\n          const messageId = m.messageId ?? \\\"\\\";\\n          return {\\n            message_id: messageId,\\n            subject: m.subject ?? \\\"(no subject)\\\",\\n            from: m.sender ?? \\\"unknown\\\",\\n            gmail_link: `https://mail.google.com/mail/u/0/#inbox/${messageId}`,\\n          };\\n        })\\n        .filter((e) => e.message_id !== \\\"\\\");\\n\\n      if (emails.length === 0) continue;\\n\\n      reminders.push({\\n        label_id: labelId,\\n        label_name: labelName,\\n        due_datetime: parsed.iso,\\n        emails,\\n      });\\n    }\\n\\n    if (reminders.length > 0) {\\n      const firedIds = reminders.map((r) => r.label_id);\\n      setState({\\n        firedLabelIds: [...alreadyFired, ...firedIds].slice(-200),\\n      });\\n    }\\n\\n    return { reminders };\\n  },\\n  filter: (result) => result.reminders.length > 0,\\n}).attach({\\n  workflow: followupRemind,\\n});\\n\\nfunction parseDueDate(labelName: string): { due: Date; iso: string } | null {\\n  const escaped = FOLLOWUP_LABEL_PREFIX.replace(/[.*+?^${}()|[\\\\]\\\\\\\\]/g, \\\"\\\\\\\\$&\\\");\\n  const match = labelName.match(new RegExp(`^${escaped}(\\\\\\\\d{4}-\\\\\\\\d{2}-\\\\\\\\d{2})(?:-(\\\\\\\\d{4}))?$`));\\n  if (!match) return null;\\n\\n  const datePart = match[1]!;\\n  const timePart = match[2] ?? FOLLOWUP_DEFAULT_HOUR;\\n  const hours = timePart.slice(0, 2);\\n  const mins = timePart.slice(2, 4);\\n\\n  const due = new Date(`${datePart}T${hours}:${mins}:00${FOLLOWUP_TZ_OFFSET}`);\\n  if (isNaN(due.getTime())) return null;\\n\\n  return { due, iso: due.toISOString() };\\n}\\n\",\n\t\t\t\"src/triggers/inbox-digest-cron.ts\": \"import { defineCronSource } from \\\"@keystrokehq/keystroke/trigger\\\";\\nimport inboxDigest from \\\"../workflows/inbox-digest\\\";\\nimport { SHEILA_CHANNEL, TIMEZONE } from \\\"../lib/config\\\";\\n\\nexport default defineCronSource({\\n  slug: \\\"inbox-digest-cron\\\",\\n  name: \\\"Inbox Digest Cron\\\",\\n  description: `Posts an inbox digest to #${SHEILA_CHANNEL} at 9am, 12pm, 5pm, and 8pm.`,\\n  schedule: \\\"0 9,12,17,20 * * *\\\",\\n  timezone: TIMEZONE,\\n}).attach({\\n  workflow: inboxDigest,\\n});\\n\",\n\t\t\t\"src/triggers/inbox-triage-poll.ts\": \"import { definePollSource } from \\\"@keystrokehq/keystroke/trigger\\\";\\nimport { z } from \\\"zod\\\";\\nimport { gmailFetchEmails } from \\\"@keystrokehq/gmail/actions\\\";\\nimport inboxTriage from \\\"../workflows/inbox-triage\\\";\\nimport { TIMEZONE } from \\\"../lib/config\\\";\\n\\nexport default definePollSource({\\n  slug: \\\"inbox-triage-poll\\\",\\n  name: \\\"Inbox Triage Poll\\\",\\n  description: \\\"Checks inbox every 15 min for new unread emails to triage through Sheila.\\\",\\n  schedule: \\\"*/15 * * * *\\\",\\n  timezone: TIMEZONE,\\n  state: z.object({\\n    processedIds: z.array(z.string()).default([]),\\n  }),\\n  run: async ({ state, setState }) => {\\n    const result = await gmailFetchEmails.run({\\n      query: \\\"is:unread in:inbox\\\",\\n      verbose: true,\\n      max_results: 20,\\n    });\\n\\n    type Msg = {\\n      messageId?: string | null;\\n      threadId?: string | null;\\n      subject?: string | null;\\n      sender?: string | null;\\n      messageText?: string | null;\\n      messageTimestamp?: string | null;\\n      displayUrl?: string | null;\\n    };\\n\\n    const messages = (result as { messages?: Msg[] }).messages ?? [];\\n    const processed = state?.processedIds ?? [];\\n\\n    const newMessages = messages.filter((m) => m.messageId && !processed.includes(m.messageId));\\n\\n    const emails = newMessages.map((m) => {\\n      const messageId = m.messageId ?? \\\"\\\";\\n      return {\\n        message_id: messageId,\\n        thread_id: m.threadId ?? \\\"\\\",\\n        subject: m.subject ?? \\\"(no subject)\\\",\\n        from: m.sender ?? \\\"unknown\\\",\\n        date: m.messageTimestamp ?? \\\"\\\",\\n        body: (m.messageText ?? \\\"\\\").slice(0, 500),\\n        gmail_link: `https://mail.google.com/mail/u/0/#inbox/${messageId}`,\\n      };\\n    });\\n\\n    const newIds = newMessages\\n      .map((m) => m.messageId)\\n      .filter((id): id is string => typeof id === \\\"string\\\");\\n\\n    setState({\\n      processedIds: [...processed, ...newIds].slice(-500),\\n    });\\n\\n    return { emails };\\n  },\\n  filter: (result) => result.emails.length > 0,\\n}).attach({\\n  workflow: inboxTriage,\\n});\\n\",\n\t\t\t\"src/triggers/meeting-prep-poll.ts\": \"import { definePollSource } from \\\"@keystrokehq/keystroke/trigger\\\";\\nimport { z } from \\\"zod\\\";\\nimport { googlecalendarEventsList } from \\\"@keystrokehq/googlecalendar/actions\\\";\\nimport meetingPrep from \\\"../workflows/meeting-prep\\\";\\nimport { TIMEZONE } from \\\"../lib/config\\\";\\n\\nexport default definePollSource({\\n  slug: \\\"meeting-prep-poll\\\",\\n  name: \\\"Meeting Prep Poll\\\",\\n  description:\\n    \\\"Checks calendar every 5 minutes for meetings starting in ~30 min and fires the meeting-prep workflow.\\\",\\n  schedule: \\\"*/5 * * * *\\\",\\n  timezone: TIMEZONE,\\n  state: z.object({\\n    briefedEventIds: z.array(z.string()).default([]),\\n  }),\\n  run: async ({ state, setState }) => {\\n    const now = new Date();\\n    const inThirtyMin = new Date(now.getTime() + 30 * 60 * 1000);\\n    const inFortyMin = new Date(now.getTime() + 40 * 60 * 1000);\\n\\n    const timeMin = inThirtyMin.toISOString();\\n    const timeMax = inFortyMin.toISOString();\\n\\n    const result = await googlecalendarEventsList.run({\\n      calendarId: \\\"primary\\\",\\n      timeMin,\\n      timeMax,\\n      singleEvents: true,\\n      orderBy: \\\"startTime\\\",\\n      maxResults: 10,\\n    });\\n\\n    const eventsRaw = (result as { items?: unknown[] }).items ?? [];\\n    const alreadyBriefed = state?.briefedEventIds ?? [];\\n\\n    const upcoming = eventsRaw\\n      .map((e) => {\\n        const event = e as {\\n          id?: string;\\n          summary?: string;\\n          start?: { dateTime?: string };\\n          attendees?: Array<{ email?: string }>;\\n        };\\n        const eventId = event.id;\\n        if (!eventId || alreadyBriefed.includes(eventId)) return null;\\n        const attendees = (event.attendees ?? [])\\n          .map((a) => a.email)\\n          .filter((email): email is string => typeof email === \\\"string\\\");\\n        return {\\n          event_id: eventId,\\n          summary: event.summary ?? \\\"Untitled meeting\\\",\\n          start_time: event.start?.dateTime ?? timeMin,\\n          attendees,\\n        };\\n      })\\n      .filter((e): e is NonNullable<typeof e> => e !== null);\\n\\n    const newBriefed = [...alreadyBriefed, ...upcoming.map((e) => e.event_id)];\\n    setState({\\n      briefedEventIds: newBriefed.slice(-100),\\n    });\\n\\n    return { meetings: upcoming };\\n  },\\n  filter: (result) => result.meetings.length > 0,\\n}).attach({\\n  workflow: meetingPrep,\\n});\\n\",\n\t\t\t\"src/workflows/followup-remind.ts\": \"import { defineWorkflow } from \\\"@keystrokehq/keystroke/workflow\\\";\\nimport { z } from \\\"zod\\\";\\nimport { gmailBatchModifyMessages } from \\\"@keystrokehq/gmail/actions\\\";\\nimport { slackbotSendMessage } from \\\"@keystrokehq/slackbot/actions\\\";\\nimport { SHEILA_CHANNEL } from \\\"../lib/config\\\";\\n\\nexport default defineWorkflow({\\n  slug: \\\"followup-remind\\\",\\n  name: \\\"Follow-up Reminder\\\",\\n  description: \\\"Posts due follow-up emails to Slack and removes the follow-up label.\\\",\\n  input: z.object({\\n    reminders: z.array(\\n      z.object({\\n        label_id: z.string(),\\n        label_name: z.string(),\\n        due_datetime: z.string(),\\n        emails: z.array(\\n          z.object({\\n            message_id: z.string(),\\n            subject: z.string(),\\n            from: z.string(),\\n            gmail_link: z.string(),\\n          }),\\n        ),\\n      }),\\n    ),\\n  }),\\n  output: z.object({\\n    reminded: z.number(),\\n  }),\\n  async run(input) {\\n    let count = 0;\\n\\n    for (const reminder of input.reminders) {\\n      const emailLines = reminder.emails\\n        .map((e) => `• ${e.subject} — from ${e.from}\\\\n  ${e.gmail_link}`)\\n        .join(\\\"\\\\n\\\");\\n\\n      await slackbotSendMessage.run({\\n        channel: SHEILA_CHANNEL,\\n        markdown_text: `⏰ **Follow-up reminder** — due ${reminder.due_datetime}\\\\n\\\\n${emailLines}`,\\n      });\\n\\n      const messageIds = reminder.emails.map((e) => e.message_id);\\n      if (messageIds.length > 0) {\\n        await gmailBatchModifyMessages.run({\\n          messageIds,\\n          removeLabelIds: [reminder.label_id],\\n        });\\n      }\\n\\n      count += reminder.emails.length;\\n    }\\n\\n    return { reminded: count };\\n  },\\n});\\n\",\n\t\t\t\"src/workflows/inbox-digest.ts\": \"import { defineWorkflow, promptLlm } from \\\"@keystrokehq/keystroke/workflow\\\";\\nimport { z } from \\\"zod\\\";\\nimport { gmailFetchEmails, gmailBatchModifyMessages } from \\\"@keystrokehq/gmail/actions\\\";\\nimport { slackbotSendMessage } from \\\"@keystrokehq/slackbot/actions\\\";\\nimport { LABEL_PENDING_DIGEST, OWNER_NAME, SHEILA_CHANNEL } from \\\"../lib/config\\\";\\nimport { resolveLabelId } from \\\"../lib/gmail-labels\\\";\\n\\nexport default defineWorkflow({\\n  slug: \\\"inbox-digest\\\",\\n  name: \\\"Inbox Digest\\\",\\n  description:\\n    \\\"Collects emails labeled for digest and posts a structured summary to Slack several times a day.\\\",\\n  input: z.object({}),\\n  output: z.object({\\n    posted: z.boolean(),\\n    count: z.number(),\\n  }),\\n  async run() {\\n    const pendingDigestId = await resolveLabelId(LABEL_PENDING_DIGEST);\\n\\n    const result = await gmailFetchEmails.run({\\n      label_ids: [pendingDigestId],\\n      verbose: true,\\n      max_results: 50,\\n    });\\n\\n    type Msg = {\\n      messageId?: string | null;\\n      threadId?: string | null;\\n      subject?: string | null;\\n      sender?: string | null;\\n      messageText?: string | null;\\n      messageTimestamp?: string | null;\\n    };\\n\\n    const messages = (result as { messages?: Msg[] }).messages ?? [];\\n    if (messages.length === 0) {\\n      return { posted: false, count: 0 };\\n    }\\n\\n    const emailData = messages\\n      .map((m) => {\\n        const messageId = m.messageId ?? \\\"\\\";\\n        const link = `https://mail.google.com/mail/u/0/#inbox/${messageId}`;\\n        const body = (m.messageText ?? \\\"\\\").slice(0, 300);\\n        return `- From: ${m.sender ?? \\\"unknown\\\"}\\\\n  Subject: ${m.subject ?? \\\"(no subject)\\\"}\\\\n  Link: ${link}\\\\n  Preview: ${body}`;\\n      })\\n      .join(\\\"\\\\n\\\");\\n\\n    const digestText = await promptLlm(\\n      `You are Sheila, ${OWNER_NAME}'s AI secretary. Write an inbox digest. Group emails by category: Investors, Customers/Prospects, Partners, Vendors, Internal, Personal, Other. For each email include a one-line summary and the Gmail link. Be concise. Voice: terse, professional, a little fun.\\n\\nEmails:\\n${emailData}\\n\\nFormat the digest as:\\n📬 **Inbox Digest**\\n\\n**Investors**\\n- [summary] — [link]\\n\\n**Customers/Prospects**\\n- [summary] — [link]\\n\\n(only include sections that have emails)\\n\\nEnd with a line: \\\"Drafts waiting in Gmail for your review.\\\" if any of these emails had drafts created during triage. If unsure, include the line.`,\\n      { model: \\\"anthropic/claude-sonnet-5\\\" },\\n    );\\n\\n    await slackbotSendMessage.run({\\n      channel: SHEILA_CHANNEL,\\n      markdown_text: digestText,\\n    });\\n\\n    const messageIds = messages\\n      .map((m) => m.messageId)\\n      .filter((id): id is string => typeof id === \\\"string\\\");\\n\\n    if (messageIds.length > 0) {\\n      await gmailBatchModifyMessages.run({\\n        messageIds,\\n        removeLabelIds: [pendingDigestId],\\n      });\\n    }\\n\\n    return { posted: true, count: messages.length };\\n  },\\n});\\n\",\n\t\t\t\"src/workflows/inbox-triage.ts\": \"import { defineWorkflow, promptLlm } from \\\"@keystrokehq/keystroke/workflow\\\";\\nimport { z } from \\\"zod\\\";\\nimport { gmailBatchModifyMessages, gmailCreateEmailDraft } from \\\"@keystrokehq/gmail/actions\\\";\\nimport { slackbotSendMessage } from \\\"@keystrokehq/slackbot/actions\\\";\\nimport {\\n  COMPANY_NAME,\\n  INTERNAL_DOMAINS,\\n  LABEL_HANDLED,\\n  LABEL_PENDING_DIGEST,\\n  OWNER_NAME,\\n  SHEILA_CHANNEL,\\n} from \\\"../lib/config\\\";\\nimport { resolveLabelId } from \\\"../lib/gmail-labels\\\";\\n\\nconst internalDomainList = INTERNAL_DOMAINS.join(\\\", \\\");\\n\\nconst TRIAGE_RULES = `## Archive silently (spam / marketing)\\n- Marketing emails, newsletters, promotional content, webinar announcements\\n- Cold sales outreach from tools/services the owner doesn't use\\n- Automated notifications that aren't actionable (social digests, app updates)\\n- Receipts, order confirmations, shipping notifications\\n- Job board alerts, recruiter blasts, cold outreach platforms\\n- Vendor newsletters and routine product updates — archive unless it's a failure/alert\\n\\n## Urgent (post to #${SHEILA_CHANNEL} immediately)\\n- Inbound investor interest in ${COMPANY_NAME} (if relevant)\\n- Failed deploys, CI failures, build breaks\\n- Usage spikes, quota warnings, rate limit alerts\\n- Billing issues, payment failures, invoice problems\\n- Security alerts, unauthorized access warnings\\n- Vendor alerts (ONLY if failure/alert/warning, not routine updates)\\n- Internal team emails from ${internalDomainList} that need a response\\n\\n## Digest (collect for scheduled summary)\\n- ${COMPANY_NAME} product interest or demo requests\\n- Support requests from users\\n- General inquiries about ${COMPANY_NAME}\\n- Partnership inquiries\\n- Emails from known contacts\\n- Non-urgent vendor emails (product updates, changelogs, routine notifications)\\n\\n## Leave in inbox (owner should see themselves)\\n- Personal emails from friends/family\\n- Anything ambiguous that doesn't clearly fit another bucket\\n- Emails that seem sensitive or need personal judgment\\n\\n## Contact categories\\n- investor: VCs, angels, anyone expressing investment interest in ${COMPANY_NAME}\\n- customer_prospect: People using or evaluating ${COMPANY_NAME}\\n- partner: Integration partners, service providers\\n- vendor: Companies whose tools the owner uses\\n- internal: Team (${internalDomainList})\\n- personal: Friends, family, non-work contacts\\n\\n## Draft reply guidelines\\n- Never draft replies to no-reply, noreply, do-not-reply, or noreply@ sender addresses. Set draft_reply to null for those.\\n- Write in the owner's voice: terse, professional, direct, a little fun. No preamble. Lead with the point. Short sentences. No corporate speak.`;\\n\\nconst TriageResult = z.object({\\n  classifications: z.array(\\n    z.object({\\n      message_id: z.string(),\\n      bucket: z.enum([\\\"archive\\\", \\\"urgent\\\", \\\"digest\\\", \\\"leave\\\"]),\\n      category: z\\n        .enum([\\n          \\\"investor\\\",\\n          \\\"customer_prospect\\\",\\n          \\\"partner\\\",\\n          \\\"vendor\\\",\\n          \\\"internal\\\",\\n          \\\"personal\\\",\\n          \\\"unknown\\\",\\n        ])\\n        .nullable(),\\n      summary: z.string(),\\n      draft_reply: z.string().nullable(),\\n    }),\\n  ),\\n});\\n\\nexport default defineWorkflow({\\n  slug: \\\"inbox-triage\\\",\\n  name: \\\"Inbox Triage\\\",\\n  description:\\n    \\\"Classifies new unread inbox emails, archives spam, drafts replies for important ones, posts urgent items to Slack immediately.\\\",\\n  input: z.object({\\n    emails: z.array(\\n      z.object({\\n        message_id: z.string(),\\n        thread_id: z.string(),\\n        subject: z.string(),\\n        from: z.string(),\\n        date: z.string(),\\n        body: z.string(),\\n        gmail_link: z.string(),\\n      }),\\n    ),\\n  }),\\n  output: z.object({\\n    archived: z.number(),\\n    urgent: z.number(),\\n    digested: z.number(),\\n    left: z.number(),\\n  }),\\n  async run(input) {\\n    if (input.emails.length === 0) {\\n      return { archived: 0, urgent: 0, digested: 0, left: 0 };\\n    }\\n\\n    const pendingDigestId = await resolveLabelId(LABEL_PENDING_DIGEST);\\n    const handledId = await resolveLabelId(LABEL_HANDLED);\\n\\n    const emailData = input.emails\\n      .map(\\n        (e) =>\\n          `ID: ${e.message_id}\\\\nFrom: ${e.from}\\\\nSubject: ${e.subject}\\\\nDate: ${e.date}\\\\nBody: ${e.body}`,\\n      )\\n      .join(\\\"\\\\n---\\\\n\\\");\\n\\n    const { classifications } = await promptLlm(\\n      `You are Sheila, ${OWNER_NAME}'s AI secretary. Classify each email into exactly one bucket.\\n\\n${TRIAGE_RULES}\\n\\nEmails to classify:\\n${emailData}\\n\\nFor each email, provide:\\n- message_id: the exact email ID\\n- bucket: \\\"archive\\\" | \\\"urgent\\\" | \\\"digest\\\" | \\\"leave\\\"\\n- category: the contact category or null if archive/leave\\n- summary: one-line summary of what the email is about\\n- draft_reply: if bucket is \\\"urgent\\\" or \\\"digest\\\", write a draft reply in the owner's voice. Only the reply body, no subject. If archive or leave, use null.`,\\n      { model: \\\"anthropic/claude-sonnet-5\\\", outputSchema: TriageResult },\\n    );\\n\\n    const classified = classifications ?? [];\\n\\n    if (classified.length === 0) {\\n      return { archived: 0, urgent: 0, digested: 0, left: input.emails.length };\\n    }\\n\\n    const archiveIds = classified.filter((c) => c.bucket === \\\"archive\\\").map((c) => c.message_id);\\n\\n    if (archiveIds.length > 0) {\\n      await gmailBatchModifyMessages.run({\\n        messageIds: archiveIds,\\n        removeLabelIds: [\\\"INBOX\\\", \\\"UNREAD\\\"],\\n        addLabelIds: [handledId],\\n      });\\n    }\\n\\n    const urgentItems = classified.filter((c) => c.bucket === \\\"urgent\\\");\\n\\n    for (const c of urgentItems) {\\n      const email = input.emails.find((e) => e.message_id === c.message_id);\\n      if (!email) continue;\\n\\n      if (c.draft_reply) {\\n        const recipient = extractEmail(email.from);\\n        await gmailCreateEmailDraft.run({\\n          thread_id: email.thread_id || undefined,\\n          recipient_email: recipient,\\n          body: c.draft_reply,\\n        });\\n      }\\n\\n      const draftNote = c.draft_reply\\n        ? `**Draft in Gmail:** ${c.draft_reply.slice(0, 200)}${c.draft_reply.length > 200 ? \\\"...\\\" : \\\"\\\"}`\\n        : \\\"No draft — review manually.\\\";\\n\\n      await slackbotSendMessage.run({\\n        channel: SHEILA_CHANNEL,\\n        markdown_text: `🚨 **URGENT** — ${c.summary}\\\\n\\\\nFrom: ${email.from}\\\\n${email.gmail_link}\\\\n\\\\n${draftNote}`,\\n      });\\n    }\\n\\n    const digestItems = classified.filter((c) => c.bucket === \\\"digest\\\");\\n    const digestIds = digestItems.map((c) => c.message_id);\\n\\n    if (digestIds.length > 0) {\\n      await gmailBatchModifyMessages.run({\\n        messageIds: digestIds,\\n        addLabelIds: [pendingDigestId],\\n      });\\n\\n      for (const c of digestItems) {\\n        if (!c.draft_reply) continue;\\n        const email = input.emails.find((e) => e.message_id === c.message_id);\\n        if (!email) continue;\\n\\n        const recipient = extractEmail(email.from);\\n        await gmailCreateEmailDraft.run({\\n          thread_id: email.thread_id || undefined,\\n          recipient_email: recipient,\\n          body: c.draft_reply,\\n        });\\n      }\\n    }\\n\\n    const leftCount = classified.filter((c) => c.bucket === \\\"leave\\\").length;\\n\\n    return {\\n      archived: archiveIds.length,\\n      urgent: urgentItems.length,\\n      digested: digestIds.length,\\n      left: leftCount,\\n    };\\n  },\\n});\\n\\nfunction extractEmail(fromHeader: string): string {\\n  const match = fromHeader.match(/<(.+?)>/);\\n  return match ? match[1]! : fromHeader.trim();\\n}\\n\",\n\t\t\t\"src/workflows/meeting-prep.ts\": \"import { defineWorkflow, promptLlm } from \\\"@keystrokehq/keystroke/workflow\\\";\\nimport { z } from \\\"zod\\\";\\nimport sheila from \\\"../agents/sheila\\\";\\nimport { googlecalendarEventsGet } from \\\"@keystrokehq/googlecalendar/actions\\\";\\nimport { gmailFetchEmails } from \\\"@keystrokehq/gmail/actions\\\";\\nimport {\\n  googlemeetGetTranscriptsByConferenceRecordId,\\n  googlemeetListConferenceRecords,\\n  googlemeetListTranscriptEntries,\\n} from \\\"@keystrokehq/googlemeet/actions\\\";\\nimport { slackbotSearchMessages, slackbotSendMessage } from \\\"@keystrokehq/slackbot/actions\\\";\\nimport { OWNER_NAME, SHEILA_CHANNEL } from \\\"../lib/config\\\";\\n\\nfunction resourceId(name: string, segment: string): string | null {\\n  const match = name.match(new RegExp(`${segment}/([^/]+)`));\\n  return match?.[1] ?? null;\\n}\\n\\nexport default defineWorkflow({\\n  slug: \\\"meeting-prep\\\",\\n  name: \\\"Meeting Prep\\\",\\n  description:\\n    \\\"Gathers context for upcoming meetings and posts briefings to the Sheila Slack channel.\\\",\\n  input: z.object({\\n    meetings: z.array(\\n      z.object({\\n        event_id: z.string(),\\n        summary: z.string(),\\n        start_time: z.string(),\\n        attendees: z.array(z.string()).default([]),\\n      }),\\n    ),\\n  }),\\n  output: z.object({\\n    briefings: z.array(z.string()),\\n  }),\\n  async run(input) {\\n    const briefings: string[] = [];\\n\\n    for (const meeting of input.meetings) {\\n      const eventDetails = await googlecalendarEventsGet.run({\\n        calendar_id: \\\"primary\\\",\\n        event_id: meeting.event_id,\\n      });\\n\\n      const eventDescription =\\n        (eventDetails as { description?: string }).description ?? \\\"no description\\\";\\n\\n      let emailContext = \\\"\\\";\\n      for (const email of meeting.attendees) {\\n        const emails = await gmailFetchEmails.run({\\n          query: `from:${email}`,\\n          max_results: 5,\\n          verbose: false,\\n        });\\n        type Msg = { subject?: string; snippet?: string; date?: string };\\n        const messages = (emails as { messages?: Msg[] }).messages ?? [];\\n        if (messages.length > 0) {\\n          emailContext += `\\\\n### Emails with ${email}\\\\n`;\\n          for (const m of messages) {\\n            emailContext += `- ${m.date ?? \\\"\\\"}: ${m.subject ?? \\\"(no subject)\\\"} — ${m.snippet ?? \\\"\\\"}\\\\n`;\\n          }\\n        }\\n      }\\n\\n      let transcriptContext = \\\"\\\";\\n      try {\\n        const confRecords = await googlemeetListConferenceRecords.run({});\\n        type ConfRecord = { name?: string | null };\\n        const records =\\n          (confRecords as { conference_records?: ConfRecord[] }).conference_records ?? [];\\n        for (const record of records.slice(0, 5)) {\\n          const recordName = record.name ?? \\\"\\\";\\n          const conferenceRecordId = resourceId(recordName, \\\"conferenceRecords\\\");\\n          if (!conferenceRecordId) continue;\\n\\n          const transcriptsResult = await googlemeetGetTranscriptsByConferenceRecordId.run({\\n            conference_record_id: conferenceRecordId,\\n          });\\n          type Transcript = { name?: string | null };\\n          const transcripts =\\n            (transcriptsResult as { transcripts?: Transcript[] }).transcripts ?? [];\\n\\n          for (const transcript of transcripts.slice(0, 2)) {\\n            const transcriptId = resourceId(transcript.name ?? \\\"\\\", \\\"transcripts\\\");\\n            if (!transcriptId) continue;\\n\\n            const entriesResult = await googlemeetListTranscriptEntries.run({\\n              conference_record_id: conferenceRecordId,\\n              transcript_id: transcriptId,\\n            });\\n            type Entry = { text?: string | null; participant?: string | null };\\n            const entries =\\n              (entriesResult as { transcriptEntries?: Entry[] }).transcriptEntries ?? [];\\n            if (entries.length === 0) continue;\\n\\n            transcriptContext += `\\\\n### Past call transcript (${conferenceRecordId})\\\\n`;\\n            for (const e of entries.slice(0, 40)) {\\n              transcriptContext += `${e.participant ?? \\\"Speaker\\\"}: ${e.text ?? \\\"\\\"}\\\\n`;\\n            }\\n          }\\n        }\\n      } catch {\\n        transcriptContext = \\\"\\\";\\n      }\\n\\n      let slackContext = \\\"\\\";\\n      for (const attendee of meeting.attendees) {\\n        const slackResult = await slackbotSearchMessages.run({\\n          query: attendee,\\n          count: 10,\\n        });\\n        type SlackMsg = { text?: string; channel?: { name?: string } };\\n        const sm = (slackResult as { messages?: { matches?: SlackMsg[] } }).messages?.matches ?? [];\\n        if (sm.length > 0) {\\n          slackContext += `\\\\n### Slack mentions of ${attendee}\\\\n`;\\n          for (const m of sm) {\\n            slackContext += `- [${m.channel?.name ?? \\\"?\\\"}] ${m.text ?? \\\"\\\"}\\\\n`;\\n          }\\n        }\\n      }\\n\\n      const isFirstMeeting = emailContext === \\\"\\\" && transcriptContext === \\\"\\\" && slackContext === \\\"\\\";\\n\\n      let briefing: string;\\n\\n      if (isFirstMeeting) {\\n        const result = await sheila.prompt({\\n          message: `First-time meeting with ${meeting.attendees.join(\\\", \\\")}. Meeting: ${meeting.summary} at ${meeting.start_time}. Do quick web research on the people/company, then write a concise briefing in ${OWNER_NAME}'s voice (terse, professional, a little fun). Format: attendees, company summary, what they likely care about, suggested talking points. Bullets, not paragraphs. Return the briefing text only.`,\\n        });\\n        briefing =\\n          result.messages\\n            ?.filter((m) => m.role === \\\"assistant\\\")\\n            .map((m) => m.parts.filter((p) => p.type === \\\"text\\\").map((p) => p.text))\\n            .flat()\\n            .join(\\\"\\\\n\\\") ?? \\\"Briefing failed.\\\";\\n\\n        await slackbotSendMessage.run({\\n          channel: SHEILA_CHANNEL,\\n          markdown_text: briefing,\\n        });\\n      } else {\\n        const briefingText = await promptLlm(\\n          `You are writing a pre-meeting briefing for ${OWNER_NAME} in their voice: concise, information-dense, terse but not rude, a little fun. Professional.\\n\\nMeeting: ${meeting.summary}\\nStarts: ${meeting.start_time}\\nAttendees: ${meeting.attendees.join(\\\", \\\")}\\n\\nEvent description: ${eventDescription}\\n\\n${emailContext ? `## Past email context${emailContext}` : \\\"No past emails.\\\"}\\n\\n${transcriptContext ? `## Past call transcripts${transcriptContext}` : \\\"No prior transcripts.\\\"}\\n\\n${slackContext ? `## Slack context${slackContext}` : \\\"No relevant Slack history.\\\"}\\n\\nWrite the briefing. Format:\\n\\n**Meeting: ${meeting.summary}** — ${meeting.start_time}\\n\\n**Attendees**: [names + companies]\\n\\n**Last interaction**: [one-line summary of most recent email/call]\\n\\n**Key context**:\\n- [bullets]\\n\\n**Open items / follow-ups**:\\n- [any action items from prior calls or threads]\\n\\n**Slack context**: [anything relevant, or \\\"no relevant Slack history\\\"]\\n\\nKeep it short. Bullets, not paragraphs.`,\\n          { model: \\\"anthropic/claude-sonnet-5\\\" },\\n        );\\n\\n        briefing = briefingText;\\n\\n        await slackbotSendMessage.run({\\n          channel: SHEILA_CHANNEL,\\n          markdown_text: briefingText,\\n        });\\n      }\\n\\n      briefings.push(briefing);\\n    }\\n\\n    return { briefings };\\n  },\\n});\\n\"\n\t\t}\n\t}\n];\n//#endregion\n//#region src/templates/seed.ts\n/** Stable Postgres advisory-lock key for official template seeding. */\nconst TEMPLATE_SEED_LOCK_KEY = \"seed:official-templates\";\nasync function tryAcquireTemplateSeedLock() {\n\tif (getDatabaseHandle().dialect === \"sqlite\") return true;\n\tconst row = (await getDb().execute(sql`SELECT pg_try_advisory_lock(hashtext(${TEMPLATE_SEED_LOCK_KEY})) AS locked`)).rows[0];\n\treturn row?.locked === true || row?.locked === \"t\";\n}\nasync function releaseTemplateSeedLock() {\n\tif (getDatabaseHandle().dialect === \"sqlite\") return;\n\tawait getDb().execute(sql`SELECT pg_advisory_unlock(hashtext(${TEMPLATE_SEED_LOCK_KEY}))`);\n}\n/**\n* Upsert official templates from the build-packed seed artifact.\n* Uses a non-blocking Postgres advisory lock so only one platform machine seeds.\n* Returns whether this process ran the seed (vs skipped because another holds the lock).\n*/\nasync function seedOfficialTemplates(entries = OFFICIAL_TEMPLATE_SEED) {\n\tif (!await tryAcquireTemplateSeedLock()) return { ran: false };\n\ttry {\n\t\tawait upsertTemplatesFromSeed(entries);\n\t\treturn { ran: true };\n\t} finally {\n\t\tawait releaseTemplateSeedLock();\n\t}\n}\n//#endregion\n//#region src/templates/load-from-dir.ts\nasync function walkFiles(dir) {\n\tconst entries = await readdir(dir, { withFileTypes: true });\n\tconst files = [];\n\tfor (const entry of entries) {\n\t\tconst full = join(dir, entry.name);\n\t\tif (entry.isDirectory()) files.push(...await walkFiles(full));\n\t\telse if (entry.isFile()) files.push(full);\n\t}\n\treturn files;\n}\n/** Read official template packs from a directory of pack folders (each with template.json + src/). */\nasync function loadOfficialTemplatesFromDir(templatesRoot) {\n\tconst packDirs = (await readdir(templatesRoot, { withFileTypes: true })).filter((entry) => entry.isDirectory() && !entry.name.startsWith(\".\")).map((entry) => entry.name).sort();\n\tconst packs = [];\n\tfor (const slug of packDirs) {\n\t\tconst packRoot = join(templatesRoot, slug);\n\t\tconst manifestPath = join(packRoot, \"template.json\");\n\t\tif (!(await stat(manifestPath).catch(() => null))?.isFile()) continue;\n\t\tconst manifest = TemplateManifestSchema.parse(JSON.parse(await readFile(manifestPath, \"utf8\")));\n\t\tconst srcRoot = join(packRoot, \"src\");\n\t\tif (!(await stat(srcRoot).catch(() => null))?.isDirectory()) throw new Error(`Template pack ${slug} is missing src/`);\n\t\tconst filePaths = (await walkFiles(srcRoot)).sort();\n\t\tconst files = {};\n\t\tfor (const absolute of filePaths) {\n\t\t\tconst rel = relative(packRoot, absolute).split(\"\\\\\").join(\"/\");\n\t\t\tfiles[rel] = await readFile(absolute, \"utf8\");\n\t\t}\n\t\tpacks.push({\n\t\t\tslug,\n\t\t\tkind: manifest.kind,\n\t\t\ttitle: manifest.title,\n\t\t\tdescription: manifest.description,\n\t\t\ttags: manifest.tags,\n\t\t\trequiredApps: manifest.requiredApps,\n\t\t\tfiles\n\t\t});\n\t}\n\treturn packs;\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\tcredentialFields: entry.credentialFields ?? {},\n\t\tcredentialScheme: entry.credentialScheme ?? null\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, DeployLeaseLostError, LastOwnerError, ORG_PLATFORM_API_KEY_CONFIG_ID, OrgAppSlugTakenError, OrgPlatformApiKeyNotFoundError, OrganizationInvitationExpiredError, OrganizationInvitationForbiddenError, OrganizationInvitationNotFoundError, OrganizationMemberNotFoundError, OrganizationSlugTakenError, PLATFORM_AGENT_AGENT_END_EVENT_TYPE, PLATFORM_AGENT_AGENT_START_EVENT_TYPE, PLATFORM_AGENT_CONTEXT_COMPACTED_EVENT_TYPE, PLATFORM_AGENT_IDLE_STATUSES, PLATFORM_AGENT_MESSAGE_EVENT_TYPE, PLATFORM_AGENT_SESSION_LIST_LIMIT, PLATFORM_AGENT_SNAPSHOT_BUILD_STALE_MS, PLATFORM_AGENT_STARTABLE_STATUSES, PROJECT_AGENT_ENV_IMAGE_BUILD_STALE_MS, PROJECT_DEPLOY_LEASE_TTL_MS, ProjectArtifactSourceManifestConflictError, ProjectMemberNotFoundError, ProjectSlugTakenError, TENANT_RUNTIME_ROLE, WEBHOOK_API_KEY_CONFIG_ID, abortStagedProjectDeploy, acceptInvitation, addUserToDefaultOrgProjectInTransaction, appendPlatformAgentEvent, applyLedgerCredit, applyLedgerDebit, apps, backfillProjectUsers, bindOrganizationScope, buildDefaultOrgProjectName, buildOrgDatabaseUrl, buildOrgRedisUrl, buildTenantRuntimeDatabaseUrl, cancelPlatformAgentRun, cancelProjectDeploy, checkOrgAppSlugAvailability, checkOrganizationSlugAvailability, checkProjectSlugAvailability, claimAutoTopupPendingIntent, claimCreditExhaustedSent, claimCreditWarningSent, claimPlatformAgentProjectSnapshotCaptureGeneration, claimProjectAgentEnvImageBuild, clearAutoTopupPendingIntent, clearCreditAlertFlags, clearPlatformAgentProjectSnapshotRecovery, clearPlatformAgentSessionSandbox, clearProjectAgentSessionModalImage, clearProjectAgentSessionSandbox, closeDatabase, completePlatformAgentProjectSnapshot, completePlatformAgentRun, completeProjectAgentEnvImageBuild, completeProjectArtifact, completeProjectArtifactUnderDeployLease, countActiveMembersForOrganization, countActiveProjectsForOrganization, countPlatformAgentMessageEvents, countPlatformAgentMessageEventsBySessionIds, createConnection, createOrgAgentStorageClient, createOrgApp, createOrgContainerPresign, createOrgPlatformApiKey, createOrgStorageClient, createOrganizationForUser, createPgConnection, createProjectForOrganization, createPublishedFormToken, createRunningPlatformAgentSession, createSqliteConnection, declineInvitation, decryptCredentialPayload, decryptOAuthAppSigningSecret, deleteManagedServiceCredential, deleteOAuthAppBySlug, deleteOAuthConnectionById, deleteOrgApp, deleteProjectArtifactIfUnreferenced, deleteProjectForOrganization, deleteSecretValuesForRef, deprovisionOrgDatabase, deprovisionOrgRedis, detachPlatformAgentSessionSandboxForSnapshot, detachProjectAgentSessionSandboxForSnapshot, encryptCredentialPayload, ensureDefaultOrgProjectInTransaction, ensureDefaultOrganization, ensureDefaultOrganizationAndProject, ensureDefaultProject, ensureOAuthApp, ensureOrgPgBossGrants, ensureOrgPlatformApiKey, ensureProjectPgBossGrants, ensureProjectRepositoryRow, ensureTenantRuntimeRole, ensureWebhookApiKeyForRoute, ensureWebhookApiKeys, failPlatformAgentProjectSnapshot, failPlatformAgentRun, failProjectAgentEnvImageBuild, finalizePlatformAgentRun, findOrCreateUserByEmail, getBillingWallet, getDatabaseHandle, getDecryptedOAuthAppById, getDecryptedOAuthAppBySlug, getDecryptedOAuthConnectionByAppSlugAndExternalId, getDecryptedOAuthConnectionById, getDecryptedOAuthConnectionsByAppSlug, getGlobalOAuthAccessTokenByAppSlugAndExternalId, getManagedServiceCredential, getOAuthAppSigningSecretBySlugGlobal, getOrCreateBillingWallet, getOrCreateOrganizationBilling, getOrganizationScopeId, getWorkspaceContext, grantWelcomeCreditsIfEligible, hasCredentialFieldTemplate, hasOrganizationMembership, hasPlatformAgentEventAfterSeq, initDatabase, insertBillingEvent, insertManagedServiceCredential, insertOAuthApp, insertProjectArtifact, insertUsageEventsAndSettle, invalidateReadyProjectAgentEnvImage, inviteOrganizationMembers, inviteProjectMembers, isDatabaseInitialized, isOrganizationStorageBucketInUse, isStandaloneMode, latestDurablePlatformAgentCompactionCheckpoint, latestPlatformAgentEventByTypes, listActiveOwnerAdminEmails, listAppsForOrganization, listBillingLedgerEntries, listDecryptedOAuthConnections, listIdlePlatformAgentSessionSandboxes, listIdleProjectAgentSessionImages, listIdleProjectAgentSessionSandboxes, listManagedServiceCredentialsForOrganization, listOAuthApps, listOAuthAppsBySlackAppIdGlobal, listOAuthAppsBySlugPrefix, listOAuthAppsBySlugUnscoped, listOAuthConnectionsByAppId, listOAuthInstallationsByAppSlugAndExternalId, listOfficialApps, listOrgPlatformApiKeysForOrganization, listOrgPlatformApiKeysForUser, listPlatformAgentCompactionEvents, listPlatformAgentEvents, listPlatformAgentEventsByType, listPlatformAgentMessageEventRecords, listPlatformAgentSessionsForOrgUser, listPlatformAgentSessionsForOwner, listPlatformAgentTranscriptMessages, listPublishedFormsForOrganization, listTemplates, listUsageEventsForRuns, listWebhookApiKeys, listWebhookApiKeysForProject, listWebhookApiKeysForProjects, loadOfficialTemplatesFromDir, loadOrgPlatformApiKeyUser, mapOrgPlatformApiKeyCreator, mapOrgPlatformApiKeyCreatorOrDeleted, markProjectRepositoryContentStatus, markProjectRepositoryDeleted, markProjectRepositoryFailed, markProjectRepositoryPlatformAgentScaffolded, markProjectRepositoryReady, mcpProjectApiKeyName, normalizeUserEmail, orgDbRoleName, orgDbSchemaName, orgRedisAclSetUserArgs, orgRedisQueueSegment, orgRedisUsername, orgSchedulerRuntimeEnv, orgWorkspacesRuntimeEnv, organizationInvitationStatuses, organizationQualifiesForWelcomeCredits, organizationRowToSidebarBranding, organizationUserRoles, platformAgentEndEventId, platformAgentMessageEventId, platformAgentProjectSnapshotBuildStatuses, platformAgentProjectSnapshotRecoveryStates, platformAgentStartEventId, projectArtifactStatuses, projectStatuses, promoteProjectArtifact, provisionOrgDatabase, provisionOrgRedis, putOAuthPendingState, reconcileWalletAgainstLedger, refreshProjectDeployLease, releaseProjectDeployLease, removeOrganizationMember, removeProjectMember, replacePlatformAgentProjectSnapshotImage, replaceProjectAgentSessionModalImage, requestProjectRepositoryDeletion, requireOrganizationScopeId, requireWorkspaceContext, resetWalletPlanPeriod, resolveMigrationsFolder, resolveNewOrganizationIdentity, resolveOAuthAccessToken, resolveOrgDatabaseUrl, resolveOrgProjectDatabaseOptions, resolveOrgRuntimeDatabase, resolveOrgStorageConfig, resolvePlatformDatabaseUrl, resolvePlatformPostgresConfig, resolveTenantDatabaseUrl, revokeOrgPlatformApiKey, rotatePublishedFormToken, runMigrations, runWithOrganizationScope, runWithStandaloneScope, runWithWorkspaceContext, saveOAuthConnection, seedOfficialApps, seedOfficialTemplates, selectActiveArtifactManifestForProject, selectActiveArtifactManifestsByOrganizationId, selectActiveArtifactSourceManifestForProject, selectActiveArtifactSourceRevisionForProject, selectActiveOrganizationIds, selectActiveProjectArtifactForProject, selectAppBySlug, selectAppForOrganization, selectEnabledPublishedFormByToken, selectLastDeploymentAtByProject, selectLatestBillingEventAt, selectManagedServiceCredentialById, selectOAuthAppById, selectOAuthAppBySlug, selectOAuthConnectionByAppAndExternalId, selectOAuthConnectionById, selectOAuthConnectionsByIds, selectOAuthInstallationsByAppSlugAndExternalId, selectOrgAppBySlug, selectOrgPlatformApiKeyForOrganization, selectOrganizationBillingByStripeCustomerId, selectOrganizationById, selectOrganizationBySlug, selectOrganizationMembers, selectOrganizationUsersByUserId, selectPendingInvitationsForUser, selectPlatformAgentProjectSnapshot, selectPlatformAgentSessionForOrgUser, selectPlatformAgentSessionForOwner, selectPlatformAgentSessionForReconnect, selectProjectAgentEnvImageByOrgHash, selectProjectAgentSessionSandbox, selectProjectAgentSessionSandboxByScope, selectProjectArtifactById, selectProjectArtifactForProject, selectProjectArtifactSourceManifestForProject, selectProjectArtifactSourceRevisionForProject, selectProjectById, selectProjectDeployments, selectProjectForOrganization, selectProjectForOrganizationBySlug, selectProjectIdsForUser, selectProjectMembers, selectProjectRepositoryByProjectId, selectProjectsByOrganizationId, selectPublishedFormForWorkflow, selectReadyProjectAgentEnvImageId, selectSecretValue, selectTemplateBySlug, selectUserByEmail, selectUserById, selectUserByNormalizedEmail, selectUserOrganization, selectUserOrganizationMembership, selectUserOrganizations, selectUserProjectMembership, selectUsersByIds, setPlatformAgentSessionPackageManager, setPlatformAgentSessionSandbox, setProjectAgentSessionSandbox, summarizeUsageByMeter, summarizeUsageForRuns, takeOAuthPendingState, templates, touchPlatformAgentSessionSandbox, touchProjectAgentSessionSandbox, transitionProjectArtifactProtocolState, tryAcquireProjectDeployLease, tryStartPlatformAgentRun, unpublishFormForWorkflow, updateManagedServiceCredentialValue, updateOAuthAppBySlug, updateOAuthAppMetadataBySlug, updateOrganizationActive, updateOrganizationBilling, updateOrganizationFailed, updateOrganizationMemberRole, updateOrganizationName, updateOrganizationSidebarBranding, updateOrganizationSlug, updatePlatformAgentLastDraftCommitSha, updatePlatformAgentSessionTitle, updateProjectActive, updateProjectArtifactCandidate, updateProjectArtifactManifest, updateProjectArtifactProtocolState, updateProjectArtifactSourceManifest, updateProjectFailed, updateProjectForOrganization, updateProjectMemberRole, updateProjectSettings, updateUserById, upsertOAuthConnection, upsertOfficialApp, upsertOrganizationClaimSecret, upsertPlatformAgentProjectSnapshotBuilding, upsertProjectMember, upsertPublishedForm, upsertSecretValue, upsertTemplate, upsertTemplatesFromSeed, userOwnsOtherOrgWithWelcomeCredits, verifyOrgPlatformApiKeySecret, verifyWebhookApiKeyForRoute, webhookApiKeyName, webhookEndpointSuffix };\n\n//# sourceMappingURL=index.mjs.map","class ParseError extends Error {\n  constructor(message, options) {\n    super(message), this.name = \"ParseError\", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;\n  }\n}\nconst LF = 10, CR = 13, SPACE = 32;\nfunction noop(_arg) {\n}\nfunction createParser(callbacks) {\n  if (typeof callbacks == \"function\")\n    throw new TypeError(\n      \"`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?\"\n    );\n  const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks, pendingFragments = [];\n  let isFirstChunk = !0, id, data = \"\", dataLines = 0, eventType;\n  function feed(chunk) {\n    if (isFirstChunk && (isFirstChunk = !1, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) {\n      const trailing2 = processLines(chunk);\n      trailing2 !== \"\" && pendingFragments.push(trailing2);\n      return;\n    }\n    if (chunk.indexOf(`\n`) === -1 && chunk.indexOf(\"\\r\") === -1) {\n      pendingFragments.push(chunk);\n      return;\n    }\n    pendingFragments.push(chunk);\n    const input = pendingFragments.join(\"\");\n    pendingFragments.length = 0;\n    const trailing = processLines(input);\n    trailing !== \"\" && pendingFragments.push(trailing);\n  }\n  function processLines(chunk) {\n    let searchIndex = 0;\n    if (chunk.indexOf(\"\\r\") === -1) {\n      let lfIndex = chunk.indexOf(`\n`, searchIndex);\n      for (; lfIndex !== -1; ) {\n        if (searchIndex === lfIndex) {\n          dataLines > 0 && onEvent({ id, event: eventType, data }), id = void 0, data = \"\", dataLines = 0, eventType = void 0, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`\n`, searchIndex);\n          continue;\n        }\n        const firstCharCode = chunk.charCodeAt(searchIndex);\n        if (isDataPrefix(chunk, searchIndex, firstCharCode)) {\n          const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex);\n          if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {\n            onEvent({ id, event: eventType, data: value }), id = void 0, data = \"\", eventType = void 0, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(`\n`, searchIndex);\n            continue;\n          }\n          data = dataLines === 0 ? value : `${data}\n${value}`, dataLines++;\n        } else isEventPrefix(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice(\n          chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6,\n          lfIndex\n        ) || void 0 : parseLine(chunk, searchIndex, lfIndex);\n        searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`\n`, searchIndex);\n      }\n      return chunk.slice(searchIndex);\n    }\n    for (; searchIndex < chunk.length; ) {\n      const crIndex = chunk.indexOf(\"\\r\", searchIndex), lfIndex = chunk.indexOf(`\n`, searchIndex);\n      let lineEnd = -1;\n      if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = crIndex < lfIndex ? crIndex : lfIndex : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1)\n        break;\n      parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF && searchIndex++;\n    }\n    return chunk.slice(searchIndex);\n  }\n  function parseLine(chunk, start, end) {\n    if (start === end) {\n      dispatchEvent();\n      return;\n    }\n    const firstCharCode = chunk.charCodeAt(start);\n    if (isDataPrefix(chunk, start, firstCharCode)) {\n      const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end);\n      data = dataLines === 0 ? value2 : `${data}\n${value2}`, dataLines++;\n      return;\n    }\n    if (isEventPrefix(chunk, start, firstCharCode)) {\n      eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || void 0;\n      return;\n    }\n    if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {\n      const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);\n      id = value2.includes(\"\\0\") ? void 0 : value2;\n      return;\n    }\n    if (firstCharCode === 58) {\n      if (onComment) {\n        const line2 = chunk.slice(start, end);\n        onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));\n      }\n      return;\n    }\n    const line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(\":\");\n    if (fieldSeparatorIndex === -1) {\n      processField(line, \"\", line);\n      return;\n    }\n    const field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);\n    processField(field, value, line);\n  }\n  function processField(field, value, line) {\n    switch (field) {\n      case \"event\":\n        eventType = value || void 0;\n        break;\n      case \"data\":\n        data = dataLines === 0 ? value : `${data}\n${value}`, dataLines++;\n        break;\n      case \"id\":\n        id = value.includes(\"\\0\") ? void 0 : value;\n        break;\n      case \"retry\":\n        /^\\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(\n          new ParseError(`Invalid \\`retry\\` value: \"${value}\"`, {\n            type: \"invalid-retry\",\n            value,\n            line\n          })\n        );\n        break;\n      default:\n        onError(\n          new ParseError(\n            `Unknown field \"${field.length > 20 ? `${field.slice(0, 20)}\\u2026` : field}\"`,\n            { type: \"unknown-field\", field, value, line }\n          )\n        );\n        break;\n    }\n  }\n  function dispatchEvent() {\n    dataLines > 0 && onEvent({\n      id,\n      event: eventType,\n      data\n    }), id = void 0, data = \"\", dataLines = 0, eventType = void 0;\n  }\n  function reset(options = {}) {\n    if (options.consume && pendingFragments.length > 0) {\n      const incompleteLine = pendingFragments.join(\"\");\n      parseLine(incompleteLine, 0, incompleteLine.length);\n    }\n    isFirstChunk = !0, id = void 0, data = \"\", dataLines = 0, eventType = void 0, pendingFragments.length = 0;\n  }\n  return { feed, reset };\n}\nfunction isDataPrefix(chunk, i, firstCharCode) {\n  return firstCharCode === 100 && chunk.charCodeAt(i + 1) === 97 && chunk.charCodeAt(i + 2) === 116 && chunk.charCodeAt(i + 3) === 97 && chunk.charCodeAt(i + 4) === 58;\n}\nfunction isEventPrefix(chunk, i, firstCharCode) {\n  return firstCharCode === 101 && chunk.charCodeAt(i + 1) === 118 && chunk.charCodeAt(i + 2) === 101 && chunk.charCodeAt(i + 3) === 110 && chunk.charCodeAt(i + 4) === 116 && chunk.charCodeAt(i + 5) === 58;\n}\nexport {\n  ParseError,\n  createParser\n};\n//# sourceMappingURL=index.js.map\n","import { createParser } from \"./index.js\";\nimport { ParseError } from \"./index.js\";\nclass EventSourceParserStream extends TransformStream {\n  constructor({ onError, onRetry, onComment } = {}) {\n    let parser;\n    super({\n      start(controller) {\n        parser = createParser({\n          onEvent: (event) => {\n            controller.enqueue(event);\n          },\n          onError(error) {\n            onError === \"terminate\" ? controller.error(error) : typeof onError == \"function\" && onError(error);\n          },\n          onRetry,\n          onComment\n        });\n      },\n      transform(chunk) {\n        parser.feed(chunk);\n      }\n    });\n  }\n}\nexport {\n  EventSourceParserStream,\n  ParseError\n};\n//# sourceMappingURL=stream.js.map\n","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';\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","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 * Utilities for handling OAuth resource URIs.\n */\n/**\n * Converts a server URL to a resource URL by removing the fragment.\n * RFC 8707 section 2 states that resource URIs \"MUST NOT include a fragment component\".\n * Keeps everything else unchanged (scheme, domain, port, path, query).\n */\nexport function resourceUrlFromServerUrl(url) {\n    const resourceURL = typeof url === 'string' ? new URL(url) : new URL(url.href);\n    resourceURL.hash = ''; // Remove fragment\n    return resourceURL;\n}\n/**\n * Checks if a requested resource URL matches a configured resource URL.\n * A requested resource matches if it has the same scheme, domain, port,\n * and its path starts with the configured resource's path.\n *\n * @param requestedResource The resource URL being requested\n * @param configuredResource The resource URL that has been configured\n * @returns true if the requested resource matches the configured resource, false otherwise\n */\nexport function checkResourceAllowed({ requestedResource, configuredResource }) {\n    const requested = typeof requestedResource === 'string' ? new URL(requestedResource) : new URL(requestedResource.href);\n    const configured = typeof configuredResource === 'string' ? new URL(configuredResource) : new URL(configuredResource.href);\n    // Compare the origin (scheme, domain, and port)\n    if (requested.origin !== configured.origin) {\n        return false;\n    }\n    // Handle cases like requested=/foo and configured=/foo/\n    if (requested.pathname.length < configured.pathname.length) {\n        return false;\n    }\n    // Check if the requested path starts with the configured path\n    // Ensure both paths end with / for proper comparison\n    // This ensures that if we have paths like \"/api\" and \"/api/users\",\n    // we properly detect that \"/api/users\" is a subpath of \"/api\"\n    // By adding a trailing slash if missing, we avoid false positives\n    // where paths like \"/api123\" would incorrectly match \"/api\"\n    const requestedPath = requested.pathname.endsWith('/') ? requested.pathname : requested.pathname + '/';\n    const configuredPath = configured.pathname.endsWith('/') ? configured.pathname : configured.pathname + '/';\n    return requestedPath.startsWith(configuredPath);\n}\n//# sourceMappingURL=auth-utils.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 pkceChallenge from 'pkce-challenge';\nimport { LATEST_PROTOCOL_VERSION } from '../types.js';\nimport { OAuthErrorResponseSchema, OpenIdProviderDiscoveryMetadataSchema } from '../shared/auth.js';\nimport { OAuthClientInformationFullSchema, OAuthMetadataSchema, OAuthProtectedResourceMetadataSchema, OAuthTokensSchema } from '../shared/auth.js';\nimport { checkResourceAllowed, resourceUrlFromServerUrl } from '../shared/auth-utils.js';\nimport { InvalidClientError, InvalidClientMetadataError, InvalidGrantError, OAUTH_ERRORS, OAuthError, ServerError, UnauthorizedClientError } from '../server/auth/errors.js';\nexport class UnauthorizedError extends Error {\n    constructor(message) {\n        super(message ?? 'Unauthorized');\n    }\n}\nfunction isClientAuthMethod(method) {\n    return ['client_secret_basic', 'client_secret_post', 'none'].includes(method);\n}\nconst AUTHORIZATION_CODE_RESPONSE_TYPE = 'code';\nconst AUTHORIZATION_CODE_CHALLENGE_METHOD = 'S256';\n/**\n * Determines the best client authentication method to use based on server support and client configuration.\n *\n * Priority order (highest to lowest):\n * 1. client_secret_basic (if client secret is available)\n * 2. client_secret_post (if client secret is available)\n * 3. none (for public clients)\n *\n * @param clientInformation - OAuth client information containing credentials\n * @param supportedMethods - Authentication methods supported by the authorization server\n * @returns The selected authentication method\n */\nexport function selectClientAuthMethod(clientInformation, supportedMethods) {\n    const hasClientSecret = clientInformation.client_secret !== undefined;\n    // Prefer the method returned by the server during client registration, if valid.\n    // When server metadata is present we also require the method to be listed as supported;\n    // when supportedMethods is empty (metadata omitted the field) the DCR hint stands alone.\n    if ('token_endpoint_auth_method' in clientInformation &&\n        clientInformation.token_endpoint_auth_method &&\n        isClientAuthMethod(clientInformation.token_endpoint_auth_method) &&\n        (supportedMethods.length === 0 || supportedMethods.includes(clientInformation.token_endpoint_auth_method))) {\n        return clientInformation.token_endpoint_auth_method;\n    }\n    // If server metadata omits token_endpoint_auth_methods_supported, RFC 8414 §2 says the\n    // default is client_secret_basic. RFC 6749 §2.3.1 also requires servers to support HTTP\n    // Basic authentication for clients with a secret, making it the safest default.\n    if (supportedMethods.length === 0) {\n        return hasClientSecret ? 'client_secret_basic' : 'none';\n    }\n    // Try methods in priority order (most secure first)\n    if (hasClientSecret && supportedMethods.includes('client_secret_basic')) {\n        return 'client_secret_basic';\n    }\n    if (hasClientSecret && supportedMethods.includes('client_secret_post')) {\n        return 'client_secret_post';\n    }\n    if (supportedMethods.includes('none')) {\n        return 'none';\n    }\n    // Fallback: use what we have\n    return hasClientSecret ? 'client_secret_post' : 'none';\n}\n/**\n * Applies client authentication to the request based on the specified method.\n *\n * Implements OAuth 2.1 client authentication methods:\n * - client_secret_basic: HTTP Basic authentication (RFC 6749 Section 2.3.1)\n * - client_secret_post: Credentials in request body (RFC 6749 Section 2.3.1)\n * - none: Public client authentication (RFC 6749 Section 2.1)\n *\n * @param method - The authentication method to use\n * @param clientInformation - OAuth client information containing credentials\n * @param headers - HTTP headers object to modify\n * @param params - URL search parameters to modify\n * @throws {Error} When required credentials are missing\n */\nfunction applyClientAuthentication(method, clientInformation, headers, params) {\n    const { client_id, client_secret } = clientInformation;\n    switch (method) {\n        case 'client_secret_basic':\n            applyBasicAuth(client_id, client_secret, headers);\n            return;\n        case 'client_secret_post':\n            applyPostAuth(client_id, client_secret, params);\n            return;\n        case 'none':\n            applyPublicAuth(client_id, params);\n            return;\n        default:\n            throw new Error(`Unsupported client authentication method: ${method}`);\n    }\n}\n/**\n * Applies HTTP Basic authentication (RFC 6749 Section 2.3.1)\n */\nfunction applyBasicAuth(clientId, clientSecret, headers) {\n    if (!clientSecret) {\n        throw new Error('client_secret_basic authentication requires a client_secret');\n    }\n    const credentials = btoa(`${clientId}:${clientSecret}`);\n    headers.set('Authorization', `Basic ${credentials}`);\n}\n/**\n * Applies POST body authentication (RFC 6749 Section 2.3.1)\n */\nfunction applyPostAuth(clientId, clientSecret, params) {\n    params.set('client_id', clientId);\n    if (clientSecret) {\n        params.set('client_secret', clientSecret);\n    }\n}\n/**\n * Applies public client authentication (RFC 6749 Section 2.1)\n */\nfunction applyPublicAuth(clientId, params) {\n    params.set('client_id', clientId);\n}\n/**\n * Parses an OAuth error response from a string or Response object.\n *\n * If the input is a standard OAuth2.0 error response, it will be parsed according to the spec\n * and an instance of the appropriate OAuthError subclass will be returned.\n * If parsing fails, it falls back to a generic ServerError that includes\n * the response status (if available) and original content.\n *\n * @param input - A Response object or string containing the error response\n * @returns A Promise that resolves to an OAuthError instance\n */\nexport async function parseErrorResponse(input) {\n    const statusCode = input instanceof Response ? input.status : undefined;\n    const body = input instanceof Response ? await input.text() : input;\n    try {\n        const result = OAuthErrorResponseSchema.parse(JSON.parse(body));\n        const { error, error_description, error_uri } = result;\n        const errorClass = OAUTH_ERRORS[error] || ServerError;\n        return new errorClass(error_description || '', error_uri);\n    }\n    catch (error) {\n        // Not a valid OAuth error response, but try to inform the user of the raw data anyway\n        const errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : ''}Invalid OAuth error response: ${error}. Raw body: ${body}`;\n        return new ServerError(errorMessage);\n    }\n}\n/**\n * Orchestrates the full auth flow with a server.\n *\n * This can be used as a single entry point for all authorization functionality,\n * instead of linking together the other lower-level functions in this module.\n */\nexport async function auth(provider, options) {\n    try {\n        return await authInternal(provider, options);\n    }\n    catch (error) {\n        // Handle recoverable error types by invalidating credentials and retrying\n        if (error instanceof InvalidClientError || error instanceof UnauthorizedClientError) {\n            await provider.invalidateCredentials?.('all');\n            return await authInternal(provider, options);\n        }\n        else if (error instanceof InvalidGrantError) {\n            await provider.invalidateCredentials?.('tokens');\n            return await authInternal(provider, options);\n        }\n        // Throw otherwise\n        throw error;\n    }\n}\nasync function authInternal(provider, { serverUrl, authorizationCode, scope, resourceMetadataUrl, fetchFn }) {\n    // Check if the provider has cached discovery state to skip discovery\n    const cachedState = await provider.discoveryState?.();\n    let resourceMetadata;\n    let authorizationServerUrl;\n    let metadata;\n    // If resourceMetadataUrl is not provided, try to load it from cached state\n    // This handles browser redirects where the URL was saved before navigation\n    let effectiveResourceMetadataUrl = resourceMetadataUrl;\n    if (!effectiveResourceMetadataUrl && cachedState?.resourceMetadataUrl) {\n        effectiveResourceMetadataUrl = new URL(cachedState.resourceMetadataUrl);\n    }\n    if (cachedState?.authorizationServerUrl) {\n        // Restore discovery state from cache\n        authorizationServerUrl = cachedState.authorizationServerUrl;\n        resourceMetadata = cachedState.resourceMetadata;\n        metadata =\n            cachedState.authorizationServerMetadata ?? (await discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn }));\n        // If resource metadata wasn't cached, try to fetch it for selectResourceURL\n        if (!resourceMetadata) {\n            try {\n                resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: effectiveResourceMetadataUrl }, fetchFn);\n            }\n            catch {\n                // RFC 9728 not available — selectResourceURL will handle undefined\n            }\n        }\n        // Re-save if we enriched the cached state with missing metadata\n        if (metadata !== cachedState.authorizationServerMetadata || resourceMetadata !== cachedState.resourceMetadata) {\n            await provider.saveDiscoveryState?.({\n                authorizationServerUrl: String(authorizationServerUrl),\n                resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(),\n                resourceMetadata,\n                authorizationServerMetadata: metadata\n            });\n        }\n    }\n    else {\n        // Full discovery via RFC 9728\n        const serverInfo = await discoverOAuthServerInfo(serverUrl, { resourceMetadataUrl: effectiveResourceMetadataUrl, fetchFn });\n        authorizationServerUrl = serverInfo.authorizationServerUrl;\n        metadata = serverInfo.authorizationServerMetadata;\n        resourceMetadata = serverInfo.resourceMetadata;\n        // Persist discovery state for future use\n        // TODO: resourceMetadataUrl is only populated when explicitly provided via options\n        // or loaded from cached state. The URL derived internally by\n        // discoverOAuthProtectedResourceMetadata() is not captured back here.\n        await provider.saveDiscoveryState?.({\n            authorizationServerUrl: String(authorizationServerUrl),\n            resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(),\n            resourceMetadata,\n            authorizationServerMetadata: metadata\n        });\n    }\n    const resource = await selectResourceURL(serverUrl, provider, resourceMetadata);\n    // Apply scope selection strategy (SEP-835):\n    // 1. WWW-Authenticate scope (passed via `scope` param)\n    // 2. PRM scopes_supported\n    // 3. Client metadata scope (user-configured fallback)\n    // The resolved scope is used consistently for both DCR and the authorization request.\n    const resolvedScope = scope || resourceMetadata?.scopes_supported?.join(' ') || provider.clientMetadata.scope;\n    // Handle client registration if needed\n    let clientInformation = await Promise.resolve(provider.clientInformation());\n    if (!clientInformation) {\n        if (authorizationCode !== undefined) {\n            throw new Error('Existing OAuth client information is required when exchanging an authorization code');\n        }\n        const supportsUrlBasedClientId = metadata?.client_id_metadata_document_supported === true;\n        const clientMetadataUrl = provider.clientMetadataUrl;\n        if (clientMetadataUrl && !isHttpsUrl(clientMetadataUrl)) {\n            throw new InvalidClientMetadataError(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${clientMetadataUrl}`);\n        }\n        const shouldUseUrlBasedClientId = supportsUrlBasedClientId && clientMetadataUrl;\n        if (shouldUseUrlBasedClientId) {\n            // SEP-991: URL-based Client IDs\n            clientInformation = {\n                client_id: clientMetadataUrl\n            };\n            await provider.saveClientInformation?.(clientInformation);\n        }\n        else {\n            // Fallback to dynamic registration\n            if (!provider.saveClientInformation) {\n                throw new Error('OAuth client information must be saveable for dynamic registration');\n            }\n            const fullInformation = await registerClient(authorizationServerUrl, {\n                metadata,\n                clientMetadata: provider.clientMetadata,\n                scope: resolvedScope,\n                fetchFn\n            });\n            await provider.saveClientInformation(fullInformation);\n            clientInformation = fullInformation;\n        }\n    }\n    // Non-interactive flows (e.g., client_credentials, jwt-bearer) don't need a redirect URL\n    const nonInteractiveFlow = !provider.redirectUrl;\n    // Exchange authorization code for tokens, or fetch tokens directly for non-interactive flows\n    if (authorizationCode !== undefined || nonInteractiveFlow) {\n        const tokens = await fetchToken(provider, authorizationServerUrl, {\n            metadata,\n            resource,\n            authorizationCode,\n            fetchFn\n        });\n        await provider.saveTokens(tokens);\n        return 'AUTHORIZED';\n    }\n    const tokens = await provider.tokens();\n    // Handle token refresh or new authorization\n    if (tokens?.refresh_token) {\n        try {\n            // Attempt to refresh the token\n            const newTokens = await refreshAuthorization(authorizationServerUrl, {\n                metadata,\n                clientInformation,\n                refreshToken: tokens.refresh_token,\n                resource,\n                addClientAuthentication: provider.addClientAuthentication,\n                fetchFn\n            });\n            await provider.saveTokens(newTokens);\n            return 'AUTHORIZED';\n        }\n        catch (error) {\n            // If this is a ServerError, or an unknown type, log it out and try to continue. Otherwise, escalate so we can fix things and retry.\n            if (!(error instanceof OAuthError) || error instanceof ServerError) {\n                // Could not refresh OAuth tokens\n            }\n            else {\n                // Refresh failed for another reason, re-throw\n                throw error;\n            }\n        }\n    }\n    const state = provider.state ? await provider.state() : undefined;\n    // Start new authorization flow\n    const { authorizationUrl, codeVerifier } = await startAuthorization(authorizationServerUrl, {\n        metadata,\n        clientInformation,\n        state,\n        redirectUrl: provider.redirectUrl,\n        scope: resolvedScope,\n        resource\n    });\n    await provider.saveCodeVerifier(codeVerifier);\n    await provider.redirectToAuthorization(authorizationUrl);\n    return 'REDIRECT';\n}\n/**\n * SEP-991: URL-based Client IDs\n * Validate that the client_id is a valid URL with https scheme\n */\nexport function isHttpsUrl(value) {\n    if (!value)\n        return false;\n    try {\n        const url = new URL(value);\n        return url.protocol === 'https:' && url.pathname !== '/';\n    }\n    catch {\n        return false;\n    }\n}\nexport async function selectResourceURL(serverUrl, provider, resourceMetadata) {\n    const defaultResource = resourceUrlFromServerUrl(serverUrl);\n    // If provider has custom validation, delegate to it\n    if (provider.validateResourceURL) {\n        return await provider.validateResourceURL(defaultResource, resourceMetadata?.resource);\n    }\n    // Only include resource parameter when Protected Resource Metadata is present\n    if (!resourceMetadata) {\n        return undefined;\n    }\n    // Validate that the metadata's resource is compatible with our request\n    if (!checkResourceAllowed({ requestedResource: defaultResource, configuredResource: resourceMetadata.resource })) {\n        throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`);\n    }\n    // Prefer the resource from metadata since it's what the server is telling us to request\n    return new URL(resourceMetadata.resource);\n}\n/**\n * Extract resource_metadata, scope, and error from WWW-Authenticate header.\n */\nexport function extractWWWAuthenticateParams(res) {\n    const authenticateHeader = res.headers.get('WWW-Authenticate');\n    if (!authenticateHeader) {\n        return {};\n    }\n    const [type, scheme] = authenticateHeader.split(' ');\n    if (type.toLowerCase() !== 'bearer' || !scheme) {\n        return {};\n    }\n    const resourceMetadataMatch = extractFieldFromWwwAuth(res, 'resource_metadata') || undefined;\n    let resourceMetadataUrl;\n    if (resourceMetadataMatch) {\n        try {\n            resourceMetadataUrl = new URL(resourceMetadataMatch);\n        }\n        catch {\n            // Ignore invalid URL\n        }\n    }\n    const scope = extractFieldFromWwwAuth(res, 'scope') || undefined;\n    const error = extractFieldFromWwwAuth(res, 'error') || undefined;\n    return {\n        resourceMetadataUrl,\n        scope,\n        error\n    };\n}\n/**\n * Extracts a specific field's value from the WWW-Authenticate header string.\n *\n * @param response The HTTP response object containing the headers.\n * @param fieldName The name of the field to extract (e.g., \"realm\", \"nonce\").\n * @returns The field value\n */\nfunction extractFieldFromWwwAuth(response, fieldName) {\n    const wwwAuthHeader = response.headers.get('WWW-Authenticate');\n    if (!wwwAuthHeader) {\n        return null;\n    }\n    const pattern = new RegExp(`${fieldName}=(?:\"([^\"]+)\"|([^\\\\s,]+))`);\n    const match = wwwAuthHeader.match(pattern);\n    if (match) {\n        // Pattern matches: field_name=\"value\" or field_name=value (unquoted)\n        return match[1] || match[2];\n    }\n    return null;\n}\n/**\n * Extract resource_metadata from response header.\n * @deprecated Use `extractWWWAuthenticateParams` instead.\n */\nexport function extractResourceMetadataUrl(res) {\n    const authenticateHeader = res.headers.get('WWW-Authenticate');\n    if (!authenticateHeader) {\n        return undefined;\n    }\n    const [type, scheme] = authenticateHeader.split(' ');\n    if (type.toLowerCase() !== 'bearer' || !scheme) {\n        return undefined;\n    }\n    const regex = /resource_metadata=\"([^\"]*)\"/;\n    const match = regex.exec(authenticateHeader);\n    if (!match) {\n        return undefined;\n    }\n    try {\n        return new URL(match[1]);\n    }\n    catch {\n        return undefined;\n    }\n}\n/**\n * Looks up RFC 9728 OAuth 2.0 Protected Resource Metadata.\n *\n * If the server returns a 404 for the well-known endpoint, this function will\n * return `undefined`. Any other errors will be thrown as exceptions.\n */\nexport async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn = fetch) {\n    const response = await discoverMetadataWithFallback(serverUrl, 'oauth-protected-resource', fetchFn, {\n        protocolVersion: opts?.protocolVersion,\n        metadataUrl: opts?.resourceMetadataUrl\n    });\n    if (!response || response.status === 404) {\n        await response?.body?.cancel();\n        throw new Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);\n    }\n    if (!response.ok) {\n        await response.body?.cancel();\n        throw new Error(`HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`);\n    }\n    return OAuthProtectedResourceMetadataSchema.parse(await response.json());\n}\n/**\n * Helper function to handle fetch with CORS retry logic\n */\nasync function fetchWithCorsRetry(url, headers, fetchFn = fetch) {\n    try {\n        return await fetchFn(url, { headers });\n    }\n    catch (error) {\n        if (error instanceof TypeError) {\n            if (headers) {\n                // CORS errors come back as TypeError, retry without headers\n                return fetchWithCorsRetry(url, undefined, fetchFn);\n            }\n            else {\n                // We're getting CORS errors on retry too, return undefined\n                return undefined;\n            }\n        }\n        throw error;\n    }\n}\n/**\n * Constructs the well-known path for auth-related metadata discovery\n */\nfunction buildWellKnownPath(wellKnownPrefix, pathname = '', options = {}) {\n    // Strip trailing slash from pathname to avoid double slashes\n    if (pathname.endsWith('/')) {\n        pathname = pathname.slice(0, -1);\n    }\n    return options.prependPathname ? `${pathname}/.well-known/${wellKnownPrefix}` : `/.well-known/${wellKnownPrefix}${pathname}`;\n}\n/**\n * Tries to discover OAuth metadata at a specific URL\n */\nasync function tryMetadataDiscovery(url, protocolVersion, fetchFn = fetch) {\n    const headers = {\n        'MCP-Protocol-Version': protocolVersion\n    };\n    return await fetchWithCorsRetry(url, headers, fetchFn);\n}\n/**\n * Determines if fallback to root discovery should be attempted\n */\nfunction shouldAttemptFallback(response, pathname) {\n    return !response || (response.status >= 400 && response.status < 500 && pathname !== '/');\n}\n/**\n * Generic function for discovering OAuth metadata with fallback support\n */\nasync function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) {\n    const issuer = new URL(serverUrl);\n    const protocolVersion = opts?.protocolVersion ?? LATEST_PROTOCOL_VERSION;\n    let url;\n    if (opts?.metadataUrl) {\n        url = new URL(opts.metadataUrl);\n    }\n    else {\n        // Try path-aware discovery first\n        const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname);\n        url = new URL(wellKnownPath, opts?.metadataServerUrl ?? issuer);\n        url.search = issuer.search;\n    }\n    let response = await tryMetadataDiscovery(url, protocolVersion, fetchFn);\n    // If path-aware discovery fails with 404 and we're not already at root, try fallback to root discovery\n    if (!opts?.metadataUrl && shouldAttemptFallback(response, issuer.pathname)) {\n        const rootUrl = new URL(`/.well-known/${wellKnownType}`, issuer);\n        response = await tryMetadataDiscovery(rootUrl, protocolVersion, fetchFn);\n    }\n    return response;\n}\n/**\n * Looks up RFC 8414 OAuth 2.0 Authorization Server Metadata.\n *\n * If the server returns a 404 for the well-known endpoint, this function will\n * return `undefined`. Any other errors will be thrown as exceptions.\n *\n * @deprecated This function is deprecated in favor of `discoverAuthorizationServerMetadata`.\n */\nexport async function discoverOAuthMetadata(issuer, { authorizationServerUrl, protocolVersion } = {}, fetchFn = fetch) {\n    if (typeof issuer === 'string') {\n        issuer = new URL(issuer);\n    }\n    if (!authorizationServerUrl) {\n        authorizationServerUrl = issuer;\n    }\n    if (typeof authorizationServerUrl === 'string') {\n        authorizationServerUrl = new URL(authorizationServerUrl);\n    }\n    protocolVersion ?? (protocolVersion = LATEST_PROTOCOL_VERSION);\n    const response = await discoverMetadataWithFallback(authorizationServerUrl, 'oauth-authorization-server', fetchFn, {\n        protocolVersion,\n        metadataServerUrl: authorizationServerUrl\n    });\n    if (!response || response.status === 404) {\n        await response?.body?.cancel();\n        return undefined;\n    }\n    if (!response.ok) {\n        await response.body?.cancel();\n        throw new Error(`HTTP ${response.status} trying to load well-known OAuth metadata`);\n    }\n    return OAuthMetadataSchema.parse(await response.json());\n}\n/**\n * Builds a list of discovery URLs to try for authorization server metadata.\n * URLs are returned in priority order:\n * 1. OAuth metadata at the given URL\n * 2. OIDC metadata endpoints at the given URL\n */\nexport function buildDiscoveryUrls(authorizationServerUrl) {\n    const url = typeof authorizationServerUrl === 'string' ? new URL(authorizationServerUrl) : authorizationServerUrl;\n    const hasPath = url.pathname !== '/';\n    const urlsToTry = [];\n    if (!hasPath) {\n        // Root path: https://example.com/.well-known/oauth-authorization-server\n        urlsToTry.push({\n            url: new URL('/.well-known/oauth-authorization-server', url.origin),\n            type: 'oauth'\n        });\n        // OIDC: https://example.com/.well-known/openid-configuration\n        urlsToTry.push({\n            url: new URL(`/.well-known/openid-configuration`, url.origin),\n            type: 'oidc'\n        });\n        return urlsToTry;\n    }\n    // Strip trailing slash from pathname to avoid double slashes\n    let pathname = url.pathname;\n    if (pathname.endsWith('/')) {\n        pathname = pathname.slice(0, -1);\n    }\n    // 1. OAuth metadata at the given URL\n    // Insert well-known before the path: https://example.com/.well-known/oauth-authorization-server/tenant1\n    urlsToTry.push({\n        url: new URL(`/.well-known/oauth-authorization-server${pathname}`, url.origin),\n        type: 'oauth'\n    });\n    // 2. OIDC metadata endpoints\n    // RFC 8414 style: Insert /.well-known/openid-configuration before the path\n    urlsToTry.push({\n        url: new URL(`/.well-known/openid-configuration${pathname}`, url.origin),\n        type: 'oidc'\n    });\n    // OIDC Discovery 1.0 style: Append /.well-known/openid-configuration after the path\n    urlsToTry.push({\n        url: new URL(`${pathname}/.well-known/openid-configuration`, url.origin),\n        type: 'oidc'\n    });\n    return urlsToTry;\n}\n/**\n * Discovers authorization server metadata with support for RFC 8414 OAuth 2.0 Authorization Server Metadata\n * and OpenID Connect Discovery 1.0 specifications.\n *\n * This function implements a fallback strategy for authorization server discovery:\n * 1. Attempts RFC 8414 OAuth metadata discovery first\n * 2. If OAuth discovery fails, falls back to OpenID Connect Discovery\n *\n * @param authorizationServerUrl - The authorization server URL obtained from the MCP Server's\n *                                 protected resource metadata, or the MCP server's URL if the\n *                                 metadata was not found.\n * @param options - Configuration options\n * @param options.fetchFn - Optional fetch function for making HTTP requests, defaults to global fetch\n * @param options.protocolVersion - MCP protocol version to use, defaults to LATEST_PROTOCOL_VERSION\n * @returns Promise resolving to authorization server metadata, or undefined if discovery fails\n */\nexport async function discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn = fetch, protocolVersion = LATEST_PROTOCOL_VERSION } = {}) {\n    const headers = {\n        'MCP-Protocol-Version': protocolVersion,\n        Accept: 'application/json'\n    };\n    // Get the list of URLs to try\n    const urlsToTry = buildDiscoveryUrls(authorizationServerUrl);\n    // Try each URL in order\n    for (const { url: endpointUrl, type } of urlsToTry) {\n        const response = await fetchWithCorsRetry(endpointUrl, headers, fetchFn);\n        if (!response) {\n            /**\n             * CORS error occurred - don't throw as the endpoint may not allow CORS,\n             * continue trying other possible endpoints\n             */\n            continue;\n        }\n        if (!response.ok) {\n            await response.body?.cancel();\n            // Continue looking for any 4xx response code.\n            if (response.status >= 400 && response.status < 500) {\n                continue; // Try next URL\n            }\n            throw new Error(`HTTP ${response.status} trying to load ${type === 'oauth' ? 'OAuth' : 'OpenID provider'} metadata from ${endpointUrl}`);\n        }\n        // Parse and validate based on type\n        if (type === 'oauth') {\n            return OAuthMetadataSchema.parse(await response.json());\n        }\n        else {\n            return OpenIdProviderDiscoveryMetadataSchema.parse(await response.json());\n        }\n    }\n    return undefined;\n}\n/**\n * Discovers the authorization server for an MCP server following\n * {@link https://datatracker.ietf.org/doc/html/rfc9728 | RFC 9728} (OAuth 2.0 Protected\n * Resource Metadata), with fallback to treating the server URL as the\n * authorization server.\n *\n * This function combines two discovery steps into one call:\n * 1. Probes `/.well-known/oauth-protected-resource` on the MCP server to find the\n *    authorization server URL (RFC 9728).\n * 2. Fetches authorization server metadata from that URL (RFC 8414 / OpenID Connect Discovery).\n *\n * Use this when you need the authorization server metadata for operations outside the\n * {@linkcode auth} orchestrator, such as token refresh or token revocation.\n *\n * @param serverUrl - The MCP resource server URL\n * @param opts - Optional configuration\n * @param opts.resourceMetadataUrl - Override URL for the protected resource metadata endpoint\n * @param opts.fetchFn - Custom fetch function for HTTP requests\n * @returns Authorization server URL, metadata, and resource metadata (if available)\n */\nexport async function discoverOAuthServerInfo(serverUrl, opts) {\n    let resourceMetadata;\n    let authorizationServerUrl;\n    try {\n        resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: opts?.resourceMetadataUrl }, opts?.fetchFn);\n        if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) {\n            authorizationServerUrl = resourceMetadata.authorization_servers[0];\n        }\n    }\n    catch {\n        // RFC 9728 not supported -- fall back to treating the server URL as the authorization server\n    }\n    // If we don't get a valid authorization server from protected resource metadata,\n    // fall back to the legacy MCP spec behavior: MCP server base URL acts as the authorization server\n    if (!authorizationServerUrl) {\n        authorizationServerUrl = String(new URL('/', serverUrl));\n    }\n    const authorizationServerMetadata = await discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn: opts?.fetchFn });\n    return {\n        authorizationServerUrl,\n        authorizationServerMetadata,\n        resourceMetadata\n    };\n}\n/**\n * Begins the authorization flow with the given server, by generating a PKCE challenge and constructing the authorization URL.\n */\nexport async function startAuthorization(authorizationServerUrl, { metadata, clientInformation, redirectUrl, scope, state, resource }) {\n    let authorizationUrl;\n    if (metadata) {\n        authorizationUrl = new URL(metadata.authorization_endpoint);\n        if (!metadata.response_types_supported.includes(AUTHORIZATION_CODE_RESPONSE_TYPE)) {\n            throw new Error(`Incompatible auth server: does not support response type ${AUTHORIZATION_CODE_RESPONSE_TYPE}`);\n        }\n        if (metadata.code_challenge_methods_supported &&\n            !metadata.code_challenge_methods_supported.includes(AUTHORIZATION_CODE_CHALLENGE_METHOD)) {\n            throw new Error(`Incompatible auth server: does not support code challenge method ${AUTHORIZATION_CODE_CHALLENGE_METHOD}`);\n        }\n    }\n    else {\n        authorizationUrl = new URL('/authorize', authorizationServerUrl);\n    }\n    // Generate PKCE challenge\n    const challenge = await pkceChallenge();\n    const codeVerifier = challenge.code_verifier;\n    const codeChallenge = challenge.code_challenge;\n    authorizationUrl.searchParams.set('response_type', AUTHORIZATION_CODE_RESPONSE_TYPE);\n    authorizationUrl.searchParams.set('client_id', clientInformation.client_id);\n    authorizationUrl.searchParams.set('code_challenge', codeChallenge);\n    authorizationUrl.searchParams.set('code_challenge_method', AUTHORIZATION_CODE_CHALLENGE_METHOD);\n    authorizationUrl.searchParams.set('redirect_uri', String(redirectUrl));\n    if (state) {\n        authorizationUrl.searchParams.set('state', state);\n    }\n    if (scope) {\n        authorizationUrl.searchParams.set('scope', scope);\n    }\n    if (scope?.includes('offline_access')) {\n        // if the request includes the OIDC-only \"offline_access\" scope,\n        // we need to set the prompt to \"consent\" to ensure the user is prompted to grant offline access\n        // https://openid.net/specs/openid-connect-core-1_0.html#OfflineAccess\n        authorizationUrl.searchParams.append('prompt', 'consent');\n    }\n    if (resource) {\n        authorizationUrl.searchParams.set('resource', resource.href);\n    }\n    return { authorizationUrl, codeVerifier };\n}\n/**\n * Prepares token request parameters for an authorization code exchange.\n *\n * This is the default implementation used by fetchToken when the provider\n * doesn't implement prepareTokenRequest.\n *\n * @param authorizationCode - The authorization code received from the authorization endpoint\n * @param codeVerifier - The PKCE code verifier\n * @param redirectUri - The redirect URI used in the authorization request\n * @returns URLSearchParams for the authorization_code grant\n */\nexport function prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri) {\n    return new URLSearchParams({\n        grant_type: 'authorization_code',\n        code: authorizationCode,\n        code_verifier: codeVerifier,\n        redirect_uri: String(redirectUri)\n    });\n}\n/**\n * Internal helper to execute a token request with the given parameters.\n * Used by exchangeAuthorization, refreshAuthorization, and fetchToken.\n */\nasync function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequestParams, clientInformation, addClientAuthentication, resource, fetchFn }) {\n    const tokenUrl = metadata?.token_endpoint ? new URL(metadata.token_endpoint) : new URL('/token', authorizationServerUrl);\n    const headers = new Headers({\n        'Content-Type': 'application/x-www-form-urlencoded',\n        Accept: 'application/json'\n    });\n    if (resource) {\n        tokenRequestParams.set('resource', resource.href);\n    }\n    if (addClientAuthentication) {\n        await addClientAuthentication(headers, tokenRequestParams, tokenUrl, metadata);\n    }\n    else if (clientInformation) {\n        const supportedMethods = metadata?.token_endpoint_auth_methods_supported ?? [];\n        const authMethod = selectClientAuthMethod(clientInformation, supportedMethods);\n        applyClientAuthentication(authMethod, clientInformation, headers, tokenRequestParams);\n    }\n    const response = await (fetchFn ?? fetch)(tokenUrl, {\n        method: 'POST',\n        headers,\n        body: tokenRequestParams\n    });\n    if (!response.ok) {\n        throw await parseErrorResponse(response);\n    }\n    return OAuthTokensSchema.parse(await response.json());\n}\n/**\n * Exchanges an authorization code for an access token with the given server.\n *\n * Supports multiple client authentication methods as specified in OAuth 2.1:\n * - Automatically selects the best authentication method based on server support\n * - Falls back to appropriate defaults when server metadata is unavailable\n *\n * @param authorizationServerUrl - The authorization server's base URL\n * @param options - Configuration object containing client info, auth code, etc.\n * @returns Promise resolving to OAuth tokens\n * @throws {Error} When token exchange fails or authentication is invalid\n */\nexport async function exchangeAuthorization(authorizationServerUrl, { metadata, clientInformation, authorizationCode, codeVerifier, redirectUri, resource, addClientAuthentication, fetchFn }) {\n    const tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri);\n    return executeTokenRequest(authorizationServerUrl, {\n        metadata,\n        tokenRequestParams,\n        clientInformation,\n        addClientAuthentication,\n        resource,\n        fetchFn\n    });\n}\n/**\n * Exchange a refresh token for an updated access token.\n *\n * Supports multiple client authentication methods as specified in OAuth 2.1:\n * - Automatically selects the best authentication method based on server support\n * - Preserves the original refresh token if a new one is not returned\n *\n * @param authorizationServerUrl - The authorization server's base URL\n * @param options - Configuration object containing client info, refresh token, etc.\n * @returns Promise resolving to OAuth tokens (preserves original refresh_token if not replaced)\n * @throws {Error} When token refresh fails or authentication is invalid\n */\nexport async function refreshAuthorization(authorizationServerUrl, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }) {\n    const tokenRequestParams = new URLSearchParams({\n        grant_type: 'refresh_token',\n        refresh_token: refreshToken\n    });\n    const tokens = await executeTokenRequest(authorizationServerUrl, {\n        metadata,\n        tokenRequestParams,\n        clientInformation,\n        addClientAuthentication,\n        resource,\n        fetchFn\n    });\n    // Preserve original refresh token if server didn't return a new one\n    return { refresh_token: refreshToken, ...tokens };\n}\n/**\n * Unified token fetching that works with any grant type via provider.prepareTokenRequest().\n *\n * This function provides a single entry point for obtaining tokens regardless of the\n * OAuth grant type. The provider's prepareTokenRequest() method determines which grant\n * to use and supplies the grant-specific parameters.\n *\n * @param provider - OAuth client provider that implements prepareTokenRequest()\n * @param authorizationServerUrl - The authorization server's base URL\n * @param options - Configuration for the token request\n * @returns Promise resolving to OAuth tokens\n * @throws {Error} When provider doesn't implement prepareTokenRequest or token fetch fails\n *\n * @example\n * // Provider for client_credentials:\n * class MyProvider implements OAuthClientProvider {\n *   prepareTokenRequest(scope) {\n *     const params = new URLSearchParams({ grant_type: 'client_credentials' });\n *     if (scope) params.set('scope', scope);\n *     return params;\n *   }\n *   // ... other methods\n * }\n *\n * const tokens = await fetchToken(provider, authServerUrl, { metadata });\n */\nexport async function fetchToken(provider, authorizationServerUrl, { metadata, resource, authorizationCode, fetchFn } = {}) {\n    const scope = provider.clientMetadata.scope;\n    // Use provider's prepareTokenRequest if available, otherwise fall back to authorization_code\n    let tokenRequestParams;\n    if (provider.prepareTokenRequest) {\n        tokenRequestParams = await provider.prepareTokenRequest(scope);\n    }\n    // Default to authorization_code grant if no custom prepareTokenRequest\n    if (!tokenRequestParams) {\n        if (!authorizationCode) {\n            throw new Error('Either provider.prepareTokenRequest() or authorizationCode is required');\n        }\n        if (!provider.redirectUrl) {\n            throw new Error('redirectUrl is required for authorization_code flow');\n        }\n        const codeVerifier = await provider.codeVerifier();\n        tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, provider.redirectUrl);\n    }\n    const clientInformation = await provider.clientInformation();\n    return executeTokenRequest(authorizationServerUrl, {\n        metadata,\n        tokenRequestParams,\n        clientInformation: clientInformation ?? undefined,\n        addClientAuthentication: provider.addClientAuthentication,\n        resource,\n        fetchFn\n    });\n}\n/**\n * Performs OAuth 2.0 Dynamic Client Registration according to RFC 7591.\n *\n * If `scope` is provided, it overrides `clientMetadata.scope` in the registration\n * request body. This allows callers to apply the Scope Selection Strategy (SEP-835)\n * consistently across both DCR and the subsequent authorization request.\n */\nexport async function registerClient(authorizationServerUrl, { metadata, clientMetadata, scope, fetchFn }) {\n    let registrationUrl;\n    if (metadata) {\n        if (!metadata.registration_endpoint) {\n            throw new Error('Incompatible auth server: does not support dynamic client registration');\n        }\n        registrationUrl = new URL(metadata.registration_endpoint);\n    }\n    else {\n        registrationUrl = new URL('/register', authorizationServerUrl);\n    }\n    const response = await (fetchFn ?? fetch)(registrationUrl, {\n        method: 'POST',\n        headers: {\n            'Content-Type': 'application/json'\n        },\n        body: JSON.stringify({\n            ...clientMetadata,\n            ...(scope !== undefined ? { scope } : {})\n        })\n    });\n    if (!response.ok) {\n        throw await parseErrorResponse(response);\n    }\n    return OAuthClientInformationFullSchema.parse(await response.json());\n}\n//# sourceMappingURL=auth.js.map","// zod-compat.ts\n// ----------------------------------------------------\n// Unified types + helpers to accept Zod v3 and v4 (Mini)\n// ----------------------------------------------------\nimport * as z3rt from 'zod/v3';\nimport * as z4mini from 'zod/v4-mini';\n// --- Runtime detection ---\nexport function isZ4Schema(s) {\n    // Present on Zod 4 (Classic & Mini) schemas; absent on Zod 3\n    const schema = s;\n    return !!schema._zod;\n}\n// --- Schema construction ---\nexport function objectFromShape(shape) {\n    const values = Object.values(shape);\n    if (values.length === 0)\n        return z4mini.object({}); // default to v4 Mini\n    const allV4 = values.every(isZ4Schema);\n    const allV3 = values.every(s => !isZ4Schema(s));\n    if (allV4)\n        return z4mini.object(shape);\n    if (allV3)\n        return z3rt.object(shape);\n    throw new Error('Mixed Zod versions detected in object shape.');\n}\n// --- Unified parsing ---\nexport function safeParse(schema, data) {\n    if (isZ4Schema(schema)) {\n        // Mini exposes top-level safeParse\n        const result = z4mini.safeParse(schema, data);\n        return result;\n    }\n    const v3Schema = schema;\n    const result = v3Schema.safeParse(data);\n    return result;\n}\nexport async function safeParseAsync(schema, data) {\n    if (isZ4Schema(schema)) {\n        // Mini exposes top-level safeParseAsync\n        const result = await z4mini.safeParseAsync(schema, data);\n        return result;\n    }\n    const v3Schema = schema;\n    const result = await v3Schema.safeParseAsync(data);\n    return result;\n}\n// --- Shape extraction ---\nexport function getObjectShape(schema) {\n    if (!schema)\n        return undefined;\n    // Zod v3 exposes `.shape`; Zod v4 keeps the shape on `_zod.def.shape`\n    let rawShape;\n    if (isZ4Schema(schema)) {\n        const v4Schema = schema;\n        rawShape = v4Schema._zod?.def?.shape;\n    }\n    else {\n        const v3Schema = schema;\n        rawShape = v3Schema.shape;\n    }\n    if (!rawShape)\n        return undefined;\n    if (typeof rawShape === 'function') {\n        try {\n            return rawShape();\n        }\n        catch {\n            return undefined;\n        }\n    }\n    return rawShape;\n}\n// --- Schema normalization ---\n/**\n * Normalizes a schema to an object schema. Handles both:\n * - Already-constructed object schemas (v3 or v4)\n * - Raw shapes that need to be wrapped into object schemas\n */\nexport function normalizeObjectSchema(schema) {\n    if (!schema)\n        return undefined;\n    // First check if it's a raw shape (Record<string, AnySchema>)\n    // Raw shapes don't have _def or _zod properties and aren't schemas themselves\n    if (typeof schema === 'object') {\n        // Check if it's actually a ZodRawShapeCompat (not a schema instance)\n        // by checking if it lacks schema-like internal properties\n        const asV3 = schema;\n        const asV4 = schema;\n        // If it's not a schema instance (no _def or _zod), it might be a raw shape\n        if (!asV3._def && !asV4._zod) {\n            // Check if all values are schemas (heuristic to confirm it's a raw shape)\n            const values = Object.values(schema);\n            if (values.length > 0 &&\n                values.every(v => typeof v === 'object' &&\n                    v !== null &&\n                    (v._def !== undefined ||\n                        v._zod !== undefined ||\n                        typeof v.parse === 'function'))) {\n                return objectFromShape(schema);\n            }\n        }\n    }\n    // If we get here, it should be an AnySchema (not a raw shape)\n    // Check if it's already an object schema\n    if (isZ4Schema(schema)) {\n        // Check if it's a v4 object\n        const v4Schema = schema;\n        const def = v4Schema._zod?.def;\n        if (def && (def.type === 'object' || def.shape !== undefined)) {\n            return schema;\n        }\n    }\n    else {\n        // Check if it's a v3 object\n        const v3Schema = schema;\n        if (v3Schema.shape !== undefined) {\n            return schema;\n        }\n    }\n    return undefined;\n}\n// --- Error message extraction ---\n/**\n * Safely extracts an error message from a parse result error.\n * Zod errors can have different structures, so we handle various cases.\n */\nexport function getParseErrorMessage(error) {\n    if (error && typeof error === 'object') {\n        // Try common error structures\n        if ('message' in error && typeof error.message === 'string') {\n            return error.message;\n        }\n        if ('issues' in error && Array.isArray(error.issues) && error.issues.length > 0) {\n            const firstIssue = error.issues[0];\n            if (firstIssue && typeof firstIssue === 'object' && 'message' in firstIssue) {\n                return String(firstIssue.message);\n            }\n        }\n        // Fallback: try to stringify the error\n        try {\n            return JSON.stringify(error);\n        }\n        catch {\n            return String(error);\n        }\n    }\n    return String(error);\n}\n// --- Schema metadata access ---\n/**\n * Gets the description from a schema, if available.\n * Works with both Zod v3 and v4.\n *\n * Both versions expose a `.description` getter that returns the description\n * from their respective internal storage (v3: _def, v4: globalRegistry).\n */\nexport function getSchemaDescription(schema) {\n    return schema.description;\n}\n/**\n * Checks if a schema is optional.\n * Works with both Zod v3 and v4.\n */\nexport function isSchemaOptional(schema) {\n    if (isZ4Schema(schema)) {\n        const v4Schema = schema;\n        return v4Schema._zod?.def?.type === 'optional';\n    }\n    const v3Schema = schema;\n    // v3 has isOptional() method\n    if (typeof schema.isOptional === 'function') {\n        return schema.isOptional();\n    }\n    return v3Schema._def?.typeName === 'ZodOptional';\n}\n/**\n * Gets the literal value from a schema, if it's a literal schema.\n * Works with both Zod v3 and v4.\n * Returns undefined if the schema is not a literal or the value cannot be determined.\n */\nexport function getLiteralValue(schema) {\n    if (isZ4Schema(schema)) {\n        const v4Schema = schema;\n        const def = v4Schema._zod?.def;\n        if (def) {\n            // Try various ways to get the literal value\n            if (def.value !== undefined)\n                return def.value;\n            if (Array.isArray(def.values) && def.values.length > 0) {\n                return def.values[0];\n            }\n        }\n    }\n    const v3Schema = schema;\n    const def = v3Schema._def;\n    if (def) {\n        if (def.value !== undefined)\n            return def.value;\n        if (Array.isArray(def.values) && def.values.length > 0) {\n            return def.values[0];\n        }\n    }\n    // Fallback: check for direct value property (some Zod versions)\n    const directValue = schema.value;\n    if (directValue !== undefined)\n        return directValue;\n    return undefined;\n}\n//# sourceMappingURL=zod-compat.js.map","/**\n * Experimental task interfaces for MCP SDK.\n * WARNING: These APIs are experimental and may change without notice.\n */\n/**\n * Checks if a task status represents a terminal state.\n * Terminal states are those where the task has finished and will not change.\n *\n * @param status - The task status to check\n * @returns True if the status is terminal (completed, failed, or cancelled)\n * @experimental\n */\nexport function isTerminal(status) {\n    return status === 'completed' || status === 'failed' || status === 'cancelled';\n}\n//# sourceMappingURL=interfaces.js.map","// zod-json-schema-compat.ts\n// ----------------------------------------------------\n// JSON Schema conversion for both Zod v3 and Zod v4 (Mini)\n// v3 uses your vendored converter; v4 uses Mini's toJSONSchema\n// ----------------------------------------------------\nimport * as z4mini from 'zod/v4-mini';\nimport { getObjectShape, safeParse, isZ4Schema, getLiteralValue } from './zod-compat.js';\nimport { zodToJsonSchema } from 'zod-to-json-schema';\nfunction mapMiniTarget(t) {\n    if (!t)\n        return 'draft-7';\n    if (t === 'jsonSchema7' || t === 'draft-7')\n        return 'draft-7';\n    if (t === 'jsonSchema2019-09' || t === 'draft-2020-12')\n        return 'draft-2020-12';\n    return 'draft-7'; // fallback\n}\nexport function toJsonSchemaCompat(schema, opts) {\n    if (isZ4Schema(schema)) {\n        // v4 branch — use Mini's built-in toJSONSchema\n        return z4mini.toJSONSchema(schema, {\n            target: mapMiniTarget(opts?.target),\n            io: opts?.pipeStrategy ?? 'input'\n        });\n    }\n    // v3 branch — use vendored converter\n    return zodToJsonSchema(schema, {\n        strictUnions: opts?.strictUnions ?? true,\n        pipeStrategy: opts?.pipeStrategy ?? 'input'\n    });\n}\nexport function getMethodLiteral(schema) {\n    const shape = getObjectShape(schema);\n    const methodSchema = shape?.method;\n    if (!methodSchema) {\n        throw new Error('Schema is missing a method literal');\n    }\n    const value = getLiteralValue(methodSchema);\n    if (typeof value !== 'string') {\n        throw new Error('Schema method literal must be a string');\n    }\n    return value;\n}\nexport function parseWithCompat(schema, data) {\n    const result = safeParse(schema, data);\n    if (!result.success) {\n        throw result.error;\n    }\n    return result.data;\n}\n//# sourceMappingURL=zod-json-schema-compat.js.map","import { safeParse } from '../server/zod-compat.js';\nimport { CancelledNotificationSchema, CreateTaskResultSchema, ErrorCode, GetTaskRequestSchema, GetTaskResultSchema, GetTaskPayloadRequestSchema, ListTasksRequestSchema, ListTasksResultSchema, CancelTaskRequestSchema, CancelTaskResultSchema, isJSONRPCErrorResponse, isJSONRPCRequest, isJSONRPCResultResponse, isJSONRPCNotification, McpError, PingRequestSchema, ProgressNotificationSchema, RELATED_TASK_META_KEY, TaskStatusNotificationSchema, isTaskAugmentedRequestParams } from '../types.js';\nimport { isTerminal } from '../experimental/tasks/interfaces.js';\nimport { getMethodLiteral, parseWithCompat } from '../server/zod-json-schema-compat.js';\n/**\n * The default request timeout, in miliseconds.\n */\nexport const DEFAULT_REQUEST_TIMEOUT_MSEC = 60000;\n/**\n * Implements MCP protocol framing on top of a pluggable transport, including\n * features like request/response linking, notifications, and progress.\n */\nexport class Protocol {\n    constructor(_options) {\n        this._options = _options;\n        this._requestMessageId = 0;\n        this._requestHandlers = new Map();\n        this._requestHandlerAbortControllers = new Map();\n        this._notificationHandlers = new Map();\n        this._responseHandlers = new Map();\n        this._progressHandlers = new Map();\n        this._timeoutInfo = new Map();\n        this._pendingDebouncedNotifications = new Set();\n        // Maps task IDs to progress tokens to keep handlers alive after CreateTaskResult\n        this._taskProgressTokens = new Map();\n        this._requestResolvers = new Map();\n        this.setNotificationHandler(CancelledNotificationSchema, notification => {\n            this._oncancel(notification);\n        });\n        this.setNotificationHandler(ProgressNotificationSchema, notification => {\n            this._onprogress(notification);\n        });\n        this.setRequestHandler(PingRequestSchema, \n        // Automatic pong by default.\n        _request => ({}));\n        // Install task handlers if TaskStore is provided\n        this._taskStore = _options?.taskStore;\n        this._taskMessageQueue = _options?.taskMessageQueue;\n        if (this._taskStore) {\n            this.setRequestHandler(GetTaskRequestSchema, async (request, extra) => {\n                const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId);\n                if (!task) {\n                    throw new McpError(ErrorCode.InvalidParams, 'Failed to retrieve task: Task not found');\n                }\n                // Per spec: tasks/get responses SHALL NOT include related-task metadata\n                // as the taskId parameter is the source of truth\n                // @ts-expect-error SendResultT cannot contain GetTaskResult, but we include it in our derived types everywhere else\n                return {\n                    ...task\n                };\n            });\n            this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => {\n                const handleTaskResult = async () => {\n                    const taskId = request.params.taskId;\n                    // Deliver queued messages\n                    if (this._taskMessageQueue) {\n                        let queuedMessage;\n                        while ((queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId))) {\n                            // Handle response and error messages by routing them to the appropriate resolver\n                            if (queuedMessage.type === 'response' || queuedMessage.type === 'error') {\n                                const message = queuedMessage.message;\n                                const requestId = message.id;\n                                // Lookup resolver in _requestResolvers map\n                                const resolver = this._requestResolvers.get(requestId);\n                                if (resolver) {\n                                    // Remove resolver from map after invocation\n                                    this._requestResolvers.delete(requestId);\n                                    // Invoke resolver with response or error\n                                    if (queuedMessage.type === 'response') {\n                                        resolver(message);\n                                    }\n                                    else {\n                                        // Convert JSONRPCError to McpError\n                                        const errorMessage = message;\n                                        const error = new McpError(errorMessage.error.code, errorMessage.error.message, errorMessage.error.data);\n                                        resolver(error);\n                                    }\n                                }\n                                else {\n                                    // Handle missing resolver gracefully with error logging\n                                    const messageType = queuedMessage.type === 'response' ? 'Response' : 'Error';\n                                    this._onerror(new Error(`${messageType} handler missing for request ${requestId}`));\n                                }\n                                // Continue to next message\n                                continue;\n                            }\n                            // Send the message on the response stream by passing the relatedRequestId\n                            // This tells the transport to write the message to the tasks/result response stream\n                            await this._transport?.send(queuedMessage.message, { relatedRequestId: extra.requestId });\n                        }\n                    }\n                    // Now check task status\n                    const task = await this._taskStore.getTask(taskId, extra.sessionId);\n                    if (!task) {\n                        throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);\n                    }\n                    // Block if task is not terminal (we've already delivered all queued messages above)\n                    if (!isTerminal(task.status)) {\n                        // Wait for status change or new messages\n                        await this._waitForTaskUpdate(taskId, extra.signal);\n                        // After waking up, recursively call to deliver any new messages or result\n                        return await handleTaskResult();\n                    }\n                    // If task is terminal, return the result\n                    if (isTerminal(task.status)) {\n                        const result = await this._taskStore.getTaskResult(taskId, extra.sessionId);\n                        this._clearTaskQueue(taskId);\n                        return {\n                            ...result,\n                            _meta: {\n                                ...result._meta,\n                                [RELATED_TASK_META_KEY]: {\n                                    taskId: taskId\n                                }\n                            }\n                        };\n                    }\n                    return await handleTaskResult();\n                };\n                return await handleTaskResult();\n            });\n            this.setRequestHandler(ListTasksRequestSchema, async (request, extra) => {\n                try {\n                    const { tasks, nextCursor } = await this._taskStore.listTasks(request.params?.cursor, extra.sessionId);\n                    // @ts-expect-error SendResultT cannot contain ListTasksResult, but we include it in our derived types everywhere else\n                    return {\n                        tasks,\n                        nextCursor,\n                        _meta: {}\n                    };\n                }\n                catch (error) {\n                    throw new McpError(ErrorCode.InvalidParams, `Failed to list tasks: ${error instanceof Error ? error.message : String(error)}`);\n                }\n            });\n            this.setRequestHandler(CancelTaskRequestSchema, async (request, extra) => {\n                try {\n                    // Get the current task to check if it's in a terminal state, in case the implementation is not atomic\n                    const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId);\n                    if (!task) {\n                        throw new McpError(ErrorCode.InvalidParams, `Task not found: ${request.params.taskId}`);\n                    }\n                    // Reject cancellation of terminal tasks\n                    if (isTerminal(task.status)) {\n                        throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`);\n                    }\n                    await this._taskStore.updateTaskStatus(request.params.taskId, 'cancelled', 'Client cancelled task execution.', extra.sessionId);\n                    this._clearTaskQueue(request.params.taskId);\n                    const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId);\n                    if (!cancelledTask) {\n                        // Task was deleted during cancellation (e.g., cleanup happened)\n                        throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`);\n                    }\n                    return {\n                        _meta: {},\n                        ...cancelledTask\n                    };\n                }\n                catch (error) {\n                    // Re-throw McpError as-is\n                    if (error instanceof McpError) {\n                        throw error;\n                    }\n                    throw new McpError(ErrorCode.InvalidRequest, `Failed to cancel task: ${error instanceof Error ? error.message : String(error)}`);\n                }\n            });\n        }\n    }\n    async _oncancel(notification) {\n        if (!notification.params.requestId) {\n            return;\n        }\n        // Handle request cancellation\n        const controller = this._requestHandlerAbortControllers.get(notification.params.requestId);\n        controller?.abort(notification.params.reason);\n    }\n    _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) {\n        this._timeoutInfo.set(messageId, {\n            timeoutId: setTimeout(onTimeout, timeout),\n            startTime: Date.now(),\n            timeout,\n            maxTotalTimeout,\n            resetTimeoutOnProgress,\n            onTimeout\n        });\n    }\n    _resetTimeout(messageId) {\n        const info = this._timeoutInfo.get(messageId);\n        if (!info)\n            return false;\n        const totalElapsed = Date.now() - info.startTime;\n        if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) {\n            this._timeoutInfo.delete(messageId);\n            throw McpError.fromError(ErrorCode.RequestTimeout, 'Maximum total timeout exceeded', {\n                maxTotalTimeout: info.maxTotalTimeout,\n                totalElapsed\n            });\n        }\n        clearTimeout(info.timeoutId);\n        info.timeoutId = setTimeout(info.onTimeout, info.timeout);\n        return true;\n    }\n    _cleanupTimeout(messageId) {\n        const info = this._timeoutInfo.get(messageId);\n        if (info) {\n            clearTimeout(info.timeoutId);\n            this._timeoutInfo.delete(messageId);\n        }\n    }\n    /**\n     * Attaches to the given transport, starts it, and starts listening for messages.\n     *\n     * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward.\n     */\n    async connect(transport) {\n        if (this._transport) {\n            throw new Error('Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.');\n        }\n        this._transport = transport;\n        const _onclose = this.transport?.onclose;\n        this._transport.onclose = () => {\n            _onclose?.();\n            this._onclose();\n        };\n        const _onerror = this.transport?.onerror;\n        this._transport.onerror = (error) => {\n            _onerror?.(error);\n            this._onerror(error);\n        };\n        const _onmessage = this._transport?.onmessage;\n        this._transport.onmessage = (message, extra) => {\n            _onmessage?.(message, extra);\n            if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {\n                this._onresponse(message);\n            }\n            else if (isJSONRPCRequest(message)) {\n                this._onrequest(message, extra);\n            }\n            else if (isJSONRPCNotification(message)) {\n                this._onnotification(message);\n            }\n            else {\n                this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`));\n            }\n        };\n        await this._transport.start();\n    }\n    _onclose() {\n        const responseHandlers = this._responseHandlers;\n        this._responseHandlers = new Map();\n        this._progressHandlers.clear();\n        this._taskProgressTokens.clear();\n        this._pendingDebouncedNotifications.clear();\n        for (const info of this._timeoutInfo.values()) {\n            clearTimeout(info.timeoutId);\n        }\n        this._timeoutInfo.clear();\n        // Abort all in-flight request handlers so they stop sending messages\n        for (const controller of this._requestHandlerAbortControllers.values()) {\n            controller.abort();\n        }\n        this._requestHandlerAbortControllers.clear();\n        const error = McpError.fromError(ErrorCode.ConnectionClosed, 'Connection closed');\n        this._transport = undefined;\n        this.onclose?.();\n        for (const handler of responseHandlers.values()) {\n            handler(error);\n        }\n    }\n    _onerror(error) {\n        this.onerror?.(error);\n    }\n    _onnotification(notification) {\n        const handler = this._notificationHandlers.get(notification.method) ?? this.fallbackNotificationHandler;\n        // Ignore notifications not being subscribed to.\n        if (handler === undefined) {\n            return;\n        }\n        // Starting with Promise.resolve() puts any synchronous errors into the monad as well.\n        Promise.resolve()\n            .then(() => handler(notification))\n            .catch(error => this._onerror(new Error(`Uncaught error in notification handler: ${error}`)));\n    }\n    _onrequest(request, extra) {\n        const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler;\n        // Capture the current transport at request time to ensure responses go to the correct client\n        const capturedTransport = this._transport;\n        // Extract taskId from request metadata if present (needed early for method not found case)\n        const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;\n        if (handler === undefined) {\n            const errorResponse = {\n                jsonrpc: '2.0',\n                id: request.id,\n                error: {\n                    code: ErrorCode.MethodNotFound,\n                    message: 'Method not found'\n                }\n            };\n            // Queue or send the error response based on whether this is a task-related request\n            if (relatedTaskId && this._taskMessageQueue) {\n                this._enqueueTaskMessage(relatedTaskId, {\n                    type: 'error',\n                    message: errorResponse,\n                    timestamp: Date.now()\n                }, capturedTransport?.sessionId).catch(error => this._onerror(new Error(`Failed to enqueue error response: ${error}`)));\n            }\n            else {\n                capturedTransport\n                    ?.send(errorResponse)\n                    .catch(error => this._onerror(new Error(`Failed to send an error response: ${error}`)));\n            }\n            return;\n        }\n        const abortController = new AbortController();\n        this._requestHandlerAbortControllers.set(request.id, abortController);\n        const taskCreationParams = isTaskAugmentedRequestParams(request.params) ? request.params.task : undefined;\n        const taskStore = this._taskStore ? this.requestTaskStore(request, capturedTransport?.sessionId) : undefined;\n        const fullExtra = {\n            signal: abortController.signal,\n            sessionId: capturedTransport?.sessionId,\n            _meta: request.params?._meta,\n            sendNotification: async (notification) => {\n                if (abortController.signal.aborted)\n                    return;\n                // Include related-task metadata if this request is part of a task\n                const notificationOptions = { relatedRequestId: request.id };\n                if (relatedTaskId) {\n                    notificationOptions.relatedTask = { taskId: relatedTaskId };\n                }\n                await this.notification(notification, notificationOptions);\n            },\n            sendRequest: async (r, resultSchema, options) => {\n                if (abortController.signal.aborted) {\n                    throw new McpError(ErrorCode.ConnectionClosed, 'Request was cancelled');\n                }\n                // Include related-task metadata if this request is part of a task\n                const requestOptions = { ...options, relatedRequestId: request.id };\n                if (relatedTaskId && !requestOptions.relatedTask) {\n                    requestOptions.relatedTask = { taskId: relatedTaskId };\n                }\n                // Set task status to input_required when sending a request within a task context\n                // Use the taskId from options (explicit) or fall back to relatedTaskId (inherited)\n                const effectiveTaskId = requestOptions.relatedTask?.taskId ?? relatedTaskId;\n                if (effectiveTaskId && taskStore) {\n                    await taskStore.updateTaskStatus(effectiveTaskId, 'input_required');\n                }\n                return await this.request(r, resultSchema, requestOptions);\n            },\n            authInfo: extra?.authInfo,\n            requestId: request.id,\n            requestInfo: extra?.requestInfo,\n            taskId: relatedTaskId,\n            taskStore: taskStore,\n            taskRequestedTtl: taskCreationParams?.ttl,\n            closeSSEStream: extra?.closeSSEStream,\n            closeStandaloneSSEStream: extra?.closeStandaloneSSEStream\n        };\n        // Starting with Promise.resolve() puts any synchronous errors into the monad as well.\n        Promise.resolve()\n            .then(() => {\n            // If this request asked for task creation, check capability first\n            if (taskCreationParams) {\n                // Check if the request method supports task creation\n                this.assertTaskHandlerCapability(request.method);\n            }\n        })\n            .then(() => handler(request, fullExtra))\n            .then(async (result) => {\n            if (abortController.signal.aborted) {\n                // Request was cancelled\n                return;\n            }\n            const response = {\n                result,\n                jsonrpc: '2.0',\n                id: request.id\n            };\n            // Queue or send the response based on whether this is a task-related request\n            if (relatedTaskId && this._taskMessageQueue) {\n                await this._enqueueTaskMessage(relatedTaskId, {\n                    type: 'response',\n                    message: response,\n                    timestamp: Date.now()\n                }, capturedTransport?.sessionId);\n            }\n            else {\n                await capturedTransport?.send(response);\n            }\n        }, async (error) => {\n            if (abortController.signal.aborted) {\n                // Request was cancelled\n                return;\n            }\n            const errorResponse = {\n                jsonrpc: '2.0',\n                id: request.id,\n                error: {\n                    code: Number.isSafeInteger(error['code']) ? error['code'] : ErrorCode.InternalError,\n                    message: error.message ?? 'Internal error',\n                    ...(error['data'] !== undefined && { data: error['data'] })\n                }\n            };\n            // Queue or send the error response based on whether this is a task-related request\n            if (relatedTaskId && this._taskMessageQueue) {\n                await this._enqueueTaskMessage(relatedTaskId, {\n                    type: 'error',\n                    message: errorResponse,\n                    timestamp: Date.now()\n                }, capturedTransport?.sessionId);\n            }\n            else {\n                await capturedTransport?.send(errorResponse);\n            }\n        })\n            .catch(error => this._onerror(new Error(`Failed to send response: ${error}`)))\n            .finally(() => {\n            // Only delete if the stored controller is still ours; after close()+connect(),\n            // a new connection may have reused the same request ID with a different controller.\n            if (this._requestHandlerAbortControllers.get(request.id) === abortController) {\n                this._requestHandlerAbortControllers.delete(request.id);\n            }\n        });\n    }\n    _onprogress(notification) {\n        const { progressToken, ...params } = notification.params;\n        const messageId = Number(progressToken);\n        const handler = this._progressHandlers.get(messageId);\n        if (!handler) {\n            this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`));\n            return;\n        }\n        const responseHandler = this._responseHandlers.get(messageId);\n        const timeoutInfo = this._timeoutInfo.get(messageId);\n        if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) {\n            try {\n                this._resetTimeout(messageId);\n            }\n            catch (error) {\n                // Clean up if maxTotalTimeout was exceeded\n                this._responseHandlers.delete(messageId);\n                this._progressHandlers.delete(messageId);\n                this._cleanupTimeout(messageId);\n                responseHandler(error);\n                return;\n            }\n        }\n        handler(params);\n    }\n    _onresponse(response) {\n        const messageId = Number(response.id);\n        // Check if this is a response to a queued request\n        const resolver = this._requestResolvers.get(messageId);\n        if (resolver) {\n            this._requestResolvers.delete(messageId);\n            if (isJSONRPCResultResponse(response)) {\n                resolver(response);\n            }\n            else {\n                const error = new McpError(response.error.code, response.error.message, response.error.data);\n                resolver(error);\n            }\n            return;\n        }\n        const handler = this._responseHandlers.get(messageId);\n        if (handler === undefined) {\n            this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));\n            return;\n        }\n        this._responseHandlers.delete(messageId);\n        this._cleanupTimeout(messageId);\n        // Keep progress handler alive for CreateTaskResult responses\n        let isTaskResponse = false;\n        if (isJSONRPCResultResponse(response) && response.result && typeof response.result === 'object') {\n            const result = response.result;\n            if (result.task && typeof result.task === 'object') {\n                const task = result.task;\n                if (typeof task.taskId === 'string') {\n                    isTaskResponse = true;\n                    this._taskProgressTokens.set(task.taskId, messageId);\n                }\n            }\n        }\n        if (!isTaskResponse) {\n            this._progressHandlers.delete(messageId);\n        }\n        if (isJSONRPCResultResponse(response)) {\n            handler(response);\n        }\n        else {\n            const error = McpError.fromError(response.error.code, response.error.message, response.error.data);\n            handler(error);\n        }\n    }\n    get transport() {\n        return this._transport;\n    }\n    /**\n     * Closes the connection.\n     */\n    async close() {\n        await this._transport?.close();\n    }\n    /**\n     * Sends a request and returns an AsyncGenerator that yields response messages.\n     * The generator is guaranteed to end with either a 'result' or 'error' message.\n     *\n     * @example\n     * ```typescript\n     * const stream = protocol.requestStream(request, resultSchema, options);\n     * for await (const message of stream) {\n     *   switch (message.type) {\n     *     case 'taskCreated':\n     *       console.log('Task created:', message.task.taskId);\n     *       break;\n     *     case 'taskStatus':\n     *       console.log('Task status:', message.task.status);\n     *       break;\n     *     case 'result':\n     *       console.log('Final result:', message.result);\n     *       break;\n     *     case 'error':\n     *       console.error('Error:', message.error);\n     *       break;\n     *   }\n     * }\n     * ```\n     *\n     * @experimental Use `client.experimental.tasks.requestStream()` to access this method.\n     */\n    async *requestStream(request, resultSchema, options) {\n        const { task } = options ?? {};\n        // For non-task requests, just yield the result\n        if (!task) {\n            try {\n                const result = await this.request(request, resultSchema, options);\n                yield { type: 'result', result };\n            }\n            catch (error) {\n                yield {\n                    type: 'error',\n                    error: error instanceof McpError ? error : new McpError(ErrorCode.InternalError, String(error))\n                };\n            }\n            return;\n        }\n        // For task-augmented requests, we need to poll for status\n        // First, make the request to create the task\n        let taskId;\n        try {\n            // Send the request and get the CreateTaskResult\n            const createResult = await this.request(request, CreateTaskResultSchema, options);\n            // Extract taskId from the result\n            if (createResult.task) {\n                taskId = createResult.task.taskId;\n                yield { type: 'taskCreated', task: createResult.task };\n            }\n            else {\n                throw new McpError(ErrorCode.InternalError, 'Task creation did not return a task');\n            }\n            // Poll for task completion\n            while (true) {\n                // Get current task status\n                const task = await this.getTask({ taskId }, options);\n                yield { type: 'taskStatus', task };\n                // Check if task is terminal\n                if (isTerminal(task.status)) {\n                    if (task.status === 'completed') {\n                        // Get the final result\n                        const result = await this.getTaskResult({ taskId }, resultSchema, options);\n                        yield { type: 'result', result };\n                    }\n                    else if (task.status === 'failed') {\n                        yield {\n                            type: 'error',\n                            error: new McpError(ErrorCode.InternalError, `Task ${taskId} failed`)\n                        };\n                    }\n                    else if (task.status === 'cancelled') {\n                        yield {\n                            type: 'error',\n                            error: new McpError(ErrorCode.InternalError, `Task ${taskId} was cancelled`)\n                        };\n                    }\n                    return;\n                }\n                // When input_required, call tasks/result to deliver queued messages\n                // (elicitation, sampling) via SSE and block until terminal\n                if (task.status === 'input_required') {\n                    const result = await this.getTaskResult({ taskId }, resultSchema, options);\n                    yield { type: 'result', result };\n                    return;\n                }\n                // Wait before polling again\n                const pollInterval = task.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1000;\n                await new Promise(resolve => setTimeout(resolve, pollInterval));\n                // Check if cancelled\n                options?.signal?.throwIfAborted();\n            }\n        }\n        catch (error) {\n            yield {\n                type: 'error',\n                error: error instanceof McpError ? error : new McpError(ErrorCode.InternalError, String(error))\n            };\n        }\n    }\n    /**\n     * Sends a request and waits for a response.\n     *\n     * Do not use this method to emit notifications! Use notification() instead.\n     */\n    request(request, resultSchema, options) {\n        const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {};\n        // Send the request\n        return new Promise((resolve, reject) => {\n            const earlyReject = (error) => {\n                reject(error);\n            };\n            if (!this._transport) {\n                earlyReject(new Error('Not connected'));\n                return;\n            }\n            if (this._options?.enforceStrictCapabilities === true) {\n                try {\n                    this.assertCapabilityForMethod(request.method);\n                    // If task creation is requested, also check task capabilities\n                    if (task) {\n                        this.assertTaskCapability(request.method);\n                    }\n                }\n                catch (e) {\n                    earlyReject(e);\n                    return;\n                }\n            }\n            options?.signal?.throwIfAborted();\n            const messageId = this._requestMessageId++;\n            const jsonrpcRequest = {\n                ...request,\n                jsonrpc: '2.0',\n                id: messageId\n            };\n            if (options?.onprogress) {\n                this._progressHandlers.set(messageId, options.onprogress);\n                jsonrpcRequest.params = {\n                    ...request.params,\n                    _meta: {\n                        ...(request.params?._meta || {}),\n                        progressToken: messageId\n                    }\n                };\n            }\n            // Augment with task creation parameters if provided\n            if (task) {\n                jsonrpcRequest.params = {\n                    ...jsonrpcRequest.params,\n                    task: task\n                };\n            }\n            // Augment with related task metadata if relatedTask is provided\n            if (relatedTask) {\n                jsonrpcRequest.params = {\n                    ...jsonrpcRequest.params,\n                    _meta: {\n                        ...(jsonrpcRequest.params?._meta || {}),\n                        [RELATED_TASK_META_KEY]: relatedTask\n                    }\n                };\n            }\n            const cancel = (reason) => {\n                this._responseHandlers.delete(messageId);\n                this._progressHandlers.delete(messageId);\n                this._cleanupTimeout(messageId);\n                this._transport\n                    ?.send({\n                    jsonrpc: '2.0',\n                    method: 'notifications/cancelled',\n                    params: {\n                        requestId: messageId,\n                        reason: String(reason)\n                    }\n                }, { relatedRequestId, resumptionToken, onresumptiontoken })\n                    .catch(error => this._onerror(new Error(`Failed to send cancellation: ${error}`)));\n                // Wrap the reason in an McpError if it isn't already\n                const error = reason instanceof McpError ? reason : new McpError(ErrorCode.RequestTimeout, String(reason));\n                reject(error);\n            };\n            this._responseHandlers.set(messageId, response => {\n                if (options?.signal?.aborted) {\n                    return;\n                }\n                if (response instanceof Error) {\n                    return reject(response);\n                }\n                try {\n                    const parseResult = safeParse(resultSchema, response.result);\n                    if (!parseResult.success) {\n                        // Type guard: if success is false, error is guaranteed to exist\n                        reject(parseResult.error);\n                    }\n                    else {\n                        resolve(parseResult.data);\n                    }\n                }\n                catch (error) {\n                    reject(error);\n                }\n            });\n            options?.signal?.addEventListener('abort', () => {\n                cancel(options?.signal?.reason);\n            });\n            const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC;\n            const timeoutHandler = () => cancel(McpError.fromError(ErrorCode.RequestTimeout, 'Request timed out', { timeout }));\n            this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false);\n            // Queue request if related to a task\n            const relatedTaskId = relatedTask?.taskId;\n            if (relatedTaskId) {\n                // Store the response resolver for this request so responses can be routed back\n                const responseResolver = (response) => {\n                    const handler = this._responseHandlers.get(messageId);\n                    if (handler) {\n                        handler(response);\n                    }\n                    else {\n                        // Log error when resolver is missing, but don't fail\n                        this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`));\n                    }\n                };\n                this._requestResolvers.set(messageId, responseResolver);\n                this._enqueueTaskMessage(relatedTaskId, {\n                    type: 'request',\n                    message: jsonrpcRequest,\n                    timestamp: Date.now()\n                }).catch(error => {\n                    this._cleanupTimeout(messageId);\n                    reject(error);\n                });\n                // Don't send through transport - queued messages are delivered via tasks/result only\n                // This prevents duplicate delivery for bidirectional transports\n            }\n            else {\n                // No related task - send through transport normally\n                this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch(error => {\n                    this._cleanupTimeout(messageId);\n                    reject(error);\n                });\n            }\n        });\n    }\n    /**\n     * Gets the current status of a task.\n     *\n     * @experimental Use `client.experimental.tasks.getTask()` to access this method.\n     */\n    async getTask(params, options) {\n        // @ts-expect-error SendRequestT cannot directly contain GetTaskRequest, but we ensure all type instantiations contain it anyways\n        return this.request({ method: 'tasks/get', params }, GetTaskResultSchema, options);\n    }\n    /**\n     * Retrieves the result of a completed task.\n     *\n     * @experimental Use `client.experimental.tasks.getTaskResult()` to access this method.\n     */\n    async getTaskResult(params, resultSchema, options) {\n        // @ts-expect-error SendRequestT cannot directly contain GetTaskPayloadRequest, but we ensure all type instantiations contain it anyways\n        return this.request({ method: 'tasks/result', params }, resultSchema, options);\n    }\n    /**\n     * Lists tasks, optionally starting from a pagination cursor.\n     *\n     * @experimental Use `client.experimental.tasks.listTasks()` to access this method.\n     */\n    async listTasks(params, options) {\n        // @ts-expect-error SendRequestT cannot directly contain ListTasksRequest, but we ensure all type instantiations contain it anyways\n        return this.request({ method: 'tasks/list', params }, ListTasksResultSchema, options);\n    }\n    /**\n     * Cancels a specific task.\n     *\n     * @experimental Use `client.experimental.tasks.cancelTask()` to access this method.\n     */\n    async cancelTask(params, options) {\n        // @ts-expect-error SendRequestT cannot directly contain CancelTaskRequest, but we ensure all type instantiations contain it anyways\n        return this.request({ method: 'tasks/cancel', params }, CancelTaskResultSchema, options);\n    }\n    /**\n     * Emits a notification, which is a one-way message that does not expect a response.\n     */\n    async notification(notification, options) {\n        if (!this._transport) {\n            throw new Error('Not connected');\n        }\n        this.assertNotificationCapability(notification.method);\n        // Queue notification if related to a task\n        const relatedTaskId = options?.relatedTask?.taskId;\n        if (relatedTaskId) {\n            // Build the JSONRPC notification with metadata\n            const jsonrpcNotification = {\n                ...notification,\n                jsonrpc: '2.0',\n                params: {\n                    ...notification.params,\n                    _meta: {\n                        ...(notification.params?._meta || {}),\n                        [RELATED_TASK_META_KEY]: options.relatedTask\n                    }\n                }\n            };\n            await this._enqueueTaskMessage(relatedTaskId, {\n                type: 'notification',\n                message: jsonrpcNotification,\n                timestamp: Date.now()\n            });\n            // Don't send through transport - queued messages are delivered via tasks/result only\n            // This prevents duplicate delivery for bidirectional transports\n            return;\n        }\n        const debouncedMethods = this._options?.debouncedNotificationMethods ?? [];\n        // A notification can only be debounced if it's in the list AND it's \"simple\"\n        // (i.e., has no parameters and no related request ID or related task that could be lost).\n        const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !options?.relatedRequestId && !options?.relatedTask;\n        if (canDebounce) {\n            // If a notification of this type is already scheduled, do nothing.\n            if (this._pendingDebouncedNotifications.has(notification.method)) {\n                return;\n            }\n            // Mark this notification type as pending.\n            this._pendingDebouncedNotifications.add(notification.method);\n            // Schedule the actual send to happen in the next microtask.\n            // This allows all synchronous calls in the current event loop tick to be coalesced.\n            Promise.resolve().then(() => {\n                // Un-mark the notification so the next one can be scheduled.\n                this._pendingDebouncedNotifications.delete(notification.method);\n                // SAFETY CHECK: If the connection was closed while this was pending, abort.\n                if (!this._transport) {\n                    return;\n                }\n                let jsonrpcNotification = {\n                    ...notification,\n                    jsonrpc: '2.0'\n                };\n                // Augment with related task metadata if relatedTask is provided\n                if (options?.relatedTask) {\n                    jsonrpcNotification = {\n                        ...jsonrpcNotification,\n                        params: {\n                            ...jsonrpcNotification.params,\n                            _meta: {\n                                ...(jsonrpcNotification.params?._meta || {}),\n                                [RELATED_TASK_META_KEY]: options.relatedTask\n                            }\n                        }\n                    };\n                }\n                // Send the notification, but don't await it here to avoid blocking.\n                // Handle potential errors with a .catch().\n                this._transport?.send(jsonrpcNotification, options).catch(error => this._onerror(error));\n            });\n            // Return immediately.\n            return;\n        }\n        let jsonrpcNotification = {\n            ...notification,\n            jsonrpc: '2.0'\n        };\n        // Augment with related task metadata if relatedTask is provided\n        if (options?.relatedTask) {\n            jsonrpcNotification = {\n                ...jsonrpcNotification,\n                params: {\n                    ...jsonrpcNotification.params,\n                    _meta: {\n                        ...(jsonrpcNotification.params?._meta || {}),\n                        [RELATED_TASK_META_KEY]: options.relatedTask\n                    }\n                }\n            };\n        }\n        await this._transport.send(jsonrpcNotification, options);\n    }\n    /**\n     * Registers a handler to invoke when this protocol object receives a request with the given method.\n     *\n     * Note that this will replace any previous request handler for the same method.\n     */\n    setRequestHandler(requestSchema, handler) {\n        const method = getMethodLiteral(requestSchema);\n        this.assertRequestHandlerCapability(method);\n        this._requestHandlers.set(method, (request, extra) => {\n            const parsed = parseWithCompat(requestSchema, request);\n            return Promise.resolve(handler(parsed, extra));\n        });\n    }\n    /**\n     * Removes the request handler for the given method.\n     */\n    removeRequestHandler(method) {\n        this._requestHandlers.delete(method);\n    }\n    /**\n     * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed.\n     */\n    assertCanSetRequestHandler(method) {\n        if (this._requestHandlers.has(method)) {\n            throw new Error(`A request handler for ${method} already exists, which would be overridden`);\n        }\n    }\n    /**\n     * Registers a handler to invoke when this protocol object receives a notification with the given method.\n     *\n     * Note that this will replace any previous notification handler for the same method.\n     */\n    setNotificationHandler(notificationSchema, handler) {\n        const method = getMethodLiteral(notificationSchema);\n        this._notificationHandlers.set(method, notification => {\n            const parsed = parseWithCompat(notificationSchema, notification);\n            return Promise.resolve(handler(parsed));\n        });\n    }\n    /**\n     * Removes the notification handler for the given method.\n     */\n    removeNotificationHandler(method) {\n        this._notificationHandlers.delete(method);\n    }\n    /**\n     * Cleans up the progress handler associated with a task.\n     * This should be called when a task reaches a terminal status.\n     */\n    _cleanupTaskProgressHandler(taskId) {\n        const progressToken = this._taskProgressTokens.get(taskId);\n        if (progressToken !== undefined) {\n            this._progressHandlers.delete(progressToken);\n            this._taskProgressTokens.delete(taskId);\n        }\n    }\n    /**\n     * Enqueues a task-related message for side-channel delivery via tasks/result.\n     * @param taskId The task ID to associate the message with\n     * @param message The message to enqueue\n     * @param sessionId Optional session ID for binding the operation to a specific session\n     * @throws Error if taskStore is not configured or if enqueue fails (e.g., queue overflow)\n     *\n     * Note: If enqueue fails, it's the TaskMessageQueue implementation's responsibility to handle\n     * the error appropriately (e.g., by failing the task, logging, etc.). The Protocol layer\n     * simply propagates the error.\n     */\n    async _enqueueTaskMessage(taskId, message, sessionId) {\n        // Task message queues are only used when taskStore is configured\n        if (!this._taskStore || !this._taskMessageQueue) {\n            throw new Error('Cannot enqueue task message: taskStore and taskMessageQueue are not configured');\n        }\n        const maxQueueSize = this._options?.maxTaskQueueSize;\n        await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize);\n    }\n    /**\n     * Clears the message queue for a task and rejects any pending request resolvers.\n     * @param taskId The task ID whose queue should be cleared\n     * @param sessionId Optional session ID for binding the operation to a specific session\n     */\n    async _clearTaskQueue(taskId, sessionId) {\n        if (this._taskMessageQueue) {\n            // Reject any pending request resolvers\n            const messages = await this._taskMessageQueue.dequeueAll(taskId, sessionId);\n            for (const message of messages) {\n                if (message.type === 'request' && isJSONRPCRequest(message.message)) {\n                    // Extract request ID from the message\n                    const requestId = message.message.id;\n                    const resolver = this._requestResolvers.get(requestId);\n                    if (resolver) {\n                        resolver(new McpError(ErrorCode.InternalError, 'Task cancelled or completed'));\n                        this._requestResolvers.delete(requestId);\n                    }\n                    else {\n                        // Log error when resolver is missing during cleanup for better observability\n                        this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`));\n                    }\n                }\n            }\n        }\n    }\n    /**\n     * Waits for a task update (new messages or status change) with abort signal support.\n     * Uses polling to check for updates at the task's configured poll interval.\n     * @param taskId The task ID to wait for\n     * @param signal Abort signal to cancel the wait\n     * @returns Promise that resolves when an update occurs or rejects if aborted\n     */\n    async _waitForTaskUpdate(taskId, signal) {\n        // Get the task's poll interval, falling back to default\n        let interval = this._options?.defaultTaskPollInterval ?? 1000;\n        try {\n            const task = await this._taskStore?.getTask(taskId);\n            if (task?.pollInterval) {\n                interval = task.pollInterval;\n            }\n        }\n        catch {\n            // Use default interval if task lookup fails\n        }\n        return new Promise((resolve, reject) => {\n            if (signal.aborted) {\n                reject(new McpError(ErrorCode.InvalidRequest, 'Request cancelled'));\n                return;\n            }\n            // Wait for the poll interval, then resolve so caller can check for updates\n            const timeoutId = setTimeout(resolve, interval);\n            // Clean up timeout and reject if aborted\n            signal.addEventListener('abort', () => {\n                clearTimeout(timeoutId);\n                reject(new McpError(ErrorCode.InvalidRequest, 'Request cancelled'));\n            }, { once: true });\n        });\n    }\n    requestTaskStore(request, sessionId) {\n        const taskStore = this._taskStore;\n        if (!taskStore) {\n            throw new Error('No task store configured');\n        }\n        return {\n            createTask: async (taskParams) => {\n                if (!request) {\n                    throw new Error('No request provided');\n                }\n                return await taskStore.createTask(taskParams, request.id, {\n                    method: request.method,\n                    params: request.params\n                }, sessionId);\n            },\n            getTask: async (taskId) => {\n                const task = await taskStore.getTask(taskId, sessionId);\n                if (!task) {\n                    throw new McpError(ErrorCode.InvalidParams, 'Failed to retrieve task: Task not found');\n                }\n                return task;\n            },\n            storeTaskResult: async (taskId, status, result) => {\n                await taskStore.storeTaskResult(taskId, status, result, sessionId);\n                // Get updated task state and send notification\n                const task = await taskStore.getTask(taskId, sessionId);\n                if (task) {\n                    const notification = TaskStatusNotificationSchema.parse({\n                        method: 'notifications/tasks/status',\n                        params: task\n                    });\n                    await this.notification(notification);\n                    if (isTerminal(task.status)) {\n                        this._cleanupTaskProgressHandler(taskId);\n                        // Don't clear queue here - it will be cleared after delivery via tasks/result\n                    }\n                }\n            },\n            getTaskResult: taskId => {\n                return taskStore.getTaskResult(taskId, sessionId);\n            },\n            updateTaskStatus: async (taskId, status, statusMessage) => {\n                // Check if task exists\n                const task = await taskStore.getTask(taskId, sessionId);\n                if (!task) {\n                    throw new McpError(ErrorCode.InvalidParams, `Task \"${taskId}\" not found - it may have been cleaned up`);\n                }\n                // Don't allow transitions from terminal states\n                if (isTerminal(task.status)) {\n                    throw new McpError(ErrorCode.InvalidParams, `Cannot update task \"${taskId}\" from terminal status \"${task.status}\" to \"${status}\". Terminal states (completed, failed, cancelled) cannot transition to other states.`);\n                }\n                await taskStore.updateTaskStatus(taskId, status, statusMessage, sessionId);\n                // Get updated task state and send notification\n                const updatedTask = await taskStore.getTask(taskId, sessionId);\n                if (updatedTask) {\n                    const notification = TaskStatusNotificationSchema.parse({\n                        method: 'notifications/tasks/status',\n                        params: updatedTask\n                    });\n                    await this.notification(notification);\n                    if (isTerminal(updatedTask.status)) {\n                        this._cleanupTaskProgressHandler(taskId);\n                        // Don't clear queue here - it will be cleared after delivery via tasks/result\n                    }\n                }\n            },\n            listTasks: cursor => {\n                return taskStore.listTasks(cursor, sessionId);\n            }\n        };\n    }\n}\nfunction isPlainObject(value) {\n    return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\nexport function mergeCapabilities(base, additional) {\n    const result = { ...base };\n    for (const key in additional) {\n        const k = key;\n        const addValue = additional[k];\n        if (addValue === undefined)\n            continue;\n        const baseValue = result[k];\n        if (isPlainObject(baseValue) && isPlainObject(addValue)) {\n            result[k] = { ...baseValue, ...addValue };\n        }\n        else {\n            result[k] = addValue;\n        }\n    }\n    return result;\n}\n//# sourceMappingURL=protocol.js.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+\\-.]*:)?(?:\\/?\\/(?:(?:[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,\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","/**\n * Experimental client task features for MCP SDK.\n * WARNING: These APIs are experimental and may change without notice.\n *\n * @experimental\n */\nimport { CallToolResultSchema, McpError, ErrorCode } from '../../types.js';\n/**\n * Experimental task features for MCP clients.\n *\n * Access via `client.experimental.tasks`:\n * ```typescript\n * const stream = client.experimental.tasks.callToolStream({ name: 'tool', arguments: {} });\n * const task = await client.experimental.tasks.getTask(taskId);\n * ```\n *\n * @experimental\n */\nexport class ExperimentalClientTasks {\n    constructor(_client) {\n        this._client = _client;\n    }\n    /**\n     * Calls a tool and returns an AsyncGenerator that yields response messages.\n     * The generator is guaranteed to end with either a 'result' or 'error' message.\n     *\n     * This method provides streaming access to tool execution, allowing you to\n     * observe intermediate task status updates for long-running tool calls.\n     * Automatically validates structured output if the tool has an outputSchema.\n     *\n     * @example\n     * ```typescript\n     * const stream = client.experimental.tasks.callToolStream({ name: 'myTool', arguments: {} });\n     * for await (const message of stream) {\n     *   switch (message.type) {\n     *     case 'taskCreated':\n     *       console.log('Tool execution started:', message.task.taskId);\n     *       break;\n     *     case 'taskStatus':\n     *       console.log('Tool status:', message.task.status);\n     *       break;\n     *     case 'result':\n     *       console.log('Tool result:', message.result);\n     *       break;\n     *     case 'error':\n     *       console.error('Tool error:', message.error);\n     *       break;\n     *   }\n     * }\n     * ```\n     *\n     * @param params - Tool call parameters (name and arguments)\n     * @param resultSchema - Zod schema for validating the result (defaults to CallToolResultSchema)\n     * @param options - Optional request options (timeout, signal, task creation params, etc.)\n     * @returns AsyncGenerator that yields ResponseMessage objects\n     *\n     * @experimental\n     */\n    async *callToolStream(params, resultSchema = CallToolResultSchema, options) {\n        // Access Client's internal methods\n        const clientInternal = this._client;\n        // Add task creation parameters if server supports it and not explicitly provided\n        const optionsWithTask = {\n            ...options,\n            // We check if the tool is known to be a task during auto-configuration, but assume\n            // the caller knows what they're doing if they pass this explicitly\n            task: options?.task ?? (clientInternal.isToolTask(params.name) ? {} : undefined)\n        };\n        const stream = clientInternal.requestStream({ method: 'tools/call', params }, resultSchema, optionsWithTask);\n        // Get the validator for this tool (if it has an output schema)\n        const validator = clientInternal.getToolOutputValidator(params.name);\n        // Iterate through the stream and validate the final result if needed\n        for await (const message of stream) {\n            // If this is a result message and the tool has an output schema, validate it\n            if (message.type === 'result' && validator) {\n                const result = message.result;\n                // If tool has outputSchema, it MUST return structuredContent (unless it's an error)\n                if (!result.structuredContent && !result.isError) {\n                    yield {\n                        type: 'error',\n                        error: new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`)\n                    };\n                    return;\n                }\n                // Only validate structured content if present (not when there's an error)\n                if (result.structuredContent) {\n                    try {\n                        // Validate the structured content against the schema\n                        const validationResult = validator(result.structuredContent);\n                        if (!validationResult.valid) {\n                            yield {\n                                type: 'error',\n                                error: new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`)\n                            };\n                            return;\n                        }\n                    }\n                    catch (error) {\n                        if (error instanceof McpError) {\n                            yield { type: 'error', error };\n                            return;\n                        }\n                        yield {\n                            type: 'error',\n                            error: new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`)\n                        };\n                        return;\n                    }\n                }\n            }\n            // Yield the message (either validated result or any other message type)\n            yield message;\n        }\n    }\n    /**\n     * Gets the current status of a task.\n     *\n     * @param taskId - The task identifier\n     * @param options - Optional request options\n     * @returns The task status\n     *\n     * @experimental\n     */\n    async getTask(taskId, options) {\n        return this._client.getTask({ taskId }, options);\n    }\n    /**\n     * Retrieves the result of a completed task.\n     *\n     * @param taskId - The task identifier\n     * @param resultSchema - Zod schema for validating the result\n     * @param options - Optional request options\n     * @returns The task result\n     *\n     * @experimental\n     */\n    async getTaskResult(taskId, resultSchema, options) {\n        // Delegate to the client's underlying Protocol method\n        return this._client.getTaskResult({ taskId }, resultSchema, options);\n    }\n    /**\n     * Lists tasks with optional pagination.\n     *\n     * @param cursor - Optional pagination cursor\n     * @param options - Optional request options\n     * @returns List of tasks with optional next cursor\n     *\n     * @experimental\n     */\n    async listTasks(cursor, options) {\n        // Delegate to the client's underlying Protocol method\n        return this._client.listTasks(cursor ? { cursor } : undefined, options);\n    }\n    /**\n     * Cancels a running task.\n     *\n     * @param taskId - The task identifier\n     * @param options - Optional request options\n     *\n     * @experimental\n     */\n    async cancelTask(taskId, options) {\n        // Delegate to the client's underlying Protocol method\n        return this._client.cancelTask({ taskId }, options);\n    }\n    /**\n     * Sends a request and returns an AsyncGenerator that yields response messages.\n     * The generator is guaranteed to end with either a 'result' or 'error' message.\n     *\n     * This method provides streaming access to request processing, allowing you to\n     * observe intermediate task status updates for task-augmented requests.\n     *\n     * @param request - The request to send\n     * @param resultSchema - Zod schema for validating the result\n     * @param options - Optional request options (timeout, signal, task creation params, etc.)\n     * @returns AsyncGenerator that yields ResponseMessage objects\n     *\n     * @experimental\n     */\n    requestStream(request, resultSchema, options) {\n        return this._client.requestStream(request, resultSchema, options);\n    }\n}\n//# sourceMappingURL=client.js.map","/**\n * Experimental task capability assertion helpers.\n * WARNING: These APIs are experimental and may change without notice.\n *\n * @experimental\n */\n/**\n * Asserts that task creation is supported for tools/call.\n * Used by Client.assertTaskCapability and Server.assertTaskHandlerCapability.\n *\n * @param requests - The task requests capability object\n * @param method - The method being checked\n * @param entityName - 'Server' or 'Client' for error messages\n * @throws Error if the capability is not supported\n *\n * @experimental\n */\nexport function assertToolsCallTaskCapability(requests, method, entityName) {\n    if (!requests) {\n        throw new Error(`${entityName} does not support task creation (required for ${method})`);\n    }\n    switch (method) {\n        case 'tools/call':\n            if (!requests.tools?.call) {\n                throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`);\n            }\n            break;\n        default:\n            // Method doesn't support tasks, which is fine - no error\n            break;\n    }\n}\n/**\n * Asserts that task creation is supported for sampling/createMessage or elicitation/create.\n * Used by Server.assertTaskCapability and Client.assertTaskHandlerCapability.\n *\n * @param requests - The task requests capability object\n * @param method - The method being checked\n * @param entityName - 'Server' or 'Client' for error messages\n * @throws Error if the capability is not supported\n *\n * @experimental\n */\nexport function assertClientRequestTaskCapability(requests, method, entityName) {\n    if (!requests) {\n        throw new Error(`${entityName} does not support task creation (required for ${method})`);\n    }\n    switch (method) {\n        case 'sampling/createMessage':\n            if (!requests.sampling?.createMessage) {\n                throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`);\n            }\n            break;\n        case 'elicitation/create':\n            if (!requests.elicitation?.create) {\n                throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`);\n            }\n            break;\n        default:\n            // Method doesn't support tasks, which is fine - no error\n            break;\n    }\n}\n//# sourceMappingURL=helpers.js.map","import { mergeCapabilities, Protocol } from '../shared/protocol.js';\nimport { CallToolResultSchema, CompleteResultSchema, EmptyResultSchema, ErrorCode, GetPromptResultSchema, InitializeResultSchema, LATEST_PROTOCOL_VERSION, ListPromptsResultSchema, ListResourcesResultSchema, ListResourceTemplatesResultSchema, ListToolsResultSchema, McpError, ReadResourceResultSchema, SUPPORTED_PROTOCOL_VERSIONS, ElicitResultSchema, ElicitRequestSchema, CreateTaskResultSchema, CreateMessageRequestSchema, CreateMessageResultSchema, CreateMessageResultWithToolsSchema, ToolListChangedNotificationSchema, PromptListChangedNotificationSchema, ResourceListChangedNotificationSchema, ListChangedOptionsBaseSchema } from '../types.js';\nimport { AjvJsonSchemaValidator } from '../validation/ajv-provider.js';\nimport { getObjectShape, isZ4Schema, safeParse } from '../server/zod-compat.js';\nimport { ExperimentalClientTasks } from '../experimental/tasks/client.js';\nimport { assertToolsCallTaskCapability, assertClientRequestTaskCapability } from '../experimental/tasks/helpers.js';\n/**\n * Elicitation default application helper. Applies defaults to the data based on the schema.\n *\n * @param schema - The schema to apply defaults to.\n * @param data - The data to apply defaults to.\n */\nfunction applyElicitationDefaults(schema, data) {\n    if (!schema || data === null || typeof data !== 'object')\n        return;\n    // Handle object properties\n    if (schema.type === 'object' && schema.properties && typeof schema.properties === 'object') {\n        const obj = data;\n        const props = schema.properties;\n        for (const key of Object.keys(props)) {\n            const propSchema = props[key];\n            // If missing or explicitly undefined, apply default if present\n            if (obj[key] === undefined && Object.prototype.hasOwnProperty.call(propSchema, 'default')) {\n                obj[key] = propSchema.default;\n            }\n            // Recurse into existing nested objects/arrays\n            if (obj[key] !== undefined) {\n                applyElicitationDefaults(propSchema, obj[key]);\n            }\n        }\n    }\n    if (Array.isArray(schema.anyOf)) {\n        for (const sub of schema.anyOf) {\n            // Skip boolean schemas (true/false are valid JSON Schemas but have no defaults)\n            if (typeof sub !== 'boolean') {\n                applyElicitationDefaults(sub, data);\n            }\n        }\n    }\n    // Combine schemas\n    if (Array.isArray(schema.oneOf)) {\n        for (const sub of schema.oneOf) {\n            // Skip boolean schemas (true/false are valid JSON Schemas but have no defaults)\n            if (typeof sub !== 'boolean') {\n                applyElicitationDefaults(sub, data);\n            }\n        }\n    }\n}\n/**\n * Determines which elicitation modes are supported based on declared client capabilities.\n *\n * According to the spec:\n * - An empty elicitation capability object defaults to form mode support (backwards compatibility)\n * - URL mode is only supported if explicitly declared\n *\n * @param capabilities - The client's elicitation capabilities\n * @returns An object indicating which modes are supported\n */\nexport function getSupportedElicitationModes(capabilities) {\n    if (!capabilities) {\n        return { supportsFormMode: false, supportsUrlMode: false };\n    }\n    const hasFormCapability = capabilities.form !== undefined;\n    const hasUrlCapability = capabilities.url !== undefined;\n    // If neither form nor url are explicitly declared, form mode is supported (backwards compatibility)\n    const supportsFormMode = hasFormCapability || (!hasFormCapability && !hasUrlCapability);\n    const supportsUrlMode = hasUrlCapability;\n    return { supportsFormMode, supportsUrlMode };\n}\n/**\n * An MCP client on top of a pluggable transport.\n *\n * The client will automatically begin the initialization flow with the server when connect() is called.\n *\n * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters:\n *\n * ```typescript\n * // Custom schemas\n * const CustomRequestSchema = RequestSchema.extend({...})\n * const CustomNotificationSchema = NotificationSchema.extend({...})\n * const CustomResultSchema = ResultSchema.extend({...})\n *\n * // Type aliases\n * type CustomRequest = z.infer<typeof CustomRequestSchema>\n * type CustomNotification = z.infer<typeof CustomNotificationSchema>\n * type CustomResult = z.infer<typeof CustomResultSchema>\n *\n * // Create typed client\n * const client = new Client<CustomRequest, CustomNotification, CustomResult>({\n *   name: \"CustomClient\",\n *   version: \"1.0.0\"\n * })\n * ```\n */\nexport class Client extends Protocol {\n    /**\n     * Initializes this client with the given name and version information.\n     */\n    constructor(_clientInfo, options) {\n        super(options);\n        this._clientInfo = _clientInfo;\n        this._cachedToolOutputValidators = new Map();\n        this._cachedKnownTaskTools = new Set();\n        this._cachedRequiredTaskTools = new Set();\n        this._listChangedDebounceTimers = new Map();\n        this._capabilities = options?.capabilities ?? {};\n        this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator();\n        // Store list changed config for setup after connection (when we know server capabilities)\n        if (options?.listChanged) {\n            this._pendingListChangedConfig = options.listChanged;\n        }\n    }\n    /**\n     * Set up handlers for list changed notifications based on config and server capabilities.\n     * This should only be called after initialization when server capabilities are known.\n     * Handlers are silently skipped if the server doesn't advertise the corresponding listChanged capability.\n     * @internal\n     */\n    _setupListChangedHandlers(config) {\n        if (config.tools && this._serverCapabilities?.tools?.listChanged) {\n            this._setupListChangedHandler('tools', ToolListChangedNotificationSchema, config.tools, async () => {\n                const result = await this.listTools();\n                return result.tools;\n            });\n        }\n        if (config.prompts && this._serverCapabilities?.prompts?.listChanged) {\n            this._setupListChangedHandler('prompts', PromptListChangedNotificationSchema, config.prompts, async () => {\n                const result = await this.listPrompts();\n                return result.prompts;\n            });\n        }\n        if (config.resources && this._serverCapabilities?.resources?.listChanged) {\n            this._setupListChangedHandler('resources', ResourceListChangedNotificationSchema, config.resources, async () => {\n                const result = await this.listResources();\n                return result.resources;\n            });\n        }\n    }\n    /**\n     * Access experimental features.\n     *\n     * WARNING: These APIs are experimental and may change without notice.\n     *\n     * @experimental\n     */\n    get experimental() {\n        if (!this._experimental) {\n            this._experimental = {\n                tasks: new ExperimentalClientTasks(this)\n            };\n        }\n        return this._experimental;\n    }\n    /**\n     * Registers new capabilities. This can only be called before connecting to a transport.\n     *\n     * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization).\n     */\n    registerCapabilities(capabilities) {\n        if (this.transport) {\n            throw new Error('Cannot register capabilities after connecting to transport');\n        }\n        this._capabilities = mergeCapabilities(this._capabilities, capabilities);\n    }\n    /**\n     * Override request handler registration to enforce client-side validation for elicitation.\n     */\n    setRequestHandler(requestSchema, handler) {\n        const shape = getObjectShape(requestSchema);\n        const methodSchema = shape?.method;\n        if (!methodSchema) {\n            throw new Error('Schema is missing a method literal');\n        }\n        // Extract literal value using type-safe property access\n        let methodValue;\n        if (isZ4Schema(methodSchema)) {\n            const v4Schema = methodSchema;\n            const v4Def = v4Schema._zod?.def;\n            methodValue = v4Def?.value ?? v4Schema.value;\n        }\n        else {\n            const v3Schema = methodSchema;\n            const legacyDef = v3Schema._def;\n            methodValue = legacyDef?.value ?? v3Schema.value;\n        }\n        if (typeof methodValue !== 'string') {\n            throw new Error('Schema method literal must be a string');\n        }\n        const method = methodValue;\n        if (method === 'elicitation/create') {\n            const wrappedHandler = async (request, extra) => {\n                const validatedRequest = safeParse(ElicitRequestSchema, request);\n                if (!validatedRequest.success) {\n                    // Type guard: if success is false, error is guaranteed to exist\n                    const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);\n                    throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation request: ${errorMessage}`);\n                }\n                const { params } = validatedRequest.data;\n                params.mode = params.mode ?? 'form';\n                const { supportsFormMode, supportsUrlMode } = getSupportedElicitationModes(this._capabilities.elicitation);\n                if (params.mode === 'form' && !supportsFormMode) {\n                    throw new McpError(ErrorCode.InvalidParams, 'Client does not support form-mode elicitation requests');\n                }\n                if (params.mode === 'url' && !supportsUrlMode) {\n                    throw new McpError(ErrorCode.InvalidParams, 'Client does not support URL-mode elicitation requests');\n                }\n                const result = await Promise.resolve(handler(request, extra));\n                // When task creation is requested, validate and return CreateTaskResult\n                if (params.task) {\n                    const taskValidationResult = safeParse(CreateTaskResultSchema, result);\n                    if (!taskValidationResult.success) {\n                        const errorMessage = taskValidationResult.error instanceof Error\n                            ? taskValidationResult.error.message\n                            : String(taskValidationResult.error);\n                        throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);\n                    }\n                    return taskValidationResult.data;\n                }\n                // For non-task requests, validate against ElicitResultSchema\n                const validationResult = safeParse(ElicitResultSchema, result);\n                if (!validationResult.success) {\n                    // Type guard: if success is false, error is guaranteed to exist\n                    const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);\n                    throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation result: ${errorMessage}`);\n                }\n                const validatedResult = validationResult.data;\n                const requestedSchema = params.mode === 'form' ? params.requestedSchema : undefined;\n                if (params.mode === 'form' && validatedResult.action === 'accept' && validatedResult.content && requestedSchema) {\n                    if (this._capabilities.elicitation?.form?.applyDefaults) {\n                        try {\n                            applyElicitationDefaults(requestedSchema, validatedResult.content);\n                        }\n                        catch {\n                            // gracefully ignore errors in default application\n                        }\n                    }\n                }\n                return validatedResult;\n            };\n            // Install the wrapped handler\n            return super.setRequestHandler(requestSchema, wrappedHandler);\n        }\n        if (method === 'sampling/createMessage') {\n            const wrappedHandler = async (request, extra) => {\n                const validatedRequest = safeParse(CreateMessageRequestSchema, request);\n                if (!validatedRequest.success) {\n                    const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);\n                    throw new McpError(ErrorCode.InvalidParams, `Invalid sampling request: ${errorMessage}`);\n                }\n                const { params } = validatedRequest.data;\n                const result = await Promise.resolve(handler(request, extra));\n                // When task creation is requested, validate and return CreateTaskResult\n                if (params.task) {\n                    const taskValidationResult = safeParse(CreateTaskResultSchema, result);\n                    if (!taskValidationResult.success) {\n                        const errorMessage = taskValidationResult.error instanceof Error\n                            ? taskValidationResult.error.message\n                            : String(taskValidationResult.error);\n                        throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);\n                    }\n                    return taskValidationResult.data;\n                }\n                // For non-task requests, validate against appropriate schema based on tools presence\n                const hasTools = params.tools || params.toolChoice;\n                const resultSchema = hasTools ? CreateMessageResultWithToolsSchema : CreateMessageResultSchema;\n                const validationResult = safeParse(resultSchema, result);\n                if (!validationResult.success) {\n                    const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);\n                    throw new McpError(ErrorCode.InvalidParams, `Invalid sampling result: ${errorMessage}`);\n                }\n                return validationResult.data;\n            };\n            // Install the wrapped handler\n            return super.setRequestHandler(requestSchema, wrappedHandler);\n        }\n        // Other handlers use default behavior\n        return super.setRequestHandler(requestSchema, handler);\n    }\n    assertCapability(capability, method) {\n        if (!this._serverCapabilities?.[capability]) {\n            throw new Error(`Server does not support ${capability} (required for ${method})`);\n        }\n    }\n    async connect(transport, options) {\n        await super.connect(transport);\n        // When transport sessionId is already set this means we are trying to reconnect.\n        // In this case we don't need to initialize again.\n        if (transport.sessionId !== undefined) {\n            return;\n        }\n        try {\n            const result = await this.request({\n                method: 'initialize',\n                params: {\n                    protocolVersion: LATEST_PROTOCOL_VERSION,\n                    capabilities: this._capabilities,\n                    clientInfo: this._clientInfo\n                }\n            }, InitializeResultSchema, options);\n            if (result === undefined) {\n                throw new Error(`Server sent invalid initialize result: ${result}`);\n            }\n            if (!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) {\n                throw new Error(`Server's protocol version is not supported: ${result.protocolVersion}`);\n            }\n            this._serverCapabilities = result.capabilities;\n            this._serverVersion = result.serverInfo;\n            // HTTP transports must set the protocol version in each header after initialization.\n            if (transport.setProtocolVersion) {\n                transport.setProtocolVersion(result.protocolVersion);\n            }\n            this._instructions = result.instructions;\n            await this.notification({\n                method: 'notifications/initialized'\n            });\n            // Set up list changed handlers now that we know server capabilities\n            if (this._pendingListChangedConfig) {\n                this._setupListChangedHandlers(this._pendingListChangedConfig);\n                this._pendingListChangedConfig = undefined;\n            }\n        }\n        catch (error) {\n            // Disconnect if initialization fails.\n            void this.close();\n            throw error;\n        }\n    }\n    /**\n     * After initialization has completed, this will be populated with the server's reported capabilities.\n     */\n    getServerCapabilities() {\n        return this._serverCapabilities;\n    }\n    /**\n     * After initialization has completed, this will be populated with information about the server's name and version.\n     */\n    getServerVersion() {\n        return this._serverVersion;\n    }\n    /**\n     * After initialization has completed, this may be populated with information about the server's instructions.\n     */\n    getInstructions() {\n        return this._instructions;\n    }\n    assertCapabilityForMethod(method) {\n        switch (method) {\n            case 'logging/setLevel':\n                if (!this._serverCapabilities?.logging) {\n                    throw new Error(`Server does not support logging (required for ${method})`);\n                }\n                break;\n            case 'prompts/get':\n            case 'prompts/list':\n                if (!this._serverCapabilities?.prompts) {\n                    throw new Error(`Server does not support prompts (required for ${method})`);\n                }\n                break;\n            case 'resources/list':\n            case 'resources/templates/list':\n            case 'resources/read':\n            case 'resources/subscribe':\n            case 'resources/unsubscribe':\n                if (!this._serverCapabilities?.resources) {\n                    throw new Error(`Server does not support resources (required for ${method})`);\n                }\n                if (method === 'resources/subscribe' && !this._serverCapabilities.resources.subscribe) {\n                    throw new Error(`Server does not support resource subscriptions (required for ${method})`);\n                }\n                break;\n            case 'tools/call':\n            case 'tools/list':\n                if (!this._serverCapabilities?.tools) {\n                    throw new Error(`Server does not support tools (required for ${method})`);\n                }\n                break;\n            case 'completion/complete':\n                if (!this._serverCapabilities?.completions) {\n                    throw new Error(`Server does not support completions (required for ${method})`);\n                }\n                break;\n            case 'initialize':\n                // No specific capability required for initialize\n                break;\n            case 'ping':\n                // No specific capability required for ping\n                break;\n        }\n    }\n    assertNotificationCapability(method) {\n        switch (method) {\n            case 'notifications/roots/list_changed':\n                if (!this._capabilities.roots?.listChanged) {\n                    throw new Error(`Client does not support roots list changed notifications (required for ${method})`);\n                }\n                break;\n            case 'notifications/initialized':\n                // No specific capability required for initialized\n                break;\n            case 'notifications/cancelled':\n                // Cancellation notifications are always allowed\n                break;\n            case 'notifications/progress':\n                // Progress notifications are always allowed\n                break;\n        }\n    }\n    assertRequestHandlerCapability(method) {\n        // Task handlers are registered in Protocol constructor before _capabilities is initialized\n        // Skip capability check for task methods during initialization\n        if (!this._capabilities) {\n            return;\n        }\n        switch (method) {\n            case 'sampling/createMessage':\n                if (!this._capabilities.sampling) {\n                    throw new Error(`Client does not support sampling capability (required for ${method})`);\n                }\n                break;\n            case 'elicitation/create':\n                if (!this._capabilities.elicitation) {\n                    throw new Error(`Client does not support elicitation capability (required for ${method})`);\n                }\n                break;\n            case 'roots/list':\n                if (!this._capabilities.roots) {\n                    throw new Error(`Client does not support roots capability (required for ${method})`);\n                }\n                break;\n            case 'tasks/get':\n            case 'tasks/list':\n            case 'tasks/result':\n            case 'tasks/cancel':\n                if (!this._capabilities.tasks) {\n                    throw new Error(`Client does not support tasks capability (required for ${method})`);\n                }\n                break;\n            case 'ping':\n                // No specific capability required for ping\n                break;\n        }\n    }\n    assertTaskCapability(method) {\n        assertToolsCallTaskCapability(this._serverCapabilities?.tasks?.requests, method, 'Server');\n    }\n    assertTaskHandlerCapability(method) {\n        // Task handlers are registered in Protocol constructor before _capabilities is initialized\n        // Skip capability check for task methods during initialization\n        if (!this._capabilities) {\n            return;\n        }\n        assertClientRequestTaskCapability(this._capabilities.tasks?.requests, method, 'Client');\n    }\n    async ping(options) {\n        return this.request({ method: 'ping' }, EmptyResultSchema, options);\n    }\n    async complete(params, options) {\n        return this.request({ method: 'completion/complete', params }, CompleteResultSchema, options);\n    }\n    async setLoggingLevel(level, options) {\n        return this.request({ method: 'logging/setLevel', params: { level } }, EmptyResultSchema, options);\n    }\n    async getPrompt(params, options) {\n        return this.request({ method: 'prompts/get', params }, GetPromptResultSchema, options);\n    }\n    async listPrompts(params, options) {\n        return this.request({ method: 'prompts/list', params }, ListPromptsResultSchema, options);\n    }\n    async listResources(params, options) {\n        return this.request({ method: 'resources/list', params }, ListResourcesResultSchema, options);\n    }\n    async listResourceTemplates(params, options) {\n        return this.request({ method: 'resources/templates/list', params }, ListResourceTemplatesResultSchema, options);\n    }\n    async readResource(params, options) {\n        return this.request({ method: 'resources/read', params }, ReadResourceResultSchema, options);\n    }\n    async subscribeResource(params, options) {\n        return this.request({ method: 'resources/subscribe', params }, EmptyResultSchema, options);\n    }\n    async unsubscribeResource(params, options) {\n        return this.request({ method: 'resources/unsubscribe', params }, EmptyResultSchema, options);\n    }\n    /**\n     * Calls a tool and waits for the result. Automatically validates structured output if the tool has an outputSchema.\n     *\n     * For task-based execution with streaming behavior, use client.experimental.tasks.callToolStream() instead.\n     */\n    async callTool(params, resultSchema = CallToolResultSchema, options) {\n        // Guard: required-task tools need experimental API\n        if (this.isToolTaskRequired(params.name)) {\n            throw new McpError(ErrorCode.InvalidRequest, `Tool \"${params.name}\" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);\n        }\n        const result = await this.request({ method: 'tools/call', params }, resultSchema, options);\n        // Check if the tool has an outputSchema\n        const validator = this.getToolOutputValidator(params.name);\n        if (validator) {\n            // If tool has outputSchema, it MUST return structuredContent (unless it's an error)\n            if (!result.structuredContent && !result.isError) {\n                throw new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`);\n            }\n            // Only validate structured content if present (not when there's an error)\n            if (result.structuredContent) {\n                try {\n                    // Validate the structured content against the schema\n                    const validationResult = validator(result.structuredContent);\n                    if (!validationResult.valid) {\n                        throw new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`);\n                    }\n                }\n                catch (error) {\n                    if (error instanceof McpError) {\n                        throw error;\n                    }\n                    throw new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`);\n                }\n            }\n        }\n        return result;\n    }\n    isToolTask(toolName) {\n        if (!this._serverCapabilities?.tasks?.requests?.tools?.call) {\n            return false;\n        }\n        return this._cachedKnownTaskTools.has(toolName);\n    }\n    /**\n     * Check if a tool requires task-based execution.\n     * Unlike isToolTask which includes 'optional' tools, this only checks for 'required'.\n     */\n    isToolTaskRequired(toolName) {\n        return this._cachedRequiredTaskTools.has(toolName);\n    }\n    /**\n     * Cache validators for tool output schemas.\n     * Called after listTools() to pre-compile validators for better performance.\n     */\n    cacheToolMetadata(tools) {\n        this._cachedToolOutputValidators.clear();\n        this._cachedKnownTaskTools.clear();\n        this._cachedRequiredTaskTools.clear();\n        for (const tool of tools) {\n            // If the tool has an outputSchema, create and cache the validator\n            if (tool.outputSchema) {\n                const toolValidator = this._jsonSchemaValidator.getValidator(tool.outputSchema);\n                this._cachedToolOutputValidators.set(tool.name, toolValidator);\n            }\n            // If the tool supports task-based execution, cache that information\n            const taskSupport = tool.execution?.taskSupport;\n            if (taskSupport === 'required' || taskSupport === 'optional') {\n                this._cachedKnownTaskTools.add(tool.name);\n            }\n            if (taskSupport === 'required') {\n                this._cachedRequiredTaskTools.add(tool.name);\n            }\n        }\n    }\n    /**\n     * Get cached validator for a tool\n     */\n    getToolOutputValidator(toolName) {\n        return this._cachedToolOutputValidators.get(toolName);\n    }\n    async listTools(params, options) {\n        const result = await this.request({ method: 'tools/list', params }, ListToolsResultSchema, options);\n        // Cache the tools and their output schemas for future validation\n        this.cacheToolMetadata(result.tools);\n        return result;\n    }\n    /**\n     * Set up a single list changed handler.\n     * @internal\n     */\n    _setupListChangedHandler(listType, notificationSchema, options, fetcher) {\n        // Validate options using Zod schema (validates autoRefresh and debounceMs)\n        const parseResult = ListChangedOptionsBaseSchema.safeParse(options);\n        if (!parseResult.success) {\n            throw new Error(`Invalid ${listType} listChanged options: ${parseResult.error.message}`);\n        }\n        // Validate callback\n        if (typeof options.onChanged !== 'function') {\n            throw new Error(`Invalid ${listType} listChanged options: onChanged must be a function`);\n        }\n        const { autoRefresh, debounceMs } = parseResult.data;\n        const { onChanged } = options;\n        const refresh = async () => {\n            if (!autoRefresh) {\n                onChanged(null, null);\n                return;\n            }\n            try {\n                const items = await fetcher();\n                onChanged(null, items);\n            }\n            catch (e) {\n                const error = e instanceof Error ? e : new Error(String(e));\n                onChanged(error, null);\n            }\n        };\n        const handler = () => {\n            if (debounceMs) {\n                // Clear any pending debounce timer for this list type\n                const existingTimer = this._listChangedDebounceTimers.get(listType);\n                if (existingTimer) {\n                    clearTimeout(existingTimer);\n                }\n                // Set up debounced refresh\n                const timer = setTimeout(refresh, debounceMs);\n                this._listChangedDebounceTimers.set(listType, timer);\n            }\n            else {\n                // No debounce, refresh immediately\n                refresh();\n            }\n        };\n        // Register notification handler\n        this.setNotificationHandler(notificationSchema, handler);\n    }\n    async sendRootsListChanged() {\n        return this.notification({ method: 'notifications/roots/list_changed' });\n    }\n}\n//# sourceMappingURL=index.js.map","/**\n * Normalizes HeadersInit to a plain Record<string, string> for manipulation.\n * Handles Headers objects, arrays of tuples, and plain objects.\n */\nexport function normalizeHeaders(headers) {\n    if (!headers)\n        return {};\n    if (headers instanceof Headers) {\n        return Object.fromEntries(headers.entries());\n    }\n    if (Array.isArray(headers)) {\n        return Object.fromEntries(headers);\n    }\n    return { ...headers };\n}\n/**\n * Creates a fetch function that includes base RequestInit options.\n * This ensures requests inherit settings like credentials, mode, headers, etc. from the base init.\n *\n * @param baseFetch - The base fetch function to wrap (defaults to global fetch)\n * @param baseInit - The base RequestInit to merge with each request\n * @returns A wrapped fetch function that merges base options with call-specific options\n */\nexport function createFetchWithInit(baseFetch = fetch, baseInit) {\n    if (!baseInit) {\n        return baseFetch;\n    }\n    // Return a wrapped fetch that merges base RequestInit with call-specific init\n    return async (url, init) => {\n        const mergedInit = {\n            ...baseInit,\n            ...init,\n            // Headers need special handling - merge instead of replace\n            headers: init?.headers ? { ...normalizeHeaders(baseInit.headers), ...normalizeHeaders(init.headers) } : baseInit.headers\n        };\n        return baseFetch(url, mergedInit);\n    };\n}\n//# sourceMappingURL=transport.js.map","import { createFetchWithInit, normalizeHeaders } from '../shared/transport.js';\nimport { isInitializedNotification, isJSONRPCRequest, isJSONRPCResultResponse, JSONRPCMessageSchema } from '../types.js';\nimport { auth, extractWWWAuthenticateParams, UnauthorizedError } from './auth.js';\nimport { EventSourceParserStream } from 'eventsource-parser/stream';\n// Default reconnection options for StreamableHTTP connections\nconst DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS = {\n    initialReconnectionDelay: 1000,\n    maxReconnectionDelay: 30000,\n    reconnectionDelayGrowFactor: 1.5,\n    maxRetries: 2\n};\nexport class StreamableHTTPError extends Error {\n    constructor(code, message) {\n        super(`Streamable HTTP error: ${message}`);\n        this.code = code;\n    }\n}\n/**\n * Client transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification.\n * It will connect to a server using HTTP POST for sending messages and HTTP GET with Server-Sent Events\n * for receiving messages.\n */\nexport class StreamableHTTPClientTransport {\n    constructor(url, opts) {\n        this._hasCompletedAuthFlow = false; // Circuit breaker: detect auth success followed by immediate 401\n        this._url = url;\n        this._resourceMetadataUrl = undefined;\n        this._scope = undefined;\n        this._requestInit = opts?.requestInit;\n        this._authProvider = opts?.authProvider;\n        this._fetch = opts?.fetch;\n        this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit);\n        this._sessionId = opts?.sessionId;\n        this._reconnectionOptions = opts?.reconnectionOptions ?? DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS;\n    }\n    async _authThenStart() {\n        if (!this._authProvider) {\n            throw new UnauthorizedError('No auth provider');\n        }\n        let result;\n        try {\n            result = await auth(this._authProvider, {\n                serverUrl: this._url,\n                resourceMetadataUrl: this._resourceMetadataUrl,\n                scope: this._scope,\n                fetchFn: this._fetchWithInit\n            });\n        }\n        catch (error) {\n            this.onerror?.(error);\n            throw error;\n        }\n        if (result !== 'AUTHORIZED') {\n            throw new UnauthorizedError();\n        }\n        return await this._startOrAuthSse({ resumptionToken: undefined });\n    }\n    async _commonHeaders() {\n        const headers = {};\n        if (this._authProvider) {\n            const tokens = await this._authProvider.tokens();\n            if (tokens) {\n                headers['Authorization'] = `Bearer ${tokens.access_token}`;\n            }\n        }\n        if (this._sessionId) {\n            headers['mcp-session-id'] = this._sessionId;\n        }\n        if (this._protocolVersion) {\n            headers['mcp-protocol-version'] = this._protocolVersion;\n        }\n        const extraHeaders = normalizeHeaders(this._requestInit?.headers);\n        return new Headers({\n            ...headers,\n            ...extraHeaders\n        });\n    }\n    async _startOrAuthSse(options) {\n        const { resumptionToken } = options;\n        try {\n            // Try to open an initial SSE stream with GET to listen for server messages\n            // This is optional according to the spec - server may not support it\n            const headers = await this._commonHeaders();\n            headers.set('Accept', 'text/event-stream');\n            // Include Last-Event-ID header for resumable streams if provided\n            if (resumptionToken) {\n                headers.set('last-event-id', resumptionToken);\n            }\n            const response = await (this._fetch ?? fetch)(this._url, {\n                method: 'GET',\n                headers,\n                signal: this._abortController?.signal\n            });\n            if (!response.ok) {\n                await response.body?.cancel();\n                if (response.status === 401 && this._authProvider) {\n                    // Need to authenticate\n                    return await this._authThenStart();\n                }\n                // 405 indicates that the server does not offer an SSE stream at GET endpoint\n                // This is an expected case that should not trigger an error\n                if (response.status === 405) {\n                    return;\n                }\n                throw new StreamableHTTPError(response.status, `Failed to open SSE stream: ${response.statusText}`);\n            }\n            this._handleSseStream(response.body, options, true);\n        }\n        catch (error) {\n            this.onerror?.(error);\n            throw error;\n        }\n    }\n    /**\n     * Calculates the next reconnection delay using  backoff algorithm\n     *\n     * @param attempt Current reconnection attempt count for the specific stream\n     * @returns Time to wait in milliseconds before next reconnection attempt\n     */\n    _getNextReconnectionDelay(attempt) {\n        // Use server-provided retry value if available\n        if (this._serverRetryMs !== undefined) {\n            return this._serverRetryMs;\n        }\n        // Fall back to exponential backoff\n        const initialDelay = this._reconnectionOptions.initialReconnectionDelay;\n        const growFactor = this._reconnectionOptions.reconnectionDelayGrowFactor;\n        const maxDelay = this._reconnectionOptions.maxReconnectionDelay;\n        // Cap at maximum delay\n        return Math.min(initialDelay * Math.pow(growFactor, attempt), maxDelay);\n    }\n    /**\n     * Schedule a reconnection attempt using server-provided retry interval or backoff\n     *\n     * @param lastEventId The ID of the last received event for resumability\n     * @param attemptCount Current reconnection attempt count for this specific stream\n     */\n    _scheduleReconnection(options, attemptCount = 0) {\n        // Use provided options or default options\n        const maxRetries = this._reconnectionOptions.maxRetries;\n        // Check if we've exceeded maximum retry attempts\n        if (attemptCount >= maxRetries) {\n            this.onerror?.(new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`));\n            return;\n        }\n        // Calculate next delay based on current attempt count\n        const delay = this._getNextReconnectionDelay(attemptCount);\n        // Schedule the reconnection\n        this._reconnectionTimeout = setTimeout(() => {\n            // Use the last event ID to resume where we left off\n            this._startOrAuthSse(options).catch(error => {\n                this.onerror?.(new Error(`Failed to reconnect SSE stream: ${error instanceof Error ? error.message : String(error)}`));\n                // Schedule another attempt if this one failed, incrementing the attempt counter\n                this._scheduleReconnection(options, attemptCount + 1);\n            });\n        }, delay);\n    }\n    _handleSseStream(stream, options, isReconnectable) {\n        if (!stream) {\n            return;\n        }\n        const { onresumptiontoken, replayMessageId } = options;\n        let lastEventId;\n        // Track whether we've received a priming event (event with ID)\n        // Per spec, server SHOULD send a priming event with ID before closing\n        let hasPrimingEvent = false;\n        // Track whether we've received a response - if so, no need to reconnect\n        // Reconnection is for when server disconnects BEFORE sending response\n        let receivedResponse = false;\n        const processStream = async () => {\n            // this is the closest we can get to trying to catch network errors\n            // if something happens reader will throw\n            try {\n                // Create a pipeline: binary stream -> text decoder -> SSE parser\n                const reader = stream\n                    .pipeThrough(new TextDecoderStream())\n                    .pipeThrough(new EventSourceParserStream({\n                    onRetry: (retryMs) => {\n                        // Capture server-provided retry value for reconnection timing\n                        this._serverRetryMs = retryMs;\n                    }\n                }))\n                    .getReader();\n                while (true) {\n                    const { value: event, done } = await reader.read();\n                    if (done) {\n                        break;\n                    }\n                    // Update last event ID if provided\n                    if (event.id) {\n                        lastEventId = event.id;\n                        // Mark that we've received a priming event - stream is now resumable\n                        hasPrimingEvent = true;\n                        onresumptiontoken?.(event.id);\n                    }\n                    // Skip events with no data (priming events, keep-alives)\n                    if (!event.data) {\n                        continue;\n                    }\n                    if (!event.event || event.event === 'message') {\n                        try {\n                            const message = JSONRPCMessageSchema.parse(JSON.parse(event.data));\n                            if (isJSONRPCResultResponse(message)) {\n                                // Mark that we received a response - no need to reconnect for this request\n                                receivedResponse = true;\n                                if (replayMessageId !== undefined) {\n                                    message.id = replayMessageId;\n                                }\n                            }\n                            this.onmessage?.(message);\n                        }\n                        catch (error) {\n                            this.onerror?.(error);\n                        }\n                    }\n                }\n                // Handle graceful server-side disconnect\n                // Server may close connection after sending event ID and retry field\n                // Reconnect if: already reconnectable (GET stream) OR received a priming event (POST stream with event ID)\n                // BUT don't reconnect if we already received a response - the request is complete\n                const canResume = isReconnectable || hasPrimingEvent;\n                const needsReconnect = canResume && !receivedResponse;\n                if (needsReconnect && this._abortController && !this._abortController.signal.aborted) {\n                    this._scheduleReconnection({\n                        resumptionToken: lastEventId,\n                        onresumptiontoken,\n                        replayMessageId\n                    }, 0);\n                }\n            }\n            catch (error) {\n                // Handle stream errors - likely a network disconnect\n                this.onerror?.(new Error(`SSE stream disconnected: ${error}`));\n                // Attempt to reconnect if the stream disconnects unexpectedly and we aren't closing\n                // Reconnect if: already reconnectable (GET stream) OR received a priming event (POST stream with event ID)\n                // BUT don't reconnect if we already received a response - the request is complete\n                const canResume = isReconnectable || hasPrimingEvent;\n                const needsReconnect = canResume && !receivedResponse;\n                if (needsReconnect && this._abortController && !this._abortController.signal.aborted) {\n                    // Use the exponential backoff reconnection strategy\n                    try {\n                        this._scheduleReconnection({\n                            resumptionToken: lastEventId,\n                            onresumptiontoken,\n                            replayMessageId\n                        }, 0);\n                    }\n                    catch (error) {\n                        this.onerror?.(new Error(`Failed to reconnect: ${error instanceof Error ? error.message : String(error)}`));\n                    }\n                }\n            }\n        };\n        processStream();\n    }\n    async start() {\n        if (this._abortController) {\n            throw new Error('StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.');\n        }\n        this._abortController = new AbortController();\n    }\n    /**\n     * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth.\n     */\n    async finishAuth(authorizationCode) {\n        if (!this._authProvider) {\n            throw new UnauthorizedError('No auth provider');\n        }\n        const result = await auth(this._authProvider, {\n            serverUrl: this._url,\n            authorizationCode,\n            resourceMetadataUrl: this._resourceMetadataUrl,\n            scope: this._scope,\n            fetchFn: this._fetchWithInit\n        });\n        if (result !== 'AUTHORIZED') {\n            throw new UnauthorizedError('Failed to authorize');\n        }\n    }\n    async close() {\n        if (this._reconnectionTimeout) {\n            clearTimeout(this._reconnectionTimeout);\n            this._reconnectionTimeout = undefined;\n        }\n        this._abortController?.abort();\n        this.onclose?.();\n    }\n    async send(message, options) {\n        try {\n            const { resumptionToken, onresumptiontoken } = options || {};\n            if (resumptionToken) {\n                // If we have at last event ID, we need to reconnect the SSE stream\n                this._startOrAuthSse({ resumptionToken, replayMessageId: isJSONRPCRequest(message) ? message.id : undefined }).catch(err => this.onerror?.(err));\n                return;\n            }\n            const headers = await this._commonHeaders();\n            headers.set('content-type', 'application/json');\n            headers.set('accept', 'application/json, text/event-stream');\n            const init = {\n                ...this._requestInit,\n                method: 'POST',\n                headers,\n                body: JSON.stringify(message),\n                signal: this._abortController?.signal\n            };\n            const response = await (this._fetch ?? fetch)(this._url, init);\n            // Handle session ID received during initialization\n            const sessionId = response.headers.get('mcp-session-id');\n            if (sessionId) {\n                this._sessionId = sessionId;\n            }\n            if (!response.ok) {\n                const text = await response.text().catch(() => null);\n                if (response.status === 401 && this._authProvider) {\n                    // Prevent infinite recursion when server returns 401 after successful auth\n                    if (this._hasCompletedAuthFlow) {\n                        throw new StreamableHTTPError(401, 'Server returned 401 after successful authentication');\n                    }\n                    const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);\n                    this._resourceMetadataUrl = resourceMetadataUrl;\n                    this._scope = scope;\n                    const result = await auth(this._authProvider, {\n                        serverUrl: this._url,\n                        resourceMetadataUrl: this._resourceMetadataUrl,\n                        scope: this._scope,\n                        fetchFn: this._fetchWithInit\n                    });\n                    if (result !== 'AUTHORIZED') {\n                        throw new UnauthorizedError();\n                    }\n                    // Mark that we completed auth flow\n                    this._hasCompletedAuthFlow = true;\n                    // Purposely _not_ awaited, so we don't call onerror twice\n                    return this.send(message);\n                }\n                if (response.status === 403 && this._authProvider) {\n                    const { resourceMetadataUrl, scope, error } = extractWWWAuthenticateParams(response);\n                    if (error === 'insufficient_scope') {\n                        const wwwAuthHeader = response.headers.get('WWW-Authenticate');\n                        // Check if we've already tried upscoping with this header to prevent infinite loops.\n                        if (this._lastUpscopingHeader === wwwAuthHeader) {\n                            throw new StreamableHTTPError(403, 'Server returned 403 after trying upscoping');\n                        }\n                        if (scope) {\n                            this._scope = scope;\n                        }\n                        if (resourceMetadataUrl) {\n                            this._resourceMetadataUrl = resourceMetadataUrl;\n                        }\n                        // Mark that upscoping was tried.\n                        this._lastUpscopingHeader = wwwAuthHeader ?? undefined;\n                        const result = await auth(this._authProvider, {\n                            serverUrl: this._url,\n                            resourceMetadataUrl: this._resourceMetadataUrl,\n                            scope: this._scope,\n                            fetchFn: this._fetch\n                        });\n                        if (result !== 'AUTHORIZED') {\n                            throw new UnauthorizedError();\n                        }\n                        return this.send(message);\n                    }\n                }\n                throw new StreamableHTTPError(response.status, `Error POSTing to endpoint: ${text}`);\n            }\n            // Reset auth loop flag on successful response\n            this._hasCompletedAuthFlow = false;\n            this._lastUpscopingHeader = undefined;\n            // If the response is 202 Accepted, there's no body to process\n            if (response.status === 202) {\n                await response.body?.cancel();\n                // if the accepted notification is initialized, we start the SSE stream\n                // if it's supported by the server\n                if (isInitializedNotification(message)) {\n                    // Start without a lastEventId since this is a fresh connection\n                    this._startOrAuthSse({ resumptionToken: undefined }).catch(err => this.onerror?.(err));\n                }\n                return;\n            }\n            // Get original message(s) for detecting request IDs\n            const messages = Array.isArray(message) ? message : [message];\n            const hasRequests = messages.filter(msg => 'method' in msg && 'id' in msg && msg.id !== undefined).length > 0;\n            // Check the response type\n            const contentType = response.headers.get('content-type');\n            if (hasRequests) {\n                if (contentType?.includes('text/event-stream')) {\n                    // Handle SSE stream responses for requests\n                    // We use the same handler as standalone streams, which now supports\n                    // reconnection with the last event ID\n                    this._handleSseStream(response.body, { onresumptiontoken }, false);\n                }\n                else if (contentType?.includes('application/json')) {\n                    // For non-streaming servers, we might get direct JSON responses\n                    const data = await response.json();\n                    const responseMessages = Array.isArray(data)\n                        ? data.map(msg => JSONRPCMessageSchema.parse(msg))\n                        : [JSONRPCMessageSchema.parse(data)];\n                    for (const msg of responseMessages) {\n                        this.onmessage?.(msg);\n                    }\n                }\n                else {\n                    await response.body?.cancel();\n                    throw new StreamableHTTPError(-1, `Unexpected content type: ${contentType}`);\n                }\n            }\n            else {\n                // No requests in message but got 200 OK - still need to release connection\n                await response.body?.cancel();\n            }\n        }\n        catch (error) {\n            this.onerror?.(error);\n            throw error;\n        }\n    }\n    get sessionId() {\n        return this._sessionId;\n    }\n    /**\n     * Terminates the current session by sending a DELETE request to the server.\n     *\n     * Clients that no longer need a particular session\n     * (e.g., because the user is leaving the client application) SHOULD send an\n     * HTTP DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly\n     * terminate the session.\n     *\n     * The server MAY respond with HTTP 405 Method Not Allowed, indicating that\n     * the server does not allow clients to terminate sessions.\n     */\n    async terminateSession() {\n        if (!this._sessionId) {\n            return; // No session to terminate\n        }\n        try {\n            const headers = await this._commonHeaders();\n            const init = {\n                ...this._requestInit,\n                method: 'DELETE',\n                headers,\n                signal: this._abortController?.signal\n            };\n            const response = await (this._fetch ?? fetch)(this._url, init);\n            await response.body?.cancel();\n            // We specifically handle 405 as a valid response according to the spec,\n            // meaning the server does not support explicit session termination\n            if (!response.ok && response.status !== 405) {\n                throw new StreamableHTTPError(response.status, `Failed to terminate session: ${response.statusText}`);\n            }\n            this._sessionId = undefined;\n        }\n        catch (error) {\n            this.onerror?.(error);\n            throw error;\n        }\n    }\n    setProtocolVersion(version) {\n        this._protocolVersion = version;\n    }\n    get protocolVersion() {\n        return this._protocolVersion;\n    }\n    /**\n     * Resume an SSE stream from a previous event ID.\n     * Opens a GET SSE connection with Last-Event-ID header to replay missed events.\n     *\n     * @param lastEventId The event ID to resume from\n     * @param options Optional callback to receive new resumption tokens\n     */\n    async resumeStream(lastEventId, options) {\n        await this._startOrAuthSse({\n            resumptionToken: lastEventId,\n            onresumptiontoken: options?.onresumptiontoken\n        });\n    }\n}\n//# sourceMappingURL=streamableHttp.js.map","import { createMCPClient } from \"@ai-sdk/mcp\";\nimport { Experimental_StdioMCPTransport } from \"@ai-sdk/mcp/mcp-stdio\";\nimport { discoverAuthorizationServerMetadata, discoverAuthorizationServerMetadata as discoverAuthorizationServerMetadata$1, discoverOAuthProtectedResourceMetadata, discoverOAuthProtectedResourceMetadata as discoverOAuthProtectedResourceMetadata$1, discoverOAuthServerInfo, exchangeAuthorization, isHttpsUrl, refreshAuthorization, registerClient, startAuthorization } from \"@modelcontextprotocol/sdk/client/auth.js\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\n//#region src/types.ts\nconst MCP = Symbol.for(\"keystroke.mcp\");\n//#endregion\n//#region src/define-mcp.ts\nfunction defineMcp(def) {\n\tconst key = def.key?.trim();\n\tif (!key) throw new Error(\"defineMcp requires key (e.g. defineMcp({ key: \\\"exa\\\", ... }))\");\n\tif (def.credentials?.length && !def.auth) throw new Error(`defineMcp(\"${key}\") declares credentials but no auth mapper`);\n\treturn {\n\t\t...def,\n\t\tkey,\n\t\t[MCP]: true\n\t};\n}\n//#endregion\n//#region src/is-mcp.ts\nfunction isMcp(value) {\n\treturn typeof value === \"object\" && value !== null && MCP in value && value[MCP] === true;\n}\n//#endregion\n//#region src/adapter.ts\nfunction createToolName(serverName, toolName) {\n\treturn `mcp__${sanitizeToolNamePart(serverName)}__${sanitizeToolNamePart(toolName)}`;\n}\nfunction sanitizeToolNamePart(value) {\n\treturn value.replace(/[^A-Za-z0-9_-]/g, \"_\").replace(/^_+|_+$/g, \"\") || \"unnamed\";\n}\nfunction normalizeInputSchema(schema) {\n\treturn {\n\t\t...schema,\n\t\ttype: schema.type ?? \"object\",\n\t\tproperties: schema.properties ?? {},\n\t\t...schema.required !== void 0 ? { required: schema.required } : {}\n\t};\n}\n/**\n* Re-key a native AI SDK {@link ToolSet} returned by `client.tools()` so every\n* tool is namespaced as `mcp__{server}__{tool}`. Prevents collisions across\n* servers and keeps tool names stable for prompts, filters, and tests.\n*/\nfunction prefixServerToolSet(serverName, toolSet) {\n\tconst prefixed = {};\n\tfor (const [name, tool] of Object.entries(toolSet)) {\n\t\tconst toolName = createToolName(serverName, name);\n\t\tif (prefixed[toolName]) throw new Error(`MCP tools from server \"${serverName}\" produced duplicate tool name \"${toolName}\".`);\n\t\tprefixed[toolName] = tool;\n\t}\n\treturn prefixed;\n}\n//#endregion\n//#region src/bearer-challenge.ts\nfunction challengeParameter(value, name) {\n\tconst match = new RegExp(`(?:^|,)\\\\s*${name}\\\\s*=\\\\s*(?:\"((?:[^\"\\\\\\\\]|\\\\\\\\.)*)\"|([^,\\\\s]+))`, \"i\").exec(value);\n\treturn (match?.[1] ?? match?.[2])?.replace(/\\\\([\"\\\\])/g, \"$1\").trim() || void 0;\n}\n/** Parse the Bearer challenge even when another authentication scheme appears first. */\nfunction parseMcpBearerChallenge(response) {\n\tconst header = response.headers.get(\"www-authenticate\");\n\tif (!header) return {};\n\tconst bearer = /(?:^|,)\\s*Bearer(?:\\s+|$)/i.exec(header);\n\tif (!bearer) return {};\n\tconst parameters = header.slice(bearer.index + bearer[0].length);\n\tconst resourceMetadata = challengeParameter(parameters, \"resource_metadata\");\n\tconst scope = challengeParameter(parameters, \"scope\");\n\tconst error = challengeParameter(parameters, \"error\");\n\tlet resourceMetadataUrl;\n\tif (resourceMetadata) try {\n\t\tresourceMetadataUrl = new URL(resourceMetadata);\n\t} catch {}\n\treturn {\n\t\t...resourceMetadataUrl ? { resourceMetadataUrl } : {},\n\t\t...scope ? { scope } : {},\n\t\t...error ? { error } : {}\n\t};\n}\n//#endregion\n//#region src/scope-challenge.ts\nvar McpInsufficientScopeError = class extends Error {\n\tserverName;\n\trequiredScopes;\n\tresourceMetadataUrl;\n\treconnectRequired = true;\n\tretryable = false;\n\tconstructor(serverName, requiredScopes, resourceMetadataUrl) {\n\t\tconst scopeList = requiredScopes.length ? ` Required scopes: ${requiredScopes.join(\" \")}.` : \"\";\n\t\tsuper(`MCP server \"${serverName}\" requires additional authorization.${scopeList} Reconnect it.`);\n\t\tthis.serverName = serverName;\n\t\tthis.requiredScopes = requiredScopes;\n\t\tthis.resourceMetadataUrl = resourceMetadataUrl;\n\t\tthis.name = \"McpInsufficientScopeError\";\n\t}\n};\n/** Detect runtime RFC 6750 insufficient-scope challenges without hidden retries. */\nfunction createMcpScopeAwareFetch(serverName, fetchFn = fetch) {\n\treturn async (input, init) => {\n\t\tconst response = await fetchFn(input, init);\n\t\tif (response.status !== 403) return response;\n\t\tconst challenge = parseMcpBearerChallenge(response);\n\t\tif (challenge.error !== \"insufficient_scope\") return response;\n\t\tawait response.body?.cancel().catch(() => void 0);\n\t\tthrow new McpInsufficientScopeError(serverName, challenge.scope?.split(/\\s+/).filter(Boolean) ?? [], challenge.resourceMetadataUrl?.toString());\n\t};\n}\n//#endregion\n//#region src/connect.ts\nasync function connectMcpServer(name, options) {\n\tconst url = options.url instanceof URL ? options.url : new URL(options.url);\n\tconst scopeAwareFetch = createMcpScopeAwareFetch(name, options.fetch);\n\tconst client = await createMCPClient({\n\t\ttransport: {\n\t\t\ttype: options.transport === \"sse\" ? \"sse\" : \"http\",\n\t\t\turl: url.toString(),\n\t\t\t...options.headers ? { headers: options.headers } : {},\n\t\t\tfetch: scopeAwareFetch\n\t\t},\n\t\tclientName: options.clientName ?? \"keystroke\",\n\t\t...options.clientVersion ? { version: options.clientVersion } : {}\n\t});\n\ttry {\n\t\treturn {\n\t\t\tname,\n\t\t\ttoolSet: prefixServerToolSet(name, await client.tools()),\n\t\t\tclient,\n\t\t\tclose: () => client.close()\n\t\t};\n\t} catch (error) {\n\t\tawait client.close().catch(() => void 0);\n\t\tthrow error;\n\t}\n}\n//#endregion\n//#region src/connect-stdio.ts\nasync function connectMcpStdio(name, options) {\n\tconst client = await createMCPClient({\n\t\ttransport: new Experimental_StdioMCPTransport({\n\t\t\tcommand: options.command,\n\t\t\targs: options.args,\n\t\t\tenv: options.env,\n\t\t\tcwd: options.cwd,\n\t\t\tstderr: options.stderr\n\t\t}),\n\t\tclientName: options.clientName ?? \"keystroke\",\n\t\t...options.clientVersion ? { version: options.clientVersion } : {}\n\t});\n\ttry {\n\t\treturn {\n\t\t\tname,\n\t\t\ttoolSet: prefixServerToolSet(name, await client.tools()),\n\t\t\tclient,\n\t\t\tclose: () => client.close()\n\t\t};\n\t} catch (error) {\n\t\tawait client.close().catch(() => void 0);\n\t\tthrow error;\n\t}\n}\n//#endregion\n//#region src/connect-definition.ts\nasync function connectMcpDefinition(def, auth) {\n\tconst common = {\n\t\tclientName: def.clientName,\n\t\tclientVersion: def.clientVersion\n\t};\n\tif (def.transport.type === \"http\") return connectMcpServer(def.key, {\n\t\turl: applyAuthSearchParams(def.transport.url, auth?.searchParams),\n\t\ttransport: def.transport.transport,\n\t\theaders: auth?.headers,\n\t\trequestInit: def.requestInit,\n\t\tfetch: def.fetch,\n\t\t...common\n\t});\n\treturn connectMcpStdio(def.key, {\n\t\tcommand: def.transport.command,\n\t\targs: def.transport.args,\n\t\tcwd: def.transport.cwd,\n\t\tstderr: def.transport.stderr,\n\t\tenv: auth?.env,\n\t\t...common\n\t});\n}\nfunction applyAuthSearchParams(url, searchParams) {\n\tif (!searchParams) return url;\n\tconst resolved = url instanceof URL ? new URL(url) : new URL(url);\n\tfor (const [key, value] of Object.entries(searchParams)) resolved.searchParams.set(key, value);\n\treturn resolved;\n}\n//#endregion\n//#region src/oauth-scopes.ts\n/** Union OAuth scope names from metadata sources, preserving first-seen order. */\nfunction mergeOAuthScopes(...lists) {\n\tconst seen = /* @__PURE__ */ new Set();\n\tconst result = [];\n\tfor (const list of lists) {\n\t\tif (!list?.length) continue;\n\t\tfor (const scope of list) {\n\t\t\tconst trimmed = scope.trim();\n\t\t\tif (trimmed && !seen.has(trimmed)) {\n\t\t\t\tseen.add(trimmed);\n\t\t\t\tresult.push(trimmed);\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}\n//#endregion\n//#region src/public-http-url.ts\n/** Thrown when a URL is not safe for server-side outbound fetch (SSRF guard). */\nvar PublicHttpUrlError = class extends Error {\n\tconstructor(message) {\n\t\tsuper(message);\n\t\tthis.name = \"PublicHttpUrlError\";\n\t}\n};\nconst BLOCKED_HOSTNAMES = new Set([\n\t\"localhost\",\n\t\"metadata.google.internal\",\n\t\"metadata.goog\"\n]);\nfunction normalizeHostname(hostname) {\n\tconst trimmed = hostname.trim().toLowerCase();\n\tif (trimmed.startsWith(\"[\") && trimmed.endsWith(\"]\")) return trimmed.slice(1, -1);\n\treturn trimmed;\n}\nfunction parseIpv4Octets(hostname) {\n\tconst parts = hostname.split(\".\");\n\tif (parts.length !== 4) return null;\n\tconst octets = [];\n\tfor (const part of parts) {\n\t\tif (!/^\\d+$/.test(part)) return null;\n\t\tconst value = Number(part);\n\t\tif (value > 255) return null;\n\t\toctets.push(value);\n\t}\n\treturn octets;\n}\nfunction isPrivateIpv4(octets) {\n\tconst a = octets[0];\n\tconst b = octets[1];\n\tif (a === void 0 || b === void 0) return true;\n\tif (a === 0 || a === 10 || a === 127) return true;\n\tif (a === 169 && b === 254) return true;\n\tif (a === 172 && b >= 16 && b <= 31) return true;\n\tif (a === 192 && b === 168) return true;\n\treturn false;\n}\nfunction isPrivateIpv6(hostname) {\n\tif (hostname === \"::1\") return true;\n\tif (hostname.startsWith(\"fe80:\")) return true;\n\tif (hostname.startsWith(\"fc\") || hostname.startsWith(\"fd\")) return true;\n\treturn false;\n}\nfunction isBlockedHost(hostname) {\n\tif (BLOCKED_HOSTNAMES.has(hostname)) return true;\n\tif (hostname.endsWith(\".localhost\")) return true;\n\tconst ipv4 = parseIpv4Octets(hostname);\n\tif (ipv4) return isPrivateIpv4(ipv4);\n\tif (hostname.includes(\":\")) return isPrivateIpv6(hostname);\n\treturn false;\n}\n/** Validate that a URL is safe to fetch from the platform (http/https, public hosts only). */\nfunction assertPublicHttpUrl(urlString) {\n\tlet url;\n\ttry {\n\t\turl = new URL(urlString.trim());\n\t} catch {\n\t\tthrow new PublicHttpUrlError(\"Invalid URL\");\n\t}\n\tif (url.protocol !== \"http:\" && url.protocol !== \"https:\") throw new PublicHttpUrlError(\"URL must use http or https\");\n\tif (isBlockedHost(normalizeHostname(url.hostname))) throw new PublicHttpUrlError(\"URL host is not allowed\");\n\treturn url;\n}\n//#endregion\n//#region src/fetch-public-http.ts\nconst DEFAULT_MAX_REDIRECTS = 5;\n/**\n* Fetch a URL that must remain on public http(s) hosts.\n* Validates the initial URL and every redirect Location (no private/metadata hosts).\n*/\nasync function fetchPublicHttp(urlString, options = {}) {\n\tconst { maxRedirects = DEFAULT_MAX_REDIRECTS, fetchFn = fetch, ...init } = options;\n\tlet current = assertPublicHttpUrl(urlString).toString();\n\tlet hopInit = { ...init };\n\tfor (let hop = 0; hop <= maxRedirects; hop++) {\n\t\tconst response = await fetchFn(current, {\n\t\t\t...hopInit,\n\t\t\tredirect: \"manual\"\n\t\t});\n\t\tif (response.status < 300 || response.status >= 400) return response;\n\t\tconst location = response.headers.get(\"location\");\n\t\tawait response.body?.cancel().catch(() => void 0);\n\t\tif (!location) throw new PublicHttpUrlError(\"Redirect missing Location\");\n\t\tlet next;\n\t\ttry {\n\t\t\tnext = new URL(location, current);\n\t\t} catch {\n\t\t\tthrow new PublicHttpUrlError(\"Invalid redirect Location\");\n\t\t}\n\t\tcurrent = assertPublicHttpUrl(next.toString()).toString();\n\t\tif (response.status === 301 || response.status === 302 || response.status === 303) {\n\t\t\tconst { body: _body, ...rest } = hopInit;\n\t\t\thopInit = {\n\t\t\t\t...rest,\n\t\t\t\tmethod: \"GET\"\n\t\t\t};\n\t\t}\n\t}\n\tthrow new PublicHttpUrlError(\"Too many redirects\");\n}\n/** Wrap `fetch` so every outbound URL (including SDK follow-ups) passes `assertPublicHttpUrl`. */\nfunction createPublicHttpFetch(fetchFn = fetch) {\n\treturn async (input, init) => {\n\t\tconst url = typeof input === \"string\" ? input : input instanceof URL ? input.href : input.url;\n\t\tassertPublicHttpUrl(url);\n\t\treturn fetchPublicHttp(url, {\n\t\t\t...init,\n\t\t\tfetchFn\n\t\t});\n\t};\n}\n//#endregion\n//#region src/probe.ts\nconst MCP_AUTHORIZATION_PROTOCOL_VERSION = \"2025-11-25\";\nfunction resourceNameFromMetadata(metadata) {\n\treturn metadata?.resource_name?.trim() || void 0;\n}\nasync function probeUnauthenticatedStatus(url, fetchFn) {\n\ttry {\n\t\tconst response = await fetchFn(url, {\n\t\t\tmethod: \"GET\",\n\t\t\theaders: { Accept: \"application/json, text/event-stream\" }\n\t\t});\n\t\tconst wwwAuthenticate = response.headers.get(\"www-authenticate\");\n\t\tawait response.body?.cancel();\n\t\treturn {\n\t\t\tstatus: response.status,\n\t\t\twwwAuthenticate\n\t\t};\n\t} catch {\n\t\treturn {};\n\t}\n}\nfunction assertHttps(value, label) {\n\tif (new URL(value).protocol !== \"https:\") throw new Error(`${label} must use HTTPS`);\n}\nfunction assertPublicHttpsUrl(value, label) {\n\tassertPublicHttpUrl(value);\n\tassertHttps(value, label);\n}\nfunction assertResourceIdentity(serverUrl, resource) {\n\tconst resourceUrl = new URL(resource);\n\tif (serverUrl.hash || resourceUrl.hash || resourceUrl.toString() !== serverUrl.toString()) throw new Error(\"MCP protected resource does not match the requested MCP server URL\");\n}\nfunction validateAuthorizationServerMetadata(authorizationServerUrl, metadata) {\n\tif (metadata.issuer !== authorizationServerUrl) throw new Error(\"MCP authorization server metadata issuer does not match authorization server\");\n\tif (!metadata.authorization_endpoint || !metadata.token_endpoint) throw new Error(\"MCP authorization server metadata is missing required endpoints\");\n\tassertPublicHttpsUrl(metadata.authorization_endpoint, \"MCP authorization endpoint\");\n\tassertPublicHttpsUrl(metadata.token_endpoint, \"MCP token endpoint\");\n\tif (metadata.registration_endpoint) assertPublicHttpsUrl(metadata.registration_endpoint, \"MCP registration endpoint\");\n}\nasync function discoverMcpOAuthServerFromProbe(url, safeFetch, initial) {\n\tconst serverUrl = new URL(url);\n\tassertHttps(serverUrl, \"MCP server URL\");\n\tconst { status } = initial;\n\tconst wwwAuthenticate = status === 401 ? initial.wwwAuthenticate : void 0;\n\tlet resourceMetadataUrl;\n\tlet challengeScope;\n\tif (wwwAuthenticate) {\n\t\tconst params = parseMcpBearerChallenge(new Response(null, { headers: { \"www-authenticate\": wwwAuthenticate } }));\n\t\tresourceMetadataUrl = params.resourceMetadataUrl;\n\t\tchallengeScope = params.scope?.trim() || void 0;\n\t\tif (resourceMetadataUrl) {\n\t\t\tassertPublicHttpUrl(resourceMetadataUrl.toString());\n\t\t\tassertHttps(resourceMetadataUrl, \"MCP resource metadata URL\");\n\t\t}\n\t}\n\tconst resourceMetadata = await discoverOAuthProtectedResourceMetadata$1(serverUrl, {\n\t\tprotocolVersion: MCP_AUTHORIZATION_PROTOCOL_VERSION,\n\t\t...resourceMetadataUrl ? { resourceMetadataUrl } : {}\n\t}, safeFetch);\n\tif (!resourceMetadata.resource) throw new Error(\"MCP protected resource metadata is missing resource\");\n\tif (!resourceMetadata.authorization_servers?.length) throw new Error(\"MCP protected resource metadata is missing authorization_servers\");\n\tassertResourceIdentity(serverUrl, resourceMetadata.resource);\n\tconst authorizationServerUrl = resourceMetadata.authorization_servers[0];\n\tif (!authorizationServerUrl) throw new Error(\"MCP protected resource metadata is missing authorization_servers\");\n\tassertPublicHttpsUrl(authorizationServerUrl, \"MCP authorization server URL\");\n\tconst authorizationServerMetadata = await discoverAuthorizationServerMetadata$1(authorizationServerUrl, {\n\t\tfetchFn: safeFetch,\n\t\tprotocolVersion: MCP_AUTHORIZATION_PROTOCOL_VERSION\n\t});\n\tif (!authorizationServerMetadata) throw new Error(\"MCP authorization server metadata was not found\");\n\tvalidateAuthorizationServerMetadata(authorizationServerUrl, authorizationServerMetadata);\n\treturn {\n\t\tauthorizationServerUrl,\n\t\tauthorizationServerMetadata,\n\t\tresourceMetadata,\n\t\t...resourceMetadataUrl ? { resourceMetadataUrl: resourceMetadataUrl.toString() } : {},\n\t\t...challengeScope ? { challengeScope } : {},\n\t\t...status !== void 0 ? { unauthenticatedStatus: status } : {}\n\t};\n}\n/**\n* Discover an MCP authorization server without the legacy origin fallback.\n* MCP 2025-11-25 requires protected-resource metadata for AS selection.\n*/\nasync function discoverMcpOAuthServer(url, fetchFn = fetch) {\n\tassertPublicHttpUrl(url);\n\tconst safeFetch = createPublicHttpFetch(fetchFn);\n\treturn discoverMcpOAuthServerFromProbe(url, safeFetch, await probeUnauthenticatedStatus(url, safeFetch));\n}\nfunction scopesFromMetadata(metadata) {\n\tif (!metadata?.scopes_supported?.length) return [];\n\treturn metadata.scopes_supported;\n}\nfunction logProbeFallback(phase, error) {\n\tif (process.env.NODE_ENV === \"test\" || process.env.VITEST) return;\n\tconst detail = error instanceof Error ? error.message : String(error);\n\tconsole.warn(`[mcp-probe] ${phase} failed: ${detail}`);\n}\nasync function probeMcpAuth(url, fetchFn = fetch) {\n\tassertPublicHttpUrl(url);\n\tconst safeFetch = createPublicHttpFetch(fetchFn);\n\tconst initial = await probeUnauthenticatedStatus(url, safeFetch);\n\ttry {\n\t\tconst discovered = await discoverMcpOAuthServerFromProbe(url, safeFetch, initial);\n\t\tconst metadata = discovered.authorizationServerMetadata;\n\t\tif (metadata?.authorization_endpoint && metadata.token_endpoint) return {\n\t\t\turl,\n\t\t\tmode: \"oauth\",\n\t\t\tunauthenticatedStatus: initial.status,\n\t\t\toauth: {\n\t\t\t\tissuer: metadata.issuer,\n\t\t\t\tauthorizationEndpoint: metadata.authorization_endpoint,\n\t\t\t\ttokenEndpoint: metadata.token_endpoint,\n\t\t\t\tregistrationEndpoint: metadata.registration_endpoint,\n\t\t\t\tscopes: discovered.challengeScope ? discovered.challengeScope.split(/\\s+/).filter(Boolean) : scopesFromMetadata(discovered.resourceMetadata),\n\t\t\t\tresource: discovered.resourceMetadata?.resource,\n\t\t\t\tresourceName: resourceNameFromMetadata(discovered.resourceMetadata)\n\t\t\t}\n\t\t};\n\t} catch (error) {\n\t\tlogProbeFallback(\"discoverMcpOAuthServer\", error);\n\t}\n\tif (initial.status === 401 || initial.status === 403) return {\n\t\turl,\n\t\tmode: \"token\",\n\t\tunauthenticatedStatus: initial.status,\n\t\tscheme: \"BEARER_TOKEN\"\n\t};\n\treturn {\n\t\turl,\n\t\tmode: \"none\",\n\t\tunauthenticatedStatus: initial.status\n\t};\n}\n//#endregion\n//#region src/probe-server-info.ts\n/** Best-effort server metadata for no-auth MCP servers (initialize handshake). */\nasync function probeMcpServerInfo(url, fetchFn = fetch) {\n\tassertPublicHttpUrl(url);\n\tconst safeFetch = createPublicHttpFetch(fetchFn);\n\tconst client = new Client({\n\t\tname: \"keystroke\",\n\t\tversion: \"0.0.0\"\n\t});\n\tconst transport = new StreamableHTTPClientTransport(new URL(url), { fetch: safeFetch });\n\ttry {\n\t\tawait client.connect(transport);\n\t\tconst info = client.getServerVersion();\n\t\tif (!info) return;\n\t\treturn {\n\t\t\tname: info.name,\n\t\t\ttitle: info.title,\n\t\t\tdescription: info.description,\n\t\t\tversion: info.version\n\t\t};\n\t} catch {\n\t\treturn;\n\t} finally {\n\t\tawait client.close().catch(() => void 0);\n\t}\n}\n//#endregion\n//#region src/read-client.ts\nconst DEFAULT_TIMEOUT_MS = 15e3;\n/**\n* Connect a read-only MCP client over Streamable HTTP, run `fn`, and always close.\n*\n* Used for public docs MCP and for listing tools on connected custom MCP apps\n* (pass `headers` with a bearer / API token). Callers use `listTools` / `callTool`.\n*/\nasync function withMcpReadClient(url, fn, options) {\n\tconst timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n\tconst signal = AbortSignal.timeout(timeoutMs);\n\tconst baseFetch = options?.fetch ?? fetch;\n\tconst timedFetch = (input, init) => baseFetch(input, {\n\t\t...init,\n\t\tsignal: init?.signal ?? signal\n\t});\n\tconst client = new Client({\n\t\tname: \"keystroke-cli\",\n\t\tversion: \"0.0.0\"\n\t});\n\tconst transport = new StreamableHTTPClientTransport(url instanceof URL ? url : new URL(url), {\n\t\t...options?.headers ? { requestInit: { headers: options.headers } } : {},\n\t\tfetch: timedFetch\n\t});\n\ttry {\n\t\tawait client.connect(transport);\n\t\treturn await fn(client);\n\t} finally {\n\t\tawait client.close().catch(() => void 0);\n\t}\n}\n//#endregion\n//#region src/list-server-tools.ts\n/** Cap outbound tools/list pages so a hostile MCP cannot hang callers. */\nconst MAX_MCP_TOOL_PAGES = 20;\n/** Cap accumulated tools across pages. */\nconst MAX_MCP_TOOLS = 500;\nasync function listAllPages(client) {\n\tconst tools = [];\n\tlet cursor;\n\tlet pages = 0;\n\tdo {\n\t\tpages += 1;\n\t\tif (pages > 20) throw new Error(`MCP tools/list exceeded 20 pages`);\n\t\tconst page = await client.listTools(cursor ? { cursor } : void 0);\n\t\tfor (const tool of page.tools) tools.push({\n\t\t\tname: tool.name,\n\t\t\t...tool.description ? { description: tool.description } : {},\n\t\t\t...tool.inputSchema && typeof tool.inputSchema === \"object\" && !Array.isArray(tool.inputSchema) ? { inputSchema: tool.inputSchema } : {}\n\t\t});\n\t\tif (tools.length > 500) throw new Error(`MCP tools/list exceeded 500 tools`);\n\t\tcursor = page.nextCursor;\n\t} while (cursor);\n\treturn tools;\n}\n/** Live `tools/list` over Streamable HTTP (used by `apps actions list` and MCP inspect). */\nasync function listMcpServerTools(url, options) {\n\treturn withMcpReadClient(url, (client) => listAllPages(client), options?.headers || options?.fetch || options?.timeoutMs ? {\n\t\t...options.headers ? { headers: options.headers } : {},\n\t\t...options.fetch ? { fetch: options.fetch } : {},\n\t\t...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {}\n\t} : void 0);\n}\n//#endregion\nexport { MAX_MCP_TOOLS, MAX_MCP_TOOL_PAGES, MCP, McpInsufficientScopeError, PublicHttpUrlError, assertPublicHttpUrl, connectMcpDefinition, connectMcpServer, connectMcpStdio, createMcpScopeAwareFetch, createPublicHttpFetch, createToolName, defineMcp, discoverAuthorizationServerMetadata, discoverMcpOAuthServer, discoverOAuthProtectedResourceMetadata, discoverOAuthServerInfo, exchangeAuthorization, fetchPublicHttp, isHttpsUrl, isMcp, listMcpServerTools, mergeOAuthScopes, normalizeInputSchema, prefixServerToolSet, probeMcpAuth, probeMcpServerInfo, refreshAuthorization, registerClient, startAuthorization, withMcpReadClient };\n\n//# sourceMappingURL=index.mjs.map","'use strict';\n\nconst ALIAS = Symbol.for('yaml.alias');\nconst DOC = Symbol.for('yaml.document');\nconst MAP = Symbol.for('yaml.map');\nconst PAIR = Symbol.for('yaml.pair');\nconst SCALAR = Symbol.for('yaml.scalar');\nconst SEQ = Symbol.for('yaml.seq');\nconst NODE_TYPE = Symbol.for('yaml.node.type');\nconst isAlias = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === ALIAS;\nconst isDocument = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === DOC;\nconst isMap = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === MAP;\nconst isPair = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === PAIR;\nconst isScalar = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SCALAR;\nconst isSeq = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SEQ;\nfunction isCollection(node) {\n    if (node && typeof node === 'object')\n        switch (node[NODE_TYPE]) {\n            case MAP:\n            case SEQ:\n                return true;\n        }\n    return false;\n}\nfunction isNode(node) {\n    if (node && typeof node === 'object')\n        switch (node[NODE_TYPE]) {\n            case ALIAS:\n            case MAP:\n            case SCALAR:\n            case SEQ:\n                return true;\n        }\n    return false;\n}\nconst hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor;\n\nexports.ALIAS = ALIAS;\nexports.DOC = DOC;\nexports.MAP = MAP;\nexports.NODE_TYPE = NODE_TYPE;\nexports.PAIR = PAIR;\nexports.SCALAR = SCALAR;\nexports.SEQ = SEQ;\nexports.hasAnchor = hasAnchor;\nexports.isAlias = isAlias;\nexports.isCollection = isCollection;\nexports.isDocument = isDocument;\nexports.isMap = isMap;\nexports.isNode = isNode;\nexports.isPair = isPair;\nexports.isScalar = isScalar;\nexports.isSeq = isSeq;\n","'use strict';\n\nvar identity = require('./nodes/identity.js');\n\nconst BREAK = Symbol('break visit');\nconst SKIP = Symbol('skip children');\nconst REMOVE = Symbol('remove node');\n/**\n * Apply a visitor to an AST node or document.\n *\n * Walks through the tree (depth-first) starting from `node`, calling a\n * `visitor` function with three arguments:\n *   - `key`: For sequence values and map `Pair`, the node's index in the\n *     collection. Within a `Pair`, `'key'` or `'value'`, correspondingly.\n *     `null` for the root node.\n *   - `node`: The current node.\n *   - `path`: The ancestry of the current node.\n *\n * The return value of the visitor may be used to control the traversal:\n *   - `undefined` (default): Do nothing and continue\n *   - `visit.SKIP`: Do not visit the children of this node, continue with next\n *     sibling\n *   - `visit.BREAK`: Terminate traversal completely\n *   - `visit.REMOVE`: Remove the current node, then continue with the next one\n *   - `Node`: Replace the current node, then continue by visiting it\n *   - `number`: While iterating the items of a sequence or map, set the index\n *     of the next step. This is useful especially if the index of the current\n *     node has changed.\n *\n * If `visitor` is a single function, it will be called with all values\n * encountered in the tree, including e.g. `null` values. Alternatively,\n * separate visitor functions may be defined for each `Map`, `Pair`, `Seq`,\n * `Alias` and `Scalar` node. To define the same visitor function for more than\n * one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar)\n * and `Node` (alias, map, seq & scalar) targets. Of all these, only the most\n * specific defined one will be used for each node.\n */\nfunction visit(node, visitor) {\n    const visitor_ = initVisitor(visitor);\n    if (identity.isDocument(node)) {\n        const cd = visit_(null, node.contents, visitor_, Object.freeze([node]));\n        if (cd === REMOVE)\n            node.contents = null;\n    }\n    else\n        visit_(null, node, visitor_, Object.freeze([]));\n}\n// Without the `as symbol` casts, TS declares these in the `visit`\n// namespace using `var`, but then complains about that because\n// `unique symbol` must be `const`.\n/** Terminate visit traversal completely */\nvisit.BREAK = BREAK;\n/** Do not visit the children of the current node */\nvisit.SKIP = SKIP;\n/** Remove the current node */\nvisit.REMOVE = REMOVE;\nfunction visit_(key, node, visitor, path) {\n    const ctrl = callVisitor(key, node, visitor, path);\n    if (identity.isNode(ctrl) || identity.isPair(ctrl)) {\n        replaceNode(key, path, ctrl);\n        return visit_(key, ctrl, visitor, path);\n    }\n    if (typeof ctrl !== 'symbol') {\n        if (identity.isCollection(node)) {\n            path = Object.freeze(path.concat(node));\n            for (let i = 0; i < node.items.length; ++i) {\n                const ci = visit_(i, node.items[i], visitor, path);\n                if (typeof ci === 'number')\n                    i = ci - 1;\n                else if (ci === BREAK)\n                    return BREAK;\n                else if (ci === REMOVE) {\n                    node.items.splice(i, 1);\n                    i -= 1;\n                }\n            }\n        }\n        else if (identity.isPair(node)) {\n            path = Object.freeze(path.concat(node));\n            const ck = visit_('key', node.key, visitor, path);\n            if (ck === BREAK)\n                return BREAK;\n            else if (ck === REMOVE)\n                node.key = null;\n            const cv = visit_('value', node.value, visitor, path);\n            if (cv === BREAK)\n                return BREAK;\n            else if (cv === REMOVE)\n                node.value = null;\n        }\n    }\n    return ctrl;\n}\n/**\n * Apply an async visitor to an AST node or document.\n *\n * Walks through the tree (depth-first) starting from `node`, calling a\n * `visitor` function with three arguments:\n *   - `key`: For sequence values and map `Pair`, the node's index in the\n *     collection. Within a `Pair`, `'key'` or `'value'`, correspondingly.\n *     `null` for the root node.\n *   - `node`: The current node.\n *   - `path`: The ancestry of the current node.\n *\n * The return value of the visitor may be used to control the traversal:\n *   - `Promise`: Must resolve to one of the following values\n *   - `undefined` (default): Do nothing and continue\n *   - `visit.SKIP`: Do not visit the children of this node, continue with next\n *     sibling\n *   - `visit.BREAK`: Terminate traversal completely\n *   - `visit.REMOVE`: Remove the current node, then continue with the next one\n *   - `Node`: Replace the current node, then continue by visiting it\n *   - `number`: While iterating the items of a sequence or map, set the index\n *     of the next step. This is useful especially if the index of the current\n *     node has changed.\n *\n * If `visitor` is a single function, it will be called with all values\n * encountered in the tree, including e.g. `null` values. Alternatively,\n * separate visitor functions may be defined for each `Map`, `Pair`, `Seq`,\n * `Alias` and `Scalar` node. To define the same visitor function for more than\n * one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar)\n * and `Node` (alias, map, seq & scalar) targets. Of all these, only the most\n * specific defined one will be used for each node.\n */\nasync function visitAsync(node, visitor) {\n    const visitor_ = initVisitor(visitor);\n    if (identity.isDocument(node)) {\n        const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node]));\n        if (cd === REMOVE)\n            node.contents = null;\n    }\n    else\n        await visitAsync_(null, node, visitor_, Object.freeze([]));\n}\n// Without the `as symbol` casts, TS declares these in the `visit`\n// namespace using `var`, but then complains about that because\n// `unique symbol` must be `const`.\n/** Terminate visit traversal completely */\nvisitAsync.BREAK = BREAK;\n/** Do not visit the children of the current node */\nvisitAsync.SKIP = SKIP;\n/** Remove the current node */\nvisitAsync.REMOVE = REMOVE;\nasync function visitAsync_(key, node, visitor, path) {\n    const ctrl = await callVisitor(key, node, visitor, path);\n    if (identity.isNode(ctrl) || identity.isPair(ctrl)) {\n        replaceNode(key, path, ctrl);\n        return visitAsync_(key, ctrl, visitor, path);\n    }\n    if (typeof ctrl !== 'symbol') {\n        if (identity.isCollection(node)) {\n            path = Object.freeze(path.concat(node));\n            for (let i = 0; i < node.items.length; ++i) {\n                const ci = await visitAsync_(i, node.items[i], visitor, path);\n                if (typeof ci === 'number')\n                    i = ci - 1;\n                else if (ci === BREAK)\n                    return BREAK;\n                else if (ci === REMOVE) {\n                    node.items.splice(i, 1);\n                    i -= 1;\n                }\n            }\n        }\n        else if (identity.isPair(node)) {\n            path = Object.freeze(path.concat(node));\n            const ck = await visitAsync_('key', node.key, visitor, path);\n            if (ck === BREAK)\n                return BREAK;\n            else if (ck === REMOVE)\n                node.key = null;\n            const cv = await visitAsync_('value', node.value, visitor, path);\n            if (cv === BREAK)\n                return BREAK;\n            else if (cv === REMOVE)\n                node.value = null;\n        }\n    }\n    return ctrl;\n}\nfunction initVisitor(visitor) {\n    if (typeof visitor === 'object' &&\n        (visitor.Collection || visitor.Node || visitor.Value)) {\n        return Object.assign({\n            Alias: visitor.Node,\n            Map: visitor.Node,\n            Scalar: visitor.Node,\n            Seq: visitor.Node\n        }, visitor.Value && {\n            Map: visitor.Value,\n            Scalar: visitor.Value,\n            Seq: visitor.Value\n        }, visitor.Collection && {\n            Map: visitor.Collection,\n            Seq: visitor.Collection\n        }, visitor);\n    }\n    return visitor;\n}\nfunction callVisitor(key, node, visitor, path) {\n    if (typeof visitor === 'function')\n        return visitor(key, node, path);\n    if (identity.isMap(node))\n        return visitor.Map?.(key, node, path);\n    if (identity.isSeq(node))\n        return visitor.Seq?.(key, node, path);\n    if (identity.isPair(node))\n        return visitor.Pair?.(key, node, path);\n    if (identity.isScalar(node))\n        return visitor.Scalar?.(key, node, path);\n    if (identity.isAlias(node))\n        return visitor.Alias?.(key, node, path);\n    return undefined;\n}\nfunction replaceNode(key, path, node) {\n    const parent = path[path.length - 1];\n    if (identity.isCollection(parent)) {\n        parent.items[key] = node;\n    }\n    else if (identity.isPair(parent)) {\n        if (key === 'key')\n            parent.key = node;\n        else\n            parent.value = node;\n    }\n    else if (identity.isDocument(parent)) {\n        parent.contents = node;\n    }\n    else {\n        const pt = identity.isAlias(parent) ? 'alias' : 'scalar';\n        throw new Error(`Cannot replace node with ${pt} parent`);\n    }\n}\n\nexports.visit = visit;\nexports.visitAsync = visitAsync;\n","'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar visit = require('../visit.js');\n\nconst escapeChars = {\n    '!': '%21',\n    ',': '%2C',\n    '[': '%5B',\n    ']': '%5D',\n    '{': '%7B',\n    '}': '%7D'\n};\nconst escapeTagName = (tn) => tn.replace(/[!,[\\]{}]/g, ch => escapeChars[ch]);\nclass Directives {\n    constructor(yaml, tags) {\n        /**\n         * The directives-end/doc-start marker `---`. If `null`, a marker may still be\n         * included in the document's stringified representation.\n         */\n        this.docStart = null;\n        /** The doc-end marker `...`.  */\n        this.docEnd = false;\n        this.yaml = Object.assign({}, Directives.defaultYaml, yaml);\n        this.tags = Object.assign({}, Directives.defaultTags, tags);\n    }\n    clone() {\n        const copy = new Directives(this.yaml, this.tags);\n        copy.docStart = this.docStart;\n        return copy;\n    }\n    /**\n     * During parsing, get a Directives instance for the current document and\n     * update the stream state according to the current version's spec.\n     */\n    atDocument() {\n        const res = new Directives(this.yaml, this.tags);\n        switch (this.yaml.version) {\n            case '1.1':\n                this.atNextDocument = true;\n                break;\n            case '1.2':\n                this.atNextDocument = false;\n                this.yaml = {\n                    explicit: Directives.defaultYaml.explicit,\n                    version: '1.2'\n                };\n                this.tags = Object.assign({}, Directives.defaultTags);\n                break;\n        }\n        return res;\n    }\n    /**\n     * @param onError - May be called even if the action was successful\n     * @returns `true` on success\n     */\n    add(line, onError) {\n        if (this.atNextDocument) {\n            this.yaml = { explicit: Directives.defaultYaml.explicit, version: '1.1' };\n            this.tags = Object.assign({}, Directives.defaultTags);\n            this.atNextDocument = false;\n        }\n        const parts = line.trim().split(/[ \\t]+/);\n        const name = parts.shift();\n        switch (name) {\n            case '%TAG': {\n                if (parts.length !== 2) {\n                    onError(0, '%TAG directive should contain exactly two parts');\n                    if (parts.length < 2)\n                        return false;\n                }\n                const [handle, prefix] = parts;\n                this.tags[handle] = prefix;\n                return true;\n            }\n            case '%YAML': {\n                this.yaml.explicit = true;\n                if (parts.length !== 1) {\n                    onError(0, '%YAML directive should contain exactly one part');\n                    return false;\n                }\n                const [version] = parts;\n                if (version === '1.1' || version === '1.2') {\n                    this.yaml.version = version;\n                    return true;\n                }\n                else {\n                    const isValid = /^\\d+\\.\\d+$/.test(version);\n                    onError(6, `Unsupported YAML version ${version}`, isValid);\n                    return false;\n                }\n            }\n            default:\n                onError(0, `Unknown directive ${name}`, true);\n                return false;\n        }\n    }\n    /**\n     * Resolves a tag, matching handles to those defined in %TAG directives.\n     *\n     * @returns Resolved tag, which may also be the non-specific tag `'!'` or a\n     *   `'!local'` tag, or `null` if unresolvable.\n     */\n    tagName(source, onError) {\n        if (source === '!')\n            return '!'; // non-specific tag\n        if (source[0] !== '!') {\n            onError(`Not a valid tag: ${source}`);\n            return null;\n        }\n        if (source[1] === '<') {\n            const verbatim = source.slice(2, -1);\n            if (verbatim === '!' || verbatim === '!!') {\n                onError(`Verbatim tags aren't resolved, so ${source} is invalid.`);\n                return null;\n            }\n            if (source[source.length - 1] !== '>')\n                onError('Verbatim tags must end with a >');\n            return verbatim;\n        }\n        const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s);\n        if (!suffix)\n            onError(`The ${source} tag has no suffix`);\n        const prefix = this.tags[handle];\n        if (prefix) {\n            try {\n                return prefix + decodeURIComponent(suffix);\n            }\n            catch (error) {\n                onError(String(error));\n                return null;\n            }\n        }\n        if (handle === '!')\n            return source; // local tag\n        onError(`Could not resolve tag: ${source}`);\n        return null;\n    }\n    /**\n     * Given a fully resolved tag, returns its printable string form,\n     * taking into account current tag prefixes and defaults.\n     */\n    tagString(tag) {\n        for (const [handle, prefix] of Object.entries(this.tags)) {\n            if (tag.startsWith(prefix))\n                return handle + escapeTagName(tag.substring(prefix.length));\n        }\n        return tag[0] === '!' ? tag : `!<${tag}>`;\n    }\n    toString(doc) {\n        const lines = this.yaml.explicit\n            ? [`%YAML ${this.yaml.version || '1.2'}`]\n            : [];\n        const tagEntries = Object.entries(this.tags);\n        let tagNames;\n        if (doc && tagEntries.length > 0 && identity.isNode(doc.contents)) {\n            const tags = {};\n            visit.visit(doc.contents, (_key, node) => {\n                if (identity.isNode(node) && node.tag)\n                    tags[node.tag] = true;\n            });\n            tagNames = Object.keys(tags);\n        }\n        else\n            tagNames = [];\n        for (const [handle, prefix] of tagEntries) {\n            if (handle === '!!' && prefix === 'tag:yaml.org,2002:')\n                continue;\n            if (!doc || tagNames.some(tn => tn.startsWith(prefix)))\n                lines.push(`%TAG ${handle} ${prefix}`);\n        }\n        return lines.join('\\n');\n    }\n}\nDirectives.defaultYaml = { explicit: false, version: '1.2' };\nDirectives.defaultTags = { '!!': 'tag:yaml.org,2002:' };\n\nexports.Directives = Directives;\n","'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar visit = require('../visit.js');\n\n/**\n * Verify that the input string is a valid anchor.\n *\n * Will throw on errors.\n */\nfunction anchorIsValid(anchor) {\n    if (/[\\x00-\\x19\\s,[\\]{}]/.test(anchor)) {\n        const sa = JSON.stringify(anchor);\n        const msg = `Anchor must not contain whitespace or control characters: ${sa}`;\n        throw new Error(msg);\n    }\n    return true;\n}\nfunction anchorNames(root) {\n    const anchors = new Set();\n    visit.visit(root, {\n        Value(_key, node) {\n            if (node.anchor)\n                anchors.add(node.anchor);\n        }\n    });\n    return anchors;\n}\n/** Find a new anchor name with the given `prefix` and a one-indexed suffix. */\nfunction findNewAnchor(prefix, exclude) {\n    for (let i = 1; true; ++i) {\n        const name = `${prefix}${i}`;\n        if (!exclude.has(name))\n            return name;\n    }\n}\nfunction createNodeAnchors(doc, prefix) {\n    const aliasObjects = [];\n    const sourceObjects = new Map();\n    let prevAnchors = null;\n    return {\n        onAnchor: (source) => {\n            aliasObjects.push(source);\n            prevAnchors ?? (prevAnchors = anchorNames(doc));\n            const anchor = findNewAnchor(prefix, prevAnchors);\n            prevAnchors.add(anchor);\n            return anchor;\n        },\n        /**\n         * With circular references, the source node is only resolved after all\n         * of its child nodes are. This is why anchors are set only after all of\n         * the nodes have been created.\n         */\n        setAnchors: () => {\n            for (const source of aliasObjects) {\n                const ref = sourceObjects.get(source);\n                if (typeof ref === 'object' &&\n                    ref.anchor &&\n                    (identity.isScalar(ref.node) || identity.isCollection(ref.node))) {\n                    ref.node.anchor = ref.anchor;\n                }\n                else {\n                    const error = new Error('Failed to resolve repeated object (this should not happen)');\n                    error.source = source;\n                    throw error;\n                }\n            }\n        },\n        sourceObjects\n    };\n}\n\nexports.anchorIsValid = anchorIsValid;\nexports.anchorNames = anchorNames;\nexports.createNodeAnchors = createNodeAnchors;\nexports.findNewAnchor = findNewAnchor;\n","'use strict';\n\n/**\n * Applies the JSON.parse reviver algorithm as defined in the ECMA-262 spec,\n * in section 24.5.1.1 \"Runtime Semantics: InternalizeJSONProperty\" of the\n * 2021 edition: https://tc39.es/ecma262/#sec-json.parse\n *\n * Includes extensions for handling Map and Set objects.\n */\nfunction applyReviver(reviver, obj, key, val) {\n    if (val && typeof val === 'object') {\n        if (Array.isArray(val)) {\n            for (let i = 0, len = val.length; i < len; ++i) {\n                const v0 = val[i];\n                const v1 = applyReviver(reviver, val, String(i), v0);\n                // eslint-disable-next-line @typescript-eslint/no-array-delete\n                if (v1 === undefined)\n                    delete val[i];\n                else if (v1 !== v0)\n                    val[i] = v1;\n            }\n        }\n        else if (val instanceof Map) {\n            for (const k of Array.from(val.keys())) {\n                const v0 = val.get(k);\n                const v1 = applyReviver(reviver, val, k, v0);\n                if (v1 === undefined)\n                    val.delete(k);\n                else if (v1 !== v0)\n                    val.set(k, v1);\n            }\n        }\n        else if (val instanceof Set) {\n            for (const v0 of Array.from(val)) {\n                const v1 = applyReviver(reviver, val, v0, v0);\n                if (v1 === undefined)\n                    val.delete(v0);\n                else if (v1 !== v0) {\n                    val.delete(v0);\n                    val.add(v1);\n                }\n            }\n        }\n        else {\n            for (const [k, v0] of Object.entries(val)) {\n                const v1 = applyReviver(reviver, val, k, v0);\n                if (v1 === undefined)\n                    delete val[k];\n                else if (v1 !== v0)\n                    val[k] = v1;\n            }\n        }\n    }\n    return reviver.call(obj, key, val);\n}\n\nexports.applyReviver = applyReviver;\n","'use strict';\n\nvar identity = require('./identity.js');\n\n/**\n * Recursively convert any node or its contents to native JavaScript\n *\n * @param value - The input value\n * @param arg - If `value` defines a `toJSON()` method, use this\n *   as its first argument\n * @param ctx - Conversion context, originally set in Document#toJS(). If\n *   `{ keep: true }` is not set, output should be suitable for JSON\n *   stringification.\n */\nfunction toJS(value, arg, ctx) {\n    // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n    if (Array.isArray(value))\n        return value.map((v, i) => toJS(v, String(i), ctx));\n    if (value && typeof value.toJSON === 'function') {\n        // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n        if (!ctx || !identity.hasAnchor(value))\n            return value.toJSON(arg, ctx);\n        const data = { aliasCount: 0, count: 1, res: undefined };\n        ctx.anchors.set(value, data);\n        ctx.onCreate = res => {\n            data.res = res;\n            delete ctx.onCreate;\n        };\n        const res = value.toJSON(arg, ctx);\n        if (ctx.onCreate)\n            ctx.onCreate(res);\n        return res;\n    }\n    if (typeof value === 'bigint' && !ctx?.keep)\n        return Number(value);\n    return value;\n}\n\nexports.toJS = toJS;\n","'use strict';\n\nvar applyReviver = require('../doc/applyReviver.js');\nvar identity = require('./identity.js');\nvar toJS = require('./toJS.js');\n\nclass NodeBase {\n    constructor(type) {\n        Object.defineProperty(this, identity.NODE_TYPE, { value: type });\n    }\n    /** Create a copy of this node.  */\n    clone() {\n        const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));\n        if (this.range)\n            copy.range = this.range.slice();\n        return copy;\n    }\n    /** A plain JavaScript representation of this node. */\n    toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {\n        if (!identity.isDocument(doc))\n            throw new TypeError('A document argument is required');\n        const ctx = {\n            anchors: new Map(),\n            doc,\n            keep: true,\n            mapAsMap: mapAsMap === true,\n            mapKeyWarned: false,\n            maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100\n        };\n        const res = toJS.toJS(this, '', ctx);\n        if (typeof onAnchor === 'function')\n            for (const { count, res } of ctx.anchors.values())\n                onAnchor(res, count);\n        return typeof reviver === 'function'\n            ? applyReviver.applyReviver(reviver, { '': res }, '', res)\n            : res;\n    }\n}\n\nexports.NodeBase = NodeBase;\n","'use strict';\n\nvar anchors = require('../doc/anchors.js');\nvar visit = require('../visit.js');\nvar identity = require('./identity.js');\nvar Node = require('./Node.js');\nvar toJS = require('./toJS.js');\n\nclass Alias extends Node.NodeBase {\n    constructor(source) {\n        super(identity.ALIAS);\n        this.source = source;\n        Object.defineProperty(this, 'tag', {\n            set() {\n                throw new Error('Alias nodes cannot have tags');\n            }\n        });\n    }\n    /**\n     * Resolve the value of this alias within `doc`, finding the last\n     * instance of the `source` anchor before this node.\n     */\n    resolve(doc, ctx) {\n        if (ctx?.maxAliasCount === 0)\n            throw new ReferenceError('Alias resolution is disabled');\n        let nodes;\n        if (ctx?.aliasResolveCache) {\n            nodes = ctx.aliasResolveCache;\n        }\n        else {\n            nodes = [];\n            visit.visit(doc, {\n                Node: (_key, node) => {\n                    if (identity.isAlias(node) || identity.hasAnchor(node))\n                        nodes.push(node);\n                }\n            });\n            if (ctx)\n                ctx.aliasResolveCache = nodes;\n        }\n        let found = undefined;\n        for (const node of nodes) {\n            if (node === this)\n                break;\n            if (node.anchor === this.source)\n                found = node;\n        }\n        return found;\n    }\n    toJSON(_arg, ctx) {\n        if (!ctx)\n            return { source: this.source };\n        const { anchors, doc, maxAliasCount } = ctx;\n        const source = this.resolve(doc, ctx);\n        if (!source) {\n            const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;\n            throw new ReferenceError(msg);\n        }\n        let data = anchors.get(source);\n        if (!data) {\n            // Resolve anchors for Node.prototype.toJS()\n            toJS.toJS(source, null, ctx);\n            data = anchors.get(source);\n        }\n        /* istanbul ignore if */\n        if (data?.res === undefined) {\n            const msg = 'This should not happen: Alias anchor was not resolved?';\n            throw new ReferenceError(msg);\n        }\n        if (maxAliasCount >= 0) {\n            data.count += 1;\n            if (data.aliasCount === 0)\n                data.aliasCount = getAliasCount(doc, source, anchors);\n            if (data.count * data.aliasCount > maxAliasCount) {\n                const msg = 'Excessive alias count indicates a resource exhaustion attack';\n                throw new ReferenceError(msg);\n            }\n        }\n        return data.res;\n    }\n    toString(ctx, _onComment, _onChompKeep) {\n        const src = `*${this.source}`;\n        if (ctx) {\n            anchors.anchorIsValid(this.source);\n            if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) {\n                const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;\n                throw new Error(msg);\n            }\n            if (ctx.implicitKey)\n                return `${src} `;\n        }\n        return src;\n    }\n}\nfunction getAliasCount(doc, node, anchors) {\n    if (identity.isAlias(node)) {\n        const source = node.resolve(doc);\n        const anchor = anchors && source && anchors.get(source);\n        return anchor ? anchor.count * anchor.aliasCount : 0;\n    }\n    else if (identity.isCollection(node)) {\n        let count = 0;\n        for (const item of node.items) {\n            const c = getAliasCount(doc, item, anchors);\n            if (c > count)\n                count = c;\n        }\n        return count;\n    }\n    else if (identity.isPair(node)) {\n        const kc = getAliasCount(doc, node.key, anchors);\n        const vc = getAliasCount(doc, node.value, anchors);\n        return Math.max(kc, vc);\n    }\n    return 1;\n}\n\nexports.Alias = Alias;\n","'use strict';\n\nvar identity = require('./identity.js');\nvar Node = require('./Node.js');\nvar toJS = require('./toJS.js');\n\nconst isScalarValue = (value) => !value || (typeof value !== 'function' && typeof value !== 'object');\nclass Scalar extends Node.NodeBase {\n    constructor(value) {\n        super(identity.SCALAR);\n        this.value = value;\n    }\n    toJSON(arg, ctx) {\n        return ctx?.keep ? this.value : toJS.toJS(this.value, arg, ctx);\n    }\n    toString() {\n        return String(this.value);\n    }\n}\nScalar.BLOCK_FOLDED = 'BLOCK_FOLDED';\nScalar.BLOCK_LITERAL = 'BLOCK_LITERAL';\nScalar.PLAIN = 'PLAIN';\nScalar.QUOTE_DOUBLE = 'QUOTE_DOUBLE';\nScalar.QUOTE_SINGLE = 'QUOTE_SINGLE';\n\nexports.Scalar = Scalar;\nexports.isScalarValue = isScalarValue;\n","'use strict';\n\nvar Alias = require('../nodes/Alias.js');\nvar identity = require('../nodes/identity.js');\nvar Scalar = require('../nodes/Scalar.js');\n\nconst defaultTagPrefix = 'tag:yaml.org,2002:';\nfunction findTagObject(value, tagName, tags) {\n    if (tagName) {\n        const match = tags.filter(t => t.tag === tagName);\n        const tagObj = match.find(t => !t.format) ?? match[0];\n        if (!tagObj)\n            throw new Error(`Tag ${tagName} not found`);\n        return tagObj;\n    }\n    return tags.find(t => t.identify?.(value) && !t.format);\n}\nfunction createNode(value, tagName, ctx) {\n    if (identity.isDocument(value))\n        value = value.contents;\n    if (identity.isNode(value))\n        return value;\n    if (identity.isPair(value)) {\n        const map = ctx.schema[identity.MAP].createNode?.(ctx.schema, null, ctx);\n        map.items.push(value);\n        return map;\n    }\n    if (value instanceof String ||\n        value instanceof Number ||\n        value instanceof Boolean ||\n        (typeof BigInt !== 'undefined' && value instanceof BigInt) // not supported everywhere\n    ) {\n        // https://tc39.es/ecma262/#sec-serializejsonproperty\n        value = value.valueOf();\n    }\n    const { aliasDuplicateObjects, onAnchor, onTagObj, schema, sourceObjects } = ctx;\n    // Detect duplicate references to the same object & use Alias nodes for all\n    // after first. The `ref` wrapper allows for circular references to resolve.\n    let ref = undefined;\n    if (aliasDuplicateObjects && value && typeof value === 'object') {\n        ref = sourceObjects.get(value);\n        if (ref) {\n            ref.anchor ?? (ref.anchor = onAnchor(value));\n            return new Alias.Alias(ref.anchor);\n        }\n        else {\n            ref = { anchor: null, node: null };\n            sourceObjects.set(value, ref);\n        }\n    }\n    if (tagName?.startsWith('!!'))\n        tagName = defaultTagPrefix + tagName.slice(2);\n    let tagObj = findTagObject(value, tagName, schema.tags);\n    if (!tagObj) {\n        if (value && typeof value.toJSON === 'function') {\n            // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n            value = value.toJSON();\n        }\n        if (!value || typeof value !== 'object') {\n            const node = new Scalar.Scalar(value);\n            if (ref)\n                ref.node = node;\n            return node;\n        }\n        tagObj =\n            value instanceof Map\n                ? schema[identity.MAP]\n                : Symbol.iterator in Object(value)\n                    ? schema[identity.SEQ]\n                    : schema[identity.MAP];\n    }\n    if (onTagObj) {\n        onTagObj(tagObj);\n        delete ctx.onTagObj;\n    }\n    const node = tagObj?.createNode\n        ? tagObj.createNode(ctx.schema, value, ctx)\n        : typeof tagObj?.nodeClass?.from === 'function'\n            ? tagObj.nodeClass.from(ctx.schema, value, ctx)\n            : new Scalar.Scalar(value);\n    if (tagName)\n        node.tag = tagName;\n    else if (!tagObj.default)\n        node.tag = tagObj.tag;\n    if (ref)\n        ref.node = node;\n    return node;\n}\n\nexports.createNode = createNode;\n","'use strict';\n\nvar createNode = require('../doc/createNode.js');\nvar identity = require('./identity.js');\nvar Node = require('./Node.js');\n\nfunction collectionFromPath(schema, path, value) {\n    let v = value;\n    for (let i = path.length - 1; i >= 0; --i) {\n        const k = path[i];\n        if (typeof k === 'number' && Number.isInteger(k) && k >= 0) {\n            const a = [];\n            a[k] = v;\n            v = a;\n        }\n        else {\n            v = new Map([[k, v]]);\n        }\n    }\n    return createNode.createNode(v, undefined, {\n        aliasDuplicateObjects: false,\n        keepUndefined: false,\n        onAnchor: () => {\n            throw new Error('This should not happen, please report a bug.');\n        },\n        schema,\n        sourceObjects: new Map()\n    });\n}\n// Type guard is intentionally a little wrong so as to be more useful,\n// as it does not cover untypable empty non-string iterables (e.g. []).\nconst isEmptyPath = (path) => path == null ||\n    (typeof path === 'object' && !!path[Symbol.iterator]().next().done);\nclass Collection extends Node.NodeBase {\n    constructor(type, schema) {\n        super(type);\n        Object.defineProperty(this, 'schema', {\n            value: schema,\n            configurable: true,\n            enumerable: false,\n            writable: true\n        });\n    }\n    /**\n     * Create a copy of this collection.\n     *\n     * @param schema - If defined, overwrites the original's schema\n     */\n    clone(schema) {\n        const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));\n        if (schema)\n            copy.schema = schema;\n        copy.items = copy.items.map(it => identity.isNode(it) || identity.isPair(it) ? it.clone(schema) : it);\n        if (this.range)\n            copy.range = this.range.slice();\n        return copy;\n    }\n    /**\n     * Adds a value to the collection. For `!!map` and `!!omap` the value must\n     * be a Pair instance or a `{ key, value }` object, which may not have a key\n     * that already exists in the map.\n     */\n    addIn(path, value) {\n        if (isEmptyPath(path))\n            this.add(value);\n        else {\n            const [key, ...rest] = path;\n            const node = this.get(key, true);\n            if (identity.isCollection(node))\n                node.addIn(rest, value);\n            else if (node === undefined && this.schema)\n                this.set(key, collectionFromPath(this.schema, rest, value));\n            else\n                throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);\n        }\n    }\n    /**\n     * Removes a value from the collection.\n     * @returns `true` if the item was found and removed.\n     */\n    deleteIn(path) {\n        const [key, ...rest] = path;\n        if (rest.length === 0)\n            return this.delete(key);\n        const node = this.get(key, true);\n        if (identity.isCollection(node))\n            return node.deleteIn(rest);\n        else\n            throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);\n    }\n    /**\n     * Returns item at `key`, or `undefined` if not found. By default unwraps\n     * scalar values from their surrounding node; to disable set `keepScalar` to\n     * `true` (collections are always returned intact).\n     */\n    getIn(path, keepScalar) {\n        const [key, ...rest] = path;\n        const node = this.get(key, true);\n        if (rest.length === 0)\n            return !keepScalar && identity.isScalar(node) ? node.value : node;\n        else\n            return identity.isCollection(node) ? node.getIn(rest, keepScalar) : undefined;\n    }\n    hasAllNullValues(allowScalar) {\n        return this.items.every(node => {\n            if (!identity.isPair(node))\n                return false;\n            const n = node.value;\n            return (n == null ||\n                (allowScalar &&\n                    identity.isScalar(n) &&\n                    n.value == null &&\n                    !n.commentBefore &&\n                    !n.comment &&\n                    !n.tag));\n        });\n    }\n    /**\n     * Checks if the collection includes a value with the key `key`.\n     */\n    hasIn(path) {\n        const [key, ...rest] = path;\n        if (rest.length === 0)\n            return this.has(key);\n        const node = this.get(key, true);\n        return identity.isCollection(node) ? node.hasIn(rest) : false;\n    }\n    /**\n     * Sets a value in this collection. For `!!set`, `value` needs to be a\n     * boolean to add/remove the item from the set.\n     */\n    setIn(path, value) {\n        const [key, ...rest] = path;\n        if (rest.length === 0) {\n            this.set(key, value);\n        }\n        else {\n            const node = this.get(key, true);\n            if (identity.isCollection(node))\n                node.setIn(rest, value);\n            else if (node === undefined && this.schema)\n                this.set(key, collectionFromPath(this.schema, rest, value));\n            else\n                throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);\n        }\n    }\n}\n\nexports.Collection = Collection;\nexports.collectionFromPath = collectionFromPath;\nexports.isEmptyPath = isEmptyPath;\n","'use strict';\n\n/**\n * Stringifies a comment.\n *\n * Empty comment lines are left empty,\n * lines consisting of a single space are replaced by `#`,\n * and all other lines are prefixed with a `#`.\n */\nconst stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, '#');\nfunction indentComment(comment, indent) {\n    if (/^\\n+$/.test(comment))\n        return comment.substring(1);\n    return indent ? comment.replace(/^(?! *$)/gm, indent) : comment;\n}\nconst lineComment = (str, indent, comment) => str.endsWith('\\n')\n    ? indentComment(comment, indent)\n    : comment.includes('\\n')\n        ? '\\n' + indentComment(comment, indent)\n        : (str.endsWith(' ') ? '' : ' ') + comment;\n\nexports.indentComment = indentComment;\nexports.lineComment = lineComment;\nexports.stringifyComment = stringifyComment;\n","'use strict';\n\nconst FOLD_FLOW = 'flow';\nconst FOLD_BLOCK = 'block';\nconst FOLD_QUOTED = 'quoted';\n/**\n * Tries to keep input at up to `lineWidth` characters, splitting only on spaces\n * not followed by newlines or spaces unless `mode` is `'quoted'`. Lines are\n * terminated with `\\n` and started with `indent`.\n */\nfunction foldFlowLines(text, indent, mode = 'flow', { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) {\n    if (!lineWidth || lineWidth < 0)\n        return text;\n    if (lineWidth < minContentWidth)\n        minContentWidth = 0;\n    const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length);\n    if (text.length <= endStep)\n        return text;\n    const folds = [];\n    const escapedFolds = {};\n    let end = lineWidth - indent.length;\n    if (typeof indentAtStart === 'number') {\n        if (indentAtStart > lineWidth - Math.max(2, minContentWidth))\n            folds.push(0);\n        else\n            end = lineWidth - indentAtStart;\n    }\n    let split = undefined;\n    let prev = undefined;\n    let overflow = false;\n    let i = -1;\n    let escStart = -1;\n    let escEnd = -1;\n    if (mode === FOLD_BLOCK) {\n        i = consumeMoreIndentedLines(text, i, indent.length);\n        if (i !== -1)\n            end = i + endStep;\n    }\n    for (let ch; (ch = text[(i += 1)]);) {\n        if (mode === FOLD_QUOTED && ch === '\\\\') {\n            escStart = i;\n            switch (text[i + 1]) {\n                case 'x':\n                    i += 3;\n                    break;\n                case 'u':\n                    i += 5;\n                    break;\n                case 'U':\n                    i += 9;\n                    break;\n                default:\n                    i += 1;\n            }\n            escEnd = i;\n        }\n        if (ch === '\\n') {\n            if (mode === FOLD_BLOCK)\n                i = consumeMoreIndentedLines(text, i, indent.length);\n            end = i + indent.length + endStep;\n            split = undefined;\n        }\n        else {\n            if (ch === ' ' &&\n                prev &&\n                prev !== ' ' &&\n                prev !== '\\n' &&\n                prev !== '\\t') {\n                // space surrounded by non-space can be replaced with newline + indent\n                const next = text[i + 1];\n                if (next && next !== ' ' && next !== '\\n' && next !== '\\t')\n                    split = i;\n            }\n            if (i >= end) {\n                if (split) {\n                    folds.push(split);\n                    end = split + endStep;\n                    split = undefined;\n                }\n                else if (mode === FOLD_QUOTED) {\n                    // white-space collected at end may stretch past lineWidth\n                    while (prev === ' ' || prev === '\\t') {\n                        prev = ch;\n                        ch = text[(i += 1)];\n                        overflow = true;\n                    }\n                    // Account for newline escape, but don't break preceding escape\n                    const j = i > escEnd + 1 ? i - 2 : escStart - 1;\n                    // Bail out if lineWidth & minContentWidth are shorter than an escape string\n                    if (escapedFolds[j])\n                        return text;\n                    folds.push(j);\n                    escapedFolds[j] = true;\n                    end = j + endStep;\n                    split = undefined;\n                }\n                else {\n                    overflow = true;\n                }\n            }\n        }\n        prev = ch;\n    }\n    if (overflow && onOverflow)\n        onOverflow();\n    if (folds.length === 0)\n        return text;\n    if (onFold)\n        onFold();\n    let res = text.slice(0, folds[0]);\n    for (let i = 0; i < folds.length; ++i) {\n        const fold = folds[i];\n        const end = folds[i + 1] || text.length;\n        if (fold === 0)\n            res = `\\n${indent}${text.slice(0, end)}`;\n        else {\n            if (mode === FOLD_QUOTED && escapedFolds[fold])\n                res += `${text[fold]}\\\\`;\n            res += `\\n${indent}${text.slice(fold + 1, end)}`;\n        }\n    }\n    return res;\n}\n/**\n * Presumes `i + 1` is at the start of a line\n * @returns index of last newline in more-indented block\n */\nfunction consumeMoreIndentedLines(text, i, indent) {\n    let end = i;\n    let start = i + 1;\n    let ch = text[start];\n    while (ch === ' ' || ch === '\\t') {\n        if (i < start + indent) {\n            ch = text[++i];\n        }\n        else {\n            do {\n                ch = text[++i];\n            } while (ch && ch !== '\\n');\n            end = i;\n            start = i + 1;\n            ch = text[start];\n        }\n    }\n    return end;\n}\n\nexports.FOLD_BLOCK = FOLD_BLOCK;\nexports.FOLD_FLOW = FOLD_FLOW;\nexports.FOLD_QUOTED = FOLD_QUOTED;\nexports.foldFlowLines = foldFlowLines;\n","'use strict';\n\nvar Scalar = require('../nodes/Scalar.js');\nvar foldFlowLines = require('./foldFlowLines.js');\n\nconst getFoldOptions = (ctx, isBlock) => ({\n    indentAtStart: isBlock ? ctx.indent.length : ctx.indentAtStart,\n    lineWidth: ctx.options.lineWidth,\n    minContentWidth: ctx.options.minContentWidth\n});\n// Also checks for lines starting with %, as parsing the output as YAML 1.1 will\n// presume that's starting a new document.\nconst containsDocumentMarker = (str) => /^(%|---|\\.\\.\\.)/m.test(str);\nfunction lineLengthOverLimit(str, lineWidth, indentLength) {\n    if (!lineWidth || lineWidth < 0)\n        return false;\n    const limit = lineWidth - indentLength;\n    const strLen = str.length;\n    if (strLen <= limit)\n        return false;\n    for (let i = 0, start = 0; i < strLen; ++i) {\n        if (str[i] === '\\n') {\n            if (i - start > limit)\n                return true;\n            start = i + 1;\n            if (strLen - start <= limit)\n                return false;\n        }\n    }\n    return true;\n}\nfunction doubleQuotedString(value, ctx) {\n    const json = JSON.stringify(value);\n    if (ctx.options.doubleQuotedAsJSON)\n        return json;\n    const { implicitKey } = ctx;\n    const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength;\n    const indent = ctx.indent || (containsDocumentMarker(value) ? '  ' : '');\n    let str = '';\n    let start = 0;\n    for (let i = 0, ch = json[i]; ch; ch = json[++i]) {\n        if (ch === ' ' && json[i + 1] === '\\\\' && json[i + 2] === 'n') {\n            // space before newline needs to be escaped to not be folded\n            str += json.slice(start, i) + '\\\\ ';\n            i += 1;\n            start = i;\n            ch = '\\\\';\n        }\n        if (ch === '\\\\')\n            switch (json[i + 1]) {\n                case 'u':\n                    {\n                        str += json.slice(start, i);\n                        const code = json.substr(i + 2, 4);\n                        switch (code) {\n                            case '0000':\n                                str += '\\\\0';\n                                break;\n                            case '0007':\n                                str += '\\\\a';\n                                break;\n                            case '000b':\n                                str += '\\\\v';\n                                break;\n                            case '001b':\n                                str += '\\\\e';\n                                break;\n                            case '0085':\n                                str += '\\\\N';\n                                break;\n                            case '00a0':\n                                str += '\\\\_';\n                                break;\n                            case '2028':\n                                str += '\\\\L';\n                                break;\n                            case '2029':\n                                str += '\\\\P';\n                                break;\n                            default:\n                                if (code.substr(0, 2) === '00')\n                                    str += '\\\\x' + code.substr(2);\n                                else\n                                    str += json.substr(i, 6);\n                        }\n                        i += 5;\n                        start = i + 1;\n                    }\n                    break;\n                case 'n':\n                    if (implicitKey ||\n                        json[i + 2] === '\"' ||\n                        json.length < minMultiLineLength) {\n                        i += 1;\n                    }\n                    else {\n                        // folding will eat first newline\n                        str += json.slice(start, i) + '\\n\\n';\n                        while (json[i + 2] === '\\\\' &&\n                            json[i + 3] === 'n' &&\n                            json[i + 4] !== '\"') {\n                            str += '\\n';\n                            i += 2;\n                        }\n                        str += indent;\n                        // space after newline needs to be escaped to not be folded\n                        if (json[i + 2] === ' ')\n                            str += '\\\\';\n                        i += 1;\n                        start = i + 1;\n                    }\n                    break;\n                default:\n                    i += 1;\n            }\n    }\n    str = start ? str + json.slice(start) : json;\n    return implicitKey\n        ? str\n        : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_QUOTED, getFoldOptions(ctx, false));\n}\nfunction singleQuotedString(value, ctx) {\n    if (ctx.options.singleQuote === false ||\n        (ctx.implicitKey && value.includes('\\n')) ||\n        /[ \\t]\\n|\\n[ \\t]/.test(value) // single quoted string can't have leading or trailing whitespace around newline\n    )\n        return doubleQuotedString(value, ctx);\n    const indent = ctx.indent || (containsDocumentMarker(value) ? '  ' : '');\n    const res = \"'\" + value.replace(/'/g, \"''\").replace(/\\n+/g, `$&\\n${indent}`) + \"'\";\n    return ctx.implicitKey\n        ? res\n        : foldFlowLines.foldFlowLines(res, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false));\n}\nfunction quotedString(value, ctx) {\n    const { singleQuote } = ctx.options;\n    let qs;\n    if (singleQuote === false)\n        qs = doubleQuotedString;\n    else {\n        const hasDouble = value.includes('\"');\n        const hasSingle = value.includes(\"'\");\n        if (hasDouble && !hasSingle)\n            qs = singleQuotedString;\n        else if (hasSingle && !hasDouble)\n            qs = doubleQuotedString;\n        else\n            qs = singleQuote ? singleQuotedString : doubleQuotedString;\n    }\n    return qs(value, ctx);\n}\n// The negative lookbehind avoids a polynomial search,\n// but isn't supported yet on Safari: https://caniuse.com/js-regexp-lookbehind\nlet blockEndNewlines;\ntry {\n    blockEndNewlines = new RegExp('(^|(?<!\\n))\\n+(?!\\n|$)', 'g');\n}\ncatch {\n    blockEndNewlines = /\\n+(?!\\n|$)/g;\n}\nfunction blockString({ comment, type, value }, ctx, onComment, onChompKeep) {\n    const { blockQuote, commentString, lineWidth } = ctx.options;\n    // 1. Block can't end in whitespace unless the last line is non-empty.\n    // 2. Strings consisting of only whitespace are best rendered explicitly.\n    if (!blockQuote || /\\n[\\t ]+$/.test(value)) {\n        return quotedString(value, ctx);\n    }\n    const indent = ctx.indent ||\n        (ctx.forceBlockIndent || containsDocumentMarker(value) ? '  ' : '');\n    const literal = blockQuote === 'literal'\n        ? true\n        : blockQuote === 'folded' || type === Scalar.Scalar.BLOCK_FOLDED\n            ? false\n            : type === Scalar.Scalar.BLOCK_LITERAL\n                ? true\n                : !lineLengthOverLimit(value, lineWidth, indent.length);\n    if (!value)\n        return literal ? '|\\n' : '>\\n';\n    // determine chomping from whitespace at value end\n    let chomp;\n    let endStart;\n    for (endStart = value.length; endStart > 0; --endStart) {\n        const ch = value[endStart - 1];\n        if (ch !== '\\n' && ch !== '\\t' && ch !== ' ')\n            break;\n    }\n    let end = value.substring(endStart);\n    const endNlPos = end.indexOf('\\n');\n    if (endNlPos === -1) {\n        chomp = '-'; // strip\n    }\n    else if (value === end || endNlPos !== end.length - 1) {\n        chomp = '+'; // keep\n        if (onChompKeep)\n            onChompKeep();\n    }\n    else {\n        chomp = ''; // clip\n    }\n    if (end) {\n        value = value.slice(0, -end.length);\n        if (end[end.length - 1] === '\\n')\n            end = end.slice(0, -1);\n        end = end.replace(blockEndNewlines, `$&${indent}`);\n    }\n    // determine indent indicator from whitespace at value start\n    let startWithSpace = false;\n    let startEnd;\n    let startNlPos = -1;\n    for (startEnd = 0; startEnd < value.length; ++startEnd) {\n        const ch = value[startEnd];\n        if (ch === ' ')\n            startWithSpace = true;\n        else if (ch === '\\n')\n            startNlPos = startEnd;\n        else\n            break;\n    }\n    let start = value.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd);\n    if (start) {\n        value = value.substring(start.length);\n        start = start.replace(/\\n+/g, `$&${indent}`);\n    }\n    const indentSize = indent ? '2' : '1'; // root is at -1\n    // Leading | or > is added later\n    let header = (startWithSpace ? indentSize : '') + chomp;\n    if (comment) {\n        header += ' ' + commentString(comment.replace(/ ?[\\r\\n]+/g, ' '));\n        if (onComment)\n            onComment();\n    }\n    if (!literal) {\n        const foldedValue = value\n            .replace(/\\n+/g, '\\n$&')\n            .replace(/(?:^|\\n)([\\t ].*)(?:([\\n\\t ]*)\\n(?![\\n\\t ]))?/g, '$1$2') // more-indented lines aren't folded\n            //                ^ more-ind. ^ empty     ^ capture next empty lines only at end of indent\n            .replace(/\\n+/g, `$&${indent}`);\n        let literalFallback = false;\n        const foldOptions = getFoldOptions(ctx, true);\n        if (blockQuote !== 'folded' && type !== Scalar.Scalar.BLOCK_FOLDED) {\n            foldOptions.onOverflow = () => {\n                literalFallback = true;\n            };\n        }\n        const body = foldFlowLines.foldFlowLines(`${start}${foldedValue}${end}`, indent, foldFlowLines.FOLD_BLOCK, foldOptions);\n        if (!literalFallback)\n            return `>${header}\\n${indent}${body}`;\n    }\n    value = value.replace(/\\n+/g, `$&${indent}`);\n    return `|${header}\\n${indent}${start}${value}${end}`;\n}\nfunction plainString(item, ctx, onComment, onChompKeep) {\n    const { type, value } = item;\n    const { actualString, implicitKey, indent, indentStep, inFlow } = ctx;\n    if ((implicitKey && value.includes('\\n')) ||\n        (inFlow && /[[\\]{},]/.test(value))) {\n        return quotedString(value, ctx);\n    }\n    if (/^[\\n\\t ,[\\]{}#&*!|>'\"%@`]|^[?-]$|^[?-][ \\t]|[\\n:][ \\t]|[ \\t]\\n|[\\n\\t ]#|[\\n\\t :]$/.test(value)) {\n        // not allowed:\n        // - '-' or '?'\n        // - start with an indicator character (except [?:-]) or /[?-] /\n        // - '\\n ', ': ' or ' \\n' anywhere\n        // - '#' not preceded by a non-space char\n        // - end with ' ' or ':'\n        return implicitKey || inFlow || !value.includes('\\n')\n            ? quotedString(value, ctx)\n            : blockString(item, ctx, onComment, onChompKeep);\n    }\n    if (!implicitKey &&\n        !inFlow &&\n        type !== Scalar.Scalar.PLAIN &&\n        value.includes('\\n')) {\n        // Where allowed & type not set explicitly, prefer block style for multiline strings\n        return blockString(item, ctx, onComment, onChompKeep);\n    }\n    if (containsDocumentMarker(value)) {\n        if (indent === '') {\n            ctx.forceBlockIndent = true;\n            return blockString(item, ctx, onComment, onChompKeep);\n        }\n        else if (implicitKey && indent === indentStep) {\n            return quotedString(value, ctx);\n        }\n    }\n    const str = value.replace(/\\n+/g, `$&\\n${indent}`);\n    // Verify that output will be parsed as a string, as e.g. plain numbers and\n    // booleans get parsed with those types in v1.2 (e.g. '42', 'true' & '0.9e-3'),\n    // and others in v1.1.\n    if (actualString) {\n        const test = (tag) => tag.default && tag.tag !== 'tag:yaml.org,2002:str' && tag.test?.test(str);\n        const { compat, tags } = ctx.doc.schema;\n        if (tags.some(test) || compat?.some(test))\n            return quotedString(value, ctx);\n    }\n    return implicitKey\n        ? str\n        : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false));\n}\nfunction stringifyString(item, ctx, onComment, onChompKeep) {\n    const { implicitKey, inFlow } = ctx;\n    const ss = typeof item.value === 'string'\n        ? item\n        : Object.assign({}, item, { value: String(item.value) });\n    let { type } = item;\n    if (type !== Scalar.Scalar.QUOTE_DOUBLE) {\n        // force double quotes on control characters & unpaired surrogates\n        if (/[\\x00-\\x08\\x0b-\\x1f\\x7f-\\x9f\\u{D800}-\\u{DFFF}]/u.test(ss.value))\n            type = Scalar.Scalar.QUOTE_DOUBLE;\n    }\n    const _stringify = (_type) => {\n        switch (_type) {\n            case Scalar.Scalar.BLOCK_FOLDED:\n            case Scalar.Scalar.BLOCK_LITERAL:\n                return implicitKey || inFlow\n                    ? quotedString(ss.value, ctx) // blocks are not valid inside flow containers\n                    : blockString(ss, ctx, onComment, onChompKeep);\n            case Scalar.Scalar.QUOTE_DOUBLE:\n                return doubleQuotedString(ss.value, ctx);\n            case Scalar.Scalar.QUOTE_SINGLE:\n                return singleQuotedString(ss.value, ctx);\n            case Scalar.Scalar.PLAIN:\n                return plainString(ss, ctx, onComment, onChompKeep);\n            default:\n                return null;\n        }\n    };\n    let res = _stringify(type);\n    if (res === null) {\n        const { defaultKeyType, defaultStringType } = ctx.options;\n        const t = (implicitKey && defaultKeyType) || defaultStringType;\n        res = _stringify(t);\n        if (res === null)\n            throw new Error(`Unsupported default string type ${t}`);\n    }\n    return res;\n}\n\nexports.stringifyString = stringifyString;\n","'use strict';\n\nvar anchors = require('../doc/anchors.js');\nvar identity = require('../nodes/identity.js');\nvar stringifyComment = require('./stringifyComment.js');\nvar stringifyString = require('./stringifyString.js');\n\nfunction createStringifyContext(doc, options) {\n    const opt = Object.assign({\n        blockQuote: true,\n        commentString: stringifyComment.stringifyComment,\n        defaultKeyType: null,\n        defaultStringType: 'PLAIN',\n        directives: null,\n        doubleQuotedAsJSON: false,\n        doubleQuotedMinMultiLineLength: 40,\n        falseStr: 'false',\n        flowCollectionPadding: true,\n        indentSeq: true,\n        lineWidth: 80,\n        minContentWidth: 20,\n        nullStr: 'null',\n        simpleKeys: false,\n        singleQuote: null,\n        trailingComma: false,\n        trueStr: 'true',\n        verifyAliasOrder: true\n    }, doc.schema.toStringOptions, options);\n    let inFlow;\n    switch (opt.collectionStyle) {\n        case 'block':\n            inFlow = false;\n            break;\n        case 'flow':\n            inFlow = true;\n            break;\n        default:\n            inFlow = null;\n    }\n    return {\n        anchors: new Set(),\n        doc,\n        flowCollectionPadding: opt.flowCollectionPadding ? ' ' : '',\n        indent: '',\n        indentStep: typeof opt.indent === 'number' ? ' '.repeat(opt.indent) : '  ',\n        inFlow,\n        options: opt\n    };\n}\nfunction getTagObject(tags, item) {\n    if (item.tag) {\n        const match = tags.filter(t => t.tag === item.tag);\n        if (match.length > 0)\n            return match.find(t => t.format === item.format) ?? match[0];\n    }\n    let tagObj = undefined;\n    let obj;\n    if (identity.isScalar(item)) {\n        obj = item.value;\n        let match = tags.filter(t => t.identify?.(obj));\n        if (match.length > 1) {\n            const testMatch = match.filter(t => t.test);\n            if (testMatch.length > 0)\n                match = testMatch;\n        }\n        tagObj =\n            match.find(t => t.format === item.format) ?? match.find(t => !t.format);\n    }\n    else {\n        obj = item;\n        tagObj = tags.find(t => t.nodeClass && obj instanceof t.nodeClass);\n    }\n    if (!tagObj) {\n        const name = obj?.constructor?.name ?? (obj === null ? 'null' : typeof obj);\n        throw new Error(`Tag not resolved for ${name} value`);\n    }\n    return tagObj;\n}\n// needs to be called before value stringifier to allow for circular anchor refs\nfunction stringifyProps(node, tagObj, { anchors: anchors$1, doc }) {\n    if (!doc.directives)\n        return '';\n    const props = [];\n    const anchor = (identity.isScalar(node) || identity.isCollection(node)) && node.anchor;\n    if (anchor && anchors.anchorIsValid(anchor)) {\n        anchors$1.add(anchor);\n        props.push(`&${anchor}`);\n    }\n    const tag = node.tag ?? (tagObj.default ? null : tagObj.tag);\n    if (tag)\n        props.push(doc.directives.tagString(tag));\n    return props.join(' ');\n}\nfunction stringify(item, ctx, onComment, onChompKeep) {\n    if (identity.isPair(item))\n        return item.toString(ctx, onComment, onChompKeep);\n    if (identity.isAlias(item)) {\n        if (ctx.doc.directives)\n            return item.toString(ctx);\n        if (ctx.resolvedAliases?.has(item)) {\n            throw new TypeError(`Cannot stringify circular structure without alias nodes`);\n        }\n        else {\n            if (ctx.resolvedAliases)\n                ctx.resolvedAliases.add(item);\n            else\n                ctx.resolvedAliases = new Set([item]);\n            item = item.resolve(ctx.doc);\n        }\n    }\n    let tagObj = undefined;\n    const node = identity.isNode(item)\n        ? item\n        : ctx.doc.createNode(item, { onTagObj: o => (tagObj = o) });\n    tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node));\n    const props = stringifyProps(node, tagObj, ctx);\n    if (props.length > 0)\n        ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1;\n    const str = typeof tagObj.stringify === 'function'\n        ? tagObj.stringify(node, ctx, onComment, onChompKeep)\n        : identity.isScalar(node)\n            ? stringifyString.stringifyString(node, ctx, onComment, onChompKeep)\n            : node.toString(ctx, onComment, onChompKeep);\n    if (!props)\n        return str;\n    return identity.isScalar(node) || str[0] === '{' || str[0] === '['\n        ? `${props} ${str}`\n        : `${props}\\n${ctx.indent}${str}`;\n}\n\nexports.createStringifyContext = createStringifyContext;\nexports.stringify = stringify;\n","'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar Scalar = require('../nodes/Scalar.js');\nvar stringify = require('./stringify.js');\nvar stringifyComment = require('./stringifyComment.js');\n\nfunction stringifyPair({ key, value }, ctx, onComment, onChompKeep) {\n    const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx;\n    let keyComment = (identity.isNode(key) && key.comment) || null;\n    if (simpleKeys) {\n        if (keyComment) {\n            throw new Error('With simple keys, key nodes cannot have comments');\n        }\n        if (identity.isCollection(key) || (!identity.isNode(key) && typeof key === 'object')) {\n            const msg = 'With simple keys, collection cannot be used as a key value';\n            throw new Error(msg);\n        }\n    }\n    let explicitKey = !simpleKeys &&\n        (!key ||\n            (keyComment && value == null && !ctx.inFlow) ||\n            identity.isCollection(key) ||\n            (identity.isScalar(key)\n                ? key.type === Scalar.Scalar.BLOCK_FOLDED || key.type === Scalar.Scalar.BLOCK_LITERAL\n                : typeof key === 'object'));\n    ctx = Object.assign({}, ctx, {\n        allNullValues: false,\n        implicitKey: !explicitKey && (simpleKeys || !allNullValues),\n        indent: indent + indentStep\n    });\n    let keyCommentDone = false;\n    let chompKeep = false;\n    let str = stringify.stringify(key, ctx, () => (keyCommentDone = true), () => (chompKeep = true));\n    if (!explicitKey && !ctx.inFlow && str.length > 1024) {\n        if (simpleKeys)\n            throw new Error('With simple keys, single line scalar must not span more than 1024 characters');\n        explicitKey = true;\n    }\n    if (ctx.inFlow) {\n        if (allNullValues || value == null) {\n            if (keyCommentDone && onComment)\n                onComment();\n            return str === '' ? '?' : explicitKey ? `? ${str}` : str;\n        }\n    }\n    else if ((allNullValues && !simpleKeys) || (value == null && explicitKey)) {\n        str = `? ${str}`;\n        if (keyComment && !keyCommentDone) {\n            str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));\n        }\n        else if (chompKeep && onChompKeep)\n            onChompKeep();\n        return str;\n    }\n    if (keyCommentDone)\n        keyComment = null;\n    if (explicitKey) {\n        if (keyComment)\n            str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));\n        str = `? ${str}\\n${indent}:`;\n    }\n    else {\n        str = `${str}:`;\n        if (keyComment)\n            str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));\n    }\n    let vsb, vcb, valueComment;\n    if (identity.isNode(value)) {\n        vsb = !!value.spaceBefore;\n        vcb = value.commentBefore;\n        valueComment = value.comment;\n    }\n    else {\n        vsb = false;\n        vcb = null;\n        valueComment = null;\n        if (value && typeof value === 'object')\n            value = doc.createNode(value);\n    }\n    ctx.implicitKey = false;\n    if (!explicitKey && !keyComment && identity.isScalar(value))\n        ctx.indentAtStart = str.length + 1;\n    chompKeep = false;\n    if (!indentSeq &&\n        indentStep.length >= 2 &&\n        !ctx.inFlow &&\n        !explicitKey &&\n        identity.isSeq(value) &&\n        !value.flow &&\n        !value.tag &&\n        !value.anchor) {\n        // If indentSeq === false, consider '- ' as part of indentation where possible\n        ctx.indent = ctx.indent.substring(2);\n    }\n    let valueCommentDone = false;\n    const valueStr = stringify.stringify(value, ctx, () => (valueCommentDone = true), () => (chompKeep = true));\n    let ws = ' ';\n    if (keyComment || vsb || vcb) {\n        ws = vsb ? '\\n' : '';\n        if (vcb) {\n            const cs = commentString(vcb);\n            ws += `\\n${stringifyComment.indentComment(cs, ctx.indent)}`;\n        }\n        if (valueStr === '' && !ctx.inFlow) {\n            if (ws === '\\n' && valueComment)\n                ws = '\\n\\n';\n        }\n        else {\n            ws += `\\n${ctx.indent}`;\n        }\n    }\n    else if (!explicitKey && identity.isCollection(value)) {\n        const vs0 = valueStr[0];\n        const nl0 = valueStr.indexOf('\\n');\n        const hasNewline = nl0 !== -1;\n        const flow = ctx.inFlow ?? value.flow ?? value.items.length === 0;\n        if (hasNewline || !flow) {\n            let hasPropsLine = false;\n            if (hasNewline && (vs0 === '&' || vs0 === '!')) {\n                let sp0 = valueStr.indexOf(' ');\n                if (vs0 === '&' &&\n                    sp0 !== -1 &&\n                    sp0 < nl0 &&\n                    valueStr[sp0 + 1] === '!') {\n                    sp0 = valueStr.indexOf(' ', sp0 + 1);\n                }\n                if (sp0 === -1 || nl0 < sp0)\n                    hasPropsLine = true;\n            }\n            if (!hasPropsLine)\n                ws = `\\n${ctx.indent}`;\n        }\n    }\n    else if (valueStr === '' || valueStr[0] === '\\n') {\n        ws = '';\n    }\n    str += ws + valueStr;\n    if (ctx.inFlow) {\n        if (valueCommentDone && onComment)\n            onComment();\n    }\n    else if (valueComment && !valueCommentDone) {\n        str += stringifyComment.lineComment(str, ctx.indent, commentString(valueComment));\n    }\n    else if (chompKeep && onChompKeep) {\n        onChompKeep();\n    }\n    return str;\n}\n\nexports.stringifyPair = stringifyPair;\n","'use strict';\n\nvar node_process = require('process');\n\nfunction debug(logLevel, ...messages) {\n    if (logLevel === 'debug')\n        console.log(...messages);\n}\nfunction warn(logLevel, warning) {\n    if (logLevel === 'debug' || logLevel === 'warn') {\n        if (typeof node_process.emitWarning === 'function')\n            node_process.emitWarning(warning);\n        else\n            console.warn(warning);\n    }\n}\n\nexports.debug = debug;\nexports.warn = warn;\n","'use strict';\n\nvar identity = require('../../nodes/identity.js');\nvar Scalar = require('../../nodes/Scalar.js');\n\n// If the value associated with a merge key is a single mapping node, each of\n// its key/value pairs is inserted into the current mapping, unless the key\n// already exists in it. If the value associated with the merge key is a\n// sequence, then this sequence is expected to contain mapping nodes and each\n// of these nodes is merged in turn according to its order in the sequence.\n// Keys in mapping nodes earlier in the sequence override keys specified in\n// later mapping nodes. -- http://yaml.org/type/merge.html\nconst MERGE_KEY = '<<';\nconst merge = {\n    identify: value => value === MERGE_KEY ||\n        (typeof value === 'symbol' && value.description === MERGE_KEY),\n    default: 'key',\n    tag: 'tag:yaml.org,2002:merge',\n    test: /^<<$/,\n    resolve: () => Object.assign(new Scalar.Scalar(Symbol(MERGE_KEY)), {\n        addToJSMap: addMergeToJSMap\n    }),\n    stringify: () => MERGE_KEY\n};\nconst isMergeKey = (ctx, key) => (merge.identify(key) ||\n    (identity.isScalar(key) &&\n        (!key.type || key.type === Scalar.Scalar.PLAIN) &&\n        merge.identify(key.value))) &&\n    ctx?.doc.schema.tags.some(tag => tag.tag === merge.tag && tag.default);\nfunction addMergeToJSMap(ctx, map, value) {\n    const source = resolveAliasValue(ctx, value);\n    if (identity.isSeq(source))\n        for (const it of source.items)\n            mergeValue(ctx, map, it);\n    else if (Array.isArray(source))\n        for (const it of source)\n            mergeValue(ctx, map, it);\n    else\n        mergeValue(ctx, map, source);\n}\nfunction mergeValue(ctx, map, value) {\n    const source = resolveAliasValue(ctx, value);\n    if (!identity.isMap(source))\n        throw new Error('Merge sources must be maps or map aliases');\n    const srcMap = source.toJSON(null, ctx, Map);\n    for (const [key, value] of srcMap) {\n        if (map instanceof Map) {\n            if (!map.has(key))\n                map.set(key, value);\n        }\n        else if (map instanceof Set) {\n            map.add(key);\n        }\n        else if (!Object.prototype.hasOwnProperty.call(map, key)) {\n            Object.defineProperty(map, key, {\n                value,\n                writable: true,\n                enumerable: true,\n                configurable: true\n            });\n        }\n    }\n    return map;\n}\nfunction resolveAliasValue(ctx, value) {\n    return ctx && identity.isAlias(value) ? value.resolve(ctx.doc, ctx) : value;\n}\n\nexports.addMergeToJSMap = addMergeToJSMap;\nexports.isMergeKey = isMergeKey;\nexports.merge = merge;\n","'use strict';\n\nvar log = require('../log.js');\nvar merge = require('../schema/yaml-1.1/merge.js');\nvar stringify = require('../stringify/stringify.js');\nvar identity = require('./identity.js');\nvar toJS = require('./toJS.js');\n\nfunction addPairToJSMap(ctx, map, { key, value }) {\n    if (identity.isNode(key) && key.addToJSMap)\n        key.addToJSMap(ctx, map, value);\n    // TODO: Should drop this special case for bare << handling\n    else if (merge.isMergeKey(ctx, key))\n        merge.addMergeToJSMap(ctx, map, value);\n    else {\n        const jsKey = toJS.toJS(key, '', ctx);\n        if (map instanceof Map) {\n            map.set(jsKey, toJS.toJS(value, jsKey, ctx));\n        }\n        else if (map instanceof Set) {\n            map.add(jsKey);\n        }\n        else {\n            const stringKey = stringifyKey(key, jsKey, ctx);\n            const jsValue = toJS.toJS(value, stringKey, ctx);\n            if (stringKey in map)\n                Object.defineProperty(map, stringKey, {\n                    value: jsValue,\n                    writable: true,\n                    enumerable: true,\n                    configurable: true\n                });\n            else\n                map[stringKey] = jsValue;\n        }\n    }\n    return map;\n}\nfunction stringifyKey(key, jsKey, ctx) {\n    if (jsKey === null)\n        return '';\n    // eslint-disable-next-line @typescript-eslint/no-base-to-string\n    if (typeof jsKey !== 'object')\n        return String(jsKey);\n    if (identity.isNode(key) && ctx?.doc) {\n        const strCtx = stringify.createStringifyContext(ctx.doc, {});\n        strCtx.anchors = new Set();\n        for (const node of ctx.anchors.keys())\n            strCtx.anchors.add(node.anchor);\n        strCtx.inFlow = true;\n        strCtx.inStringifyKey = true;\n        const strKey = key.toString(strCtx);\n        if (!ctx.mapKeyWarned) {\n            let jsonStr = JSON.stringify(strKey);\n            if (jsonStr.length > 40)\n                jsonStr = jsonStr.substring(0, 36) + '...\"';\n            log.warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`);\n            ctx.mapKeyWarned = true;\n        }\n        return strKey;\n    }\n    return JSON.stringify(jsKey);\n}\n\nexports.addPairToJSMap = addPairToJSMap;\n","'use strict';\n\nvar createNode = require('../doc/createNode.js');\nvar stringifyPair = require('../stringify/stringifyPair.js');\nvar addPairToJSMap = require('./addPairToJSMap.js');\nvar identity = require('./identity.js');\n\nfunction createPair(key, value, ctx) {\n    const k = createNode.createNode(key, undefined, ctx);\n    const v = createNode.createNode(value, undefined, ctx);\n    return new Pair(k, v);\n}\nclass Pair {\n    constructor(key, value = null) {\n        Object.defineProperty(this, identity.NODE_TYPE, { value: identity.PAIR });\n        this.key = key;\n        this.value = value;\n    }\n    clone(schema) {\n        let { key, value } = this;\n        if (identity.isNode(key))\n            key = key.clone(schema);\n        if (identity.isNode(value))\n            value = value.clone(schema);\n        return new Pair(key, value);\n    }\n    toJSON(_, ctx) {\n        const pair = ctx?.mapAsMap ? new Map() : {};\n        return addPairToJSMap.addPairToJSMap(ctx, pair, this);\n    }\n    toString(ctx, onComment, onChompKeep) {\n        return ctx?.doc\n            ? stringifyPair.stringifyPair(this, ctx, onComment, onChompKeep)\n            : JSON.stringify(this);\n    }\n}\n\nexports.Pair = Pair;\nexports.createPair = createPair;\n","'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar stringify = require('./stringify.js');\nvar stringifyComment = require('./stringifyComment.js');\n\nfunction stringifyCollection(collection, ctx, options) {\n    const flow = ctx.inFlow ?? collection.flow;\n    const stringify = flow ? stringifyFlowCollection : stringifyBlockCollection;\n    return stringify(collection, ctx, options);\n}\nfunction stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) {\n    const { indent, options: { commentString } } = ctx;\n    const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null });\n    let chompKeep = false; // flag for the preceding node's status\n    const lines = [];\n    for (let i = 0; i < items.length; ++i) {\n        const item = items[i];\n        let comment = null;\n        if (identity.isNode(item)) {\n            if (!chompKeep && item.spaceBefore)\n                lines.push('');\n            addCommentBefore(ctx, lines, item.commentBefore, chompKeep);\n            if (item.comment)\n                comment = item.comment;\n        }\n        else if (identity.isPair(item)) {\n            const ik = identity.isNode(item.key) ? item.key : null;\n            if (ik) {\n                if (!chompKeep && ik.spaceBefore)\n                    lines.push('');\n                addCommentBefore(ctx, lines, ik.commentBefore, chompKeep);\n            }\n        }\n        chompKeep = false;\n        let str = stringify.stringify(item, itemCtx, () => (comment = null), () => (chompKeep = true));\n        if (comment)\n            str += stringifyComment.lineComment(str, itemIndent, commentString(comment));\n        if (chompKeep && comment)\n            chompKeep = false;\n        lines.push(blockItemPrefix + str);\n    }\n    let str;\n    if (lines.length === 0) {\n        str = flowChars.start + flowChars.end;\n    }\n    else {\n        str = lines[0];\n        for (let i = 1; i < lines.length; ++i) {\n            const line = lines[i];\n            str += line ? `\\n${indent}${line}` : '\\n';\n        }\n    }\n    if (comment) {\n        str += '\\n' + stringifyComment.indentComment(commentString(comment), indent);\n        if (onComment)\n            onComment();\n    }\n    else if (chompKeep && onChompKeep)\n        onChompKeep();\n    return str;\n}\nfunction stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) {\n    const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx;\n    itemIndent += indentStep;\n    const itemCtx = Object.assign({}, ctx, {\n        indent: itemIndent,\n        inFlow: true,\n        type: null\n    });\n    let reqNewline = false;\n    let linesAtValue = 0;\n    const lines = [];\n    for (let i = 0; i < items.length; ++i) {\n        const item = items[i];\n        let comment = null;\n        if (identity.isNode(item)) {\n            if (item.spaceBefore)\n                lines.push('');\n            addCommentBefore(ctx, lines, item.commentBefore, false);\n            if (item.comment)\n                comment = item.comment;\n        }\n        else if (identity.isPair(item)) {\n            const ik = identity.isNode(item.key) ? item.key : null;\n            if (ik) {\n                if (ik.spaceBefore)\n                    lines.push('');\n                addCommentBefore(ctx, lines, ik.commentBefore, false);\n                if (ik.comment)\n                    reqNewline = true;\n            }\n            const iv = identity.isNode(item.value) ? item.value : null;\n            if (iv) {\n                if (iv.comment)\n                    comment = iv.comment;\n                if (iv.commentBefore)\n                    reqNewline = true;\n            }\n            else if (item.value == null && ik?.comment) {\n                comment = ik.comment;\n            }\n        }\n        if (comment)\n            reqNewline = true;\n        let str = stringify.stringify(item, itemCtx, () => (comment = null));\n        reqNewline || (reqNewline = lines.length > linesAtValue || str.includes('\\n'));\n        if (i < items.length - 1) {\n            str += ',';\n        }\n        else if (ctx.options.trailingComma) {\n            if (ctx.options.lineWidth > 0) {\n                reqNewline || (reqNewline = lines.reduce((sum, line) => sum + line.length + 2, 2) +\n                    (str.length + 2) >\n                    ctx.options.lineWidth);\n            }\n            if (reqNewline) {\n                str += ',';\n            }\n        }\n        if (comment)\n            str += stringifyComment.lineComment(str, itemIndent, commentString(comment));\n        lines.push(str);\n        linesAtValue = lines.length;\n    }\n    const { start, end } = flowChars;\n    if (lines.length === 0) {\n        return start + end;\n    }\n    else {\n        if (!reqNewline) {\n            const len = lines.reduce((sum, line) => sum + line.length + 2, 2);\n            reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth;\n        }\n        if (reqNewline) {\n            let str = start;\n            for (const line of lines)\n                str += line ? `\\n${indentStep}${indent}${line}` : '\\n';\n            return `${str}\\n${indent}${end}`;\n        }\n        else {\n            return `${start}${fcPadding}${lines.join(' ')}${fcPadding}${end}`;\n        }\n    }\n}\nfunction addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) {\n    if (comment && chompKeep)\n        comment = comment.replace(/^\\n+/, '');\n    if (comment) {\n        const ic = stringifyComment.indentComment(commentString(comment), indent);\n        lines.push(ic.trimStart()); // Avoid double indent on first line\n    }\n}\n\nexports.stringifyCollection = stringifyCollection;\n","'use strict';\n\nvar stringifyCollection = require('../stringify/stringifyCollection.js');\nvar addPairToJSMap = require('./addPairToJSMap.js');\nvar Collection = require('./Collection.js');\nvar identity = require('./identity.js');\nvar Pair = require('./Pair.js');\nvar Scalar = require('./Scalar.js');\n\nfunction findPair(items, key) {\n    const k = identity.isScalar(key) ? key.value : key;\n    for (const it of items) {\n        if (identity.isPair(it)) {\n            if (it.key === key || it.key === k)\n                return it;\n            if (identity.isScalar(it.key) && it.key.value === k)\n                return it;\n        }\n    }\n    return undefined;\n}\nclass YAMLMap extends Collection.Collection {\n    static get tagName() {\n        return 'tag:yaml.org,2002:map';\n    }\n    constructor(schema) {\n        super(identity.MAP, schema);\n        this.items = [];\n    }\n    /**\n     * A generic collection parsing method that can be extended\n     * to other node classes that inherit from YAMLMap\n     */\n    static from(schema, obj, ctx) {\n        const { keepUndefined, replacer } = ctx;\n        const map = new this(schema);\n        const add = (key, value) => {\n            if (typeof replacer === 'function')\n                value = replacer.call(obj, key, value);\n            else if (Array.isArray(replacer) && !replacer.includes(key))\n                return;\n            if (value !== undefined || keepUndefined)\n                map.items.push(Pair.createPair(key, value, ctx));\n        };\n        if (obj instanceof Map) {\n            for (const [key, value] of obj)\n                add(key, value);\n        }\n        else if (obj && typeof obj === 'object') {\n            for (const key of Object.keys(obj))\n                add(key, obj[key]);\n        }\n        if (typeof schema.sortMapEntries === 'function') {\n            map.items.sort(schema.sortMapEntries);\n        }\n        return map;\n    }\n    /**\n     * Adds a value to the collection.\n     *\n     * @param overwrite - If not set `true`, using a key that is already in the\n     *   collection will throw. Otherwise, overwrites the previous value.\n     */\n    add(pair, overwrite) {\n        let _pair;\n        if (identity.isPair(pair))\n            _pair = pair;\n        else if (!pair || typeof pair !== 'object' || !('key' in pair)) {\n            // In TypeScript, this never happens.\n            _pair = new Pair.Pair(pair, pair?.value);\n        }\n        else\n            _pair = new Pair.Pair(pair.key, pair.value);\n        const prev = findPair(this.items, _pair.key);\n        const sortEntries = this.schema?.sortMapEntries;\n        if (prev) {\n            if (!overwrite)\n                throw new Error(`Key ${_pair.key} already set`);\n            // For scalars, keep the old node & its comments and anchors\n            if (identity.isScalar(prev.value) && Scalar.isScalarValue(_pair.value))\n                prev.value.value = _pair.value;\n            else\n                prev.value = _pair.value;\n        }\n        else if (sortEntries) {\n            const i = this.items.findIndex(item => sortEntries(_pair, item) < 0);\n            if (i === -1)\n                this.items.push(_pair);\n            else\n                this.items.splice(i, 0, _pair);\n        }\n        else {\n            this.items.push(_pair);\n        }\n    }\n    delete(key) {\n        const it = findPair(this.items, key);\n        if (!it)\n            return false;\n        const del = this.items.splice(this.items.indexOf(it), 1);\n        return del.length > 0;\n    }\n    get(key, keepScalar) {\n        const it = findPair(this.items, key);\n        const node = it?.value;\n        return (!keepScalar && identity.isScalar(node) ? node.value : node) ?? undefined;\n    }\n    has(key) {\n        return !!findPair(this.items, key);\n    }\n    set(key, value) {\n        this.add(new Pair.Pair(key, value), true);\n    }\n    /**\n     * @param ctx - Conversion context, originally set in Document#toJS()\n     * @param {Class} Type - If set, forces the returned collection type\n     * @returns Instance of Type, Map, or Object\n     */\n    toJSON(_, ctx, Type) {\n        const map = Type ? new Type() : ctx?.mapAsMap ? new Map() : {};\n        if (ctx?.onCreate)\n            ctx.onCreate(map);\n        for (const item of this.items)\n            addPairToJSMap.addPairToJSMap(ctx, map, item);\n        return map;\n    }\n    toString(ctx, onComment, onChompKeep) {\n        if (!ctx)\n            return JSON.stringify(this);\n        for (const item of this.items) {\n            if (!identity.isPair(item))\n                throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`);\n        }\n        if (!ctx.allNullValues && this.hasAllNullValues(false))\n            ctx = Object.assign({}, ctx, { allNullValues: true });\n        return stringifyCollection.stringifyCollection(this, ctx, {\n            blockItemPrefix: '',\n            flowChars: { start: '{', end: '}' },\n            itemIndent: ctx.indent || '',\n            onChompKeep,\n            onComment\n        });\n    }\n}\n\nexports.YAMLMap = YAMLMap;\nexports.findPair = findPair;\n","'use strict';\n\nvar identity = require('../../nodes/identity.js');\nvar YAMLMap = require('../../nodes/YAMLMap.js');\n\nconst map = {\n    collection: 'map',\n    default: true,\n    nodeClass: YAMLMap.YAMLMap,\n    tag: 'tag:yaml.org,2002:map',\n    resolve(map, onError) {\n        if (!identity.isMap(map))\n            onError('Expected a mapping for this tag');\n        return map;\n    },\n    createNode: (schema, obj, ctx) => YAMLMap.YAMLMap.from(schema, obj, ctx)\n};\n\nexports.map = map;\n","'use strict';\n\nvar createNode = require('../doc/createNode.js');\nvar stringifyCollection = require('../stringify/stringifyCollection.js');\nvar Collection = require('./Collection.js');\nvar identity = require('./identity.js');\nvar Scalar = require('./Scalar.js');\nvar toJS = require('./toJS.js');\n\nclass YAMLSeq extends Collection.Collection {\n    static get tagName() {\n        return 'tag:yaml.org,2002:seq';\n    }\n    constructor(schema) {\n        super(identity.SEQ, schema);\n        this.items = [];\n    }\n    add(value) {\n        this.items.push(value);\n    }\n    /**\n     * Removes a value from the collection.\n     *\n     * `key` must contain a representation of an integer for this to succeed.\n     * It may be wrapped in a `Scalar`.\n     *\n     * @returns `true` if the item was found and removed.\n     */\n    delete(key) {\n        const idx = asItemIndex(key);\n        if (typeof idx !== 'number')\n            return false;\n        const del = this.items.splice(idx, 1);\n        return del.length > 0;\n    }\n    get(key, keepScalar) {\n        const idx = asItemIndex(key);\n        if (typeof idx !== 'number')\n            return undefined;\n        const it = this.items[idx];\n        return !keepScalar && identity.isScalar(it) ? it.value : it;\n    }\n    /**\n     * Checks if the collection includes a value with the key `key`.\n     *\n     * `key` must contain a representation of an integer for this to succeed.\n     * It may be wrapped in a `Scalar`.\n     */\n    has(key) {\n        const idx = asItemIndex(key);\n        return typeof idx === 'number' && idx < this.items.length;\n    }\n    /**\n     * Sets a value in this collection. For `!!set`, `value` needs to be a\n     * boolean to add/remove the item from the set.\n     *\n     * If `key` does not contain a representation of an integer, this will throw.\n     * It may be wrapped in a `Scalar`.\n     */\n    set(key, value) {\n        const idx = asItemIndex(key);\n        if (typeof idx !== 'number')\n            throw new Error(`Expected a valid index, not ${key}.`);\n        const prev = this.items[idx];\n        if (identity.isScalar(prev) && Scalar.isScalarValue(value))\n            prev.value = value;\n        else\n            this.items[idx] = value;\n    }\n    toJSON(_, ctx) {\n        const seq = [];\n        if (ctx?.onCreate)\n            ctx.onCreate(seq);\n        let i = 0;\n        for (const item of this.items)\n            seq.push(toJS.toJS(item, String(i++), ctx));\n        return seq;\n    }\n    toString(ctx, onComment, onChompKeep) {\n        if (!ctx)\n            return JSON.stringify(this);\n        return stringifyCollection.stringifyCollection(this, ctx, {\n            blockItemPrefix: '- ',\n            flowChars: { start: '[', end: ']' },\n            itemIndent: (ctx.indent || '') + '  ',\n            onChompKeep,\n            onComment\n        });\n    }\n    static from(schema, obj, ctx) {\n        const { replacer } = ctx;\n        const seq = new this(schema);\n        if (obj && Symbol.iterator in Object(obj)) {\n            let i = 0;\n            for (let it of obj) {\n                if (typeof replacer === 'function') {\n                    const key = obj instanceof Set ? it : String(i++);\n                    it = replacer.call(obj, key, it);\n                }\n                seq.items.push(createNode.createNode(it, undefined, ctx));\n            }\n        }\n        return seq;\n    }\n}\nfunction asItemIndex(key) {\n    let idx = identity.isScalar(key) ? key.value : key;\n    if (idx && typeof idx === 'string')\n        idx = Number(idx);\n    return typeof idx === 'number' && Number.isInteger(idx) && idx >= 0\n        ? idx\n        : null;\n}\n\nexports.YAMLSeq = YAMLSeq;\n","'use strict';\n\nvar identity = require('../../nodes/identity.js');\nvar YAMLSeq = require('../../nodes/YAMLSeq.js');\n\nconst seq = {\n    collection: 'seq',\n    default: true,\n    nodeClass: YAMLSeq.YAMLSeq,\n    tag: 'tag:yaml.org,2002:seq',\n    resolve(seq, onError) {\n        if (!identity.isSeq(seq))\n            onError('Expected a sequence for this tag');\n        return seq;\n    },\n    createNode: (schema, obj, ctx) => YAMLSeq.YAMLSeq.from(schema, obj, ctx)\n};\n\nexports.seq = seq;\n","'use strict';\n\nvar stringifyString = require('../../stringify/stringifyString.js');\n\nconst string = {\n    identify: value => typeof value === 'string',\n    default: true,\n    tag: 'tag:yaml.org,2002:str',\n    resolve: str => str,\n    stringify(item, ctx, onComment, onChompKeep) {\n        ctx = Object.assign({ actualString: true }, ctx);\n        return stringifyString.stringifyString(item, ctx, onComment, onChompKeep);\n    }\n};\n\nexports.string = string;\n","'use strict';\n\nvar Scalar = require('../../nodes/Scalar.js');\n\nconst nullTag = {\n    identify: value => value == null,\n    createNode: () => new Scalar.Scalar(null),\n    default: true,\n    tag: 'tag:yaml.org,2002:null',\n    test: /^(?:~|[Nn]ull|NULL)?$/,\n    resolve: () => new Scalar.Scalar(null),\n    stringify: ({ source }, ctx) => typeof source === 'string' && nullTag.test.test(source)\n        ? source\n        : ctx.options.nullStr\n};\n\nexports.nullTag = nullTag;\n","'use strict';\n\nvar Scalar = require('../../nodes/Scalar.js');\n\nconst boolTag = {\n    identify: value => typeof value === 'boolean',\n    default: true,\n    tag: 'tag:yaml.org,2002:bool',\n    test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,\n    resolve: str => new Scalar.Scalar(str[0] === 't' || str[0] === 'T'),\n    stringify({ source, value }, ctx) {\n        if (source && boolTag.test.test(source)) {\n            const sv = source[0] === 't' || source[0] === 'T';\n            if (value === sv)\n                return source;\n        }\n        return value ? ctx.options.trueStr : ctx.options.falseStr;\n    }\n};\n\nexports.boolTag = boolTag;\n","'use strict';\n\nfunction stringifyNumber({ format, minFractionDigits, tag, value }) {\n    if (typeof value === 'bigint')\n        return String(value);\n    const num = typeof value === 'number' ? value : Number(value);\n    if (!isFinite(num))\n        return isNaN(num) ? '.nan' : num < 0 ? '-.inf' : '.inf';\n    let n = Object.is(value, -0) ? '-0' : JSON.stringify(value);\n    if (!format &&\n        minFractionDigits &&\n        (!tag || tag === 'tag:yaml.org,2002:float') &&\n        /^-?\\d/.test(n) &&\n        !n.includes('e')) {\n        let i = n.indexOf('.');\n        if (i < 0) {\n            i = n.length;\n            n += '.';\n        }\n        let d = minFractionDigits - (n.length - i - 1);\n        while (d-- > 0)\n            n += '0';\n    }\n    return n;\n}\n\nexports.stringifyNumber = stringifyNumber;\n","'use strict';\n\nvar Scalar = require('../../nodes/Scalar.js');\nvar stringifyNumber = require('../../stringify/stringifyNumber.js');\n\nconst floatNaN = {\n    identify: value => typeof value === 'number',\n    default: true,\n    tag: 'tag:yaml.org,2002:float',\n    test: /^(?:[-+]?\\.(?:inf|Inf|INF)|\\.nan|\\.NaN|\\.NAN)$/,\n    resolve: str => str.slice(-3).toLowerCase() === 'nan'\n        ? NaN\n        : str[0] === '-'\n            ? Number.NEGATIVE_INFINITY\n            : Number.POSITIVE_INFINITY,\n    stringify: stringifyNumber.stringifyNumber\n};\nconst floatExp = {\n    identify: value => typeof value === 'number',\n    default: true,\n    tag: 'tag:yaml.org,2002:float',\n    format: 'EXP',\n    test: /^[-+]?(?:\\.[0-9]+|[0-9]+(?:\\.[0-9]*)?)[eE][-+]?[0-9]+$/,\n    resolve: str => parseFloat(str),\n    stringify(node) {\n        const num = Number(node.value);\n        return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node);\n    }\n};\nconst float = {\n    identify: value => typeof value === 'number',\n    default: true,\n    tag: 'tag:yaml.org,2002:float',\n    test: /^[-+]?(?:\\.[0-9]+|[0-9]+\\.[0-9]*)$/,\n    resolve(str) {\n        const node = new Scalar.Scalar(parseFloat(str));\n        const dot = str.indexOf('.');\n        if (dot !== -1 && str[str.length - 1] === '0')\n            node.minFractionDigits = str.length - dot - 1;\n        return node;\n    },\n    stringify: stringifyNumber.stringifyNumber\n};\n\nexports.float = float;\nexports.floatExp = floatExp;\nexports.floatNaN = floatNaN;\n","'use strict';\n\nvar stringifyNumber = require('../../stringify/stringifyNumber.js');\n\nconst intIdentify = (value) => typeof value === 'bigint' || Number.isInteger(value);\nconst intResolve = (str, offset, radix, { intAsBigInt }) => (intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix));\nfunction intStringify(node, radix, prefix) {\n    const { value } = node;\n    if (intIdentify(value) && value >= 0)\n        return prefix + value.toString(radix);\n    return stringifyNumber.stringifyNumber(node);\n}\nconst intOct = {\n    identify: value => intIdentify(value) && value >= 0,\n    default: true,\n    tag: 'tag:yaml.org,2002:int',\n    format: 'OCT',\n    test: /^0o[0-7]+$/,\n    resolve: (str, _onError, opt) => intResolve(str, 2, 8, opt),\n    stringify: node => intStringify(node, 8, '0o')\n};\nconst int = {\n    identify: intIdentify,\n    default: true,\n    tag: 'tag:yaml.org,2002:int',\n    test: /^[-+]?[0-9]+$/,\n    resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),\n    stringify: stringifyNumber.stringifyNumber\n};\nconst intHex = {\n    identify: value => intIdentify(value) && value >= 0,\n    default: true,\n    tag: 'tag:yaml.org,2002:int',\n    format: 'HEX',\n    test: /^0x[0-9a-fA-F]+$/,\n    resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),\n    stringify: node => intStringify(node, 16, '0x')\n};\n\nexports.int = int;\nexports.intHex = intHex;\nexports.intOct = intOct;\n","'use strict';\n\nvar map = require('../common/map.js');\nvar _null = require('../common/null.js');\nvar seq = require('../common/seq.js');\nvar string = require('../common/string.js');\nvar bool = require('./bool.js');\nvar float = require('./float.js');\nvar int = require('./int.js');\n\nconst schema = [\n    map.map,\n    seq.seq,\n    string.string,\n    _null.nullTag,\n    bool.boolTag,\n    int.intOct,\n    int.int,\n    int.intHex,\n    float.floatNaN,\n    float.floatExp,\n    float.float\n];\n\nexports.schema = schema;\n","'use strict';\n\nvar Scalar = require('../../nodes/Scalar.js');\nvar map = require('../common/map.js');\nvar seq = require('../common/seq.js');\n\nfunction intIdentify(value) {\n    return typeof value === 'bigint' || Number.isInteger(value);\n}\nconst stringifyJSON = ({ value }) => JSON.stringify(value);\nconst jsonScalars = [\n    {\n        identify: value => typeof value === 'string',\n        default: true,\n        tag: 'tag:yaml.org,2002:str',\n        resolve: str => str,\n        stringify: stringifyJSON\n    },\n    {\n        identify: value => value == null,\n        createNode: () => new Scalar.Scalar(null),\n        default: true,\n        tag: 'tag:yaml.org,2002:null',\n        test: /^null$/,\n        resolve: () => null,\n        stringify: stringifyJSON\n    },\n    {\n        identify: value => typeof value === 'boolean',\n        default: true,\n        tag: 'tag:yaml.org,2002:bool',\n        test: /^true$|^false$/,\n        resolve: str => str === 'true',\n        stringify: stringifyJSON\n    },\n    {\n        identify: intIdentify,\n        default: true,\n        tag: 'tag:yaml.org,2002:int',\n        test: /^-?(?:0|[1-9][0-9]*)$/,\n        resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10),\n        stringify: ({ value }) => intIdentify(value) ? value.toString() : JSON.stringify(value)\n    },\n    {\n        identify: value => typeof value === 'number',\n        default: true,\n        tag: 'tag:yaml.org,2002:float',\n        test: /^-?(?:0|[1-9][0-9]*)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,\n        resolve: str => parseFloat(str),\n        stringify: stringifyJSON\n    }\n];\nconst jsonError = {\n    default: true,\n    tag: '',\n    test: /^/,\n    resolve(str, onError) {\n        onError(`Unresolved plain scalar ${JSON.stringify(str)}`);\n        return str;\n    }\n};\nconst schema = [map.map, seq.seq].concat(jsonScalars, jsonError);\n\nexports.schema = schema;\n","'use strict';\n\nvar node_buffer = require('buffer');\nvar Scalar = require('../../nodes/Scalar.js');\nvar stringifyString = require('../../stringify/stringifyString.js');\n\nconst binary = {\n    identify: value => value instanceof Uint8Array, // Buffer inherits from Uint8Array\n    default: false,\n    tag: 'tag:yaml.org,2002:binary',\n    /**\n     * Returns a Buffer in node and an Uint8Array in browsers\n     *\n     * To use the resulting buffer as an image, you'll want to do something like:\n     *\n     *   const blob = new Blob([buffer], { type: 'image/jpeg' })\n     *   document.querySelector('#photo').src = URL.createObjectURL(blob)\n     */\n    resolve(src, onError) {\n        if (typeof node_buffer.Buffer === 'function') {\n            return node_buffer.Buffer.from(src, 'base64');\n        }\n        else if (typeof atob === 'function') {\n            // On IE 11, atob() can't handle newlines\n            const str = atob(src.replace(/[\\n\\r]/g, ''));\n            const buffer = new Uint8Array(str.length);\n            for (let i = 0; i < str.length; ++i)\n                buffer[i] = str.charCodeAt(i);\n            return buffer;\n        }\n        else {\n            onError('This environment does not support reading binary tags; either Buffer or atob is required');\n            return src;\n        }\n    },\n    stringify({ comment, type, value }, ctx, onComment, onChompKeep) {\n        if (!value)\n            return '';\n        const buf = value; // checked earlier by binary.identify()\n        let str;\n        if (typeof node_buffer.Buffer === 'function') {\n            str =\n                buf instanceof node_buffer.Buffer\n                    ? buf.toString('base64')\n                    : node_buffer.Buffer.from(buf.buffer).toString('base64');\n        }\n        else if (typeof btoa === 'function') {\n            let s = '';\n            for (let i = 0; i < buf.length; ++i)\n                s += String.fromCharCode(buf[i]);\n            str = btoa(s);\n        }\n        else {\n            throw new Error('This environment does not support writing binary tags; either Buffer or btoa is required');\n        }\n        type ?? (type = Scalar.Scalar.BLOCK_LITERAL);\n        if (type !== Scalar.Scalar.QUOTE_DOUBLE) {\n            const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth);\n            const n = Math.ceil(str.length / lineWidth);\n            const lines = new Array(n);\n            for (let i = 0, o = 0; i < n; ++i, o += lineWidth) {\n                lines[i] = str.substr(o, lineWidth);\n            }\n            str = lines.join(type === Scalar.Scalar.BLOCK_LITERAL ? '\\n' : ' ');\n        }\n        return stringifyString.stringifyString({ comment, type, value: str }, ctx, onComment, onChompKeep);\n    }\n};\n\nexports.binary = binary;\n","'use strict';\n\nvar identity = require('../../nodes/identity.js');\nvar Pair = require('../../nodes/Pair.js');\nvar Scalar = require('../../nodes/Scalar.js');\nvar YAMLSeq = require('../../nodes/YAMLSeq.js');\n\nfunction resolvePairs(seq, onError) {\n    if (identity.isSeq(seq)) {\n        for (let i = 0; i < seq.items.length; ++i) {\n            let item = seq.items[i];\n            if (identity.isPair(item))\n                continue;\n            else if (identity.isMap(item)) {\n                if (item.items.length > 1)\n                    onError('Each pair must have its own sequence indicator');\n                const pair = item.items[0] || new Pair.Pair(new Scalar.Scalar(null));\n                if (item.commentBefore)\n                    pair.key.commentBefore = pair.key.commentBefore\n                        ? `${item.commentBefore}\\n${pair.key.commentBefore}`\n                        : item.commentBefore;\n                if (item.comment) {\n                    const cn = pair.value ?? pair.key;\n                    cn.comment = cn.comment\n                        ? `${item.comment}\\n${cn.comment}`\n                        : item.comment;\n                }\n                item = pair;\n            }\n            seq.items[i] = identity.isPair(item) ? item : new Pair.Pair(item);\n        }\n    }\n    else\n        onError('Expected a sequence for this tag');\n    return seq;\n}\nfunction createPairs(schema, iterable, ctx) {\n    const { replacer } = ctx;\n    const pairs = new YAMLSeq.YAMLSeq(schema);\n    pairs.tag = 'tag:yaml.org,2002:pairs';\n    let i = 0;\n    if (iterable && Symbol.iterator in Object(iterable))\n        for (let it of iterable) {\n            if (typeof replacer === 'function')\n                it = replacer.call(iterable, String(i++), it);\n            let key, value;\n            if (Array.isArray(it)) {\n                if (it.length === 2) {\n                    key = it[0];\n                    value = it[1];\n                }\n                else\n                    throw new TypeError(`Expected [key, value] tuple: ${it}`);\n            }\n            else if (it && it instanceof Object) {\n                const keys = Object.keys(it);\n                if (keys.length === 1) {\n                    key = keys[0];\n                    value = it[key];\n                }\n                else {\n                    throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`);\n                }\n            }\n            else {\n                key = it;\n            }\n            pairs.items.push(Pair.createPair(key, value, ctx));\n        }\n    return pairs;\n}\nconst pairs = {\n    collection: 'seq',\n    default: false,\n    tag: 'tag:yaml.org,2002:pairs',\n    resolve: resolvePairs,\n    createNode: createPairs\n};\n\nexports.createPairs = createPairs;\nexports.pairs = pairs;\nexports.resolvePairs = resolvePairs;\n","'use strict';\n\nvar identity = require('../../nodes/identity.js');\nvar toJS = require('../../nodes/toJS.js');\nvar YAMLMap = require('../../nodes/YAMLMap.js');\nvar YAMLSeq = require('../../nodes/YAMLSeq.js');\nvar pairs = require('./pairs.js');\n\nclass YAMLOMap extends YAMLSeq.YAMLSeq {\n    constructor() {\n        super();\n        this.add = YAMLMap.YAMLMap.prototype.add.bind(this);\n        this.delete = YAMLMap.YAMLMap.prototype.delete.bind(this);\n        this.get = YAMLMap.YAMLMap.prototype.get.bind(this);\n        this.has = YAMLMap.YAMLMap.prototype.has.bind(this);\n        this.set = YAMLMap.YAMLMap.prototype.set.bind(this);\n        this.tag = YAMLOMap.tag;\n    }\n    /**\n     * If `ctx` is given, the return type is actually `Map<unknown, unknown>`,\n     * but TypeScript won't allow widening the signature of a child method.\n     */\n    toJSON(_, ctx) {\n        if (!ctx)\n            return super.toJSON(_);\n        const map = new Map();\n        if (ctx?.onCreate)\n            ctx.onCreate(map);\n        for (const pair of this.items) {\n            let key, value;\n            if (identity.isPair(pair)) {\n                key = toJS.toJS(pair.key, '', ctx);\n                value = toJS.toJS(pair.value, key, ctx);\n            }\n            else {\n                key = toJS.toJS(pair, '', ctx);\n            }\n            if (map.has(key))\n                throw new Error('Ordered maps must not include duplicate keys');\n            map.set(key, value);\n        }\n        return map;\n    }\n    static from(schema, iterable, ctx) {\n        const pairs$1 = pairs.createPairs(schema, iterable, ctx);\n        const omap = new this();\n        omap.items = pairs$1.items;\n        return omap;\n    }\n}\nYAMLOMap.tag = 'tag:yaml.org,2002:omap';\nconst omap = {\n    collection: 'seq',\n    identify: value => value instanceof Map,\n    nodeClass: YAMLOMap,\n    default: false,\n    tag: 'tag:yaml.org,2002:omap',\n    resolve(seq, onError) {\n        const pairs$1 = pairs.resolvePairs(seq, onError);\n        const seenKeys = [];\n        for (const { key } of pairs$1.items) {\n            if (identity.isScalar(key)) {\n                if (seenKeys.includes(key.value)) {\n                    onError(`Ordered maps must not include duplicate keys: ${key.value}`);\n                }\n                else {\n                    seenKeys.push(key.value);\n                }\n            }\n        }\n        return Object.assign(new YAMLOMap(), pairs$1);\n    },\n    createNode: (schema, iterable, ctx) => YAMLOMap.from(schema, iterable, ctx)\n};\n\nexports.YAMLOMap = YAMLOMap;\nexports.omap = omap;\n","'use strict';\n\nvar Scalar = require('../../nodes/Scalar.js');\n\nfunction boolStringify({ value, source }, ctx) {\n    const boolObj = value ? trueTag : falseTag;\n    if (source && boolObj.test.test(source))\n        return source;\n    return value ? ctx.options.trueStr : ctx.options.falseStr;\n}\nconst trueTag = {\n    identify: value => value === true,\n    default: true,\n    tag: 'tag:yaml.org,2002:bool',\n    test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,\n    resolve: () => new Scalar.Scalar(true),\n    stringify: boolStringify\n};\nconst falseTag = {\n    identify: value => value === false,\n    default: true,\n    tag: 'tag:yaml.org,2002:bool',\n    test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,\n    resolve: () => new Scalar.Scalar(false),\n    stringify: boolStringify\n};\n\nexports.falseTag = falseTag;\nexports.trueTag = trueTag;\n","'use strict';\n\nvar Scalar = require('../../nodes/Scalar.js');\nvar stringifyNumber = require('../../stringify/stringifyNumber.js');\n\nconst floatNaN = {\n    identify: value => typeof value === 'number',\n    default: true,\n    tag: 'tag:yaml.org,2002:float',\n    test: /^(?:[-+]?\\.(?:inf|Inf|INF)|\\.nan|\\.NaN|\\.NAN)$/,\n    resolve: (str) => str.slice(-3).toLowerCase() === 'nan'\n        ? NaN\n        : str[0] === '-'\n            ? Number.NEGATIVE_INFINITY\n            : Number.POSITIVE_INFINITY,\n    stringify: stringifyNumber.stringifyNumber\n};\nconst floatExp = {\n    identify: value => typeof value === 'number',\n    default: true,\n    tag: 'tag:yaml.org,2002:float',\n    format: 'EXP',\n    test: /^[-+]?(?:[0-9][0-9_]*)?(?:\\.[0-9_]*)?[eE][-+]?[0-9]+$/,\n    resolve: (str) => parseFloat(str.replace(/_/g, '')),\n    stringify(node) {\n        const num = Number(node.value);\n        return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node);\n    }\n};\nconst float = {\n    identify: value => typeof value === 'number',\n    default: true,\n    tag: 'tag:yaml.org,2002:float',\n    test: /^[-+]?(?:[0-9][0-9_]*)?\\.[0-9_]*$/,\n    resolve(str) {\n        const node = new Scalar.Scalar(parseFloat(str.replace(/_/g, '')));\n        const dot = str.indexOf('.');\n        if (dot !== -1) {\n            const f = str.substring(dot + 1).replace(/_/g, '');\n            if (f[f.length - 1] === '0')\n                node.minFractionDigits = f.length;\n        }\n        return node;\n    },\n    stringify: stringifyNumber.stringifyNumber\n};\n\nexports.float = float;\nexports.floatExp = floatExp;\nexports.floatNaN = floatNaN;\n","'use strict';\n\nvar stringifyNumber = require('../../stringify/stringifyNumber.js');\n\nconst intIdentify = (value) => typeof value === 'bigint' || Number.isInteger(value);\nfunction intResolve(str, offset, radix, { intAsBigInt }) {\n    const sign = str[0];\n    if (sign === '-' || sign === '+')\n        offset += 1;\n    str = str.substring(offset).replace(/_/g, '');\n    if (intAsBigInt) {\n        switch (radix) {\n            case 2:\n                str = `0b${str}`;\n                break;\n            case 8:\n                str = `0o${str}`;\n                break;\n            case 16:\n                str = `0x${str}`;\n                break;\n        }\n        const n = BigInt(str);\n        return sign === '-' ? BigInt(-1) * n : n;\n    }\n    const n = parseInt(str, radix);\n    return sign === '-' ? -1 * n : n;\n}\nfunction intStringify(node, radix, prefix) {\n    const { value } = node;\n    if (intIdentify(value)) {\n        const str = value.toString(radix);\n        return value < 0 ? '-' + prefix + str.substr(1) : prefix + str;\n    }\n    return stringifyNumber.stringifyNumber(node);\n}\nconst intBin = {\n    identify: intIdentify,\n    default: true,\n    tag: 'tag:yaml.org,2002:int',\n    format: 'BIN',\n    test: /^[-+]?0b[0-1_]+$/,\n    resolve: (str, _onError, opt) => intResolve(str, 2, 2, opt),\n    stringify: node => intStringify(node, 2, '0b')\n};\nconst intOct = {\n    identify: intIdentify,\n    default: true,\n    tag: 'tag:yaml.org,2002:int',\n    format: 'OCT',\n    test: /^[-+]?0[0-7_]+$/,\n    resolve: (str, _onError, opt) => intResolve(str, 1, 8, opt),\n    stringify: node => intStringify(node, 8, '0')\n};\nconst int = {\n    identify: intIdentify,\n    default: true,\n    tag: 'tag:yaml.org,2002:int',\n    test: /^[-+]?[0-9][0-9_]*$/,\n    resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),\n    stringify: stringifyNumber.stringifyNumber\n};\nconst intHex = {\n    identify: intIdentify,\n    default: true,\n    tag: 'tag:yaml.org,2002:int',\n    format: 'HEX',\n    test: /^[-+]?0x[0-9a-fA-F_]+$/,\n    resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),\n    stringify: node => intStringify(node, 16, '0x')\n};\n\nexports.int = int;\nexports.intBin = intBin;\nexports.intHex = intHex;\nexports.intOct = intOct;\n","'use strict';\n\nvar identity = require('../../nodes/identity.js');\nvar Pair = require('../../nodes/Pair.js');\nvar YAMLMap = require('../../nodes/YAMLMap.js');\n\nclass YAMLSet extends YAMLMap.YAMLMap {\n    constructor(schema) {\n        super(schema);\n        this.tag = YAMLSet.tag;\n    }\n    add(key) {\n        let pair;\n        if (identity.isPair(key))\n            pair = key;\n        else if (key &&\n            typeof key === 'object' &&\n            'key' in key &&\n            'value' in key &&\n            key.value === null)\n            pair = new Pair.Pair(key.key, null);\n        else\n            pair = new Pair.Pair(key, null);\n        const prev = YAMLMap.findPair(this.items, pair.key);\n        if (!prev)\n            this.items.push(pair);\n    }\n    /**\n     * If `keepPair` is `true`, returns the Pair matching `key`.\n     * Otherwise, returns the value of that Pair's key.\n     */\n    get(key, keepPair) {\n        const pair = YAMLMap.findPair(this.items, key);\n        return !keepPair && identity.isPair(pair)\n            ? identity.isScalar(pair.key)\n                ? pair.key.value\n                : pair.key\n            : pair;\n    }\n    set(key, value) {\n        if (typeof value !== 'boolean')\n            throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`);\n        const prev = YAMLMap.findPair(this.items, key);\n        if (prev && !value) {\n            this.items.splice(this.items.indexOf(prev), 1);\n        }\n        else if (!prev && value) {\n            this.items.push(new Pair.Pair(key));\n        }\n    }\n    toJSON(_, ctx) {\n        return super.toJSON(_, ctx, Set);\n    }\n    toString(ctx, onComment, onChompKeep) {\n        if (!ctx)\n            return JSON.stringify(this);\n        if (this.hasAllNullValues(true))\n            return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep);\n        else\n            throw new Error('Set items must all have null values');\n    }\n    static from(schema, iterable, ctx) {\n        const { replacer } = ctx;\n        const set = new this(schema);\n        if (iterable && Symbol.iterator in Object(iterable))\n            for (let value of iterable) {\n                if (typeof replacer === 'function')\n                    value = replacer.call(iterable, value, value);\n                set.items.push(Pair.createPair(value, null, ctx));\n            }\n        return set;\n    }\n}\nYAMLSet.tag = 'tag:yaml.org,2002:set';\nconst set = {\n    collection: 'map',\n    identify: value => value instanceof Set,\n    nodeClass: YAMLSet,\n    default: false,\n    tag: 'tag:yaml.org,2002:set',\n    createNode: (schema, iterable, ctx) => YAMLSet.from(schema, iterable, ctx),\n    resolve(map, onError) {\n        if (identity.isMap(map)) {\n            if (map.hasAllNullValues(true))\n                return Object.assign(new YAMLSet(), map);\n            else\n                onError('Set items must all have null values');\n        }\n        else\n            onError('Expected a mapping for this tag');\n        return map;\n    }\n};\n\nexports.YAMLSet = YAMLSet;\nexports.set = set;\n","'use strict';\n\nvar stringifyNumber = require('../../stringify/stringifyNumber.js');\n\n/** Internal types handle bigint as number, because TS can't figure it out. */\nfunction parseSexagesimal(str, asBigInt) {\n    const sign = str[0];\n    const parts = sign === '-' || sign === '+' ? str.substring(1) : str;\n    const num = (n) => asBigInt ? BigInt(n) : Number(n);\n    const res = parts\n        .replace(/_/g, '')\n        .split(':')\n        .reduce((res, p) => res * num(60) + num(p), num(0));\n    return (sign === '-' ? num(-1) * res : res);\n}\n/**\n * hhhh:mm:ss.sss\n *\n * Internal types handle bigint as number, because TS can't figure it out.\n */\nfunction stringifySexagesimal(node) {\n    let { value } = node;\n    let num = (n) => n;\n    if (typeof value === 'bigint')\n        num = n => BigInt(n);\n    else if (isNaN(value) || !isFinite(value))\n        return stringifyNumber.stringifyNumber(node);\n    let sign = '';\n    if (value < 0) {\n        sign = '-';\n        value *= num(-1);\n    }\n    const _60 = num(60);\n    const parts = [value % _60]; // seconds, including ms\n    if (value < 60) {\n        parts.unshift(0); // at least one : is required\n    }\n    else {\n        value = (value - parts[0]) / _60;\n        parts.unshift(value % _60); // minutes\n        if (value >= 60) {\n            value = (value - parts[0]) / _60;\n            parts.unshift(value); // hours\n        }\n    }\n    return (sign +\n        parts\n            .map(n => String(n).padStart(2, '0'))\n            .join(':')\n            .replace(/000000\\d*$/, '') // % 60 may introduce error\n    );\n}\nconst intTime = {\n    identify: value => typeof value === 'bigint' || Number.isInteger(value),\n    default: true,\n    tag: 'tag:yaml.org,2002:int',\n    format: 'TIME',\n    test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,\n    resolve: (str, _onError, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt),\n    stringify: stringifySexagesimal\n};\nconst floatTime = {\n    identify: value => typeof value === 'number',\n    default: true,\n    tag: 'tag:yaml.org,2002:float',\n    format: 'TIME',\n    test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*$/,\n    resolve: str => parseSexagesimal(str, false),\n    stringify: stringifySexagesimal\n};\nconst timestamp = {\n    identify: value => value instanceof Date,\n    default: true,\n    tag: 'tag:yaml.org,2002:timestamp',\n    // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part\n    // may be omitted altogether, resulting in a date format. In such a case, the time part is\n    // assumed to be 00:00:00Z (start of day, UTC).\n    test: RegExp('^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})' + // YYYY-Mm-Dd\n        '(?:' + // time is optional\n        '(?:t|T|[ \\\\t]+)' + // t | T | whitespace\n        '([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\\\.[0-9]+)?)' + // Hh:Mm:Ss(.ss)?\n        '(?:[ \\\\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?' + // Z | +5 | -03:30\n        ')?$'),\n    resolve(str) {\n        const match = str.match(timestamp.test);\n        if (!match)\n            throw new Error('!!timestamp expects a date, starting with yyyy-mm-dd');\n        const [, year, month, day, hour, minute, second] = match.map(Number);\n        const millisec = match[7] ? Number((match[7] + '00').substr(1, 3)) : 0;\n        let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec);\n        const tz = match[8];\n        if (tz && tz !== 'Z') {\n            let d = parseSexagesimal(tz, false);\n            if (Math.abs(d) < 30)\n                d *= 60;\n            date -= 60000 * d;\n        }\n        return new Date(date);\n    },\n    stringify: ({ value }) => value?.toISOString().replace(/(T00:00:00)?\\.000Z$/, '') ?? ''\n};\n\nexports.floatTime = floatTime;\nexports.intTime = intTime;\nexports.timestamp = timestamp;\n","'use strict';\n\nvar map = require('../common/map.js');\nvar _null = require('../common/null.js');\nvar seq = require('../common/seq.js');\nvar string = require('../common/string.js');\nvar binary = require('./binary.js');\nvar bool = require('./bool.js');\nvar float = require('./float.js');\nvar int = require('./int.js');\nvar merge = require('./merge.js');\nvar omap = require('./omap.js');\nvar pairs = require('./pairs.js');\nvar set = require('./set.js');\nvar timestamp = require('./timestamp.js');\n\nconst schema = [\n    map.map,\n    seq.seq,\n    string.string,\n    _null.nullTag,\n    bool.trueTag,\n    bool.falseTag,\n    int.intBin,\n    int.intOct,\n    int.int,\n    int.intHex,\n    float.floatNaN,\n    float.floatExp,\n    float.float,\n    binary.binary,\n    merge.merge,\n    omap.omap,\n    pairs.pairs,\n    set.set,\n    timestamp.intTime,\n    timestamp.floatTime,\n    timestamp.timestamp\n];\n\nexports.schema = schema;\n","'use strict';\n\nvar map = require('./common/map.js');\nvar _null = require('./common/null.js');\nvar seq = require('./common/seq.js');\nvar string = require('./common/string.js');\nvar bool = require('./core/bool.js');\nvar float = require('./core/float.js');\nvar int = require('./core/int.js');\nvar schema = require('./core/schema.js');\nvar schema$1 = require('./json/schema.js');\nvar binary = require('./yaml-1.1/binary.js');\nvar merge = require('./yaml-1.1/merge.js');\nvar omap = require('./yaml-1.1/omap.js');\nvar pairs = require('./yaml-1.1/pairs.js');\nvar schema$2 = require('./yaml-1.1/schema.js');\nvar set = require('./yaml-1.1/set.js');\nvar timestamp = require('./yaml-1.1/timestamp.js');\n\nconst schemas = new Map([\n    ['core', schema.schema],\n    ['failsafe', [map.map, seq.seq, string.string]],\n    ['json', schema$1.schema],\n    ['yaml11', schema$2.schema],\n    ['yaml-1.1', schema$2.schema]\n]);\nconst tagsByName = {\n    binary: binary.binary,\n    bool: bool.boolTag,\n    float: float.float,\n    floatExp: float.floatExp,\n    floatNaN: float.floatNaN,\n    floatTime: timestamp.floatTime,\n    int: int.int,\n    intHex: int.intHex,\n    intOct: int.intOct,\n    intTime: timestamp.intTime,\n    map: map.map,\n    merge: merge.merge,\n    null: _null.nullTag,\n    omap: omap.omap,\n    pairs: pairs.pairs,\n    seq: seq.seq,\n    set: set.set,\n    timestamp: timestamp.timestamp\n};\nconst coreKnownTags = {\n    'tag:yaml.org,2002:binary': binary.binary,\n    'tag:yaml.org,2002:merge': merge.merge,\n    'tag:yaml.org,2002:omap': omap.omap,\n    'tag:yaml.org,2002:pairs': pairs.pairs,\n    'tag:yaml.org,2002:set': set.set,\n    'tag:yaml.org,2002:timestamp': timestamp.timestamp\n};\nfunction getTags(customTags, schemaName, addMergeTag) {\n    const schemaTags = schemas.get(schemaName);\n    if (schemaTags && !customTags) {\n        return addMergeTag && !schemaTags.includes(merge.merge)\n            ? schemaTags.concat(merge.merge)\n            : schemaTags.slice();\n    }\n    let tags = schemaTags;\n    if (!tags) {\n        if (Array.isArray(customTags))\n            tags = [];\n        else {\n            const keys = Array.from(schemas.keys())\n                .filter(key => key !== 'yaml11')\n                .map(key => JSON.stringify(key))\n                .join(', ');\n            throw new Error(`Unknown schema \"${schemaName}\"; use one of ${keys} or define customTags array`);\n        }\n    }\n    if (Array.isArray(customTags)) {\n        for (const tag of customTags)\n            tags = tags.concat(tag);\n    }\n    else if (typeof customTags === 'function') {\n        tags = customTags(tags.slice());\n    }\n    if (addMergeTag)\n        tags = tags.concat(merge.merge);\n    return tags.reduce((tags, tag) => {\n        const tagObj = typeof tag === 'string' ? tagsByName[tag] : tag;\n        if (!tagObj) {\n            const tagName = JSON.stringify(tag);\n            const keys = Object.keys(tagsByName)\n                .map(key => JSON.stringify(key))\n                .join(', ');\n            throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`);\n        }\n        if (!tags.includes(tagObj))\n            tags.push(tagObj);\n        return tags;\n    }, []);\n}\n\nexports.coreKnownTags = coreKnownTags;\nexports.getTags = getTags;\n","'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar map = require('./common/map.js');\nvar seq = require('./common/seq.js');\nvar string = require('./common/string.js');\nvar tags = require('./tags.js');\n\nconst sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0;\nclass Schema {\n    constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }) {\n        this.compat = Array.isArray(compat)\n            ? tags.getTags(compat, 'compat')\n            : compat\n                ? tags.getTags(null, compat)\n                : null;\n        this.name = (typeof schema === 'string' && schema) || 'core';\n        this.knownTags = resolveKnownTags ? tags.coreKnownTags : {};\n        this.tags = tags.getTags(customTags, this.name, merge);\n        this.toStringOptions = toStringDefaults ?? null;\n        Object.defineProperty(this, identity.MAP, { value: map.map });\n        Object.defineProperty(this, identity.SCALAR, { value: string.string });\n        Object.defineProperty(this, identity.SEQ, { value: seq.seq });\n        // Used by createMap()\n        this.sortMapEntries =\n            typeof sortMapEntries === 'function'\n                ? sortMapEntries\n                : sortMapEntries === true\n                    ? sortMapEntriesByKey\n                    : null;\n    }\n    clone() {\n        const copy = Object.create(Schema.prototype, Object.getOwnPropertyDescriptors(this));\n        copy.tags = this.tags.slice();\n        return copy;\n    }\n}\n\nexports.Schema = Schema;\n","'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar stringify = require('./stringify.js');\nvar stringifyComment = require('./stringifyComment.js');\n\nfunction stringifyDocument(doc, options) {\n    const lines = [];\n    let hasDirectives = options.directives === true;\n    if (options.directives !== false && doc.directives) {\n        const dir = doc.directives.toString(doc);\n        if (dir) {\n            lines.push(dir);\n            hasDirectives = true;\n        }\n        else if (doc.directives.docStart)\n            hasDirectives = true;\n    }\n    if (hasDirectives)\n        lines.push('---');\n    const ctx = stringify.createStringifyContext(doc, options);\n    const { commentString } = ctx.options;\n    if (doc.commentBefore) {\n        if (lines.length !== 1)\n            lines.unshift('');\n        const cs = commentString(doc.commentBefore);\n        lines.unshift(stringifyComment.indentComment(cs, ''));\n    }\n    let chompKeep = false;\n    let contentComment = null;\n    if (doc.contents) {\n        if (identity.isNode(doc.contents)) {\n            if (doc.contents.spaceBefore && hasDirectives)\n                lines.push('');\n            if (doc.contents.commentBefore) {\n                const cs = commentString(doc.contents.commentBefore);\n                lines.push(stringifyComment.indentComment(cs, ''));\n            }\n            // top-level block scalars need to be indented if followed by a comment\n            ctx.forceBlockIndent = !!doc.comment;\n            contentComment = doc.contents.comment;\n        }\n        const onChompKeep = contentComment ? undefined : () => (chompKeep = true);\n        let body = stringify.stringify(doc.contents, ctx, () => (contentComment = null), onChompKeep);\n        if (contentComment)\n            body += stringifyComment.lineComment(body, '', commentString(contentComment));\n        if ((body[0] === '|' || body[0] === '>') &&\n            lines[lines.length - 1] === '---') {\n            // Top-level block scalars with a preceding doc marker ought to use the\n            // same line for their header.\n            lines[lines.length - 1] = `--- ${body}`;\n        }\n        else\n            lines.push(body);\n    }\n    else {\n        lines.push(stringify.stringify(doc.contents, ctx));\n    }\n    if (doc.directives?.docEnd) {\n        if (doc.comment) {\n            const cs = commentString(doc.comment);\n            if (cs.includes('\\n')) {\n                lines.push('...');\n                lines.push(stringifyComment.indentComment(cs, ''));\n            }\n            else {\n                lines.push(`... ${cs}`);\n            }\n        }\n        else {\n            lines.push('...');\n        }\n    }\n    else {\n        let dc = doc.comment;\n        if (dc && chompKeep)\n            dc = dc.replace(/^\\n+/, '');\n        if (dc) {\n            if ((!chompKeep || contentComment) && lines[lines.length - 1] !== '')\n                lines.push('');\n            lines.push(stringifyComment.indentComment(commentString(dc), ''));\n        }\n    }\n    return lines.join('\\n') + '\\n';\n}\n\nexports.stringifyDocument = stringifyDocument;\n","'use strict';\n\nvar Alias = require('../nodes/Alias.js');\nvar Collection = require('../nodes/Collection.js');\nvar identity = require('../nodes/identity.js');\nvar Pair = require('../nodes/Pair.js');\nvar toJS = require('../nodes/toJS.js');\nvar Schema = require('../schema/Schema.js');\nvar stringifyDocument = require('../stringify/stringifyDocument.js');\nvar anchors = require('./anchors.js');\nvar applyReviver = require('./applyReviver.js');\nvar createNode = require('./createNode.js');\nvar directives = require('./directives.js');\n\nclass Document {\n    constructor(value, replacer, options) {\n        /** A comment before this Document */\n        this.commentBefore = null;\n        /** A comment immediately after this Document */\n        this.comment = null;\n        /** Errors encountered during parsing. */\n        this.errors = [];\n        /** Warnings encountered during parsing. */\n        this.warnings = [];\n        Object.defineProperty(this, identity.NODE_TYPE, { value: identity.DOC });\n        let _replacer = null;\n        if (typeof replacer === 'function' || Array.isArray(replacer)) {\n            _replacer = replacer;\n        }\n        else if (options === undefined && replacer) {\n            options = replacer;\n            replacer = undefined;\n        }\n        const opt = Object.assign({\n            intAsBigInt: false,\n            keepSourceTokens: false,\n            logLevel: 'warn',\n            prettyErrors: true,\n            strict: true,\n            stringKeys: false,\n            uniqueKeys: true,\n            version: '1.2'\n        }, options);\n        this.options = opt;\n        let { version } = opt;\n        if (options?._directives) {\n            this.directives = options._directives.atDocument();\n            if (this.directives.yaml.explicit)\n                version = this.directives.yaml.version;\n        }\n        else\n            this.directives = new directives.Directives({ version });\n        this.setSchema(version, options);\n        // @ts-expect-error We can't really know that this matches Contents.\n        this.contents =\n            value === undefined ? null : this.createNode(value, _replacer, options);\n    }\n    /**\n     * Create a deep copy of this Document and its contents.\n     *\n     * Custom Node values that inherit from `Object` still refer to their original instances.\n     */\n    clone() {\n        const copy = Object.create(Document.prototype, {\n            [identity.NODE_TYPE]: { value: identity.DOC }\n        });\n        copy.commentBefore = this.commentBefore;\n        copy.comment = this.comment;\n        copy.errors = this.errors.slice();\n        copy.warnings = this.warnings.slice();\n        copy.options = Object.assign({}, this.options);\n        if (this.directives)\n            copy.directives = this.directives.clone();\n        copy.schema = this.schema.clone();\n        // @ts-expect-error We can't really know that this matches Contents.\n        copy.contents = identity.isNode(this.contents)\n            ? this.contents.clone(copy.schema)\n            : this.contents;\n        if (this.range)\n            copy.range = this.range.slice();\n        return copy;\n    }\n    /** Adds a value to the document. */\n    add(value) {\n        if (assertCollection(this.contents))\n            this.contents.add(value);\n    }\n    /** Adds a value to the document. */\n    addIn(path, value) {\n        if (assertCollection(this.contents))\n            this.contents.addIn(path, value);\n    }\n    /**\n     * Create a new `Alias` node, ensuring that the target `node` has the required anchor.\n     *\n     * If `node` already has an anchor, `name` is ignored.\n     * Otherwise, the `node.anchor` value will be set to `name`,\n     * or if an anchor with that name is already present in the document,\n     * `name` will be used as a prefix for a new unique anchor.\n     * If `name` is undefined, the generated anchor will use 'a' as a prefix.\n     */\n    createAlias(node, name) {\n        if (!node.anchor) {\n            const prev = anchors.anchorNames(this);\n            node.anchor =\n                // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n                !name || prev.has(name) ? anchors.findNewAnchor(name || 'a', prev) : name;\n        }\n        return new Alias.Alias(node.anchor);\n    }\n    createNode(value, replacer, options) {\n        let _replacer = undefined;\n        if (typeof replacer === 'function') {\n            value = replacer.call({ '': value }, '', value);\n            _replacer = replacer;\n        }\n        else if (Array.isArray(replacer)) {\n            const keyToStr = (v) => typeof v === 'number' || v instanceof String || v instanceof Number;\n            const asStr = replacer.filter(keyToStr).map(String);\n            if (asStr.length > 0)\n                replacer = replacer.concat(asStr);\n            _replacer = replacer;\n        }\n        else if (options === undefined && replacer) {\n            options = replacer;\n            replacer = undefined;\n        }\n        const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {};\n        const { onAnchor, setAnchors, sourceObjects } = anchors.createNodeAnchors(this, \n        // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n        anchorPrefix || 'a');\n        const ctx = {\n            aliasDuplicateObjects: aliasDuplicateObjects ?? true,\n            keepUndefined: keepUndefined ?? false,\n            onAnchor,\n            onTagObj,\n            replacer: _replacer,\n            schema: this.schema,\n            sourceObjects\n        };\n        const node = createNode.createNode(value, tag, ctx);\n        if (flow && identity.isCollection(node))\n            node.flow = true;\n        setAnchors();\n        return node;\n    }\n    /**\n     * Convert a key and a value into a `Pair` using the current schema,\n     * recursively wrapping all values as `Scalar` or `Collection` nodes.\n     */\n    createPair(key, value, options = {}) {\n        const k = this.createNode(key, null, options);\n        const v = this.createNode(value, null, options);\n        return new Pair.Pair(k, v);\n    }\n    /**\n     * Removes a value from the document.\n     * @returns `true` if the item was found and removed.\n     */\n    delete(key) {\n        return assertCollection(this.contents) ? this.contents.delete(key) : false;\n    }\n    /**\n     * Removes a value from the document.\n     * @returns `true` if the item was found and removed.\n     */\n    deleteIn(path) {\n        if (Collection.isEmptyPath(path)) {\n            if (this.contents == null)\n                return false;\n            // @ts-expect-error Presumed impossible if Strict extends false\n            this.contents = null;\n            return true;\n        }\n        return assertCollection(this.contents)\n            ? this.contents.deleteIn(path)\n            : false;\n    }\n    /**\n     * Returns item at `key`, or `undefined` if not found. By default unwraps\n     * scalar values from their surrounding node; to disable set `keepScalar` to\n     * `true` (collections are always returned intact).\n     */\n    get(key, keepScalar) {\n        return identity.isCollection(this.contents)\n            ? this.contents.get(key, keepScalar)\n            : undefined;\n    }\n    /**\n     * Returns item at `path`, or `undefined` if not found. By default unwraps\n     * scalar values from their surrounding node; to disable set `keepScalar` to\n     * `true` (collections are always returned intact).\n     */\n    getIn(path, keepScalar) {\n        if (Collection.isEmptyPath(path))\n            return !keepScalar && identity.isScalar(this.contents)\n                ? this.contents.value\n                : this.contents;\n        return identity.isCollection(this.contents)\n            ? this.contents.getIn(path, keepScalar)\n            : undefined;\n    }\n    /**\n     * Checks if the document includes a value with the key `key`.\n     */\n    has(key) {\n        return identity.isCollection(this.contents) ? this.contents.has(key) : false;\n    }\n    /**\n     * Checks if the document includes a value at `path`.\n     */\n    hasIn(path) {\n        if (Collection.isEmptyPath(path))\n            return this.contents !== undefined;\n        return identity.isCollection(this.contents) ? this.contents.hasIn(path) : false;\n    }\n    /**\n     * Sets a value in this document. For `!!set`, `value` needs to be a\n     * boolean to add/remove the item from the set.\n     */\n    set(key, value) {\n        if (this.contents == null) {\n            // @ts-expect-error We can't really know that this matches Contents.\n            this.contents = Collection.collectionFromPath(this.schema, [key], value);\n        }\n        else if (assertCollection(this.contents)) {\n            this.contents.set(key, value);\n        }\n    }\n    /**\n     * Sets a value in this document. For `!!set`, `value` needs to be a\n     * boolean to add/remove the item from the set.\n     */\n    setIn(path, value) {\n        if (Collection.isEmptyPath(path)) {\n            // @ts-expect-error We can't really know that this matches Contents.\n            this.contents = value;\n        }\n        else if (this.contents == null) {\n            // @ts-expect-error We can't really know that this matches Contents.\n            this.contents = Collection.collectionFromPath(this.schema, Array.from(path), value);\n        }\n        else if (assertCollection(this.contents)) {\n            this.contents.setIn(path, value);\n        }\n    }\n    /**\n     * Change the YAML version and schema used by the document.\n     * A `null` version disables support for directives, explicit tags, anchors, and aliases.\n     * It also requires the `schema` option to be given as a `Schema` instance value.\n     *\n     * Overrides all previously set schema options.\n     */\n    setSchema(version, options = {}) {\n        if (typeof version === 'number')\n            version = String(version);\n        let opt;\n        switch (version) {\n            case '1.1':\n                if (this.directives)\n                    this.directives.yaml.version = '1.1';\n                else\n                    this.directives = new directives.Directives({ version: '1.1' });\n                opt = { resolveKnownTags: false, schema: 'yaml-1.1' };\n                break;\n            case '1.2':\n            case 'next':\n                if (this.directives)\n                    this.directives.yaml.version = version;\n                else\n                    this.directives = new directives.Directives({ version });\n                opt = { resolveKnownTags: true, schema: 'core' };\n                break;\n            case null:\n                if (this.directives)\n                    delete this.directives;\n                opt = null;\n                break;\n            default: {\n                const sv = JSON.stringify(version);\n                throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`);\n            }\n        }\n        // Not using `instanceof Schema` to allow for duck typing\n        if (options.schema instanceof Object)\n            this.schema = options.schema;\n        else if (opt)\n            this.schema = new Schema.Schema(Object.assign(opt, options));\n        else\n            throw new Error(`With a null YAML version, the { schema: Schema } option is required`);\n    }\n    // json & jsonArg are only used from toJSON()\n    toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {\n        const ctx = {\n            anchors: new Map(),\n            doc: this,\n            keep: !json,\n            mapAsMap: mapAsMap === true,\n            mapKeyWarned: false,\n            maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100\n        };\n        const res = toJS.toJS(this.contents, jsonArg ?? '', ctx);\n        if (typeof onAnchor === 'function')\n            for (const { count, res } of ctx.anchors.values())\n                onAnchor(res, count);\n        return typeof reviver === 'function'\n            ? applyReviver.applyReviver(reviver, { '': res }, '', res)\n            : res;\n    }\n    /**\n     * A JSON representation of the document `contents`.\n     *\n     * @param jsonArg Used by `JSON.stringify` to indicate the array index or\n     *   property name.\n     */\n    toJSON(jsonArg, onAnchor) {\n        return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor });\n    }\n    /** A YAML representation of the document. */\n    toString(options = {}) {\n        if (this.errors.length > 0)\n            throw new Error('Document with errors cannot be stringified');\n        if ('indent' in options &&\n            (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) {\n            const s = JSON.stringify(options.indent);\n            throw new Error(`\"indent\" option must be a positive integer, not ${s}`);\n        }\n        return stringifyDocument.stringifyDocument(this, options);\n    }\n}\nfunction assertCollection(contents) {\n    if (identity.isCollection(contents))\n        return true;\n    throw new Error('Expected a YAML collection as document contents');\n}\n\nexports.Document = Document;\n","'use strict';\n\nclass YAMLError extends Error {\n    constructor(name, pos, code, message) {\n        super();\n        this.name = name;\n        this.code = code;\n        this.message = message;\n        this.pos = pos;\n    }\n}\nclass YAMLParseError extends YAMLError {\n    constructor(pos, code, message) {\n        super('YAMLParseError', pos, code, message);\n    }\n}\nclass YAMLWarning extends YAMLError {\n    constructor(pos, code, message) {\n        super('YAMLWarning', pos, code, message);\n    }\n}\nconst prettifyError = (src, lc) => (error) => {\n    if (error.pos[0] === -1)\n        return;\n    error.linePos = error.pos.map(pos => lc.linePos(pos));\n    const { line, col } = error.linePos[0];\n    error.message += ` at line ${line}, column ${col}`;\n    let ci = col - 1;\n    let lineStr = src\n        .substring(lc.lineStarts[line - 1], lc.lineStarts[line])\n        .replace(/[\\n\\r]+$/, '');\n    // Trim to max 80 chars, keeping col position near the middle\n    if (ci >= 60 && lineStr.length > 80) {\n        const trimStart = Math.min(ci - 39, lineStr.length - 79);\n        lineStr = '…' + lineStr.substring(trimStart);\n        ci -= trimStart - 1;\n    }\n    if (lineStr.length > 80)\n        lineStr = lineStr.substring(0, 79) + '…';\n    // Include previous line in context if pointing at line start\n    if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) {\n        // Regexp won't match if start is trimmed\n        let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]);\n        if (prev.length > 80)\n            prev = prev.substring(0, 79) + '…\\n';\n        lineStr = prev + lineStr;\n    }\n    if (/[^ ]/.test(lineStr)) {\n        let count = 1;\n        const end = error.linePos[1];\n        if (end?.line === line && end.col > col) {\n            count = Math.max(1, Math.min(end.col - col, 80 - ci));\n        }\n        const pointer = ' '.repeat(ci) + '^'.repeat(count);\n        error.message += `:\\n\\n${lineStr}\\n${pointer}\\n`;\n    }\n};\n\nexports.YAMLError = YAMLError;\nexports.YAMLParseError = YAMLParseError;\nexports.YAMLWarning = YAMLWarning;\nexports.prettifyError = prettifyError;\n","'use strict';\n\nfunction resolveProps(tokens, { flow, indicator, next, offset, onError, parentIndent, startOnNewline }) {\n    let spaceBefore = false;\n    let atNewline = startOnNewline;\n    let hasSpace = startOnNewline;\n    let comment = '';\n    let commentSep = '';\n    let hasNewline = false;\n    let reqSpace = false;\n    let tab = null;\n    let anchor = null;\n    let tag = null;\n    let newlineAfterProp = null;\n    let comma = null;\n    let found = null;\n    let start = null;\n    for (const token of tokens) {\n        if (reqSpace) {\n            if (token.type !== 'space' &&\n                token.type !== 'newline' &&\n                token.type !== 'comma')\n                onError(token.offset, 'MISSING_CHAR', 'Tags and anchors must be separated from the next token by white space');\n            reqSpace = false;\n        }\n        if (tab) {\n            if (atNewline && token.type !== 'comment' && token.type !== 'newline') {\n                onError(tab, 'TAB_AS_INDENT', 'Tabs are not allowed as indentation');\n            }\n            tab = null;\n        }\n        switch (token.type) {\n            case 'space':\n                // At the doc level, tabs at line start may be parsed\n                // as leading white space rather than indentation.\n                // In a flow collection, only the parser handles indent.\n                if (!flow &&\n                    (indicator !== 'doc-start' || next?.type !== 'flow-collection') &&\n                    token.source.includes('\\t')) {\n                    tab = token;\n                }\n                hasSpace = true;\n                break;\n            case 'comment': {\n                if (!hasSpace)\n                    onError(token, 'MISSING_CHAR', 'Comments must be separated from other tokens by white space characters');\n                const cb = token.source.substring(1) || ' ';\n                if (!comment)\n                    comment = cb;\n                else\n                    comment += commentSep + cb;\n                commentSep = '';\n                atNewline = false;\n                break;\n            }\n            case 'newline':\n                if (atNewline) {\n                    if (comment)\n                        comment += token.source;\n                    else if (!found || indicator !== 'seq-item-ind')\n                        spaceBefore = true;\n                }\n                else\n                    commentSep += token.source;\n                atNewline = true;\n                hasNewline = true;\n                if (anchor || tag)\n                    newlineAfterProp = token;\n                hasSpace = true;\n                break;\n            case 'anchor':\n                if (anchor)\n                    onError(token, 'MULTIPLE_ANCHORS', 'A node can have at most one anchor');\n                if (token.source.endsWith(':'))\n                    onError(token.offset + token.source.length - 1, 'BAD_ALIAS', 'Anchor ending in : is ambiguous', true);\n                anchor = token;\n                start ?? (start = token.offset);\n                atNewline = false;\n                hasSpace = false;\n                reqSpace = true;\n                break;\n            case 'tag': {\n                if (tag)\n                    onError(token, 'MULTIPLE_TAGS', 'A node can have at most one tag');\n                tag = token;\n                start ?? (start = token.offset);\n                atNewline = false;\n                hasSpace = false;\n                reqSpace = true;\n                break;\n            }\n            case indicator:\n                // Could here handle preceding comments differently\n                if (anchor || tag)\n                    onError(token, 'BAD_PROP_ORDER', `Anchors and tags must be after the ${token.source} indicator`);\n                if (found)\n                    onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${token.source} in ${flow ?? 'collection'}`);\n                found = token;\n                atNewline =\n                    indicator === 'seq-item-ind' || indicator === 'explicit-key-ind';\n                hasSpace = false;\n                break;\n            case 'comma':\n                if (flow) {\n                    if (comma)\n                        onError(token, 'UNEXPECTED_TOKEN', `Unexpected , in ${flow}`);\n                    comma = token;\n                    atNewline = false;\n                    hasSpace = false;\n                    break;\n                }\n            // else fallthrough\n            default:\n                onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${token.type} token`);\n                atNewline = false;\n                hasSpace = false;\n        }\n    }\n    const last = tokens[tokens.length - 1];\n    const end = last ? last.offset + last.source.length : offset;\n    if (reqSpace &&\n        next &&\n        next.type !== 'space' &&\n        next.type !== 'newline' &&\n        next.type !== 'comma' &&\n        (next.type !== 'scalar' || next.source !== '')) {\n        onError(next.offset, 'MISSING_CHAR', 'Tags and anchors must be separated from the next token by white space');\n    }\n    if (tab &&\n        ((atNewline && tab.indent <= parentIndent) ||\n            next?.type === 'block-map' ||\n            next?.type === 'block-seq'))\n        onError(tab, 'TAB_AS_INDENT', 'Tabs are not allowed as indentation');\n    return {\n        comma,\n        found,\n        spaceBefore,\n        comment,\n        hasNewline,\n        anchor,\n        tag,\n        newlineAfterProp,\n        end,\n        start: start ?? end\n    };\n}\n\nexports.resolveProps = resolveProps;\n","'use strict';\n\nfunction containsNewline(key) {\n    if (!key)\n        return null;\n    switch (key.type) {\n        case 'alias':\n        case 'scalar':\n        case 'double-quoted-scalar':\n        case 'single-quoted-scalar':\n            if (key.source.includes('\\n'))\n                return true;\n            if (key.end)\n                for (const st of key.end)\n                    if (st.type === 'newline')\n                        return true;\n            return false;\n        case 'flow-collection':\n            for (const it of key.items) {\n                for (const st of it.start)\n                    if (st.type === 'newline')\n                        return true;\n                if (it.sep)\n                    for (const st of it.sep)\n                        if (st.type === 'newline')\n                            return true;\n                if (containsNewline(it.key) || containsNewline(it.value))\n                    return true;\n            }\n            return false;\n        default:\n            return true;\n    }\n}\n\nexports.containsNewline = containsNewline;\n","'use strict';\n\nvar utilContainsNewline = require('./util-contains-newline.js');\n\nfunction flowIndentCheck(indent, fc, onError) {\n    if (fc?.type === 'flow-collection') {\n        const end = fc.end[0];\n        if (end.indent === indent &&\n            (end.source === ']' || end.source === '}') &&\n            utilContainsNewline.containsNewline(fc)) {\n            const msg = 'Flow end indicator should be more indented than parent';\n            onError(end, 'BAD_INDENT', msg, true);\n        }\n    }\n}\n\nexports.flowIndentCheck = flowIndentCheck;\n","'use strict';\n\nvar identity = require('../nodes/identity.js');\n\nfunction mapIncludes(ctx, items, search) {\n    const { uniqueKeys } = ctx.options;\n    if (uniqueKeys === false)\n        return false;\n    const isEqual = typeof uniqueKeys === 'function'\n        ? uniqueKeys\n        : (a, b) => a === b || (identity.isScalar(a) && identity.isScalar(b) && a.value === b.value);\n    return items.some(pair => isEqual(pair.key, search));\n}\n\nexports.mapIncludes = mapIncludes;\n","'use strict';\n\nvar Pair = require('../nodes/Pair.js');\nvar YAMLMap = require('../nodes/YAMLMap.js');\nvar resolveProps = require('./resolve-props.js');\nvar utilContainsNewline = require('./util-contains-newline.js');\nvar utilFlowIndentCheck = require('./util-flow-indent-check.js');\nvar utilMapIncludes = require('./util-map-includes.js');\n\nconst startColMsg = 'All mapping items must start at the same column';\nfunction resolveBlockMap({ composeNode, composeEmptyNode }, ctx, bm, onError, tag) {\n    const NodeClass = tag?.nodeClass ?? YAMLMap.YAMLMap;\n    const map = new NodeClass(ctx.schema);\n    if (ctx.atRoot)\n        ctx.atRoot = false;\n    let offset = bm.offset;\n    let commentEnd = null;\n    for (const collItem of bm.items) {\n        const { start, key, sep, value } = collItem;\n        // key properties\n        const keyProps = resolveProps.resolveProps(start, {\n            indicator: 'explicit-key-ind',\n            next: key ?? sep?.[0],\n            offset,\n            onError,\n            parentIndent: bm.indent,\n            startOnNewline: true\n        });\n        const implicitKey = !keyProps.found;\n        if (implicitKey) {\n            if (key) {\n                if (key.type === 'block-seq')\n                    onError(offset, 'BLOCK_AS_IMPLICIT_KEY', 'A block sequence may not be used as an implicit map key');\n                else if ('indent' in key && key.indent !== bm.indent)\n                    onError(offset, 'BAD_INDENT', startColMsg);\n            }\n            if (!keyProps.anchor && !keyProps.tag && !sep) {\n                commentEnd = keyProps.end;\n                if (keyProps.comment) {\n                    if (map.comment)\n                        map.comment += '\\n' + keyProps.comment;\n                    else\n                        map.comment = keyProps.comment;\n                }\n                continue;\n            }\n            if (keyProps.newlineAfterProp || utilContainsNewline.containsNewline(key)) {\n                onError(key ?? start[start.length - 1], 'MULTILINE_IMPLICIT_KEY', 'Implicit keys need to be on a single line');\n            }\n        }\n        else if (keyProps.found?.indent !== bm.indent) {\n            onError(offset, 'BAD_INDENT', startColMsg);\n        }\n        // key value\n        ctx.atKey = true;\n        const keyStart = keyProps.end;\n        const keyNode = key\n            ? composeNode(ctx, key, keyProps, onError)\n            : composeEmptyNode(ctx, keyStart, start, null, keyProps, onError);\n        if (ctx.schema.compat)\n            utilFlowIndentCheck.flowIndentCheck(bm.indent, key, onError);\n        ctx.atKey = false;\n        if (utilMapIncludes.mapIncludes(ctx, map.items, keyNode))\n            onError(keyStart, 'DUPLICATE_KEY', 'Map keys must be unique');\n        // value properties\n        const valueProps = resolveProps.resolveProps(sep ?? [], {\n            indicator: 'map-value-ind',\n            next: value,\n            offset: keyNode.range[2],\n            onError,\n            parentIndent: bm.indent,\n            startOnNewline: !key || key.type === 'block-scalar'\n        });\n        offset = valueProps.end;\n        if (valueProps.found) {\n            if (implicitKey) {\n                if (value?.type === 'block-map' && !valueProps.hasNewline)\n                    onError(offset, 'BLOCK_AS_IMPLICIT_KEY', 'Nested mappings are not allowed in compact mappings');\n                if (ctx.options.strict &&\n                    keyProps.start < valueProps.found.offset - 1024)\n                    onError(keyNode.range, 'KEY_OVER_1024_CHARS', 'The : indicator must be at most 1024 chars after the start of an implicit block mapping key');\n            }\n            // value value\n            const valueNode = value\n                ? composeNode(ctx, value, valueProps, onError)\n                : composeEmptyNode(ctx, offset, sep, null, valueProps, onError);\n            if (ctx.schema.compat)\n                utilFlowIndentCheck.flowIndentCheck(bm.indent, value, onError);\n            offset = valueNode.range[2];\n            const pair = new Pair.Pair(keyNode, valueNode);\n            if (ctx.options.keepSourceTokens)\n                pair.srcToken = collItem;\n            map.items.push(pair);\n        }\n        else {\n            // key with no value\n            if (implicitKey)\n                onError(keyNode.range, 'MISSING_CHAR', 'Implicit map keys need to be followed by map values');\n            if (valueProps.comment) {\n                if (keyNode.comment)\n                    keyNode.comment += '\\n' + valueProps.comment;\n                else\n                    keyNode.comment = valueProps.comment;\n            }\n            const pair = new Pair.Pair(keyNode);\n            if (ctx.options.keepSourceTokens)\n                pair.srcToken = collItem;\n            map.items.push(pair);\n        }\n    }\n    if (commentEnd && commentEnd < offset)\n        onError(commentEnd, 'IMPOSSIBLE', 'Map comment with trailing content');\n    map.range = [bm.offset, offset, commentEnd ?? offset];\n    return map;\n}\n\nexports.resolveBlockMap = resolveBlockMap;\n","'use strict';\n\nvar YAMLSeq = require('../nodes/YAMLSeq.js');\nvar resolveProps = require('./resolve-props.js');\nvar utilFlowIndentCheck = require('./util-flow-indent-check.js');\n\nfunction resolveBlockSeq({ composeNode, composeEmptyNode }, ctx, bs, onError, tag) {\n    const NodeClass = tag?.nodeClass ?? YAMLSeq.YAMLSeq;\n    const seq = new NodeClass(ctx.schema);\n    if (ctx.atRoot)\n        ctx.atRoot = false;\n    if (ctx.atKey)\n        ctx.atKey = false;\n    let offset = bs.offset;\n    let commentEnd = null;\n    for (const { start, value } of bs.items) {\n        const props = resolveProps.resolveProps(start, {\n            indicator: 'seq-item-ind',\n            next: value,\n            offset,\n            onError,\n            parentIndent: bs.indent,\n            startOnNewline: true\n        });\n        if (!props.found) {\n            if (props.anchor || props.tag || value) {\n                if (value?.type === 'block-seq')\n                    onError(props.end, 'BAD_INDENT', 'All sequence items must start at the same column');\n                else\n                    onError(offset, 'MISSING_CHAR', 'Sequence item without - indicator');\n            }\n            else {\n                commentEnd = props.end;\n                if (props.comment)\n                    seq.comment = props.comment;\n                continue;\n            }\n        }\n        const node = value\n            ? composeNode(ctx, value, props, onError)\n            : composeEmptyNode(ctx, props.end, start, null, props, onError);\n        if (ctx.schema.compat)\n            utilFlowIndentCheck.flowIndentCheck(bs.indent, value, onError);\n        offset = node.range[2];\n        seq.items.push(node);\n    }\n    seq.range = [bs.offset, offset, commentEnd ?? offset];\n    return seq;\n}\n\nexports.resolveBlockSeq = resolveBlockSeq;\n","'use strict';\n\nfunction resolveEnd(end, offset, reqSpace, onError) {\n    let comment = '';\n    if (end) {\n        let hasSpace = false;\n        let sep = '';\n        for (const token of end) {\n            const { source, type } = token;\n            switch (type) {\n                case 'space':\n                    hasSpace = true;\n                    break;\n                case 'comment': {\n                    if (reqSpace && !hasSpace)\n                        onError(token, 'MISSING_CHAR', 'Comments must be separated from other tokens by white space characters');\n                    const cb = source.substring(1) || ' ';\n                    if (!comment)\n                        comment = cb;\n                    else\n                        comment += sep + cb;\n                    sep = '';\n                    break;\n                }\n                case 'newline':\n                    if (comment)\n                        sep += source;\n                    hasSpace = true;\n                    break;\n                default:\n                    onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${type} at node end`);\n            }\n            offset += source.length;\n        }\n    }\n    return { comment, offset };\n}\n\nexports.resolveEnd = resolveEnd;\n","'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar Pair = require('../nodes/Pair.js');\nvar YAMLMap = require('../nodes/YAMLMap.js');\nvar YAMLSeq = require('../nodes/YAMLSeq.js');\nvar resolveEnd = require('./resolve-end.js');\nvar resolveProps = require('./resolve-props.js');\nvar utilContainsNewline = require('./util-contains-newline.js');\nvar utilMapIncludes = require('./util-map-includes.js');\n\nconst blockMsg = 'Block collections are not allowed within flow collections';\nconst isBlock = (token) => token && (token.type === 'block-map' || token.type === 'block-seq');\nfunction resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onError, tag) {\n    const isMap = fc.start.source === '{';\n    const fcName = isMap ? 'flow map' : 'flow sequence';\n    const NodeClass = (tag?.nodeClass ?? (isMap ? YAMLMap.YAMLMap : YAMLSeq.YAMLSeq));\n    const coll = new NodeClass(ctx.schema);\n    coll.flow = true;\n    const atRoot = ctx.atRoot;\n    if (atRoot)\n        ctx.atRoot = false;\n    if (ctx.atKey)\n        ctx.atKey = false;\n    let offset = fc.offset + fc.start.source.length;\n    for (let i = 0; i < fc.items.length; ++i) {\n        const collItem = fc.items[i];\n        const { start, key, sep, value } = collItem;\n        const props = resolveProps.resolveProps(start, {\n            flow: fcName,\n            indicator: 'explicit-key-ind',\n            next: key ?? sep?.[0],\n            offset,\n            onError,\n            parentIndent: fc.indent,\n            startOnNewline: false\n        });\n        if (!props.found) {\n            if (!props.anchor && !props.tag && !sep && !value) {\n                if (i === 0 && props.comma)\n                    onError(props.comma, 'UNEXPECTED_TOKEN', `Unexpected , in ${fcName}`);\n                else if (i < fc.items.length - 1)\n                    onError(props.start, 'UNEXPECTED_TOKEN', `Unexpected empty item in ${fcName}`);\n                if (props.comment) {\n                    if (coll.comment)\n                        coll.comment += '\\n' + props.comment;\n                    else\n                        coll.comment = props.comment;\n                }\n                offset = props.end;\n                continue;\n            }\n            if (!isMap && ctx.options.strict && utilContainsNewline.containsNewline(key))\n                onError(key, // checked by containsNewline()\n                'MULTILINE_IMPLICIT_KEY', 'Implicit keys of flow sequence pairs need to be on a single line');\n        }\n        if (i === 0) {\n            if (props.comma)\n                onError(props.comma, 'UNEXPECTED_TOKEN', `Unexpected , in ${fcName}`);\n        }\n        else {\n            if (!props.comma)\n                onError(props.start, 'MISSING_CHAR', `Missing , between ${fcName} items`);\n            if (props.comment) {\n                let prevItemComment = '';\n                loop: for (const st of start) {\n                    switch (st.type) {\n                        case 'comma':\n                        case 'space':\n                            break;\n                        case 'comment':\n                            prevItemComment = st.source.substring(1);\n                            break loop;\n                        default:\n                            break loop;\n                    }\n                }\n                if (prevItemComment) {\n                    let prev = coll.items[coll.items.length - 1];\n                    if (identity.isPair(prev))\n                        prev = prev.value ?? prev.key;\n                    if (prev.comment)\n                        prev.comment += '\\n' + prevItemComment;\n                    else\n                        prev.comment = prevItemComment;\n                    props.comment = props.comment.substring(prevItemComment.length + 1);\n                }\n            }\n        }\n        if (!isMap && !sep && !props.found) {\n            // item is a value in a seq\n            // → key & sep are empty, start does not include ? or :\n            const valueNode = value\n                ? composeNode(ctx, value, props, onError)\n                : composeEmptyNode(ctx, props.end, sep, null, props, onError);\n            coll.items.push(valueNode);\n            offset = valueNode.range[2];\n            if (isBlock(value))\n                onError(valueNode.range, 'BLOCK_IN_FLOW', blockMsg);\n        }\n        else {\n            // item is a key+value pair\n            // key value\n            ctx.atKey = true;\n            const keyStart = props.end;\n            const keyNode = key\n                ? composeNode(ctx, key, props, onError)\n                : composeEmptyNode(ctx, keyStart, start, null, props, onError);\n            if (isBlock(key))\n                onError(keyNode.range, 'BLOCK_IN_FLOW', blockMsg);\n            ctx.atKey = false;\n            // value properties\n            const valueProps = resolveProps.resolveProps(sep ?? [], {\n                flow: fcName,\n                indicator: 'map-value-ind',\n                next: value,\n                offset: keyNode.range[2],\n                onError,\n                parentIndent: fc.indent,\n                startOnNewline: false\n            });\n            if (valueProps.found) {\n                if (!isMap && !props.found && ctx.options.strict) {\n                    if (sep)\n                        for (const st of sep) {\n                            if (st === valueProps.found)\n                                break;\n                            if (st.type === 'newline') {\n                                onError(st, 'MULTILINE_IMPLICIT_KEY', 'Implicit keys of flow sequence pairs need to be on a single line');\n                                break;\n                            }\n                        }\n                    if (props.start < valueProps.found.offset - 1024)\n                        onError(valueProps.found, 'KEY_OVER_1024_CHARS', 'The : indicator must be at most 1024 chars after the start of an implicit flow sequence key');\n                }\n            }\n            else if (value) {\n                if ('source' in value && value.source?.[0] === ':')\n                    onError(value, 'MISSING_CHAR', `Missing space after : in ${fcName}`);\n                else\n                    onError(valueProps.start, 'MISSING_CHAR', `Missing , or : between ${fcName} items`);\n            }\n            // value value\n            const valueNode = value\n                ? composeNode(ctx, value, valueProps, onError)\n                : valueProps.found\n                    ? composeEmptyNode(ctx, valueProps.end, sep, null, valueProps, onError)\n                    : null;\n            if (valueNode) {\n                if (isBlock(value))\n                    onError(valueNode.range, 'BLOCK_IN_FLOW', blockMsg);\n            }\n            else if (valueProps.comment) {\n                if (keyNode.comment)\n                    keyNode.comment += '\\n' + valueProps.comment;\n                else\n                    keyNode.comment = valueProps.comment;\n            }\n            const pair = new Pair.Pair(keyNode, valueNode);\n            if (ctx.options.keepSourceTokens)\n                pair.srcToken = collItem;\n            if (isMap) {\n                const map = coll;\n                if (utilMapIncludes.mapIncludes(ctx, map.items, keyNode))\n                    onError(keyStart, 'DUPLICATE_KEY', 'Map keys must be unique');\n                map.items.push(pair);\n            }\n            else {\n                const map = new YAMLMap.YAMLMap(ctx.schema);\n                map.flow = true;\n                map.items.push(pair);\n                const endRange = (valueNode ?? keyNode).range;\n                map.range = [keyNode.range[0], endRange[1], endRange[2]];\n                coll.items.push(map);\n            }\n            offset = valueNode ? valueNode.range[2] : valueProps.end;\n        }\n    }\n    const expectedEnd = isMap ? '}' : ']';\n    const [ce, ...ee] = fc.end;\n    let cePos = offset;\n    if (ce?.source === expectedEnd)\n        cePos = ce.offset + ce.source.length;\n    else {\n        const name = fcName[0].toUpperCase() + fcName.substring(1);\n        const msg = atRoot\n            ? `${name} must end with a ${expectedEnd}`\n            : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`;\n        onError(offset, atRoot ? 'MISSING_CHAR' : 'BAD_INDENT', msg);\n        if (ce && ce.source.length !== 1)\n            ee.unshift(ce);\n    }\n    if (ee.length > 0) {\n        const end = resolveEnd.resolveEnd(ee, cePos, ctx.options.strict, onError);\n        if (end.comment) {\n            if (coll.comment)\n                coll.comment += '\\n' + end.comment;\n            else\n                coll.comment = end.comment;\n        }\n        coll.range = [fc.offset, cePos, end.offset];\n    }\n    else {\n        coll.range = [fc.offset, cePos, cePos];\n    }\n    return coll;\n}\n\nexports.resolveFlowCollection = resolveFlowCollection;\n","'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar Scalar = require('../nodes/Scalar.js');\nvar YAMLMap = require('../nodes/YAMLMap.js');\nvar YAMLSeq = require('../nodes/YAMLSeq.js');\nvar resolveBlockMap = require('./resolve-block-map.js');\nvar resolveBlockSeq = require('./resolve-block-seq.js');\nvar resolveFlowCollection = require('./resolve-flow-collection.js');\n\nfunction resolveCollection(CN, ctx, token, onError, tagName, tag) {\n    const coll = token.type === 'block-map'\n        ? resolveBlockMap.resolveBlockMap(CN, ctx, token, onError, tag)\n        : token.type === 'block-seq'\n            ? resolveBlockSeq.resolveBlockSeq(CN, ctx, token, onError, tag)\n            : resolveFlowCollection.resolveFlowCollection(CN, ctx, token, onError, tag);\n    const Coll = coll.constructor;\n    // If we got a tagName matching the class, or the tag name is '!',\n    // then use the tagName from the node class used to create it.\n    if (tagName === '!' || tagName === Coll.tagName) {\n        coll.tag = Coll.tagName;\n        return coll;\n    }\n    if (tagName)\n        coll.tag = tagName;\n    return coll;\n}\nfunction composeCollection(CN, ctx, token, props, onError) {\n    const tagToken = props.tag;\n    const tagName = !tagToken\n        ? null\n        : ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg));\n    if (token.type === 'block-seq') {\n        const { anchor, newlineAfterProp: nl } = props;\n        const lastProp = anchor && tagToken\n            ? anchor.offset > tagToken.offset\n                ? anchor\n                : tagToken\n            : (anchor ?? tagToken);\n        if (lastProp && (!nl || nl.offset < lastProp.offset)) {\n            const message = 'Missing newline after block sequence props';\n            onError(lastProp, 'MISSING_CHAR', message);\n        }\n    }\n    const expType = token.type === 'block-map'\n        ? 'map'\n        : token.type === 'block-seq'\n            ? 'seq'\n            : token.start.source === '{'\n                ? 'map'\n                : 'seq';\n    // shortcut: check if it's a generic YAMLMap or YAMLSeq\n    // before jumping into the custom tag logic.\n    if (!tagToken ||\n        !tagName ||\n        tagName === '!' ||\n        (tagName === YAMLMap.YAMLMap.tagName && expType === 'map') ||\n        (tagName === YAMLSeq.YAMLSeq.tagName && expType === 'seq')) {\n        return resolveCollection(CN, ctx, token, onError, tagName);\n    }\n    let tag = ctx.schema.tags.find(t => t.tag === tagName && t.collection === expType);\n    if (!tag) {\n        const kt = ctx.schema.knownTags[tagName];\n        if (kt?.collection === expType) {\n            ctx.schema.tags.push(Object.assign({}, kt, { default: false }));\n            tag = kt;\n        }\n        else {\n            if (kt) {\n                onError(tagToken, 'BAD_COLLECTION_TYPE', `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? 'scalar'}`, true);\n            }\n            else {\n                onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, true);\n            }\n            return resolveCollection(CN, ctx, token, onError, tagName);\n        }\n    }\n    const coll = resolveCollection(CN, ctx, token, onError, tagName, tag);\n    const res = tag.resolve?.(coll, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg), ctx.options) ?? coll;\n    const node = identity.isNode(res)\n        ? res\n        : new Scalar.Scalar(res);\n    node.range = coll.range;\n    node.tag = tagName;\n    if (tag?.format)\n        node.format = tag.format;\n    return node;\n}\n\nexports.composeCollection = composeCollection;\n","'use strict';\n\nvar Scalar = require('../nodes/Scalar.js');\n\nfunction resolveBlockScalar(ctx, scalar, onError) {\n    const start = scalar.offset;\n    const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError);\n    if (!header)\n        return { value: '', type: null, comment: '', range: [start, start, start] };\n    const type = header.mode === '>' ? Scalar.Scalar.BLOCK_FOLDED : Scalar.Scalar.BLOCK_LITERAL;\n    const lines = scalar.source ? splitLines(scalar.source) : [];\n    // determine the end of content & start of chomping\n    let chompStart = lines.length;\n    for (let i = lines.length - 1; i >= 0; --i) {\n        const content = lines[i][1];\n        if (content === '' || content === '\\r')\n            chompStart = i;\n        else\n            break;\n    }\n    // shortcut for empty contents\n    if (chompStart === 0) {\n        const value = header.chomp === '+' && lines.length > 0\n            ? '\\n'.repeat(Math.max(1, lines.length - 1))\n            : '';\n        let end = start + header.length;\n        if (scalar.source)\n            end += scalar.source.length;\n        return { value, type, comment: header.comment, range: [start, end, end] };\n    }\n    // find the indentation level to trim from start\n    let trimIndent = scalar.indent + header.indent;\n    let offset = scalar.offset + header.length;\n    let contentStart = 0;\n    for (let i = 0; i < chompStart; ++i) {\n        const [indent, content] = lines[i];\n        if (content === '' || content === '\\r') {\n            if (header.indent === 0 && indent.length > trimIndent)\n                trimIndent = indent.length;\n        }\n        else {\n            if (indent.length < trimIndent) {\n                const message = 'Block scalars with more-indented leading empty lines must use an explicit indentation indicator';\n                onError(offset + indent.length, 'MISSING_CHAR', message);\n            }\n            if (header.indent === 0)\n                trimIndent = indent.length;\n            contentStart = i;\n            if (trimIndent === 0 && !ctx.atRoot) {\n                const message = 'Block scalar values in collections must be indented';\n                onError(offset, 'BAD_INDENT', message);\n            }\n            break;\n        }\n        offset += indent.length + content.length + 1;\n    }\n    // include trailing more-indented empty lines in content\n    for (let i = lines.length - 1; i >= chompStart; --i) {\n        if (lines[i][0].length > trimIndent)\n            chompStart = i + 1;\n    }\n    let value = '';\n    let sep = '';\n    let prevMoreIndented = false;\n    // leading whitespace is kept intact\n    for (let i = 0; i < contentStart; ++i)\n        value += lines[i][0].slice(trimIndent) + '\\n';\n    for (let i = contentStart; i < chompStart; ++i) {\n        let [indent, content] = lines[i];\n        offset += indent.length + content.length + 1;\n        const crlf = content[content.length - 1] === '\\r';\n        if (crlf)\n            content = content.slice(0, -1);\n        /* istanbul ignore if already caught in lexer */\n        if (content && indent.length < trimIndent) {\n            const src = header.indent\n                ? 'explicit indentation indicator'\n                : 'first line';\n            const message = `Block scalar lines must not be less indented than their ${src}`;\n            onError(offset - content.length - (crlf ? 2 : 1), 'BAD_INDENT', message);\n            indent = '';\n        }\n        if (type === Scalar.Scalar.BLOCK_LITERAL) {\n            value += sep + indent.slice(trimIndent) + content;\n            sep = '\\n';\n        }\n        else if (indent.length > trimIndent || content[0] === '\\t') {\n            // more-indented content within a folded block\n            if (sep === ' ')\n                sep = '\\n';\n            else if (!prevMoreIndented && sep === '\\n')\n                sep = '\\n\\n';\n            value += sep + indent.slice(trimIndent) + content;\n            sep = '\\n';\n            prevMoreIndented = true;\n        }\n        else if (content === '') {\n            // empty line\n            if (sep === '\\n')\n                value += '\\n';\n            else\n                sep = '\\n';\n        }\n        else {\n            value += sep + content;\n            sep = ' ';\n            prevMoreIndented = false;\n        }\n    }\n    switch (header.chomp) {\n        case '-':\n            break;\n        case '+':\n            for (let i = chompStart; i < lines.length; ++i)\n                value += '\\n' + lines[i][0].slice(trimIndent);\n            if (value[value.length - 1] !== '\\n')\n                value += '\\n';\n            break;\n        default:\n            value += '\\n';\n    }\n    const end = start + header.length + scalar.source.length;\n    return { value, type, comment: header.comment, range: [start, end, end] };\n}\nfunction parseBlockScalarHeader({ offset, props }, strict, onError) {\n    /* istanbul ignore if should not happen */\n    if (props[0].type !== 'block-scalar-header') {\n        onError(props[0], 'IMPOSSIBLE', 'Block scalar header not found');\n        return null;\n    }\n    const { source } = props[0];\n    const mode = source[0];\n    let indent = 0;\n    let chomp = '';\n    let error = -1;\n    for (let i = 1; i < source.length; ++i) {\n        const ch = source[i];\n        if (!chomp && (ch === '-' || ch === '+'))\n            chomp = ch;\n        else {\n            const n = Number(ch);\n            if (!indent && n)\n                indent = n;\n            else if (error === -1)\n                error = offset + i;\n        }\n    }\n    if (error !== -1)\n        onError(error, 'UNEXPECTED_TOKEN', `Block scalar header includes extra characters: ${source}`);\n    let hasSpace = false;\n    let comment = '';\n    let length = source.length;\n    for (let i = 1; i < props.length; ++i) {\n        const token = props[i];\n        switch (token.type) {\n            case 'space':\n                hasSpace = true;\n            // fallthrough\n            case 'newline':\n                length += token.source.length;\n                break;\n            case 'comment':\n                if (strict && !hasSpace) {\n                    const message = 'Comments must be separated from other tokens by white space characters';\n                    onError(token, 'MISSING_CHAR', message);\n                }\n                length += token.source.length;\n                comment = token.source.substring(1);\n                break;\n            case 'error':\n                onError(token, 'UNEXPECTED_TOKEN', token.message);\n                length += token.source.length;\n                break;\n            /* istanbul ignore next should not happen */\n            default: {\n                const message = `Unexpected token in block scalar header: ${token.type}`;\n                onError(token, 'UNEXPECTED_TOKEN', message);\n                const ts = token.source;\n                if (ts && typeof ts === 'string')\n                    length += ts.length;\n            }\n        }\n    }\n    return { mode, indent, chomp, comment, length };\n}\n/** @returns Array of lines split up as `[indent, content]` */\nfunction splitLines(source) {\n    const split = source.split(/\\n( *)/);\n    const first = split[0];\n    const m = first.match(/^( *)/);\n    const line0 = m?.[1]\n        ? [m[1], first.slice(m[1].length)]\n        : ['', first];\n    const lines = [line0];\n    for (let i = 1; i < split.length; i += 2)\n        lines.push([split[i], split[i + 1]]);\n    return lines;\n}\n\nexports.resolveBlockScalar = resolveBlockScalar;\n","'use strict';\n\nvar Scalar = require('../nodes/Scalar.js');\nvar resolveEnd = require('./resolve-end.js');\n\nfunction resolveFlowScalar(scalar, strict, onError) {\n    const { offset, type, source, end } = scalar;\n    let _type;\n    let value;\n    const _onError = (rel, code, msg) => onError(offset + rel, code, msg);\n    switch (type) {\n        case 'scalar':\n            _type = Scalar.Scalar.PLAIN;\n            value = plainValue(source, _onError);\n            break;\n        case 'single-quoted-scalar':\n            _type = Scalar.Scalar.QUOTE_SINGLE;\n            value = singleQuotedValue(source, _onError);\n            break;\n        case 'double-quoted-scalar':\n            _type = Scalar.Scalar.QUOTE_DOUBLE;\n            value = doubleQuotedValue(source, _onError);\n            break;\n        /* istanbul ignore next should not happen */\n        default:\n            onError(scalar, 'UNEXPECTED_TOKEN', `Expected a flow scalar value, but found: ${type}`);\n            return {\n                value: '',\n                type: null,\n                comment: '',\n                range: [offset, offset + source.length, offset + source.length]\n            };\n    }\n    const valueEnd = offset + source.length;\n    const re = resolveEnd.resolveEnd(end, valueEnd, strict, onError);\n    return {\n        value,\n        type: _type,\n        comment: re.comment,\n        range: [offset, valueEnd, re.offset]\n    };\n}\nfunction plainValue(source, onError) {\n    let badChar = '';\n    switch (source[0]) {\n        /* istanbul ignore next should not happen */\n        case '\\t':\n            badChar = 'a tab character';\n            break;\n        case ',':\n            badChar = 'flow indicator character ,';\n            break;\n        case '%':\n            badChar = 'directive indicator character %';\n            break;\n        case '|':\n        case '>': {\n            badChar = `block scalar indicator ${source[0]}`;\n            break;\n        }\n        case '@':\n        case '`': {\n            badChar = `reserved character ${source[0]}`;\n            break;\n        }\n    }\n    if (badChar)\n        onError(0, 'BAD_SCALAR_START', `Plain value cannot start with ${badChar}`);\n    return foldLines(source);\n}\nfunction singleQuotedValue(source, onError) {\n    if (source[source.length - 1] !== \"'\" || source.length === 1)\n        onError(source.length, 'MISSING_CHAR', \"Missing closing 'quote\");\n    return foldLines(source.slice(1, -1)).replace(/''/g, \"'\");\n}\nfunction foldLines(source) {\n    /**\n     * The negative lookbehind here and in the `re` RegExp is to\n     * prevent causing a polynomial search time in certain cases.\n     *\n     * The try-catch is for Safari, which doesn't support this yet:\n     * https://caniuse.com/js-regexp-lookbehind\n     */\n    let first, line;\n    try {\n        first = new RegExp('(.*?)(?<![ \\t])[ \\t]*\\r?\\n', 'sy');\n        line = new RegExp('[ \\t]*(.*?)(?:(?<![ \\t])[ \\t]*)?\\r?\\n', 'sy');\n    }\n    catch {\n        first = /(.*?)[ \\t]*\\r?\\n/sy;\n        line = /[ \\t]*(.*?)[ \\t]*\\r?\\n/sy;\n    }\n    let match = first.exec(source);\n    if (!match)\n        return source;\n    let res = match[1];\n    let sep = ' ';\n    let pos = first.lastIndex;\n    line.lastIndex = pos;\n    while ((match = line.exec(source))) {\n        if (match[1] === '') {\n            if (sep === '\\n')\n                res += sep;\n            else\n                sep = '\\n';\n        }\n        else {\n            res += sep + match[1];\n            sep = ' ';\n        }\n        pos = line.lastIndex;\n    }\n    const last = /[ \\t]*(.*)/sy;\n    last.lastIndex = pos;\n    match = last.exec(source);\n    return res + sep + (match?.[1] ?? '');\n}\nfunction doubleQuotedValue(source, onError) {\n    let res = '';\n    for (let i = 1; i < source.length - 1; ++i) {\n        const ch = source[i];\n        if (ch === '\\r' && source[i + 1] === '\\n')\n            continue;\n        if (ch === '\\n') {\n            const { fold, offset } = foldNewline(source, i);\n            res += fold;\n            i = offset;\n        }\n        else if (ch === '\\\\') {\n            let next = source[++i];\n            const cc = escapeCodes[next];\n            if (cc)\n                res += cc;\n            else if (next === '\\n') {\n                // skip escaped newlines, but still trim the following line\n                next = source[i + 1];\n                while (next === ' ' || next === '\\t')\n                    next = source[++i + 1];\n            }\n            else if (next === '\\r' && source[i + 1] === '\\n') {\n                // skip escaped CRLF newlines, but still trim the following line\n                next = source[++i + 1];\n                while (next === ' ' || next === '\\t')\n                    next = source[++i + 1];\n            }\n            else if (next === 'x' || next === 'u' || next === 'U') {\n                const length = next === 'x' ? 2 : next === 'u' ? 4 : 8;\n                res += parseCharCode(source, i + 1, length, onError);\n                i += length;\n            }\n            else {\n                const raw = source.substr(i - 1, 2);\n                onError(i - 1, 'BAD_DQ_ESCAPE', `Invalid escape sequence ${raw}`);\n                res += raw;\n            }\n        }\n        else if (ch === ' ' || ch === '\\t') {\n            // trim trailing whitespace\n            const wsStart = i;\n            let next = source[i + 1];\n            while (next === ' ' || next === '\\t')\n                next = source[++i + 1];\n            if (next !== '\\n' && !(next === '\\r' && source[i + 2] === '\\n'))\n                res += i > wsStart ? source.slice(wsStart, i + 1) : ch;\n        }\n        else {\n            res += ch;\n        }\n    }\n    if (source[source.length - 1] !== '\"' || source.length === 1)\n        onError(source.length, 'MISSING_CHAR', 'Missing closing \"quote');\n    return res;\n}\n/**\n * Fold a single newline into a space, multiple newlines to N - 1 newlines.\n * Presumes `source[offset] === '\\n'`\n */\nfunction foldNewline(source, offset) {\n    let fold = '';\n    let ch = source[offset + 1];\n    while (ch === ' ' || ch === '\\t' || ch === '\\n' || ch === '\\r') {\n        if (ch === '\\r' && source[offset + 2] !== '\\n')\n            break;\n        if (ch === '\\n')\n            fold += '\\n';\n        offset += 1;\n        ch = source[offset + 1];\n    }\n    if (!fold)\n        fold = ' ';\n    return { fold, offset };\n}\nconst escapeCodes = {\n    '0': '\\0', // null character\n    a: '\\x07', // bell character\n    b: '\\b', // backspace\n    e: '\\x1b', // escape character\n    f: '\\f', // form feed\n    n: '\\n', // line feed\n    r: '\\r', // carriage return\n    t: '\\t', // horizontal tab\n    v: '\\v', // vertical tab\n    N: '\\u0085', // Unicode next line\n    _: '\\u00a0', // Unicode non-breaking space\n    L: '\\u2028', // Unicode line separator\n    P: '\\u2029', // Unicode paragraph separator\n    ' ': ' ',\n    '\"': '\"',\n    '/': '/',\n    '\\\\': '\\\\',\n    '\\t': '\\t'\n};\nfunction parseCharCode(source, offset, length, onError) {\n    const cc = source.substr(offset, length);\n    const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc);\n    const code = ok ? parseInt(cc, 16) : NaN;\n    try {\n        return String.fromCodePoint(code);\n    }\n    catch {\n        const raw = source.substr(offset - 2, length + 2);\n        onError(offset - 2, 'BAD_DQ_ESCAPE', `Invalid escape sequence ${raw}`);\n        return raw;\n    }\n}\n\nexports.resolveFlowScalar = resolveFlowScalar;\n","'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar Scalar = require('../nodes/Scalar.js');\nvar resolveBlockScalar = require('./resolve-block-scalar.js');\nvar resolveFlowScalar = require('./resolve-flow-scalar.js');\n\nfunction composeScalar(ctx, token, tagToken, onError) {\n    const { value, type, comment, range } = token.type === 'block-scalar'\n        ? resolveBlockScalar.resolveBlockScalar(ctx, token, onError)\n        : resolveFlowScalar.resolveFlowScalar(token, ctx.options.strict, onError);\n    const tagName = tagToken\n        ? ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg))\n        : null;\n    let tag;\n    if (ctx.options.stringKeys && ctx.atKey) {\n        tag = ctx.schema[identity.SCALAR];\n    }\n    else if (tagName)\n        tag = findScalarTagByName(ctx.schema, value, tagName, tagToken, onError);\n    else if (token.type === 'scalar')\n        tag = findScalarTagByTest(ctx, value, token, onError);\n    else\n        tag = ctx.schema[identity.SCALAR];\n    let scalar;\n    try {\n        const res = tag.resolve(value, msg => onError(tagToken ?? token, 'TAG_RESOLVE_FAILED', msg), ctx.options);\n        scalar = identity.isScalar(res) ? res : new Scalar.Scalar(res);\n    }\n    catch (error) {\n        const msg = error instanceof Error ? error.message : String(error);\n        onError(tagToken ?? token, 'TAG_RESOLVE_FAILED', msg);\n        scalar = new Scalar.Scalar(value);\n    }\n    scalar.range = range;\n    scalar.source = value;\n    if (type)\n        scalar.type = type;\n    if (tagName)\n        scalar.tag = tagName;\n    if (tag.format)\n        scalar.format = tag.format;\n    if (comment)\n        scalar.comment = comment;\n    return scalar;\n}\nfunction findScalarTagByName(schema, value, tagName, tagToken, onError) {\n    if (tagName === '!')\n        return schema[identity.SCALAR]; // non-specific tag\n    const matchWithTest = [];\n    for (const tag of schema.tags) {\n        if (!tag.collection && tag.tag === tagName) {\n            if (tag.default && tag.test)\n                matchWithTest.push(tag);\n            else\n                return tag;\n        }\n    }\n    for (const tag of matchWithTest)\n        if (tag.test?.test(value))\n            return tag;\n    const kt = schema.knownTags[tagName];\n    if (kt && !kt.collection) {\n        // Ensure that the known tag is available for stringifying,\n        // but does not get used by default.\n        schema.tags.push(Object.assign({}, kt, { default: false, test: undefined }));\n        return kt;\n    }\n    onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, tagName !== 'tag:yaml.org,2002:str');\n    return schema[identity.SCALAR];\n}\nfunction findScalarTagByTest({ atKey, directives, schema }, value, token, onError) {\n    const tag = schema.tags.find(tag => (tag.default === true || (atKey && tag.default === 'key')) &&\n        tag.test?.test(value)) || schema[identity.SCALAR];\n    if (schema.compat) {\n        const compat = schema.compat.find(tag => tag.default && tag.test?.test(value)) ??\n            schema[identity.SCALAR];\n        if (tag.tag !== compat.tag) {\n            const ts = directives.tagString(tag.tag);\n            const cs = directives.tagString(compat.tag);\n            const msg = `Value may be parsed as either ${ts} or ${cs}`;\n            onError(token, 'TAG_RESOLVE_FAILED', msg, true);\n        }\n    }\n    return tag;\n}\n\nexports.composeScalar = composeScalar;\n","'use strict';\n\nfunction emptyScalarPosition(offset, before, pos) {\n    if (before) {\n        pos ?? (pos = before.length);\n        for (let i = pos - 1; i >= 0; --i) {\n            let st = before[i];\n            switch (st.type) {\n                case 'space':\n                case 'comment':\n                case 'newline':\n                    offset -= st.source.length;\n                    continue;\n            }\n            // Technically, an empty scalar is immediately after the last non-empty\n            // node, but it's more useful to place it after any whitespace.\n            st = before[++i];\n            while (st?.type === 'space') {\n                offset += st.source.length;\n                st = before[++i];\n            }\n            break;\n        }\n    }\n    return offset;\n}\n\nexports.emptyScalarPosition = emptyScalarPosition;\n","'use strict';\n\nvar Alias = require('../nodes/Alias.js');\nvar identity = require('../nodes/identity.js');\nvar composeCollection = require('./compose-collection.js');\nvar composeScalar = require('./compose-scalar.js');\nvar resolveEnd = require('./resolve-end.js');\nvar utilEmptyScalarPosition = require('./util-empty-scalar-position.js');\n\nconst CN = { composeNode, composeEmptyNode };\nfunction composeNode(ctx, token, props, onError) {\n    const atKey = ctx.atKey;\n    const { spaceBefore, comment, anchor, tag } = props;\n    let node;\n    let isSrcToken = true;\n    switch (token.type) {\n        case 'alias':\n            node = composeAlias(ctx, token, onError);\n            if (anchor || tag)\n                onError(token, 'ALIAS_PROPS', 'An alias node must not specify any properties');\n            break;\n        case 'scalar':\n        case 'single-quoted-scalar':\n        case 'double-quoted-scalar':\n        case 'block-scalar':\n            node = composeScalar.composeScalar(ctx, token, tag, onError);\n            if (anchor)\n                node.anchor = anchor.source.substring(1);\n            break;\n        case 'block-map':\n        case 'block-seq':\n        case 'flow-collection':\n            try {\n                node = composeCollection.composeCollection(CN, ctx, token, props, onError);\n                if (anchor)\n                    node.anchor = anchor.source.substring(1);\n            }\n            catch (error) {\n                // Almost certainly here due to a stack overflow\n                const message = error instanceof Error ? error.message : String(error);\n                onError(token, 'RESOURCE_EXHAUSTION', message);\n            }\n            break;\n        default: {\n            const message = token.type === 'error'\n                ? token.message\n                : `Unsupported token (type: ${token.type})`;\n            onError(token, 'UNEXPECTED_TOKEN', message);\n            isSrcToken = false;\n        }\n    }\n    node ?? (node = composeEmptyNode(ctx, token.offset, undefined, null, props, onError));\n    if (anchor && node.anchor === '')\n        onError(anchor, 'BAD_ALIAS', 'Anchor cannot be an empty string');\n    if (atKey &&\n        ctx.options.stringKeys &&\n        (!identity.isScalar(node) ||\n            typeof node.value !== 'string' ||\n            (node.tag && node.tag !== 'tag:yaml.org,2002:str'))) {\n        const msg = 'With stringKeys, all keys must be strings';\n        onError(tag ?? token, 'NON_STRING_KEY', msg);\n    }\n    if (spaceBefore)\n        node.spaceBefore = true;\n    if (comment) {\n        if (token.type === 'scalar' && token.source === '')\n            node.comment = comment;\n        else\n            node.commentBefore = comment;\n    }\n    // @ts-expect-error Type checking misses meaning of isSrcToken\n    if (ctx.options.keepSourceTokens && isSrcToken)\n        node.srcToken = token;\n    return node;\n}\nfunction composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) {\n    const token = {\n        type: 'scalar',\n        offset: utilEmptyScalarPosition.emptyScalarPosition(offset, before, pos),\n        indent: -1,\n        source: ''\n    };\n    const node = composeScalar.composeScalar(ctx, token, tag, onError);\n    if (anchor) {\n        node.anchor = anchor.source.substring(1);\n        if (node.anchor === '')\n            onError(anchor, 'BAD_ALIAS', 'Anchor cannot be an empty string');\n    }\n    if (spaceBefore)\n        node.spaceBefore = true;\n    if (comment) {\n        node.comment = comment;\n        node.range[2] = end;\n    }\n    return node;\n}\nfunction composeAlias({ options }, { offset, source, end }, onError) {\n    const alias = new Alias.Alias(source.substring(1));\n    if (alias.source === '')\n        onError(offset, 'BAD_ALIAS', 'Alias cannot be an empty string');\n    if (alias.source.endsWith(':'))\n        onError(offset + source.length - 1, 'BAD_ALIAS', 'Alias ending in : is ambiguous', true);\n    const valueEnd = offset + source.length;\n    const re = resolveEnd.resolveEnd(end, valueEnd, options.strict, onError);\n    alias.range = [offset, valueEnd, re.offset];\n    if (re.comment)\n        alias.comment = re.comment;\n    return alias;\n}\n\nexports.composeEmptyNode = composeEmptyNode;\nexports.composeNode = composeNode;\n","'use strict';\n\nvar Document = require('../doc/Document.js');\nvar composeNode = require('./compose-node.js');\nvar resolveEnd = require('./resolve-end.js');\nvar resolveProps = require('./resolve-props.js');\n\nfunction composeDoc(options, directives, { offset, start, value, end }, onError) {\n    const opts = Object.assign({ _directives: directives }, options);\n    const doc = new Document.Document(undefined, opts);\n    const ctx = {\n        atKey: false,\n        atRoot: true,\n        directives: doc.directives,\n        options: doc.options,\n        schema: doc.schema\n    };\n    const props = resolveProps.resolveProps(start, {\n        indicator: 'doc-start',\n        next: value ?? end?.[0],\n        offset,\n        onError,\n        parentIndent: 0,\n        startOnNewline: true\n    });\n    if (props.found) {\n        doc.directives.docStart = true;\n        if (value &&\n            (value.type === 'block-map' || value.type === 'block-seq') &&\n            !props.hasNewline)\n            onError(props.end, 'MISSING_CHAR', 'Block collection cannot start on same line with directives-end marker');\n    }\n    // @ts-expect-error If Contents is set, let's trust the user\n    doc.contents = value\n        ? composeNode.composeNode(ctx, value, props, onError)\n        : composeNode.composeEmptyNode(ctx, props.end, start, null, props, onError);\n    const contentEnd = doc.contents.range[2];\n    const re = resolveEnd.resolveEnd(end, contentEnd, false, onError);\n    if (re.comment)\n        doc.comment = re.comment;\n    doc.range = [offset, contentEnd, re.offset];\n    return doc;\n}\n\nexports.composeDoc = composeDoc;\n","'use strict';\n\nvar node_process = require('process');\nvar directives = require('../doc/directives.js');\nvar Document = require('../doc/Document.js');\nvar errors = require('../errors.js');\nvar identity = require('../nodes/identity.js');\nvar composeDoc = require('./compose-doc.js');\nvar resolveEnd = require('./resolve-end.js');\n\nfunction getErrorPos(src) {\n    if (typeof src === 'number')\n        return [src, src + 1];\n    if (Array.isArray(src))\n        return src.length === 2 ? src : [src[0], src[1]];\n    const { offset, source } = src;\n    return [offset, offset + (typeof source === 'string' ? source.length : 1)];\n}\nfunction parsePrelude(prelude) {\n    let comment = '';\n    let atComment = false;\n    let afterEmptyLine = false;\n    for (let i = 0; i < prelude.length; ++i) {\n        const source = prelude[i];\n        switch (source[0]) {\n            case '#':\n                comment +=\n                    (comment === '' ? '' : afterEmptyLine ? '\\n\\n' : '\\n') +\n                        (source.substring(1) || ' ');\n                atComment = true;\n                afterEmptyLine = false;\n                break;\n            case '%':\n                if (prelude[i + 1]?.[0] !== '#')\n                    i += 1;\n                atComment = false;\n                break;\n            default:\n                // This may be wrong after doc-end, but in that case it doesn't matter\n                if (!atComment)\n                    afterEmptyLine = true;\n                atComment = false;\n        }\n    }\n    return { comment, afterEmptyLine };\n}\n/**\n * Compose a stream of CST nodes into a stream of YAML Documents.\n *\n * ```ts\n * import { Composer, Parser } from 'yaml'\n *\n * const src: string = ...\n * const tokens = new Parser().parse(src)\n * const docs = new Composer().compose(tokens)\n * ```\n */\nclass Composer {\n    constructor(options = {}) {\n        this.doc = null;\n        this.atDirectives = false;\n        this.prelude = [];\n        this.errors = [];\n        this.warnings = [];\n        this.onError = (source, code, message, warning) => {\n            const pos = getErrorPos(source);\n            if (warning)\n                this.warnings.push(new errors.YAMLWarning(pos, code, message));\n            else\n                this.errors.push(new errors.YAMLParseError(pos, code, message));\n        };\n        // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n        this.directives = new directives.Directives({ version: options.version || '1.2' });\n        this.options = options;\n    }\n    decorate(doc, afterDoc) {\n        const { comment, afterEmptyLine } = parsePrelude(this.prelude);\n        //console.log({ dc: doc.comment, prelude, comment })\n        if (comment) {\n            const dc = doc.contents;\n            if (afterDoc) {\n                doc.comment = doc.comment ? `${doc.comment}\\n${comment}` : comment;\n            }\n            else if (afterEmptyLine || doc.directives.docStart || !dc) {\n                doc.commentBefore = comment;\n            }\n            else if (identity.isCollection(dc) && !dc.flow && dc.items.length > 0) {\n                let it = dc.items[0];\n                if (identity.isPair(it))\n                    it = it.key;\n                const cb = it.commentBefore;\n                it.commentBefore = cb ? `${comment}\\n${cb}` : comment;\n            }\n            else {\n                const cb = dc.commentBefore;\n                dc.commentBefore = cb ? `${comment}\\n${cb}` : comment;\n            }\n        }\n        if (afterDoc) {\n            for (let i = 0; i < this.errors.length; ++i)\n                doc.errors.push(this.errors[i]);\n            for (let i = 0; i < this.warnings.length; ++i)\n                doc.warnings.push(this.warnings[i]);\n        }\n        else {\n            doc.errors = this.errors;\n            doc.warnings = this.warnings;\n        }\n        this.prelude = [];\n        this.errors = [];\n        this.warnings = [];\n    }\n    /**\n     * Current stream status information.\n     *\n     * Mostly useful at the end of input for an empty stream.\n     */\n    streamInfo() {\n        return {\n            comment: parsePrelude(this.prelude).comment,\n            directives: this.directives,\n            errors: this.errors,\n            warnings: this.warnings\n        };\n    }\n    /**\n     * Compose tokens into documents.\n     *\n     * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.\n     * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.\n     */\n    *compose(tokens, forceDoc = false, endOffset = -1) {\n        for (const token of tokens)\n            yield* this.next(token);\n        yield* this.end(forceDoc, endOffset);\n    }\n    /** Advance the composer by one CST token. */\n    *next(token) {\n        if (node_process.env.LOG_STREAM)\n            console.dir(token, { depth: null });\n        switch (token.type) {\n            case 'directive':\n                this.directives.add(token.source, (offset, message, warning) => {\n                    const pos = getErrorPos(token);\n                    pos[0] += offset;\n                    this.onError(pos, 'BAD_DIRECTIVE', message, warning);\n                });\n                this.prelude.push(token.source);\n                this.atDirectives = true;\n                break;\n            case 'document': {\n                const doc = composeDoc.composeDoc(this.options, this.directives, token, this.onError);\n                if (this.atDirectives && !doc.directives.docStart)\n                    this.onError(token, 'MISSING_CHAR', 'Missing directives-end/doc-start indicator line');\n                this.decorate(doc, false);\n                if (this.doc)\n                    yield this.doc;\n                this.doc = doc;\n                this.atDirectives = false;\n                break;\n            }\n            case 'byte-order-mark':\n            case 'space':\n                break;\n            case 'comment':\n            case 'newline':\n                this.prelude.push(token.source);\n                break;\n            case 'error': {\n                const msg = token.source\n                    ? `${token.message}: ${JSON.stringify(token.source)}`\n                    : token.message;\n                const error = new errors.YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', msg);\n                if (this.atDirectives || !this.doc)\n                    this.errors.push(error);\n                else\n                    this.doc.errors.push(error);\n                break;\n            }\n            case 'doc-end': {\n                if (!this.doc) {\n                    const msg = 'Unexpected doc-end without preceding document';\n                    this.errors.push(new errors.YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', msg));\n                    break;\n                }\n                this.doc.directives.docEnd = true;\n                const end = resolveEnd.resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError);\n                this.decorate(this.doc, true);\n                if (end.comment) {\n                    const dc = this.doc.comment;\n                    this.doc.comment = dc ? `${dc}\\n${end.comment}` : end.comment;\n                }\n                this.doc.range[2] = end.offset;\n                break;\n            }\n            default:\n                this.errors.push(new errors.YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', `Unsupported token ${token.type}`));\n        }\n    }\n    /**\n     * Call at end of input to yield any remaining document.\n     *\n     * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.\n     * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.\n     */\n    *end(forceDoc = false, endOffset = -1) {\n        if (this.doc) {\n            this.decorate(this.doc, true);\n            yield this.doc;\n            this.doc = null;\n        }\n        else if (forceDoc) {\n            const opts = Object.assign({ _directives: this.directives }, this.options);\n            const doc = new Document.Document(undefined, opts);\n            if (this.atDirectives)\n                this.onError(endOffset, 'MISSING_CHAR', 'Missing directives-end indicator line');\n            doc.range = [0, endOffset, endOffset];\n            this.decorate(doc, false);\n            yield doc;\n        }\n    }\n}\n\nexports.Composer = Composer;\n","'use strict';\n\nvar resolveBlockScalar = require('../compose/resolve-block-scalar.js');\nvar resolveFlowScalar = require('../compose/resolve-flow-scalar.js');\nvar errors = require('../errors.js');\nvar stringifyString = require('../stringify/stringifyString.js');\n\nfunction resolveAsScalar(token, strict = true, onError) {\n    if (token) {\n        const _onError = (pos, code, message) => {\n            const offset = typeof pos === 'number' ? pos : Array.isArray(pos) ? pos[0] : pos.offset;\n            if (onError)\n                onError(offset, code, message);\n            else\n                throw new errors.YAMLParseError([offset, offset + 1], code, message);\n        };\n        switch (token.type) {\n            case 'scalar':\n            case 'single-quoted-scalar':\n            case 'double-quoted-scalar':\n                return resolveFlowScalar.resolveFlowScalar(token, strict, _onError);\n            case 'block-scalar':\n                return resolveBlockScalar.resolveBlockScalar({ options: { strict } }, token, _onError);\n        }\n    }\n    return null;\n}\n/**\n * Create a new scalar token with `value`\n *\n * Values that represent an actual string but may be parsed as a different type should use a `type` other than `'PLAIN'`,\n * as this function does not support any schema operations and won't check for such conflicts.\n *\n * @param value The string representation of the value, which will have its content properly indented.\n * @param context.end Comments and whitespace after the end of the value, or after the block scalar header. If undefined, a newline will be added.\n * @param context.implicitKey Being within an implicit key may affect the resolved type of the token's value.\n * @param context.indent The indent level of the token.\n * @param context.inFlow Is this scalar within a flow collection? This may affect the resolved type of the token's value.\n * @param context.offset The offset position of the token.\n * @param context.type The preferred type of the scalar token. If undefined, the previous type of the `token` will be used, defaulting to `'PLAIN'`.\n */\nfunction createScalarToken(value, context) {\n    const { implicitKey = false, indent, inFlow = false, offset = -1, type = 'PLAIN' } = context;\n    const source = stringifyString.stringifyString({ type, value }, {\n        implicitKey,\n        indent: indent > 0 ? ' '.repeat(indent) : '',\n        inFlow,\n        options: { blockQuote: true, lineWidth: -1 }\n    });\n    const end = context.end ?? [\n        { type: 'newline', offset: -1, indent, source: '\\n' }\n    ];\n    switch (source[0]) {\n        case '|':\n        case '>': {\n            const he = source.indexOf('\\n');\n            const head = source.substring(0, he);\n            const body = source.substring(he + 1) + '\\n';\n            const props = [\n                { type: 'block-scalar-header', offset, indent, source: head }\n            ];\n            if (!addEndtoBlockProps(props, end))\n                props.push({ type: 'newline', offset: -1, indent, source: '\\n' });\n            return { type: 'block-scalar', offset, indent, props, source: body };\n        }\n        case '\"':\n            return { type: 'double-quoted-scalar', offset, indent, source, end };\n        case \"'\":\n            return { type: 'single-quoted-scalar', offset, indent, source, end };\n        default:\n            return { type: 'scalar', offset, indent, source, end };\n    }\n}\n/**\n * Set the value of `token` to the given string `value`, overwriting any previous contents and type that it may have.\n *\n * Best efforts are made to retain any comments previously associated with the `token`,\n * though all contents within a collection's `items` will be overwritten.\n *\n * Values that represent an actual string but may be parsed as a different type should use a `type` other than `'PLAIN'`,\n * as this function does not support any schema operations and won't check for such conflicts.\n *\n * @param token Any token. If it does not include an `indent` value, the value will be stringified as if it were an implicit key.\n * @param value The string representation of the value, which will have its content properly indented.\n * @param context.afterKey In most cases, values after a key should have an additional level of indentation.\n * @param context.implicitKey Being within an implicit key may affect the resolved type of the token's value.\n * @param context.inFlow Being within a flow collection may affect the resolved type of the token's value.\n * @param context.type The preferred type of the scalar token. If undefined, the previous type of the `token` will be used, defaulting to `'PLAIN'`.\n */\nfunction setScalarValue(token, value, context = {}) {\n    let { afterKey = false, implicitKey = false, inFlow = false, type } = context;\n    let indent = 'indent' in token ? token.indent : null;\n    if (afterKey && typeof indent === 'number')\n        indent += 2;\n    if (!type)\n        switch (token.type) {\n            case 'single-quoted-scalar':\n                type = 'QUOTE_SINGLE';\n                break;\n            case 'double-quoted-scalar':\n                type = 'QUOTE_DOUBLE';\n                break;\n            case 'block-scalar': {\n                const header = token.props[0];\n                if (header.type !== 'block-scalar-header')\n                    throw new Error('Invalid block scalar header');\n                type = header.source[0] === '>' ? 'BLOCK_FOLDED' : 'BLOCK_LITERAL';\n                break;\n            }\n            default:\n                type = 'PLAIN';\n        }\n    const source = stringifyString.stringifyString({ type, value }, {\n        implicitKey: implicitKey || indent === null,\n        indent: indent !== null && indent > 0 ? ' '.repeat(indent) : '',\n        inFlow,\n        options: { blockQuote: true, lineWidth: -1 }\n    });\n    switch (source[0]) {\n        case '|':\n        case '>':\n            setBlockScalarValue(token, source);\n            break;\n        case '\"':\n            setFlowScalarValue(token, source, 'double-quoted-scalar');\n            break;\n        case \"'\":\n            setFlowScalarValue(token, source, 'single-quoted-scalar');\n            break;\n        default:\n            setFlowScalarValue(token, source, 'scalar');\n    }\n}\nfunction setBlockScalarValue(token, source) {\n    const he = source.indexOf('\\n');\n    const head = source.substring(0, he);\n    const body = source.substring(he + 1) + '\\n';\n    if (token.type === 'block-scalar') {\n        const header = token.props[0];\n        if (header.type !== 'block-scalar-header')\n            throw new Error('Invalid block scalar header');\n        header.source = head;\n        token.source = body;\n    }\n    else {\n        const { offset } = token;\n        const indent = 'indent' in token ? token.indent : -1;\n        const props = [\n            { type: 'block-scalar-header', offset, indent, source: head }\n        ];\n        if (!addEndtoBlockProps(props, 'end' in token ? token.end : undefined))\n            props.push({ type: 'newline', offset: -1, indent, source: '\\n' });\n        for (const key of Object.keys(token))\n            if (key !== 'type' && key !== 'offset')\n                delete token[key];\n        Object.assign(token, { type: 'block-scalar', indent, props, source: body });\n    }\n}\n/** @returns `true` if last token is a newline */\nfunction addEndtoBlockProps(props, end) {\n    if (end)\n        for (const st of end)\n            switch (st.type) {\n                case 'space':\n                case 'comment':\n                    props.push(st);\n                    break;\n                case 'newline':\n                    props.push(st);\n                    return true;\n            }\n    return false;\n}\nfunction setFlowScalarValue(token, source, type) {\n    switch (token.type) {\n        case 'scalar':\n        case 'double-quoted-scalar':\n        case 'single-quoted-scalar':\n            token.type = type;\n            token.source = source;\n            break;\n        case 'block-scalar': {\n            const end = token.props.slice(1);\n            let oa = source.length;\n            if (token.props[0].type === 'block-scalar-header')\n                oa -= token.props[0].source.length;\n            for (const tok of end)\n                tok.offset += oa;\n            delete token.props;\n            Object.assign(token, { type, source, end });\n            break;\n        }\n        case 'block-map':\n        case 'block-seq': {\n            const offset = token.offset + source.length;\n            const nl = { type: 'newline', offset, indent: token.indent, source: '\\n' };\n            delete token.items;\n            Object.assign(token, { type, source, end: [nl] });\n            break;\n        }\n        default: {\n            const indent = 'indent' in token ? token.indent : -1;\n            const end = 'end' in token && Array.isArray(token.end)\n                ? token.end.filter(st => st.type === 'space' ||\n                    st.type === 'comment' ||\n                    st.type === 'newline')\n                : [];\n            for (const key of Object.keys(token))\n                if (key !== 'type' && key !== 'offset')\n                    delete token[key];\n            Object.assign(token, { type, indent, source, end });\n        }\n    }\n}\n\nexports.createScalarToken = createScalarToken;\nexports.resolveAsScalar = resolveAsScalar;\nexports.setScalarValue = setScalarValue;\n","'use strict';\n\n/**\n * Stringify a CST document, token, or collection item\n *\n * Fair warning: This applies no validation whatsoever, and\n * simply concatenates the sources in their logical order.\n */\nconst stringify = (cst) => 'type' in cst ? stringifyToken(cst) : stringifyItem(cst);\nfunction stringifyToken(token) {\n    switch (token.type) {\n        case 'block-scalar': {\n            let res = '';\n            for (const tok of token.props)\n                res += stringifyToken(tok);\n            return res + token.source;\n        }\n        case 'block-map':\n        case 'block-seq': {\n            let res = '';\n            for (const item of token.items)\n                res += stringifyItem(item);\n            return res;\n        }\n        case 'flow-collection': {\n            let res = token.start.source;\n            for (const item of token.items)\n                res += stringifyItem(item);\n            for (const st of token.end)\n                res += st.source;\n            return res;\n        }\n        case 'document': {\n            let res = stringifyItem(token);\n            if (token.end)\n                for (const st of token.end)\n                    res += st.source;\n            return res;\n        }\n        default: {\n            let res = token.source;\n            if ('end' in token && token.end)\n                for (const st of token.end)\n                    res += st.source;\n            return res;\n        }\n    }\n}\nfunction stringifyItem({ start, key, sep, value }) {\n    let res = '';\n    for (const st of start)\n        res += st.source;\n    if (key)\n        res += stringifyToken(key);\n    if (sep)\n        for (const st of sep)\n            res += st.source;\n    if (value)\n        res += stringifyToken(value);\n    return res;\n}\n\nexports.stringify = stringify;\n","'use strict';\n\nconst BREAK = Symbol('break visit');\nconst SKIP = Symbol('skip children');\nconst REMOVE = Symbol('remove item');\n/**\n * Apply a visitor to a CST document or item.\n *\n * Walks through the tree (depth-first) starting from the root, calling a\n * `visitor` function with two arguments when entering each item:\n *   - `item`: The current item, which included the following members:\n *     - `start: SourceToken[]` – Source tokens before the key or value,\n *       possibly including its anchor or tag.\n *     - `key?: Token | null` – Set for pair values. May then be `null`, if\n *       the key before the `:` separator is empty.\n *     - `sep?: SourceToken[]` – Source tokens between the key and the value,\n *       which should include the `:` map value indicator if `value` is set.\n *     - `value?: Token` – The value of a sequence item, or of a map pair.\n *   - `path`: The steps from the root to the current node, as an array of\n *     `['key' | 'value', number]` tuples.\n *\n * The return value of the visitor may be used to control the traversal:\n *   - `undefined` (default): Do nothing and continue\n *   - `visit.SKIP`: Do not visit the children of this token, continue with\n *      next sibling\n *   - `visit.BREAK`: Terminate traversal completely\n *   - `visit.REMOVE`: Remove the current item, then continue with the next one\n *   - `number`: Set the index of the next step. This is useful especially if\n *     the index of the current token has changed.\n *   - `function`: Define the next visitor for this item. After the original\n *     visitor is called on item entry, next visitors are called after handling\n *     a non-empty `key` and when exiting the item.\n */\nfunction visit(cst, visitor) {\n    if ('type' in cst && cst.type === 'document')\n        cst = { start: cst.start, value: cst.value };\n    _visit(Object.freeze([]), cst, visitor);\n}\n// Without the `as symbol` casts, TS declares these in the `visit`\n// namespace using `var`, but then complains about that because\n// `unique symbol` must be `const`.\n/** Terminate visit traversal completely */\nvisit.BREAK = BREAK;\n/** Do not visit the children of the current item */\nvisit.SKIP = SKIP;\n/** Remove the current item */\nvisit.REMOVE = REMOVE;\n/** Find the item at `path` from `cst` as the root */\nvisit.itemAtPath = (cst, path) => {\n    let item = cst;\n    for (const [field, index] of path) {\n        const tok = item?.[field];\n        if (tok && 'items' in tok) {\n            item = tok.items[index];\n        }\n        else\n            return undefined;\n    }\n    return item;\n};\n/**\n * Get the immediate parent collection of the item at `path` from `cst` as the root.\n *\n * Throws an error if the collection is not found, which should never happen if the item itself exists.\n */\nvisit.parentCollection = (cst, path) => {\n    const parent = visit.itemAtPath(cst, path.slice(0, -1));\n    const field = path[path.length - 1][0];\n    const coll = parent?.[field];\n    if (coll && 'items' in coll)\n        return coll;\n    throw new Error('Parent collection not found');\n};\nfunction _visit(path, item, visitor) {\n    let ctrl = visitor(item, path);\n    if (typeof ctrl === 'symbol')\n        return ctrl;\n    for (const field of ['key', 'value']) {\n        const token = item[field];\n        if (token && 'items' in token) {\n            for (let i = 0; i < token.items.length; ++i) {\n                const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor);\n                if (typeof ci === 'number')\n                    i = ci - 1;\n                else if (ci === BREAK)\n                    return BREAK;\n                else if (ci === REMOVE) {\n                    token.items.splice(i, 1);\n                    i -= 1;\n                }\n            }\n            if (typeof ctrl === 'function' && field === 'key')\n                ctrl = ctrl(item, path);\n        }\n    }\n    return typeof ctrl === 'function' ? ctrl(item, path) : ctrl;\n}\n\nexports.visit = visit;\n","'use strict';\n\nvar cstScalar = require('./cst-scalar.js');\nvar cstStringify = require('./cst-stringify.js');\nvar cstVisit = require('./cst-visit.js');\n\n/** The byte order mark */\nconst BOM = '\\u{FEFF}';\n/** Start of doc-mode */\nconst DOCUMENT = '\\x02'; // C0: Start of Text\n/** Unexpected end of flow-mode */\nconst FLOW_END = '\\x18'; // C0: Cancel\n/** Next token is a scalar value */\nconst SCALAR = '\\x1f'; // C0: Unit Separator\n/** @returns `true` if `token` is a flow or block collection */\nconst isCollection = (token) => !!token && 'items' in token;\n/** @returns `true` if `token` is a flow or block scalar; not an alias */\nconst isScalar = (token) => !!token &&\n    (token.type === 'scalar' ||\n        token.type === 'single-quoted-scalar' ||\n        token.type === 'double-quoted-scalar' ||\n        token.type === 'block-scalar');\n/* istanbul ignore next */\n/** Get a printable representation of a lexer token */\nfunction prettyToken(token) {\n    switch (token) {\n        case BOM:\n            return '<BOM>';\n        case DOCUMENT:\n            return '<DOC>';\n        case FLOW_END:\n            return '<FLOW_END>';\n        case SCALAR:\n            return '<SCALAR>';\n        default:\n            return JSON.stringify(token);\n    }\n}\n/** Identify the type of a lexer token. May return `null` for unknown tokens. */\nfunction tokenType(source) {\n    switch (source) {\n        case BOM:\n            return 'byte-order-mark';\n        case DOCUMENT:\n            return 'doc-mode';\n        case FLOW_END:\n            return 'flow-error-end';\n        case SCALAR:\n            return 'scalar';\n        case '---':\n            return 'doc-start';\n        case '...':\n            return 'doc-end';\n        case '':\n        case '\\n':\n        case '\\r\\n':\n            return 'newline';\n        case '-':\n            return 'seq-item-ind';\n        case '?':\n            return 'explicit-key-ind';\n        case ':':\n            return 'map-value-ind';\n        case '{':\n            return 'flow-map-start';\n        case '}':\n            return 'flow-map-end';\n        case '[':\n            return 'flow-seq-start';\n        case ']':\n            return 'flow-seq-end';\n        case ',':\n            return 'comma';\n    }\n    switch (source[0]) {\n        case ' ':\n        case '\\t':\n            return 'space';\n        case '#':\n            return 'comment';\n        case '%':\n            return 'directive-line';\n        case '*':\n            return 'alias';\n        case '&':\n            return 'anchor';\n        case '!':\n            return 'tag';\n        case \"'\":\n            return 'single-quoted-scalar';\n        case '\"':\n            return 'double-quoted-scalar';\n        case '|':\n        case '>':\n            return 'block-scalar-header';\n    }\n    return null;\n}\n\nexports.createScalarToken = cstScalar.createScalarToken;\nexports.resolveAsScalar = cstScalar.resolveAsScalar;\nexports.setScalarValue = cstScalar.setScalarValue;\nexports.stringify = cstStringify.stringify;\nexports.visit = cstVisit.visit;\nexports.BOM = BOM;\nexports.DOCUMENT = DOCUMENT;\nexports.FLOW_END = FLOW_END;\nexports.SCALAR = SCALAR;\nexports.isCollection = isCollection;\nexports.isScalar = isScalar;\nexports.prettyToken = prettyToken;\nexports.tokenType = tokenType;\n","'use strict';\n\nvar cst = require('./cst.js');\n\n/*\nSTART -> stream\n\nstream\n  directive -> line-end -> stream\n  indent + line-end -> stream\n  [else] -> line-start\n\nline-end\n  comment -> line-end\n  newline -> .\n  input-end -> END\n\nline-start\n  doc-start -> doc\n  doc-end -> stream\n  [else] -> indent -> block-start\n\nblock-start\n  seq-item-start -> block-start\n  explicit-key-start -> block-start\n  map-value-start -> block-start\n  [else] -> doc\n\ndoc\n  line-end -> line-start\n  spaces -> doc\n  anchor -> doc\n  tag -> doc\n  flow-start -> flow -> doc\n  flow-end -> error -> doc\n  seq-item-start -> error -> doc\n  explicit-key-start -> error -> doc\n  map-value-start -> doc\n  alias -> doc\n  quote-start -> quoted-scalar -> doc\n  block-scalar-header -> line-end -> block-scalar(min) -> line-start\n  [else] -> plain-scalar(false, min) -> doc\n\nflow\n  line-end -> flow\n  spaces -> flow\n  anchor -> flow\n  tag -> flow\n  flow-start -> flow -> flow\n  flow-end -> .\n  seq-item-start -> error -> flow\n  explicit-key-start -> flow\n  map-value-start -> flow\n  alias -> flow\n  quote-start -> quoted-scalar -> flow\n  comma -> flow\n  [else] -> plain-scalar(true, 0) -> flow\n\nquoted-scalar\n  quote-end -> .\n  [else] -> quoted-scalar\n\nblock-scalar(min)\n  newline + peek(indent < min) -> .\n  [else] -> block-scalar(min)\n\nplain-scalar(is-flow, min)\n  scalar-end(is-flow) -> .\n  peek(newline + (indent < min)) -> .\n  [else] -> plain-scalar(min)\n*/\nfunction isEmpty(ch) {\n    switch (ch) {\n        case undefined:\n        case ' ':\n        case '\\n':\n        case '\\r':\n        case '\\t':\n            return true;\n        default:\n            return false;\n    }\n}\nconst hexDigits = new Set('0123456789ABCDEFabcdef');\nconst tagChars = new Set(\"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()\");\nconst flowIndicatorChars = new Set(',[]{}');\nconst invalidAnchorChars = new Set(' ,[]{}\\n\\r\\t');\nconst isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch);\n/**\n * Splits an input string into lexical tokens, i.e. smaller strings that are\n * easily identifiable by `tokens.tokenType()`.\n *\n * Lexing starts always in a \"stream\" context. Incomplete input may be buffered\n * until a complete token can be emitted.\n *\n * In addition to slices of the original input, the following control characters\n * may also be emitted:\n *\n * - `\\x02` (Start of Text): A document starts with the next token\n * - `\\x18` (Cancel): Unexpected end of flow-mode (indicates an error)\n * - `\\x1f` (Unit Separator): Next token is a scalar value\n * - `\\u{FEFF}` (Byte order mark): Emitted separately outside documents\n */\nclass Lexer {\n    constructor() {\n        /**\n         * Flag indicating whether the end of the current buffer marks the end of\n         * all input\n         */\n        this.atEnd = false;\n        /**\n         * Explicit indent set in block scalar header, as an offset from the current\n         * minimum indent, so e.g. set to 1 from a header `|2+`. Set to -1 if not\n         * explicitly set.\n         */\n        this.blockScalarIndent = -1;\n        /**\n         * Block scalars that include a + (keep) chomping indicator in their header\n         * include trailing empty lines, which are otherwise excluded from the\n         * scalar's contents.\n         */\n        this.blockScalarKeep = false;\n        /** Current input */\n        this.buffer = '';\n        /**\n         * Flag noting whether the map value indicator : can immediately follow this\n         * node within a flow context.\n         */\n        this.flowKey = false;\n        /** Count of surrounding flow collection levels. */\n        this.flowLevel = 0;\n        /**\n         * Minimum level of indentation required for next lines to be parsed as a\n         * part of the current scalar value.\n         */\n        this.indentNext = 0;\n        /** Indentation level of the current line. */\n        this.indentValue = 0;\n        /** Position of the next \\n character. */\n        this.lineEndPos = null;\n        /** Stores the state of the lexer if reaching the end of incpomplete input */\n        this.next = null;\n        /** A pointer to `buffer`; the current position of the lexer. */\n        this.pos = 0;\n    }\n    /**\n     * Generate YAML tokens from the `source` string. If `incomplete`,\n     * a part of the last line may be left as a buffer for the next call.\n     *\n     * @returns A generator of lexical tokens\n     */\n    *lex(source, incomplete = false) {\n        if (source) {\n            if (typeof source !== 'string')\n                throw TypeError('source is not a string');\n            this.buffer = this.buffer ? this.buffer + source : source;\n            this.lineEndPos = null;\n        }\n        this.atEnd = !incomplete;\n        let next = this.next ?? 'stream';\n        while (next && (incomplete || this.hasChars(1)))\n            next = yield* this.parseNext(next);\n    }\n    atLineEnd() {\n        let i = this.pos;\n        let ch = this.buffer[i];\n        while (ch === ' ' || ch === '\\t')\n            ch = this.buffer[++i];\n        if (!ch || ch === '#' || ch === '\\n')\n            return true;\n        if (ch === '\\r')\n            return this.buffer[i + 1] === '\\n';\n        return false;\n    }\n    charAt(n) {\n        return this.buffer[this.pos + n];\n    }\n    continueScalar(offset) {\n        let ch = this.buffer[offset];\n        if (this.indentNext > 0) {\n            let indent = 0;\n            while (ch === ' ')\n                ch = this.buffer[++indent + offset];\n            if (ch === '\\r') {\n                const next = this.buffer[indent + offset + 1];\n                if (next === '\\n' || (!next && !this.atEnd))\n                    return offset + indent + 1;\n            }\n            return ch === '\\n' || indent >= this.indentNext || (!ch && !this.atEnd)\n                ? offset + indent\n                : -1;\n        }\n        if (ch === '-' || ch === '.') {\n            const dt = this.buffer.substr(offset, 3);\n            if ((dt === '---' || dt === '...') && isEmpty(this.buffer[offset + 3]))\n                return -1;\n        }\n        return offset;\n    }\n    getLine() {\n        let end = this.lineEndPos;\n        if (typeof end !== 'number' || (end !== -1 && end < this.pos)) {\n            end = this.buffer.indexOf('\\n', this.pos);\n            this.lineEndPos = end;\n        }\n        if (end === -1)\n            return this.atEnd ? this.buffer.substring(this.pos) : null;\n        if (this.buffer[end - 1] === '\\r')\n            end -= 1;\n        return this.buffer.substring(this.pos, end);\n    }\n    hasChars(n) {\n        return this.pos + n <= this.buffer.length;\n    }\n    setNext(state) {\n        this.buffer = this.buffer.substring(this.pos);\n        this.pos = 0;\n        this.lineEndPos = null;\n        this.next = state;\n        return null;\n    }\n    peek(n) {\n        return this.buffer.substr(this.pos, n);\n    }\n    *parseNext(next) {\n        switch (next) {\n            case 'stream':\n                return yield* this.parseStream();\n            case 'line-start':\n                return yield* this.parseLineStart();\n            case 'block-start':\n                return yield* this.parseBlockStart();\n            case 'doc':\n                return yield* this.parseDocument();\n            case 'flow':\n                return yield* this.parseFlowCollection();\n            case 'quoted-scalar':\n                return yield* this.parseQuotedScalar();\n            case 'block-scalar':\n                return yield* this.parseBlockScalar();\n            case 'plain-scalar':\n                return yield* this.parsePlainScalar();\n        }\n    }\n    *parseStream() {\n        let line = this.getLine();\n        if (line === null)\n            return this.setNext('stream');\n        if (line[0] === cst.BOM) {\n            yield* this.pushCount(1);\n            line = line.substring(1);\n        }\n        if (line[0] === '%') {\n            let dirEnd = line.length;\n            let cs = line.indexOf('#');\n            while (cs !== -1) {\n                const ch = line[cs - 1];\n                if (ch === ' ' || ch === '\\t') {\n                    dirEnd = cs - 1;\n                    break;\n                }\n                else {\n                    cs = line.indexOf('#', cs + 1);\n                }\n            }\n            while (true) {\n                const ch = line[dirEnd - 1];\n                if (ch === ' ' || ch === '\\t')\n                    dirEnd -= 1;\n                else\n                    break;\n            }\n            const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true));\n            yield* this.pushCount(line.length - n); // possible comment\n            this.pushNewline();\n            return 'stream';\n        }\n        if (this.atLineEnd()) {\n            const sp = yield* this.pushSpaces(true);\n            yield* this.pushCount(line.length - sp);\n            yield* this.pushNewline();\n            return 'stream';\n        }\n        yield cst.DOCUMENT;\n        return yield* this.parseLineStart();\n    }\n    *parseLineStart() {\n        const ch = this.charAt(0);\n        if (!ch && !this.atEnd)\n            return this.setNext('line-start');\n        if (ch === '-' || ch === '.') {\n            if (!this.atEnd && !this.hasChars(4))\n                return this.setNext('line-start');\n            const s = this.peek(3);\n            if ((s === '---' || s === '...') && isEmpty(this.charAt(3))) {\n                yield* this.pushCount(3);\n                this.indentValue = 0;\n                this.indentNext = 0;\n                return s === '---' ? 'doc' : 'stream';\n            }\n        }\n        this.indentValue = yield* this.pushSpaces(false);\n        if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1)))\n            this.indentNext = this.indentValue;\n        return yield* this.parseBlockStart();\n    }\n    *parseBlockStart() {\n        const [ch0, ch1] = this.peek(2);\n        if (!ch1 && !this.atEnd)\n            return this.setNext('block-start');\n        if ((ch0 === '-' || ch0 === '?' || ch0 === ':') && isEmpty(ch1)) {\n            const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true));\n            this.indentNext = this.indentValue + 1;\n            this.indentValue += n;\n            return 'block-start';\n        }\n        return 'doc';\n    }\n    *parseDocument() {\n        yield* this.pushSpaces(true);\n        const line = this.getLine();\n        if (line === null)\n            return this.setNext('doc');\n        let n = yield* this.pushIndicators();\n        switch (line[n]) {\n            case '#':\n                yield* this.pushCount(line.length - n);\n            // fallthrough\n            case undefined:\n                yield* this.pushNewline();\n                return yield* this.parseLineStart();\n            case '{':\n            case '[':\n                yield* this.pushCount(1);\n                this.flowKey = false;\n                this.flowLevel = 1;\n                return 'flow';\n            case '}':\n            case ']':\n                // this is an error\n                yield* this.pushCount(1);\n                return 'doc';\n            case '*':\n                yield* this.pushUntil(isNotAnchorChar);\n                return 'doc';\n            case '\"':\n            case \"'\":\n                return yield* this.parseQuotedScalar();\n            case '|':\n            case '>':\n                n += yield* this.parseBlockScalarHeader();\n                n += yield* this.pushSpaces(true);\n                yield* this.pushCount(line.length - n);\n                yield* this.pushNewline();\n                return yield* this.parseBlockScalar();\n            default:\n                return yield* this.parsePlainScalar();\n        }\n    }\n    *parseFlowCollection() {\n        let nl, sp;\n        let indent = -1;\n        do {\n            nl = yield* this.pushNewline();\n            if (nl > 0) {\n                sp = yield* this.pushSpaces(false);\n                this.indentValue = indent = sp;\n            }\n            else {\n                sp = 0;\n            }\n            sp += yield* this.pushSpaces(true);\n        } while (nl + sp > 0);\n        const line = this.getLine();\n        if (line === null)\n            return this.setNext('flow');\n        if ((indent !== -1 && indent < this.indentNext && line[0] !== '#') ||\n            (indent === 0 &&\n                (line.startsWith('---') || line.startsWith('...')) &&\n                isEmpty(line[3]))) {\n            // Allowing for the terminal ] or } at the same (rather than greater)\n            // indent level as the initial [ or { is technically invalid, but\n            // failing here would be surprising to users.\n            const atFlowEndMarker = indent === this.indentNext - 1 &&\n                this.flowLevel === 1 &&\n                (line[0] === ']' || line[0] === '}');\n            if (!atFlowEndMarker) {\n                // this is an error\n                this.flowLevel = 0;\n                yield cst.FLOW_END;\n                return yield* this.parseLineStart();\n            }\n        }\n        let n = 0;\n        while (line[n] === ',') {\n            n += yield* this.pushCount(1);\n            n += yield* this.pushSpaces(true);\n            this.flowKey = false;\n        }\n        n += yield* this.pushIndicators();\n        switch (line[n]) {\n            case undefined:\n                return 'flow';\n            case '#':\n                yield* this.pushCount(line.length - n);\n                return 'flow';\n            case '{':\n            case '[':\n                yield* this.pushCount(1);\n                this.flowKey = false;\n                this.flowLevel += 1;\n                return 'flow';\n            case '}':\n            case ']':\n                yield* this.pushCount(1);\n                this.flowKey = true;\n                this.flowLevel -= 1;\n                return this.flowLevel ? 'flow' : 'doc';\n            case '*':\n                yield* this.pushUntil(isNotAnchorChar);\n                return 'flow';\n            case '\"':\n            case \"'\":\n                this.flowKey = true;\n                return yield* this.parseQuotedScalar();\n            case ':': {\n                const next = this.charAt(1);\n                if (this.flowKey || isEmpty(next) || next === ',') {\n                    this.flowKey = false;\n                    yield* this.pushCount(1);\n                    yield* this.pushSpaces(true);\n                    return 'flow';\n                }\n            }\n            // fallthrough\n            default:\n                this.flowKey = false;\n                return yield* this.parsePlainScalar();\n        }\n    }\n    *parseQuotedScalar() {\n        const quote = this.charAt(0);\n        let end = this.buffer.indexOf(quote, this.pos + 1);\n        if (quote === \"'\") {\n            while (end !== -1 && this.buffer[end + 1] === \"'\")\n                end = this.buffer.indexOf(\"'\", end + 2);\n        }\n        else {\n            // double-quote\n            while (end !== -1) {\n                let n = 0;\n                while (this.buffer[end - 1 - n] === '\\\\')\n                    n += 1;\n                if (n % 2 === 0)\n                    break;\n                end = this.buffer.indexOf('\"', end + 1);\n            }\n        }\n        // Only looking for newlines within the quotes\n        const qb = this.buffer.substring(0, end);\n        let nl = qb.indexOf('\\n', this.pos);\n        if (nl !== -1) {\n            while (nl !== -1) {\n                const cs = this.continueScalar(nl + 1);\n                if (cs === -1)\n                    break;\n                nl = qb.indexOf('\\n', cs);\n            }\n            if (nl !== -1) {\n                // this is an error caused by an unexpected unindent\n                end = nl - (qb[nl - 1] === '\\r' ? 2 : 1);\n            }\n        }\n        if (end === -1) {\n            if (!this.atEnd)\n                return this.setNext('quoted-scalar');\n            end = this.buffer.length;\n        }\n        yield* this.pushToIndex(end + 1, false);\n        return this.flowLevel ? 'flow' : 'doc';\n    }\n    *parseBlockScalarHeader() {\n        this.blockScalarIndent = -1;\n        this.blockScalarKeep = false;\n        let i = this.pos;\n        while (true) {\n            const ch = this.buffer[++i];\n            if (ch === '+')\n                this.blockScalarKeep = true;\n            else if (ch > '0' && ch <= '9')\n                this.blockScalarIndent = Number(ch) - 1;\n            else if (ch !== '-')\n                break;\n        }\n        return yield* this.pushUntil(ch => isEmpty(ch) || ch === '#');\n    }\n    *parseBlockScalar() {\n        let nl = this.pos - 1; // may be -1 if this.pos === 0\n        let indent = 0;\n        let ch;\n        loop: for (let i = this.pos; (ch = this.buffer[i]); ++i) {\n            switch (ch) {\n                case ' ':\n                    indent += 1;\n                    break;\n                case '\\n':\n                    nl = i;\n                    indent = 0;\n                    break;\n                case '\\r': {\n                    const next = this.buffer[i + 1];\n                    if (!next && !this.atEnd)\n                        return this.setNext('block-scalar');\n                    if (next === '\\n')\n                        break;\n                } // fallthrough\n                default:\n                    break loop;\n            }\n        }\n        if (!ch && !this.atEnd)\n            return this.setNext('block-scalar');\n        if (indent >= this.indentNext) {\n            if (this.blockScalarIndent === -1)\n                this.indentNext = indent;\n            else {\n                this.indentNext =\n                    this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext);\n            }\n            do {\n                const cs = this.continueScalar(nl + 1);\n                if (cs === -1)\n                    break;\n                nl = this.buffer.indexOf('\\n', cs);\n            } while (nl !== -1);\n            if (nl === -1) {\n                if (!this.atEnd)\n                    return this.setNext('block-scalar');\n                nl = this.buffer.length;\n            }\n        }\n        // Trailing insufficiently indented tabs are invalid.\n        // To catch that during parsing, we include them in the block scalar value.\n        let i = nl + 1;\n        ch = this.buffer[i];\n        while (ch === ' ')\n            ch = this.buffer[++i];\n        if (ch === '\\t') {\n            while (ch === '\\t' || ch === ' ' || ch === '\\r' || ch === '\\n')\n                ch = this.buffer[++i];\n            nl = i - 1;\n        }\n        else if (!this.blockScalarKeep) {\n            do {\n                let i = nl - 1;\n                let ch = this.buffer[i];\n                if (ch === '\\r')\n                    ch = this.buffer[--i];\n                const lastChar = i; // Drop the line if last char not more indented\n                while (ch === ' ')\n                    ch = this.buffer[--i];\n                if (ch === '\\n' && i >= this.pos && i + 1 + indent > lastChar)\n                    nl = i;\n                else\n                    break;\n            } while (true);\n        }\n        yield cst.SCALAR;\n        yield* this.pushToIndex(nl + 1, true);\n        return yield* this.parseLineStart();\n    }\n    *parsePlainScalar() {\n        const inFlow = this.flowLevel > 0;\n        let end = this.pos - 1;\n        let i = this.pos - 1;\n        let ch;\n        while ((ch = this.buffer[++i])) {\n            if (ch === ':') {\n                const next = this.buffer[i + 1];\n                if (isEmpty(next) || (inFlow && flowIndicatorChars.has(next)))\n                    break;\n                end = i;\n            }\n            else if (isEmpty(ch)) {\n                let next = this.buffer[i + 1];\n                if (ch === '\\r') {\n                    if (next === '\\n') {\n                        i += 1;\n                        ch = '\\n';\n                        next = this.buffer[i + 1];\n                    }\n                    else\n                        end = i;\n                }\n                if (next === '#' || (inFlow && flowIndicatorChars.has(next)))\n                    break;\n                if (ch === '\\n') {\n                    const cs = this.continueScalar(i + 1);\n                    if (cs === -1)\n                        break;\n                    i = Math.max(i, cs - 2); // to advance, but still account for ' #'\n                }\n            }\n            else {\n                if (inFlow && flowIndicatorChars.has(ch))\n                    break;\n                end = i;\n            }\n        }\n        if (!ch && !this.atEnd)\n            return this.setNext('plain-scalar');\n        yield cst.SCALAR;\n        yield* this.pushToIndex(end + 1, true);\n        return inFlow ? 'flow' : 'doc';\n    }\n    *pushCount(n) {\n        if (n > 0) {\n            yield this.buffer.substr(this.pos, n);\n            this.pos += n;\n            return n;\n        }\n        return 0;\n    }\n    *pushToIndex(i, allowEmpty) {\n        const s = this.buffer.slice(this.pos, i);\n        if (s) {\n            yield s;\n            this.pos += s.length;\n            return s.length;\n        }\n        else if (allowEmpty)\n            yield '';\n        return 0;\n    }\n    *pushIndicators() {\n        let n = 0;\n        loop: while (true) {\n            switch (this.charAt(0)) {\n                case '!':\n                    n += yield* this.pushTag();\n                    n += yield* this.pushSpaces(true);\n                    continue loop;\n                case '&':\n                    n += yield* this.pushUntil(isNotAnchorChar);\n                    n += yield* this.pushSpaces(true);\n                    continue loop;\n                case '-': // this is an error\n                case '?': // this is an error outside flow collections\n                case ':': {\n                    const inFlow = this.flowLevel > 0;\n                    const ch1 = this.charAt(1);\n                    if (isEmpty(ch1) || (inFlow && flowIndicatorChars.has(ch1))) {\n                        if (!inFlow)\n                            this.indentNext = this.indentValue + 1;\n                        else if (this.flowKey)\n                            this.flowKey = false;\n                        n += yield* this.pushCount(1);\n                        n += yield* this.pushSpaces(true);\n                        continue loop;\n                    }\n                }\n            }\n            break loop;\n        }\n        return n;\n    }\n    *pushTag() {\n        if (this.charAt(1) === '<') {\n            let i = this.pos + 2;\n            let ch = this.buffer[i];\n            while (!isEmpty(ch) && ch !== '>')\n                ch = this.buffer[++i];\n            return yield* this.pushToIndex(ch === '>' ? i + 1 : i, false);\n        }\n        else {\n            let i = this.pos + 1;\n            let ch = this.buffer[i];\n            while (ch) {\n                if (tagChars.has(ch))\n                    ch = this.buffer[++i];\n                else if (ch === '%' &&\n                    hexDigits.has(this.buffer[i + 1]) &&\n                    hexDigits.has(this.buffer[i + 2])) {\n                    ch = this.buffer[(i += 3)];\n                }\n                else\n                    break;\n            }\n            return yield* this.pushToIndex(i, false);\n        }\n    }\n    *pushNewline() {\n        const ch = this.buffer[this.pos];\n        if (ch === '\\n')\n            return yield* this.pushCount(1);\n        else if (ch === '\\r' && this.charAt(1) === '\\n')\n            return yield* this.pushCount(2);\n        else\n            return 0;\n    }\n    *pushSpaces(allowTabs) {\n        let i = this.pos - 1;\n        let ch;\n        do {\n            ch = this.buffer[++i];\n        } while (ch === ' ' || (allowTabs && ch === '\\t'));\n        const n = i - this.pos;\n        if (n > 0) {\n            yield this.buffer.substr(this.pos, n);\n            this.pos = i;\n        }\n        return n;\n    }\n    *pushUntil(test) {\n        let i = this.pos;\n        let ch = this.buffer[i];\n        while (!test(ch))\n            ch = this.buffer[++i];\n        return yield* this.pushToIndex(i, false);\n    }\n}\n\nexports.Lexer = Lexer;\n","'use strict';\n\n/**\n * Tracks newlines during parsing in order to provide an efficient API for\n * determining the one-indexed `{ line, col }` position for any offset\n * within the input.\n */\nclass LineCounter {\n    constructor() {\n        this.lineStarts = [];\n        /**\n         * Should be called in ascending order. Otherwise, call\n         * `lineCounter.lineStarts.sort()` before calling `linePos()`.\n         */\n        this.addNewLine = (offset) => this.lineStarts.push(offset);\n        /**\n         * Performs a binary search and returns the 1-indexed { line, col }\n         * position of `offset`. If `line === 0`, `addNewLine` has never been\n         * called or `offset` is before the first known newline.\n         */\n        this.linePos = (offset) => {\n            let low = 0;\n            let high = this.lineStarts.length;\n            while (low < high) {\n                const mid = (low + high) >> 1; // Math.floor((low + high) / 2)\n                if (this.lineStarts[mid] < offset)\n                    low = mid + 1;\n                else\n                    high = mid;\n            }\n            if (this.lineStarts[low] === offset)\n                return { line: low + 1, col: 1 };\n            if (low === 0)\n                return { line: 0, col: offset };\n            const start = this.lineStarts[low - 1];\n            return { line: low, col: offset - start + 1 };\n        };\n    }\n}\n\nexports.LineCounter = LineCounter;\n","'use strict';\n\nvar node_process = require('process');\nvar cst = require('./cst.js');\nvar lexer = require('./lexer.js');\n\nfunction includesToken(list, type) {\n    for (let i = 0; i < list.length; ++i)\n        if (list[i].type === type)\n            return true;\n    return false;\n}\nfunction findNonEmptyIndex(list) {\n    for (let i = 0; i < list.length; ++i) {\n        switch (list[i].type) {\n            case 'space':\n            case 'comment':\n            case 'newline':\n                break;\n            default:\n                return i;\n        }\n    }\n    return -1;\n}\nfunction isFlowToken(token) {\n    switch (token?.type) {\n        case 'alias':\n        case 'scalar':\n        case 'single-quoted-scalar':\n        case 'double-quoted-scalar':\n        case 'flow-collection':\n            return true;\n        default:\n            return false;\n    }\n}\nfunction getPrevProps(parent) {\n    switch (parent.type) {\n        case 'document':\n            return parent.start;\n        case 'block-map': {\n            const it = parent.items[parent.items.length - 1];\n            return it.sep ?? it.start;\n        }\n        case 'block-seq':\n            return parent.items[parent.items.length - 1].start;\n        /* istanbul ignore next should not happen */\n        default:\n            return [];\n    }\n}\n/** Note: May modify input array */\nfunction getFirstKeyStartProps(prev) {\n    if (prev.length === 0)\n        return [];\n    let i = prev.length;\n    loop: while (--i >= 0) {\n        switch (prev[i].type) {\n            case 'doc-start':\n            case 'explicit-key-ind':\n            case 'map-value-ind':\n            case 'seq-item-ind':\n            case 'newline':\n                break loop;\n        }\n    }\n    while (prev[++i]?.type === 'space') {\n        /* loop */\n    }\n    return prev.splice(i, prev.length);\n}\nfunction arrayPushArray(target, source) {\n    // May exhaust call stack with large `source` array\n    if (source.length < 1e5)\n        Array.prototype.push.apply(target, source);\n    else\n        for (let i = 0; i < source.length; ++i)\n            target.push(source[i]);\n}\nfunction fixFlowSeqItems(fc) {\n    if (fc.start.type === 'flow-seq-start') {\n        for (const it of fc.items) {\n            if (it.sep &&\n                !it.value &&\n                !includesToken(it.start, 'explicit-key-ind') &&\n                !includesToken(it.sep, 'map-value-ind')) {\n                if (it.key)\n                    it.value = it.key;\n                delete it.key;\n                if (isFlowToken(it.value)) {\n                    if (it.value.end)\n                        arrayPushArray(it.value.end, it.sep);\n                    else\n                        it.value.end = it.sep;\n                }\n                else\n                    arrayPushArray(it.start, it.sep);\n                delete it.sep;\n            }\n        }\n    }\n}\n/**\n * A YAML concrete syntax tree (CST) parser\n *\n * ```ts\n * const src: string = ...\n * for (const token of new Parser().parse(src)) {\n *   // token: Token\n * }\n * ```\n *\n * To use the parser with a user-provided lexer:\n *\n * ```ts\n * function* parse(source: string, lexer: Lexer) {\n *   const parser = new Parser()\n *   for (const lexeme of lexer.lex(source))\n *     yield* parser.next(lexeme)\n *   yield* parser.end()\n * }\n *\n * const src: string = ...\n * const lexer = new Lexer()\n * for (const token of parse(src, lexer)) {\n *   // token: Token\n * }\n * ```\n */\nclass Parser {\n    /**\n     * @param onNewLine - If defined, called separately with the start position of\n     *   each new line (in `parse()`, including the start of input).\n     */\n    constructor(onNewLine) {\n        /** If true, space and sequence indicators count as indentation */\n        this.atNewLine = true;\n        /** If true, next token is a scalar value */\n        this.atScalar = false;\n        /** Current indentation level */\n        this.indent = 0;\n        /** Current offset since the start of parsing */\n        this.offset = 0;\n        /** On the same line with a block map key */\n        this.onKeyLine = false;\n        /** Top indicates the node that's currently being built */\n        this.stack = [];\n        /** The source of the current token, set in parse() */\n        this.source = '';\n        /** The type of the current token, set in parse() */\n        this.type = '';\n        // Must be defined after `next()`\n        this.lexer = new lexer.Lexer();\n        this.onNewLine = onNewLine;\n    }\n    /**\n     * Parse `source` as a YAML stream.\n     * If `incomplete`, a part of the last line may be left as a buffer for the next call.\n     *\n     * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens.\n     *\n     * @returns A generator of tokens representing each directive, document, and other structure.\n     */\n    *parse(source, incomplete = false) {\n        if (this.onNewLine && this.offset === 0)\n            this.onNewLine(0);\n        for (const lexeme of this.lexer.lex(source, incomplete))\n            yield* this.next(lexeme);\n        if (!incomplete)\n            yield* this.end();\n    }\n    /**\n     * Advance the parser by the `source` of one lexical token.\n     */\n    *next(source) {\n        this.source = source;\n        if (node_process.env.LOG_TOKENS)\n            console.log('|', cst.prettyToken(source));\n        if (this.atScalar) {\n            this.atScalar = false;\n            yield* this.step();\n            this.offset += source.length;\n            return;\n        }\n        const type = cst.tokenType(source);\n        if (!type) {\n            const message = `Not a YAML token: ${source}`;\n            yield* this.pop({ type: 'error', offset: this.offset, message, source });\n            this.offset += source.length;\n        }\n        else if (type === 'scalar') {\n            this.atNewLine = false;\n            this.atScalar = true;\n            this.type = 'scalar';\n        }\n        else {\n            this.type = type;\n            yield* this.step();\n            switch (type) {\n                case 'newline':\n                    this.atNewLine = true;\n                    this.indent = 0;\n                    if (this.onNewLine)\n                        this.onNewLine(this.offset + source.length);\n                    break;\n                case 'space':\n                    if (this.atNewLine && source[0] === ' ')\n                        this.indent += source.length;\n                    break;\n                case 'explicit-key-ind':\n                case 'map-value-ind':\n                case 'seq-item-ind':\n                    if (this.atNewLine)\n                        this.indent += source.length;\n                    break;\n                case 'doc-mode':\n                case 'flow-error-end':\n                    return;\n                default:\n                    this.atNewLine = false;\n            }\n            this.offset += source.length;\n        }\n    }\n    /** Call at end of input to push out any remaining constructions */\n    *end() {\n        while (this.stack.length > 0)\n            yield* this.pop();\n    }\n    get sourceToken() {\n        const st = {\n            type: this.type,\n            offset: this.offset,\n            indent: this.indent,\n            source: this.source\n        };\n        return st;\n    }\n    *step() {\n        const top = this.peek(1);\n        if (this.type === 'doc-end' && top?.type !== 'doc-end') {\n            while (this.stack.length > 0)\n                yield* this.pop();\n            this.stack.push({\n                type: 'doc-end',\n                offset: this.offset,\n                source: this.source\n            });\n            return;\n        }\n        if (!top)\n            return yield* this.stream();\n        switch (top.type) {\n            case 'document':\n                return yield* this.document(top);\n            case 'alias':\n            case 'scalar':\n            case 'single-quoted-scalar':\n            case 'double-quoted-scalar':\n                return yield* this.scalar(top);\n            case 'block-scalar':\n                return yield* this.blockScalar(top);\n            case 'block-map':\n                return yield* this.blockMap(top);\n            case 'block-seq':\n                return yield* this.blockSequence(top);\n            case 'flow-collection':\n                return yield* this.flowCollection(top);\n            case 'doc-end':\n                return yield* this.documentEnd(top);\n        }\n        /* istanbul ignore next should not happen */\n        yield* this.pop();\n    }\n    peek(n) {\n        return this.stack[this.stack.length - n];\n    }\n    *pop(error) {\n        const token = error ?? this.stack.pop();\n        /* istanbul ignore if should not happen */\n        if (!token) {\n            const message = 'Tried to pop an empty stack';\n            yield { type: 'error', offset: this.offset, source: '', message };\n        }\n        else if (this.stack.length === 0) {\n            yield token;\n        }\n        else {\n            const top = this.peek(1);\n            if (token.type === 'block-scalar') {\n                // Block scalars use their parent rather than header indent\n                token.indent = 'indent' in top ? top.indent : 0;\n            }\n            else if (token.type === 'flow-collection' && top.type === 'document') {\n                // Ignore all indent for top-level flow collections\n                token.indent = 0;\n            }\n            if (token.type === 'flow-collection')\n                fixFlowSeqItems(token);\n            switch (top.type) {\n                case 'document':\n                    top.value = token;\n                    break;\n                case 'block-scalar':\n                    top.props.push(token); // error\n                    break;\n                case 'block-map': {\n                    const it = top.items[top.items.length - 1];\n                    if (it.value) {\n                        top.items.push({ start: [], key: token, sep: [] });\n                        this.onKeyLine = true;\n                        return;\n                    }\n                    else if (it.sep) {\n                        it.value = token;\n                    }\n                    else {\n                        Object.assign(it, { key: token, sep: [] });\n                        this.onKeyLine = !it.explicitKey;\n                        return;\n                    }\n                    break;\n                }\n                case 'block-seq': {\n                    const it = top.items[top.items.length - 1];\n                    if (it.value)\n                        top.items.push({ start: [], value: token });\n                    else\n                        it.value = token;\n                    break;\n                }\n                case 'flow-collection': {\n                    const it = top.items[top.items.length - 1];\n                    if (!it || it.value)\n                        top.items.push({ start: [], key: token, sep: [] });\n                    else if (it.sep)\n                        it.value = token;\n                    else\n                        Object.assign(it, { key: token, sep: [] });\n                    return;\n                }\n                /* istanbul ignore next should not happen */\n                default:\n                    yield* this.pop();\n                    yield* this.pop(token);\n            }\n            if ((top.type === 'document' ||\n                top.type === 'block-map' ||\n                top.type === 'block-seq') &&\n                (token.type === 'block-map' || token.type === 'block-seq')) {\n                const last = token.items[token.items.length - 1];\n                if (last &&\n                    !last.sep &&\n                    !last.value &&\n                    last.start.length > 0 &&\n                    findNonEmptyIndex(last.start) === -1 &&\n                    (token.indent === 0 ||\n                        last.start.every(st => st.type !== 'comment' || st.indent < token.indent))) {\n                    if (top.type === 'document')\n                        top.end = last.start;\n                    else\n                        top.items.push({ start: last.start });\n                    token.items.splice(-1, 1);\n                }\n            }\n        }\n    }\n    *stream() {\n        switch (this.type) {\n            case 'directive-line':\n                yield { type: 'directive', offset: this.offset, source: this.source };\n                return;\n            case 'byte-order-mark':\n            case 'space':\n            case 'comment':\n            case 'newline':\n                yield this.sourceToken;\n                return;\n            case 'doc-mode':\n            case 'doc-start': {\n                const doc = {\n                    type: 'document',\n                    offset: this.offset,\n                    start: []\n                };\n                if (this.type === 'doc-start')\n                    doc.start.push(this.sourceToken);\n                this.stack.push(doc);\n                return;\n            }\n        }\n        yield {\n            type: 'error',\n            offset: this.offset,\n            message: `Unexpected ${this.type} token in YAML stream`,\n            source: this.source\n        };\n    }\n    *document(doc) {\n        if (doc.value)\n            return yield* this.lineEnd(doc);\n        switch (this.type) {\n            case 'doc-start': {\n                if (findNonEmptyIndex(doc.start) !== -1) {\n                    yield* this.pop();\n                    yield* this.step();\n                }\n                else\n                    doc.start.push(this.sourceToken);\n                return;\n            }\n            case 'anchor':\n            case 'tag':\n            case 'space':\n            case 'comment':\n            case 'newline':\n                doc.start.push(this.sourceToken);\n                return;\n        }\n        const bv = this.startBlockValue(doc);\n        if (bv)\n            this.stack.push(bv);\n        else {\n            yield {\n                type: 'error',\n                offset: this.offset,\n                message: `Unexpected ${this.type} token in YAML document`,\n                source: this.source\n            };\n        }\n    }\n    *scalar(scalar) {\n        if (this.type === 'map-value-ind') {\n            const prev = getPrevProps(this.peek(2));\n            const start = getFirstKeyStartProps(prev);\n            let sep;\n            if (scalar.end) {\n                sep = scalar.end;\n                sep.push(this.sourceToken);\n                delete scalar.end;\n            }\n            else\n                sep = [this.sourceToken];\n            const map = {\n                type: 'block-map',\n                offset: scalar.offset,\n                indent: scalar.indent,\n                items: [{ start, key: scalar, sep }]\n            };\n            this.onKeyLine = true;\n            this.stack[this.stack.length - 1] = map;\n        }\n        else\n            yield* this.lineEnd(scalar);\n    }\n    *blockScalar(scalar) {\n        switch (this.type) {\n            case 'space':\n            case 'comment':\n            case 'newline':\n                scalar.props.push(this.sourceToken);\n                return;\n            case 'scalar':\n                scalar.source = this.source;\n                // block-scalar source includes trailing newline\n                this.atNewLine = true;\n                this.indent = 0;\n                if (this.onNewLine) {\n                    let nl = this.source.indexOf('\\n') + 1;\n                    while (nl !== 0) {\n                        this.onNewLine(this.offset + nl);\n                        nl = this.source.indexOf('\\n', nl) + 1;\n                    }\n                }\n                yield* this.pop();\n                break;\n            /* istanbul ignore next should not happen */\n            default:\n                yield* this.pop();\n                yield* this.step();\n        }\n    }\n    *blockMap(map) {\n        const it = map.items[map.items.length - 1];\n        // it.sep is true-ish if pair already has key or : separator\n        switch (this.type) {\n            case 'newline':\n                this.onKeyLine = false;\n                if (it.value) {\n                    const end = 'end' in it.value ? it.value.end : undefined;\n                    const last = Array.isArray(end) ? end[end.length - 1] : undefined;\n                    if (last?.type === 'comment')\n                        end?.push(this.sourceToken);\n                    else\n                        map.items.push({ start: [this.sourceToken] });\n                }\n                else if (it.sep) {\n                    it.sep.push(this.sourceToken);\n                }\n                else {\n                    it.start.push(this.sourceToken);\n                }\n                return;\n            case 'space':\n            case 'comment':\n                if (it.value) {\n                    map.items.push({ start: [this.sourceToken] });\n                }\n                else if (it.sep) {\n                    it.sep.push(this.sourceToken);\n                }\n                else {\n                    if (this.atIndentedComment(it.start, map.indent)) {\n                        const prev = map.items[map.items.length - 2];\n                        const end = prev?.value?.end;\n                        if (Array.isArray(end)) {\n                            arrayPushArray(end, it.start);\n                            end.push(this.sourceToken);\n                            map.items.pop();\n                            return;\n                        }\n                    }\n                    it.start.push(this.sourceToken);\n                }\n                return;\n        }\n        if (this.indent >= map.indent) {\n            const atMapIndent = !this.onKeyLine && this.indent === map.indent;\n            const atNextItem = atMapIndent &&\n                (it.sep || it.explicitKey) &&\n                this.type !== 'seq-item-ind';\n            // For empty nodes, assign newline-separated not indented empty tokens to following node\n            let start = [];\n            if (atNextItem && it.sep && !it.value) {\n                const nl = [];\n                for (let i = 0; i < it.sep.length; ++i) {\n                    const st = it.sep[i];\n                    switch (st.type) {\n                        case 'newline':\n                            nl.push(i);\n                            break;\n                        case 'space':\n                            break;\n                        case 'comment':\n                            if (st.indent > map.indent)\n                                nl.length = 0;\n                            break;\n                        default:\n                            nl.length = 0;\n                    }\n                }\n                if (nl.length >= 2)\n                    start = it.sep.splice(nl[1]);\n            }\n            switch (this.type) {\n                case 'anchor':\n                case 'tag':\n                    if (atNextItem || it.value) {\n                        start.push(this.sourceToken);\n                        map.items.push({ start });\n                        this.onKeyLine = true;\n                    }\n                    else if (it.sep) {\n                        it.sep.push(this.sourceToken);\n                    }\n                    else {\n                        it.start.push(this.sourceToken);\n                    }\n                    return;\n                case 'explicit-key-ind':\n                    if (!it.sep && !it.explicitKey) {\n                        it.start.push(this.sourceToken);\n                        it.explicitKey = true;\n                    }\n                    else if (atNextItem || it.value) {\n                        start.push(this.sourceToken);\n                        map.items.push({ start, explicitKey: true });\n                    }\n                    else {\n                        this.stack.push({\n                            type: 'block-map',\n                            offset: this.offset,\n                            indent: this.indent,\n                            items: [{ start: [this.sourceToken], explicitKey: true }]\n                        });\n                    }\n                    this.onKeyLine = true;\n                    return;\n                case 'map-value-ind':\n                    if (it.explicitKey) {\n                        if (!it.sep) {\n                            if (includesToken(it.start, 'newline')) {\n                                Object.assign(it, { key: null, sep: [this.sourceToken] });\n                            }\n                            else {\n                                const start = getFirstKeyStartProps(it.start);\n                                this.stack.push({\n                                    type: 'block-map',\n                                    offset: this.offset,\n                                    indent: this.indent,\n                                    items: [{ start, key: null, sep: [this.sourceToken] }]\n                                });\n                            }\n                        }\n                        else if (it.value) {\n                            map.items.push({ start: [], key: null, sep: [this.sourceToken] });\n                        }\n                        else if (includesToken(it.sep, 'map-value-ind')) {\n                            this.stack.push({\n                                type: 'block-map',\n                                offset: this.offset,\n                                indent: this.indent,\n                                items: [{ start, key: null, sep: [this.sourceToken] }]\n                            });\n                        }\n                        else if (isFlowToken(it.key) &&\n                            !includesToken(it.sep, 'newline')) {\n                            const start = getFirstKeyStartProps(it.start);\n                            const key = it.key;\n                            const sep = it.sep;\n                            sep.push(this.sourceToken);\n                            // @ts-expect-error type guard is wrong here\n                            delete it.key;\n                            // @ts-expect-error type guard is wrong here\n                            delete it.sep;\n                            this.stack.push({\n                                type: 'block-map',\n                                offset: this.offset,\n                                indent: this.indent,\n                                items: [{ start, key, sep }]\n                            });\n                        }\n                        else if (start.length > 0) {\n                            // Not actually at next item\n                            it.sep = it.sep.concat(start, this.sourceToken);\n                        }\n                        else {\n                            it.sep.push(this.sourceToken);\n                        }\n                    }\n                    else {\n                        if (!it.sep) {\n                            Object.assign(it, { key: null, sep: [this.sourceToken] });\n                        }\n                        else if (it.value || atNextItem) {\n                            map.items.push({ start, key: null, sep: [this.sourceToken] });\n                        }\n                        else if (includesToken(it.sep, 'map-value-ind')) {\n                            this.stack.push({\n                                type: 'block-map',\n                                offset: this.offset,\n                                indent: this.indent,\n                                items: [{ start: [], key: null, sep: [this.sourceToken] }]\n                            });\n                        }\n                        else {\n                            it.sep.push(this.sourceToken);\n                        }\n                    }\n                    this.onKeyLine = true;\n                    return;\n                case 'alias':\n                case 'scalar':\n                case 'single-quoted-scalar':\n                case 'double-quoted-scalar': {\n                    const fs = this.flowScalar(this.type);\n                    if (atNextItem || it.value) {\n                        map.items.push({ start, key: fs, sep: [] });\n                        this.onKeyLine = true;\n                    }\n                    else if (it.sep) {\n                        this.stack.push(fs);\n                    }\n                    else {\n                        Object.assign(it, { key: fs, sep: [] });\n                        this.onKeyLine = true;\n                    }\n                    return;\n                }\n                default: {\n                    const bv = this.startBlockValue(map);\n                    if (bv) {\n                        if (bv.type === 'block-seq') {\n                            if (!it.explicitKey &&\n                                it.sep &&\n                                !includesToken(it.sep, 'newline')) {\n                                yield* this.pop({\n                                    type: 'error',\n                                    offset: this.offset,\n                                    message: 'Unexpected block-seq-ind on same line with key',\n                                    source: this.source\n                                });\n                                return;\n                            }\n                        }\n                        else if (atMapIndent) {\n                            map.items.push({ start });\n                        }\n                        this.stack.push(bv);\n                        return;\n                    }\n                }\n            }\n        }\n        yield* this.pop();\n        yield* this.step();\n    }\n    *blockSequence(seq) {\n        const it = seq.items[seq.items.length - 1];\n        switch (this.type) {\n            case 'newline':\n                if (it.value) {\n                    const end = 'end' in it.value ? it.value.end : undefined;\n                    const last = Array.isArray(end) ? end[end.length - 1] : undefined;\n                    if (last?.type === 'comment')\n                        end?.push(this.sourceToken);\n                    else\n                        seq.items.push({ start: [this.sourceToken] });\n                }\n                else\n                    it.start.push(this.sourceToken);\n                return;\n            case 'space':\n            case 'comment':\n                if (it.value)\n                    seq.items.push({ start: [this.sourceToken] });\n                else {\n                    if (this.atIndentedComment(it.start, seq.indent)) {\n                        const prev = seq.items[seq.items.length - 2];\n                        const end = prev?.value?.end;\n                        if (Array.isArray(end)) {\n                            arrayPushArray(end, it.start);\n                            end.push(this.sourceToken);\n                            seq.items.pop();\n                            return;\n                        }\n                    }\n                    it.start.push(this.sourceToken);\n                }\n                return;\n            case 'anchor':\n            case 'tag':\n                if (it.value || this.indent <= seq.indent)\n                    break;\n                it.start.push(this.sourceToken);\n                return;\n            case 'seq-item-ind':\n                if (this.indent !== seq.indent)\n                    break;\n                if (it.value || includesToken(it.start, 'seq-item-ind'))\n                    seq.items.push({ start: [this.sourceToken] });\n                else\n                    it.start.push(this.sourceToken);\n                return;\n        }\n        if (this.indent > seq.indent) {\n            const bv = this.startBlockValue(seq);\n            if (bv) {\n                this.stack.push(bv);\n                return;\n            }\n        }\n        yield* this.pop();\n        yield* this.step();\n    }\n    *flowCollection(fc) {\n        const it = fc.items[fc.items.length - 1];\n        if (this.type === 'flow-error-end') {\n            let top;\n            do {\n                yield* this.pop();\n                top = this.peek(1);\n            } while (top?.type === 'flow-collection');\n        }\n        else if (fc.end.length === 0) {\n            switch (this.type) {\n                case 'comma':\n                case 'explicit-key-ind':\n                    if (!it || it.sep)\n                        fc.items.push({ start: [this.sourceToken] });\n                    else\n                        it.start.push(this.sourceToken);\n                    return;\n                case 'map-value-ind':\n                    if (!it || it.value)\n                        fc.items.push({ start: [], key: null, sep: [this.sourceToken] });\n                    else if (it.sep)\n                        it.sep.push(this.sourceToken);\n                    else\n                        Object.assign(it, { key: null, sep: [this.sourceToken] });\n                    return;\n                case 'space':\n                case 'comment':\n                case 'newline':\n                case 'anchor':\n                case 'tag':\n                    if (!it || it.value)\n                        fc.items.push({ start: [this.sourceToken] });\n                    else if (it.sep)\n                        it.sep.push(this.sourceToken);\n                    else\n                        it.start.push(this.sourceToken);\n                    return;\n                case 'alias':\n                case 'scalar':\n                case 'single-quoted-scalar':\n                case 'double-quoted-scalar': {\n                    const fs = this.flowScalar(this.type);\n                    if (!it || it.value)\n                        fc.items.push({ start: [], key: fs, sep: [] });\n                    else if (it.sep)\n                        this.stack.push(fs);\n                    else\n                        Object.assign(it, { key: fs, sep: [] });\n                    return;\n                }\n                case 'flow-map-end':\n                case 'flow-seq-end':\n                    fc.end.push(this.sourceToken);\n                    return;\n            }\n            const bv = this.startBlockValue(fc);\n            /* istanbul ignore else should not happen */\n            if (bv)\n                this.stack.push(bv);\n            else {\n                yield* this.pop();\n                yield* this.step();\n            }\n        }\n        else {\n            const parent = this.peek(2);\n            if (parent.type === 'block-map' &&\n                ((this.type === 'map-value-ind' && parent.indent === fc.indent) ||\n                    (this.type === 'newline' &&\n                        !parent.items[parent.items.length - 1].sep))) {\n                yield* this.pop();\n                yield* this.step();\n            }\n            else if (this.type === 'map-value-ind' &&\n                parent.type !== 'flow-collection') {\n                const prev = getPrevProps(parent);\n                const start = getFirstKeyStartProps(prev);\n                fixFlowSeqItems(fc);\n                const sep = fc.end.splice(1, fc.end.length);\n                sep.push(this.sourceToken);\n                const map = {\n                    type: 'block-map',\n                    offset: fc.offset,\n                    indent: fc.indent,\n                    items: [{ start, key: fc, sep }]\n                };\n                this.onKeyLine = true;\n                this.stack[this.stack.length - 1] = map;\n            }\n            else {\n                yield* this.lineEnd(fc);\n            }\n        }\n    }\n    flowScalar(type) {\n        if (this.onNewLine) {\n            let nl = this.source.indexOf('\\n') + 1;\n            while (nl !== 0) {\n                this.onNewLine(this.offset + nl);\n                nl = this.source.indexOf('\\n', nl) + 1;\n            }\n        }\n        return {\n            type,\n            offset: this.offset,\n            indent: this.indent,\n            source: this.source\n        };\n    }\n    startBlockValue(parent) {\n        switch (this.type) {\n            case 'alias':\n            case 'scalar':\n            case 'single-quoted-scalar':\n            case 'double-quoted-scalar':\n                return this.flowScalar(this.type);\n            case 'block-scalar-header':\n                return {\n                    type: 'block-scalar',\n                    offset: this.offset,\n                    indent: this.indent,\n                    props: [this.sourceToken],\n                    source: ''\n                };\n            case 'flow-map-start':\n            case 'flow-seq-start':\n                return {\n                    type: 'flow-collection',\n                    offset: this.offset,\n                    indent: this.indent,\n                    start: this.sourceToken,\n                    items: [],\n                    end: []\n                };\n            case 'seq-item-ind':\n                return {\n                    type: 'block-seq',\n                    offset: this.offset,\n                    indent: this.indent,\n                    items: [{ start: [this.sourceToken] }]\n                };\n            case 'explicit-key-ind': {\n                this.onKeyLine = true;\n                const prev = getPrevProps(parent);\n                const start = getFirstKeyStartProps(prev);\n                start.push(this.sourceToken);\n                return {\n                    type: 'block-map',\n                    offset: this.offset,\n                    indent: this.indent,\n                    items: [{ start, explicitKey: true }]\n                };\n            }\n            case 'map-value-ind': {\n                this.onKeyLine = true;\n                const prev = getPrevProps(parent);\n                const start = getFirstKeyStartProps(prev);\n                return {\n                    type: 'block-map',\n                    offset: this.offset,\n                    indent: this.indent,\n                    items: [{ start, key: null, sep: [this.sourceToken] }]\n                };\n            }\n        }\n        return null;\n    }\n    atIndentedComment(start, indent) {\n        if (this.type !== 'comment')\n            return false;\n        if (this.indent <= indent)\n            return false;\n        return start.every(st => st.type === 'newline' || st.type === 'space');\n    }\n    *documentEnd(docEnd) {\n        if (this.type !== 'doc-mode') {\n            if (docEnd.end)\n                docEnd.end.push(this.sourceToken);\n            else\n                docEnd.end = [this.sourceToken];\n            if (this.type === 'newline')\n                yield* this.pop();\n        }\n    }\n    *lineEnd(token) {\n        switch (this.type) {\n            case 'comma':\n            case 'doc-start':\n            case 'doc-end':\n            case 'flow-seq-end':\n            case 'flow-map-end':\n            case 'map-value-ind':\n                yield* this.pop();\n                yield* this.step();\n                break;\n            case 'newline':\n                this.onKeyLine = false;\n            // fallthrough\n            case 'space':\n            case 'comment':\n            default:\n                // all other values are errors\n                if (token.end)\n                    token.end.push(this.sourceToken);\n                else\n                    token.end = [this.sourceToken];\n                if (this.type === 'newline')\n                    yield* this.pop();\n        }\n    }\n}\n\nexports.Parser = Parser;\n","'use strict';\n\nvar composer = require('./compose/composer.js');\nvar Document = require('./doc/Document.js');\nvar errors = require('./errors.js');\nvar log = require('./log.js');\nvar identity = require('./nodes/identity.js');\nvar lineCounter = require('./parse/line-counter.js');\nvar parser = require('./parse/parser.js');\n\nfunction parseOptions(options) {\n    const prettyErrors = options.prettyErrors !== false;\n    const lineCounter$1 = options.lineCounter || (prettyErrors && new lineCounter.LineCounter()) || null;\n    return { lineCounter: lineCounter$1, prettyErrors };\n}\n/**\n * Parse the input as a stream of YAML documents.\n *\n * Documents should be separated from each other by `...` or `---` marker lines.\n *\n * @returns If an empty `docs` array is returned, it will be of type\n *   EmptyStream and contain additional stream information. In\n *   TypeScript, you should use `'empty' in docs` as a type guard for it.\n */\nfunction parseAllDocuments(source, options = {}) {\n    const { lineCounter, prettyErrors } = parseOptions(options);\n    const parser$1 = new parser.Parser(lineCounter?.addNewLine);\n    const composer$1 = new composer.Composer(options);\n    const docs = Array.from(composer$1.compose(parser$1.parse(source)));\n    if (prettyErrors && lineCounter)\n        for (const doc of docs) {\n            doc.errors.forEach(errors.prettifyError(source, lineCounter));\n            doc.warnings.forEach(errors.prettifyError(source, lineCounter));\n        }\n    if (docs.length > 0)\n        return docs;\n    return Object.assign([], { empty: true }, composer$1.streamInfo());\n}\n/** Parse an input string into a single YAML.Document */\nfunction parseDocument(source, options = {}) {\n    const { lineCounter, prettyErrors } = parseOptions(options);\n    const parser$1 = new parser.Parser(lineCounter?.addNewLine);\n    const composer$1 = new composer.Composer(options);\n    // `doc` is always set by compose.end(true) at the very latest\n    let doc = null;\n    for (const _doc of composer$1.compose(parser$1.parse(source), true, source.length)) {\n        if (!doc)\n            doc = _doc;\n        else if (doc.options.logLevel !== 'silent') {\n            doc.errors.push(new errors.YAMLParseError(_doc.range.slice(0, 2), 'MULTIPLE_DOCS', 'Source contains multiple documents; please use YAML.parseAllDocuments()'));\n            break;\n        }\n    }\n    if (prettyErrors && lineCounter) {\n        doc.errors.forEach(errors.prettifyError(source, lineCounter));\n        doc.warnings.forEach(errors.prettifyError(source, lineCounter));\n    }\n    return doc;\n}\nfunction parse(src, reviver, options) {\n    let _reviver = undefined;\n    if (typeof reviver === 'function') {\n        _reviver = reviver;\n    }\n    else if (options === undefined && reviver && typeof reviver === 'object') {\n        options = reviver;\n    }\n    const doc = parseDocument(src, options);\n    if (!doc)\n        return null;\n    doc.warnings.forEach(warning => log.warn(doc.options.logLevel, warning));\n    if (doc.errors.length > 0) {\n        if (doc.options.logLevel !== 'silent')\n            throw doc.errors[0];\n        else\n            doc.errors = [];\n    }\n    return doc.toJS(Object.assign({ reviver: _reviver }, options));\n}\nfunction stringify(value, replacer, options) {\n    let _replacer = null;\n    if (typeof replacer === 'function' || Array.isArray(replacer)) {\n        _replacer = replacer;\n    }\n    else if (options === undefined && replacer) {\n        options = replacer;\n    }\n    if (typeof options === 'string')\n        options = options.length;\n    if (typeof options === 'number') {\n        const indent = Math.round(options);\n        options = indent < 1 ? undefined : indent > 8 ? { indent: 8 } : { indent };\n    }\n    if (value === undefined) {\n        const { keepUndefined } = options ?? replacer ?? {};\n        if (!keepUndefined)\n            return undefined;\n    }\n    if (identity.isDocument(value) && !_replacer)\n        return value.toString(options);\n    return new Document.Document(value, _replacer, options).toString(options);\n}\n\nexports.parse = parse;\nexports.parseAllDocuments = parseAllDocuments;\nexports.parseDocument = parseDocument;\nexports.stringify = stringify;\n","'use strict';\n\nvar composer = require('./compose/composer.js');\nvar Document = require('./doc/Document.js');\nvar Schema = require('./schema/Schema.js');\nvar errors = require('./errors.js');\nvar Alias = require('./nodes/Alias.js');\nvar identity = require('./nodes/identity.js');\nvar Pair = require('./nodes/Pair.js');\nvar Scalar = require('./nodes/Scalar.js');\nvar YAMLMap = require('./nodes/YAMLMap.js');\nvar YAMLSeq = require('./nodes/YAMLSeq.js');\nvar cst = require('./parse/cst.js');\nvar lexer = require('./parse/lexer.js');\nvar lineCounter = require('./parse/line-counter.js');\nvar parser = require('./parse/parser.js');\nvar publicApi = require('./public-api.js');\nvar visit = require('./visit.js');\n\n\n\nexports.Composer = composer.Composer;\nexports.Document = Document.Document;\nexports.Schema = Schema.Schema;\nexports.YAMLError = errors.YAMLError;\nexports.YAMLParseError = errors.YAMLParseError;\nexports.YAMLWarning = errors.YAMLWarning;\nexports.Alias = Alias.Alias;\nexports.isAlias = identity.isAlias;\nexports.isCollection = identity.isCollection;\nexports.isDocument = identity.isDocument;\nexports.isMap = identity.isMap;\nexports.isNode = identity.isNode;\nexports.isPair = identity.isPair;\nexports.isScalar = identity.isScalar;\nexports.isSeq = identity.isSeq;\nexports.Pair = Pair.Pair;\nexports.Scalar = Scalar.Scalar;\nexports.YAMLMap = YAMLMap.YAMLMap;\nexports.YAMLSeq = YAMLSeq.YAMLSeq;\nexports.CST = cst;\nexports.Lexer = lexer.Lexer;\nexports.LineCounter = lineCounter.LineCounter;\nexports.Parser = parser.Parser;\nexports.parse = publicApi.parse;\nexports.parseAllDocuments = publicApi.parseAllDocuments;\nexports.parseDocument = publicApi.parseDocument;\nexports.stringify = publicApi.stringify;\nexports.visit = visit.visit;\nexports.visitAsync = visit.visitAsync;\n","import { C as listCredentialAssignmentsByTarget$1, _ as selectCredentialInstancesByIds$1, g as selectCredentialInstanceById$2, h as listCredentialInstancesForAssignment, v as selectCredentialInstancesForScope$2, y as selectCredentialInstancesForScopes$1 } from \"./store-BlAXCv9q.mjs\";\nimport { CREDENTIAL_SCOPE_TYPES, CredentialAccessUnavailableErrorBodySchema, SANDBOX_CREDENTIAL_CONSUMER_ID, buildConnectDeeplink, buildRequestAccessDeeplink, graphqlIntrospectionToAppTemplate, inferGraphqlAuthFromProbe, isRecord, mcpEntityId, mcpProbeToAppTemplate, normalizeCredentialList, openApiSpecToAppTemplate } from \"@keystrokehq/shared\";\nimport { decryptCredentialPayload, encryptCredentialPayload, ensureOAuthCredentialInstance, getBoundProjectScopeId, getServerTenantScopeId, isDatabaseInitialized, selectCredentialInstanceById, selectCredentialInstancesByAppSlug } from \"@keystrokehq/database\";\nimport { ensureOAuthApp, getDecryptedOAuthAppById, getDecryptedOAuthAppBySlug, getDecryptedOAuthConnectionById, listDecryptedOAuthConnections, putOAuthPendingState, resolveOAuthAccessToken, saveOAuthConnection, selectOrganizationById, selectProjectById, takeOAuthPendingState } from \"@keystrokehq/platform-database\";\nimport { readCredentialInstanceSecret } from \"@keystrokehq/secrets\";\nimport { selectCredentialInstanceById as selectCredentialInstanceById$1, selectCredentialInstancesForScope as selectCredentialInstancesForScope$1, touchCredentialInstanceLastUsed as touchCredentialInstanceLastUsed$1 } from \"@keystrokehq/credentials/store\";\nimport { jsonSchema, tool } from \"ai\";\nimport { McpInsufficientScopeError, PublicHttpUrlError, PublicHttpUrlError as PublicHttpUrlError$1, connectMcpDefinition, createPublicHttpFetch, createToolName, defineMcp as defineMcp$1, discoverMcpOAuthServer, exchangeAuthorization, fetchPublicHttp, isHttpsUrl, normalizeInputSchema, probeMcpAuth, probeMcpServerInfo, registerClient, startAuthorization, withMcpReadClient } from \"@keystrokehq/mcp\";\nimport { z } from \"zod\";\nimport { createHmac, randomBytes, timingSafeEqual } from \"node:crypto\";\nimport YAML from \"yaml\";\n//#region src/format-error.ts\nfunction formatCredentialErrorMessage(error, connect) {\n\tswitch (error.code) {\n\t\tcase \"missing_credentials\":\n\t\t\tif (connect) {\n\t\t\t\tconst connectUrl = buildConnectDeeplink({\n\t\t\t\t\twebUrl: connect.webUrl,\n\t\t\t\t\torgSlug: connect.orgSlug,\n\t\t\t\t\tappSlug: error.key\n\t\t\t\t});\n\t\t\t\treturn `This agent needs the \\`${error.key}\\` credential. Connect it here: ${connectUrl}`;\n\t\t\t}\n\t\t\treturn `This agent needs the \\`${error.key}\\` credential. Run \\`keystroke connect ${error.key}\\` or \\`keystroke credentials set ${error.key}\\` to configure it.`;\n\t\tcase \"needs_selection\":\n\t\t\tif (connect) {\n\t\t\t\tconst connectUrl = buildConnectDeeplink({\n\t\t\t\t\twebUrl: connect.webUrl,\n\t\t\t\t\torgSlug: connect.orgSlug,\n\t\t\t\t\tappSlug: error.key\n\t\t\t\t});\n\t\t\t\treturn `Multiple \\`${error.key}\\` credentials are available. Pick one here: ${connectUrl}`;\n\t\t\t}\n\t\t\treturn `Multiple \\`${error.key}\\` credentials are available. Pick one in the Keystroke dashboard before running this agent.`;\n\t\tcase \"oauth_not_configured\": return error.message;\n\t\tcase \"credential_access_unavailable\": {\n\t\t\tif (error.reason === \"reconnect_required\") {\n\t\t\t\tif (connect) {\n\t\t\t\t\tconst connectUrl = buildConnectDeeplink({\n\t\t\t\t\t\twebUrl: connect.webUrl,\n\t\t\t\t\t\torgSlug: connect.orgSlug,\n\t\t\t\t\t\tappSlug: error.appSlug\n\t\t\t\t\t});\n\t\t\t\t\treturn `Reconnect the \\`${error.appSlug}\\` credential to use it in a sandbox VM: ${connectUrl}`;\n\t\t\t\t}\n\t\t\t\treturn `Reconnect the \\`${error.appSlug}\\` credential to use it in a sandbox VM.`;\n\t\t\t}\n\t\t\tconst requestUrl = error.requestAccessUrl ?? (connect ? buildRequestAccessDeeplink({\n\t\t\t\twebUrl: connect.webUrl,\n\t\t\t\torgSlug: connect.orgSlug,\n\t\t\t\tappSlug: error.appSlug\n\t\t\t}) : void 0);\n\t\t\tif (requestUrl) return `The \\`${error.appSlug}\\` credential cannot expose secrets for sandbox VM use. Request access here: ${requestUrl}`;\n\t\t\treturn `The \\`${error.appSlug}\\` credential cannot expose secrets for sandbox VM use.`;\n\t\t}\n\t\tcase \"insufficient_scope\": {\n\t\t\tconst scopes = error.requiredScopes.length ? ` Required scopes: ${error.requiredScopes.join(\" \")}.` : \"\";\n\t\t\tif (connect) {\n\t\t\t\tconst connectUrl = buildConnectDeeplink({\n\t\t\t\t\twebUrl: connect.webUrl,\n\t\t\t\t\torgSlug: connect.orgSlug,\n\t\t\t\t\tappSlug: error.key\n\t\t\t\t});\n\t\t\t\treturn `The \\`${error.key}\\` MCP credential needs additional authorization.${scopes} Reconnect it here: ${connectUrl}`;\n\t\t\t}\n\t\t\treturn `The \\`${error.key}\\` MCP credential needs additional authorization.${scopes} Reconnect it in the Keystroke dashboard.`;\n\t\t}\n\t}\n}\n//#endregion\n//#region src/errors.ts\nvar MissingCredentialsError = class extends Error {\n\tcode = \"missing_credentials\";\n\tkey;\n\tchainAttempted;\n\tconsumer;\n\tconstructor(options) {\n\t\tsuper(`Missing credential \"${options.key}\"`);\n\t\tthis.name = \"MissingCredentialsError\";\n\t\tthis.key = options.key;\n\t\tthis.chainAttempted = options.chainAttempted;\n\t\tthis.consumer = options.consumer;\n\t}\n};\nvar NeedsSelectionError = class extends Error {\n\tcode = \"needs_selection\";\n\tkey;\n\toptions;\n\tconsumer;\n\tconstructor(options) {\n\t\tsuper(`Credential selection required for \"${options.key}\"`);\n\t\tthis.name = \"NeedsSelectionError\";\n\t\tthis.key = options.key;\n\t\tthis.options = options.options;\n\t\tthis.consumer = options.consumer;\n\t}\n};\nvar OAuthNotConfiguredError = class extends Error {\n\tcode = \"oauth_not_configured\";\n\tconstructor(message = \"OAuth token adapter is not configured\") {\n\t\tsuper(message);\n\t\tthis.name = \"OAuthNotConfiguredError\";\n\t}\n};\nvar McpInsufficientScopeCredentialError = class extends Error {\n\tkey;\n\trequiredScopes;\n\tcode = \"insufficient_scope\";\n\treconnectRequired = true;\n\tconstructor(key, requiredScopes) {\n\t\tsuper(`MCP credential \"${key}\" requires additional authorization`);\n\t\tthis.key = key;\n\t\tthis.requiredScopes = requiredScopes;\n\t\tthis.name = \"McpInsufficientScopeCredentialError\";\n\t}\n};\nvar CredentialAccessDeniedError = class extends Error {\n\tcode = \"credential_access_denied\";\n\tinstanceId;\n\tconstructor(instanceId) {\n\t\tsuper(`Credential instance \"${instanceId}\" is not accessible in this run context`);\n\t\tthis.name = \"CredentialAccessDeniedError\";\n\t\tthis.instanceId = instanceId;\n\t}\n};\nvar CredentialAccessUnavailableError = class extends Error {\n\tcode = \"credential_access_unavailable\";\n\tappSlug;\n\treason;\n\trequestAccessUrl;\n\tconsumer;\n\tconstructor(options) {\n\t\tconst defaultMessage = options.reason === \"reconnect_required\" ? `Reconnect the \\`${options.appSlug}\\` credential to use it in a sandbox VM.` : `The \\`${options.appSlug}\\` credential cannot expose secrets for sandbox VM use.`;\n\t\tsuper(options.message ?? defaultMessage);\n\t\tthis.name = \"CredentialAccessUnavailableError\";\n\t\tthis.appSlug = options.appSlug;\n\t\tthis.reason = options.reason;\n\t\tthis.requestAccessUrl = options.requestAccessUrl;\n\t\tthis.consumer = options.consumer;\n\t}\n};\nfunction isCredentialError(error) {\n\treturn error instanceof MissingCredentialsError || error instanceof NeedsSelectionError || error instanceof OAuthNotConfiguredError || error instanceof CredentialAccessUnavailableError || error instanceof McpInsufficientScopeCredentialError;\n}\nfunction credentialScopeMatchesContext(scopeType, scopeId, context) {\n\tswitch (scopeType) {\n\t\tcase \"organization\": return scopeId === context.orgId;\n\t\tcase \"project\": return scopeId === context.projectId;\n\t\tcase \"user\": return scopeId === context.userId;\n\t}\n}\n//#endregion\n//#region src/resolve-composio-oauth-mirror.ts\nconst COMPOSIO_PROXY_TOKEN_PREFIX = \"composio:\";\n/**\n* Composio → first-party OAuth dual-read helpers.\n*\n* Resolve falls back from a legacy `keystroke` row when a native package asks\n* for a non-keystroke shape:\n* - `oauth_managed` → this module (mirrored `oauth_connections`)\n* - `api_key` → dual-written instance secrets (field bag; see resolve-vault)\n*\n* Old packages that still ask for `keystroke` keep Composio descriptors.\n* New native installs write `oauth_managed` / `api_key` rows directly.\n*/\nfunction isComposioProxyAccessToken(token) {\n\treturn token.trim().startsWith(COMPOSIO_PROXY_TOKEN_PREFIX);\n}\n/** True when the stored token cannot call the provider API directly. */\nfunction isUnusableMirroredAccessToken(token) {\n\tconst trimmed = token?.trim();\n\tif (!trimmed) return true;\n\tif (isComposioProxyAccessToken(trimmed)) return true;\n\tif (trimmed === \"REDACTED\" || trimmed.includes(\"REDACTED\")) return true;\n\tif (trimmed.endsWith(\"...\")) return true;\n\treturn false;\n}\nfunction mirrorChronologyMs(connection) {\n\tconst mirroredAt = connection.metadata?.composioMirroredAt;\n\tif (typeof mirroredAt === \"string\") {\n\t\tconst parsed = Date.parse(mirroredAt);\n\t\tif (!Number.isNaN(parsed)) return parsed;\n\t}\n\treturn connection.updatedAt.getTime();\n}\n/**\n* Legacy Composio mirrors can leave several rows with the same\n* `composioConnectionId`. Prefer a usable token, then the newest\n* `composioMirroredAt` (fallback: `updatedAt`).\n*\n* When `appSlug` is set, prefer `metadata.composioToolkit` matches and never\n* select a row whose toolkit is a different app.\n*/\nfunction pickMirroredOAuthConnectionId(connections, composioConnectionId, options) {\n\tconst id = composioConnectionId.trim();\n\tif (!id) return null;\n\tlet matches = connections.filter((connection) => {\n\t\tconst mirroredId = connection.metadata?.composioConnectionId;\n\t\treturn typeof mirroredId === \"string\" && mirroredId.trim() === id;\n\t});\n\tif (matches.length === 0) return null;\n\tconst appSlug = options?.appSlug?.trim().toLowerCase();\n\tif (appSlug) {\n\t\tconst toolkitMatches = matches.filter((connection) => {\n\t\t\tconst toolkit = connection.metadata?.composioToolkit;\n\t\t\treturn typeof toolkit === \"string\" && toolkit.trim().toLowerCase() === appSlug;\n\t\t});\n\t\tif (toolkitMatches.length > 0) matches = toolkitMatches;\n\t\telse {\n\t\t\tmatches = matches.filter((connection) => {\n\t\t\t\tconst toolkit = connection.metadata?.composioToolkit;\n\t\t\t\treturn typeof toolkit !== \"string\" || toolkit.trim() === \"\";\n\t\t\t});\n\t\t\tif (matches.length === 0) return null;\n\t\t}\n\t}\n\tconst usable = matches.filter((connection) => !isUnusableMirroredAccessToken(connection.accessToken));\n\tconst pool = usable.length > 0 ? usable : matches;\n\tlet best = pool[0];\n\tfor (const candidate of pool.slice(1)) if (mirrorChronologyMs(candidate) > mirrorChronologyMs(best)) best = candidate;\n\treturn best.id;\n}\n//#endregion\n//#region src/backend/local.ts\nfunction createLocalCredentialBackend(options = {}) {\n\tconst { tokenRefresh, resolveSandboxAccessToken } = options;\n\tasync function getOAuthAccessToken(connectionId) {\n\t\tconst connection = await getDecryptedOAuthConnectionById(connectionId);\n\t\tif (!connection) throw new Error(`OAuth connection not found: ${connectionId}`);\n\t\tconst app = await getDecryptedOAuthAppById(connection.appId);\n\t\tif (!app) throw new Error(`OAuth app not found for connection: ${connectionId}`);\n\t\treturn { accessToken: await resolveOAuthAccessToken(connection, app, tokenRefresh) };\n\t}\n\treturn {\n\t\tasync resolveApiKey(instanceId, schema) {\n\t\t\tconst row = await selectCredentialInstanceById(instanceId);\n\t\t\tif (!row) throw new MissingCredentialsError({\n\t\t\t\tkey: instanceId,\n\t\t\t\tchainAttempted: [\"api_key\"]\n\t\t\t});\n\t\t\tif (row.ciphertext) {\n\t\t\t\tconst plaintext = decryptCredentialPayload(row.ciphertext);\n\t\t\t\treturn schema.parse(JSON.parse(plaintext));\n\t\t\t}\n\t\t\tconst secret = await readCredentialInstanceSecret(instanceId);\n\t\t\tif (secret) return schema.parse(JSON.parse(secret));\n\t\t\tthrow new MissingCredentialsError({\n\t\t\t\tkey: row.appSlug,\n\t\t\t\tchainAttempted: [\"api_key\"]\n\t\t\t});\n\t\t},\n\t\tgetOAuthAccessToken,\n\t\tasync getOAuthAccessTokenFromMirror({ appSlug, composioConnectionId }) {\n\t\t\tconst connectionId = pickMirroredOAuthConnectionId(await listDecryptedOAuthConnections(), composioConnectionId, { appSlug });\n\t\t\tif (!connectionId) return null;\n\t\t\treturn getOAuthAccessToken(connectionId);\n\t\t},\n\t\tasync resolveKeystrokeSandbox({ instanceId, connectionId, appSlug, schema }) {\n\t\t\tconst secret = await readCredentialInstanceSecret(instanceId);\n\t\t\tif (secret) return schema.parse(JSON.parse(secret));\n\t\t\tif (!resolveSandboxAccessToken) throw new CredentialAccessUnavailableError({\n\t\t\t\tappSlug,\n\t\t\t\treason: \"reconnect_required\"\n\t\t\t});\n\t\t\tconst resolved = await resolveSandboxAccessToken(connectionId);\n\t\t\tif (!resolved.ok) throw new CredentialAccessUnavailableError({\n\t\t\t\tappSlug,\n\t\t\t\treason: resolved.reason\n\t\t\t});\n\t\t\treturn schema.parse({ accessToken: resolved.accessToken });\n\t\t}\n\t};\n}\n//#endregion\n//#region src/backend/platform.ts\nfunction materializeUrl(baseUrl, projectId) {\n\treturn `${baseUrl}/internal/projects/${encodeURIComponent(projectId)}/credentials/materialize`;\n}\nfunction requireProjectScopeId() {\n\tconst projectId = getBoundProjectScopeId();\n\tif (!projectId) throw new Error(\"Credential backend requires project scope\");\n\treturn projectId;\n}\nfunction createPlatformCredentialBackend(options) {\n\tconst baseUrl = options.platformUrl.replace(/\\/+$/, \"\");\n\tasync function materialize(body) {\n\t\tconst response = await fetch(materializeUrl(baseUrl, requireProjectScopeId()), {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: {\n\t\t\t\tAuthorization: `Bearer ${options.workerToken}`,\n\t\t\t\t\"Content-Type\": \"application/json\"\n\t\t\t},\n\t\t\tbody: JSON.stringify(body)\n\t\t});\n\t\tif (!response.ok) {\n\t\t\tconst payload = await response.json().catch(() => null);\n\t\t\tconst unavailable = CredentialAccessUnavailableErrorBodySchema.safeParse(payload);\n\t\t\tif (unavailable.success) throw new CredentialAccessUnavailableError({\n\t\t\t\tappSlug: unavailable.data.appSlug,\n\t\t\t\treason: unavailable.data.reason,\n\t\t\t\trequestAccessUrl: unavailable.data.requestAccessUrl,\n\t\t\t\tmessage: unavailable.data.message\n\t\t\t});\n\t\t\tconst message = payload && typeof payload === \"object\" && \"message\" in payload && typeof payload.message === \"string\" ? payload.message : `Platform credential materialize failed (${response.status})`;\n\t\t\tthrow new Error(message);\n\t\t}\n\t\tconst payload = await response.json();\n\t\tif (payload.kind === \"api_key\" || payload.kind === \"keystroke\") return { value: payload.value };\n\t\treturn { accessToken: payload.accessToken };\n\t}\n\treturn {\n\t\tasync resolveApiKey(instanceId, schema) {\n\t\t\tconst { value } = await materialize({\n\t\t\t\tkind: \"api_key\",\n\t\t\t\tinstanceId\n\t\t\t});\n\t\t\treturn schema.parse(value);\n\t\t},\n\t\tasync getOAuthAccessToken(connectionId) {\n\t\t\tconst { accessToken } = await materialize({\n\t\t\t\tkind: \"oauth\",\n\t\t\t\tconnectionId\n\t\t\t});\n\t\t\tif (!accessToken) throw new Error(`Platform did not return an access token for connection: ${connectionId}`);\n\t\t\treturn { accessToken };\n\t\t},\n\t\tasync getOAuthAccessTokenFromMirror({ appSlug, composioConnectionId }) {\n\t\t\tconst { accessToken } = await materialize({\n\t\t\t\tkind: \"oauth_mirror\",\n\t\t\t\tappSlug,\n\t\t\t\tcomposioConnectionId\n\t\t\t});\n\t\t\treturn accessToken ? { accessToken } : null;\n\t\t},\n\t\tasync resolveKeystrokeSandbox({ instanceId, connectionId, appSlug, schema }) {\n\t\t\tconst { value } = await materialize({\n\t\t\t\tkind: \"keystroke\",\n\t\t\t\tinstanceId,\n\t\t\t\tconnectionId,\n\t\t\t\tappSlug\n\t\t\t});\n\t\t\treturn schema.parse(value);\n\t\t}\n\t};\n}\n//#endregion\n//#region src/backend/create-backend.ts\n/**\n* A hosted worker is identified by the platform connection it must route through:\n* `PLATFORM_URL` + `WORKER_INTERNAL_TOKEN`. Workers never hold the decryption key, so\n* they always materialize secrets over the platform internal API; everything else\n* (platform process, standalone CLI) resolves locally against its own database.\n*\n* Org workers share one platform backend; project id comes from async job scope at\n* resolve time, not from env.\n*/\nfunction isWorkerRuntime(env = process.env) {\n\treturn Boolean(env.WORKER_INTERNAL_TOKEN?.trim() && env.PLATFORM_URL?.trim());\n}\nfunction createCredentialBackend(options = {}) {\n\tif (isWorkerRuntime()) return createPlatformCredentialBackend({\n\t\tplatformUrl: process.env.PLATFORM_URL.trim(),\n\t\tworkerToken: process.env.WORKER_INTERNAL_TOKEN.trim()\n\t});\n\treturn createLocalCredentialBackend(options);\n}\n//#endregion\n//#region src/resolve-agent-connect-context.ts\n/**\n* Web connect context (org slug + web URL) for the current project scope, or\n* `null` when unavailable — standalone, no bound project scope, or no\n* `PUBLIC_WEB_URL`. Org slug comes from the platform internal API on workers\n* (no decryption key, so no direct DB), otherwise the platform DB.\n*/\nasync function resolveAgentConnectContext() {\n\tconst projectId = getBoundProjectScopeId();\n\tif (!projectId) return null;\n\tconst webUrl = process.env.PUBLIC_WEB_URL?.trim();\n\tif (!webUrl) return null;\n\tconst orgSlug = await resolveOrgSlug(projectId);\n\tif (!orgSlug) return null;\n\treturn {\n\t\torgSlug,\n\t\twebUrl\n\t};\n}\nasync function resolveOrgSlug(projectId) {\n\tif (isWorkerRuntime()) return fetchOrgSlugFromPlatform(projectId);\n\tconst project = await selectProjectById(projectId);\n\tif (!project) return null;\n\treturn (await selectOrganizationById(project.organizationId))?.slug.trim() || null;\n}\nasync function fetchOrgSlugFromPlatform(projectId) {\n\tconst platformUrl = process.env.PLATFORM_URL?.trim();\n\tconst workerToken = process.env.WORKER_INTERNAL_TOKEN?.trim();\n\tif (!platformUrl || !workerToken) return null;\n\tconst baseUrl = platformUrl.replace(/\\/+$/, \"\");\n\tconst response = await fetch(`${baseUrl}/internal/projects/${encodeURIComponent(projectId)}/connect-context`, { headers: { Authorization: `Bearer ${workerToken}` } });\n\tif (!response.ok) return null;\n\treturn (await response.json()).orgSlug?.trim() || null;\n}\n//#endregion\n//#region src/enrich-credential-error.ts\n/** Rewrite a credential error message with a web connect deeplink when context is available. */\nasync function enrichCredentialError(error) {\n\ttry {\n\t\terror.message = formatCredentialErrorMessage(error, await resolveAgentConnectContext() ?? void 0);\n\t} catch {}\n}\n//#endregion\n//#region src/capture-credential-tool-errors.ts\n/**\n* Wrap tool `execute`s so a thrown credential error is captured (and enriched\n* with a connect deeplink) before propagating. Covers both keystroke\n* {@link AgentTool}s and native AI SDK MCP tools — MCP tools resolve credentials\n* lazily inside their own `execute`, so they need the same wrapper to surface\n* missing-credential failures for workflow retry.\n*/\nfunction captureCredentialToolErrors(tools, toolSet = {}) {\n\tlet captured;\n\tconst onError = async (error) => {\n\t\tif (isCredentialError(error)) {\n\t\t\tcaptured = error;\n\t\t\tawait enrichCredentialError(error);\n\t\t}\n\t};\n\tconst wrapped = tools.map((tool) => {\n\t\tif (!tool.execute) return tool;\n\t\tconst execute = tool.execute.bind(tool);\n\t\treturn {\n\t\t\t...tool,\n\t\t\tasync execute(...args) {\n\t\t\t\ttry {\n\t\t\t\t\treturn await execute(...args);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tawait onError(error);\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t});\n\tconst wrappedToolSet = {};\n\tfor (const [name, mcpTool] of Object.entries(toolSet)) {\n\t\tconst execute = mcpTool.execute;\n\t\tif (!execute) {\n\t\t\twrappedToolSet[name] = mcpTool;\n\t\t\tcontinue;\n\t\t}\n\t\twrappedToolSet[name] = {\n\t\t\t...mcpTool,\n\t\t\texecute: async (input, options) => {\n\t\t\t\ttry {\n\t\t\t\t\treturn await execute(input, options);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tawait onError(error);\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t}\n\treturn {\n\t\ttools: wrapped,\n\t\ttoolSet: wrappedToolSet,\n\t\ttakeCredentialError: () => {\n\t\t\tconst error = captured;\n\t\t\tcaptured = void 0;\n\t\t\treturn error;\n\t\t}\n\t};\n}\n//#endregion\n//#region src/assignments.ts\nconst EMPTY_ASSIGNMENT_SET = {\n\tbyConsumer: {},\n\twildcard: {}\n};\nfunction selectAssignedInstanceId(assignments, consumerId, credentialSlug) {\n\tif (!assignments) return;\n\tif (consumerId) {\n\t\tconst specific = assignments.byConsumer[consumerId]?.[credentialSlug];\n\t\tif (specific) return specific;\n\t}\n\treturn assignments.wildcard[credentialSlug];\n}\nfunction buildAssignmentSet(rows) {\n\tconst byConsumer = {};\n\tconst wildcard = {};\n\tfor (const row of rows) {\n\t\tif (row.consumerId === \"*\") {\n\t\t\twildcard[row.credentialSlug] = row.instanceId;\n\t\t\tcontinue;\n\t\t}\n\t\tconst bucket = byConsumer[row.consumerId] ?? {};\n\t\tbucket[row.credentialSlug] = row.instanceId;\n\t\tbyConsumer[row.consumerId] = bucket;\n\t}\n\treturn {\n\t\tbyConsumer,\n\t\twildcard\n\t};\n}\nasync function loadCredentialAssignments(options) {\n\tif (!isDatabaseInitialized()) return EMPTY_ASSIGNMENT_SET;\n\treturn buildAssignmentSet(await listCredentialAssignmentsByTarget$1(options));\n}\nasync function withCredentialAssignments(context, options) {\n\tconst assignments = await loadCredentialAssignments(options);\n\treturn {\n\t\t...context,\n\t\tassignments\n\t};\n}\n//#endregion\n//#region src/resolve-keystroke-instance.ts\nfunction pickKeystrokeInstanceRow(rows, key, consumer) {\n\tif (rows.length === 0) return;\n\tif (rows.length === 1) return rows[0];\n\tconst defaults = rows.filter((row) => row.isDefault);\n\tif (defaults.length === 1) return defaults[0];\n\tif (consumer !== void 0) throw new NeedsSelectionError({\n\t\tkey,\n\t\toptions: rows.map((row) => ({\n\t\t\tid: row.id,\n\t\t\tlabel: row.name ?? row.label,\n\t\t\tscopeType: row.scopeType,\n\t\t\tscopeId: row.scopeId\n\t\t})),\n\t\tconsumer\n\t});\n\treturn rows.find((row) => row.isDefault) ?? rows[0];\n}\nasync function resolveAssignedKeystrokeInstance(app, assignments, consumerId) {\n\tconst assignedId = selectAssignedInstanceId(assignments, consumerId, app);\n\tif (!assignedId) return;\n\tconst row = await selectCredentialInstanceById$2(assignedId);\n\tif (!row || row.authKind !== \"keystroke\" || !row.connectionId || row.appSlug !== app) return;\n\treturn {\n\t\tinstanceId: assignedId,\n\t\tscopeType: row.scopeType,\n\t\tscopeId: row.scopeId\n\t};\n}\n/** Assignment lookup (when assignments provided) then ordered scope walk. User scope only when included in scopes. */\nasync function resolveKeystrokeInstanceId(options) {\n\tif (options.credentialSlug) {\n\t\tfor (const [scopeType, scopeId] of options.scopes) {\n\t\t\tconst match = (await selectCredentialInstancesForScope$2(options.app, scopeType, scopeId)).filter((row) => row.authKind === \"keystroke\" && row.connectionId).find((row) => row.slug === options.credentialSlug);\n\t\t\tif (match) return {\n\t\t\t\tinstanceId: match.id,\n\t\t\t\tscopeType: match.scopeType,\n\t\t\t\tscopeId: match.scopeId\n\t\t\t};\n\t\t}\n\t\treturn;\n\t}\n\tconst assignments = options.assignments ?? (options.assignmentTarget ? await loadCredentialAssignments({\n\t\ttargetType: options.assignmentTarget.type,\n\t\ttargetKey: options.assignmentTarget.key\n\t}) : void 0);\n\tif (assignments) {\n\t\tconst assigned = await resolveAssignedKeystrokeInstance(options.app, assignments, options.consumerId);\n\t\tif (assigned) return assigned;\n\t}\n\tfor (const [scopeType, scopeId] of options.scopes) {\n\t\tconst row = pickKeystrokeInstanceRow((await selectCredentialInstancesForScope$2(options.app, scopeType, scopeId)).filter((row) => row.authKind === \"keystroke\" && row.connectionId), options.app, options.consumer);\n\t\tif (row) return {\n\t\t\tinstanceId: row.id,\n\t\t\tscopeType: row.scopeType,\n\t\t\tscopeId: row.scopeId\n\t\t};\n\t}\n}\n//#endregion\n//#region src/describe-credential-binding.ts\nfunction toSummary(row) {\n\treturn {\n\t\tid: row.id,\n\t\tappSlug: row.appSlug,\n\t\tname: row.name,\n\t\tlabel: row.label,\n\t\tscopeType: row.scopeType,\n\t\tscopeId: row.scopeId,\n\t\tisDefault: row.isDefault\n\t};\n}\nfunction scopeCacheKey(appSlug, scopeType, scopeId) {\n\treturn `${appSlug}\\0${scopeType}\\0${scopeId}`;\n}\n/** Pick the single instance for a scope: the only one, or the unique default; else ambiguous. */\nfunction pickInstance$1(rows) {\n\tif (rows.length === 0) return { kind: \"none\" };\n\tif (rows.length === 1) return {\n\t\tkind: \"row\",\n\t\trow: rows[0]\n\t};\n\tconst defaults = rows.filter((row) => row.isDefault);\n\tif (defaults.length === 1) return {\n\t\tkind: \"row\",\n\t\trow: defaults[0]\n\t};\n\treturn { kind: \"needs-selection\" };\n}\nfunction scopeIdFor(scope, context, orgId) {\n\tswitch (scope) {\n\t\tcase \"organization\": return orgId;\n\t\tcase \"project\": return context.projectId;\n\t\tcase \"user\": return context.userId;\n\t}\n}\nfunction describeFromPreload(options, preload) {\n\tconst { key, scope, consumerId, context } = options;\n\tconst orgId = context.orgId ?? getServerTenantScopeId();\n\tconst assignedId = selectAssignedInstanceId(context.assignments, consumerId, key);\n\tif (assignedId) {\n\t\tconst row = preload.byId.get(assignedId);\n\t\tif (row && row.appSlug === key) return {\n\t\t\tpolicy: \"assigned\",\n\t\t\trow: toSummary(row)\n\t\t};\n\t}\n\tif (scope) {\n\t\tconst scopeId = scopeIdFor(scope, context, orgId);\n\t\tconst picked = scopeId ? pickInstance$1(preload.byScope.get(scopeCacheKey(key, scope, scopeId)) ?? []) : { kind: \"none\" };\n\t\tif (picked.kind === \"row\") return {\n\t\t\tpolicy: \"scope-pinned\",\n\t\t\tpinnedScope: scope,\n\t\t\trow: toSummary(picked.row)\n\t\t};\n\t\treturn {\n\t\t\tpolicy: \"unresolved\",\n\t\t\treason: picked.kind === \"needs-selection\" ? \"needs-selection\" : \"missing\",\n\t\t\tpinnedScope: scope\n\t\t};\n\t}\n\tif (context.projectId) {\n\t\tconst picked = pickInstance$1(preload.byScope.get(scopeCacheKey(key, \"project\", context.projectId)) ?? []);\n\t\tif (picked.kind === \"row\") return {\n\t\t\tpolicy: \"project-default\",\n\t\t\trow: toSummary(picked.row)\n\t\t};\n\t\tif (picked.kind === \"needs-selection\") return {\n\t\t\tpolicy: \"unresolved\",\n\t\t\treason: \"needs-selection\"\n\t\t};\n\t}\n\tif (orgId) {\n\t\tconst picked = pickInstance$1(preload.byScope.get(scopeCacheKey(key, \"organization\", orgId)) ?? []);\n\t\tif (picked.kind === \"row\") return {\n\t\t\tpolicy: \"org-default\",\n\t\t\trow: toSummary(picked.row)\n\t\t};\n\t\tif (picked.kind === \"needs-selection\") return {\n\t\t\tpolicy: \"unresolved\",\n\t\t\treason: \"needs-selection\"\n\t\t};\n\t}\n\treturn {\n\t\tpolicy: \"unresolved\",\n\t\treason: \"missing\"\n\t};\n}\nasync function describeCredentialBinding(options) {\n\tif (options.preload) return describeFromPreload(options, options.preload);\n\tconst { key, scope, consumerId, context } = options;\n\tconst orgId = context.orgId ?? getServerTenantScopeId();\n\tconst assignedId = selectAssignedInstanceId(context.assignments, consumerId, key);\n\tif (assignedId) {\n\t\tconst row = await selectCredentialInstanceById$2(assignedId);\n\t\tif (row && row.appSlug === key) return {\n\t\t\tpolicy: \"assigned\",\n\t\t\trow: toSummary(row)\n\t\t};\n\t}\n\tif (scope) {\n\t\tconst scopeId = scopeIdFor(scope, context, orgId);\n\t\tconst picked = scopeId ? pickInstance$1(await selectCredentialInstancesForScope$2(key, scope, scopeId)) : { kind: \"none\" };\n\t\tif (picked.kind === \"row\") return {\n\t\t\tpolicy: \"scope-pinned\",\n\t\t\tpinnedScope: scope,\n\t\t\trow: toSummary(picked.row)\n\t\t};\n\t\treturn {\n\t\t\tpolicy: \"unresolved\",\n\t\t\treason: picked.kind === \"needs-selection\" ? \"needs-selection\" : \"missing\",\n\t\t\tpinnedScope: scope\n\t\t};\n\t}\n\tif (context.projectId) {\n\t\tconst picked = pickInstance$1(await selectCredentialInstancesForScope$2(key, \"project\", context.projectId));\n\t\tif (picked.kind === \"row\") return {\n\t\t\tpolicy: \"project-default\",\n\t\t\trow: toSummary(picked.row)\n\t\t};\n\t\tif (picked.kind === \"needs-selection\") return {\n\t\t\tpolicy: \"unresolved\",\n\t\t\treason: \"needs-selection\"\n\t\t};\n\t}\n\tif (orgId) {\n\t\tconst picked = pickInstance$1(await selectCredentialInstancesForScope$2(key, \"organization\", orgId));\n\t\tif (picked.kind === \"row\") return {\n\t\t\tpolicy: \"org-default\",\n\t\t\trow: toSummary(picked.row)\n\t\t};\n\t\tif (picked.kind === \"needs-selection\") return {\n\t\t\tpolicy: \"unresolved\",\n\t\t\treason: \"needs-selection\"\n\t\t};\n\t}\n\treturn {\n\t\tpolicy: \"unresolved\",\n\t\treason: \"missing\"\n\t};\n}\n/**\n* Prefetch every instance needed to resolve `requirements` against `context`,\n* then describe each binding in memory (2 DB round trips total).\n*/\nasync function describeCredentialBindings(requirements, context) {\n\tif (requirements.length === 0) return [];\n\tconst orgId = context.orgId ?? getServerTenantScopeId();\n\tconst assignedIds = /* @__PURE__ */ new Set();\n\tconst scopeKeys = /* @__PURE__ */ new Map();\n\tfor (const requirement of requirements) {\n\t\tconst assignedId = selectAssignedInstanceId(context.assignments, requirement.consumerId, requirement.key);\n\t\tif (assignedId) assignedIds.add(assignedId);\n\t\tconst addScope = (scopeType, scopeId) => {\n\t\t\tif (!scopeId) return;\n\t\t\tconst key = scopeCacheKey(requirement.key, scopeType, scopeId);\n\t\t\tif (!scopeKeys.has(key)) scopeKeys.set(key, {\n\t\t\t\tappSlug: requirement.key,\n\t\t\t\tscopeType,\n\t\t\t\tscopeId\n\t\t\t});\n\t\t};\n\t\tif (requirement.scope) addScope(requirement.scope, scopeIdFor(requirement.scope, context, orgId));\n\t\telse {\n\t\t\taddScope(\"project\", context.projectId);\n\t\t\taddScope(\"organization\", orgId);\n\t\t}\n\t}\n\tconst [assignedRows, scopeRows] = await Promise.all([selectCredentialInstancesByIds$1([...assignedIds]), selectCredentialInstancesForScopes$1([...scopeKeys.values()])]);\n\tconst byId = new Map(assignedRows.map((row) => [row.id, row]));\n\tconst byScope = /* @__PURE__ */ new Map();\n\tfor (const row of scopeRows) {\n\t\tif (!row.scopeId) continue;\n\t\tconst key = scopeCacheKey(row.appSlug, row.scopeType, row.scopeId);\n\t\tconst existing = byScope.get(key) ?? [];\n\t\texisting.push(row);\n\t\tbyScope.set(key, existing);\n\t}\n\tconst preload = {\n\t\tbyId,\n\t\tbyScope\n\t};\n\treturn requirements.map((requirement) => describeFromPreload({\n\t\tkey: requirement.key,\n\t\t...requirement.scope ? { scope: requirement.scope } : {},\n\t\tconsumerId: requirement.consumerId,\n\t\tcontext,\n\t\tpreload\n\t}, preload));\n}\n//#endregion\n//#region src/parse-credential-ref.ts\nconst UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst SCOPE_PREFIXES = {\n\torg: \"organization\",\n\torganization: \"organization\",\n\tproject: \"project\",\n\tuser: \"user\"\n};\nfunction credentialScopePrefix(scopeType) {\n\tswitch (scopeType) {\n\t\tcase \"organization\": return \"org\";\n\t\tcase \"project\": return \"project\";\n\t\tcase \"user\": return \"user\";\n\t}\n}\nfunction formatCredentialRef(row) {\n\treturn `${credentialScopePrefix(row.scopeType)}/${row.slug}`;\n}\nfunction formatCredentialRefSuggestion(row) {\n\treturn `${formatCredentialRef(row)} (${row.appSlug})`;\n}\nfunction parseCredentialRef(ref) {\n\tconst trimmed = ref.trim();\n\tif (UUID_PATTERN.test(trimmed)) return {\n\t\tkind: \"uuid\",\n\t\tid: trimmed\n\t};\n\tconst parts = trimmed.split(\"/\").filter(Boolean);\n\tif (parts.length === 2) {\n\t\tconst scopeType = SCOPE_PREFIXES[parts[0].toLowerCase()];\n\t\tif (scopeType) return {\n\t\t\tkind: \"scope\",\n\t\t\tscopeType,\n\t\t\tslug: parts[1]\n\t\t};\n\t\treturn {\n\t\t\tkind: \"app\",\n\t\t\tappSlug: parts[0],\n\t\t\tslug: parts[1]\n\t\t};\n\t}\n\treturn {\n\t\tkind: \"bare\",\n\t\tslug: trimmed\n\t};\n}\nfunction matchesCredentialRef(row, parsed) {\n\tswitch (parsed.kind) {\n\t\tcase \"uuid\": return row.id === parsed.id;\n\t\tcase \"scope\": return row.scopeType === parsed.scopeType && row.slug === parsed.slug;\n\t\tcase \"app\": return row.appSlug === parsed.appSlug && row.slug === parsed.slug;\n\t\tcase \"bare\": return row.slug === parsed.slug;\n\t}\n}\n//#endregion\n//#region src/resolve-credential-ref.ts\nfunction defaultCanAccess(_row) {\n\treturn true;\n}\n/** Resolve a friendly credential ref (uuid, bare slug, scope/slug, or app/slug). */\nasync function resolveCredentialRef(options) {\n\tconst parsed = parseCredentialRef(options.ref);\n\tconst canAccess = options.canAccess ?? defaultCanAccess;\n\tif (parsed.kind === \"uuid\") {\n\t\tconst row = await selectCredentialInstanceById$2(parsed.id);\n\t\tif (!row) return {\n\t\t\terror: \"Credential instance not found\",\n\t\t\tstatus: 404\n\t\t};\n\t\tif (!canAccess(row)) return {\n\t\t\terror: \"Forbidden\",\n\t\t\tstatus: 403\n\t\t};\n\t\treturn { row };\n\t}\n\tconst candidates = (await listCredentialInstancesForAssignment({ userId: options.userId })).filter((row) => canAccess(row) && matchesCredentialRef(row, parsed));\n\tif (candidates.length === 1) return { row: candidates[0] };\n\tif (candidates.length === 0) return {\n\t\terror: \"Credential instance not found\",\n\t\tstatus: 404\n\t};\n\tconst suggestions = candidates.map((row) => formatCredentialRefSuggestion(row)).join(\", \");\n\treturn {\n\t\terror: `Ambiguous credential \"${options.ref}\". Multiple instances match: ${suggestions}`,\n\t\tstatus: 400\n\t};\n}\nfunction canAssignCredentialInstance(row, userId, projectId) {\n\tswitch (row.scopeType) {\n\t\tcase \"user\": return userId !== void 0 && row.scopeId === userId;\n\t\tcase \"project\": return row.scopeId === projectId;\n\t\tcase \"organization\": return true;\n\t}\n}\nfunction canManageCredentialInstance(row, userId) {\n\tif (row.scopeType === \"user\") return userId !== void 0 && row.scopeId === userId;\n\treturn true;\n}\n//#endregion\n//#region src/context.ts\nfunction buildCredentialRunContext(input = {}) {\n\tconst subscription = input.subscription;\n\tconst request = input.request ?? {};\n\tconst userId = request.userId ?? subscription?.userId ?? input.actor?.userId;\n\treturn {\n\t\torgId: request.orgId ?? subscription?.orgId,\n\t\tprojectId: request.projectId ?? subscription?.projectId,\n\t\tuserId,\n\t\tuserIds: request.userIds,\n\t\tselection: {\n\t\t\t...subscription?.credentialSelection,\n\t\t\t...request.selection\n\t\t}\n\t};\n}\n//#endregion\n//#region src/project-credential-backend.ts\nlet projectCredentialBackend;\n/** Set during server bootstrap so credential resolution reuses the plugin token-refresh registry. */\nfunction setProjectCredentialBackend(backend) {\n\tprojectCredentialBackend = backend;\n}\nfunction getProjectCredentialBackend() {\n\treturn projectCredentialBackend;\n}\n//#endregion\n//#region src/resolve-vault.ts\nfunction toSelectionOption(row) {\n\treturn {\n\t\tid: row.id,\n\t\tlabel: row.name ?? row.label,\n\t\tscopeType: row.scopeType,\n\t\tscopeId: row.scopeId\n\t};\n}\nfunction resolveUserId(key, context) {\n\treturn context.userIds?.[key] ?? context.userId;\n}\nfunction pickInstance(rows, key, consumer) {\n\tif (rows.length === 0) throw new MissingCredentialsError({\n\t\tkey,\n\t\tchainAttempted: [],\n\t\tconsumer\n\t});\n\tif (rows.length === 1) return rows[0];\n\tconst defaults = rows.filter((row) => row.isDefault);\n\tif (defaults.length === 1) return defaults[0];\n\tthrow new NeedsSelectionError({\n\t\tkey,\n\t\toptions: rows.map(toSelectionOption),\n\t\tconsumer\n\t});\n}\n/** Throttle window for last-used writes so bursty runs don't hammer the same row. */\nconst LAST_USED_THROTTLE_MS = 6e4;\n/**\n* Record that a credential was just resolved. Throttled (skip when touched within\n* {@link LAST_USED_THROTTLE_MS}) and best-effort: a write failure must never break resolution.\n*/\nasync function touchLastUsed(row) {\n\tconst last = row.lastUsedAt?.getTime();\n\tif (last !== void 0 && Date.now() - last < LAST_USED_THROTTLE_MS) return;\n\ttry {\n\t\tawait touchCredentialInstanceLastUsed$1(row.id);\n\t} catch {}\n}\nasync function resolveInstanceValue(row, requirement, backend, mode, consumer) {\n\tconst value = await materializeInstanceValue(row, requirement, backend, mode, consumer);\n\tawait touchLastUsed(row);\n\treturn value;\n}\nasync function materializeInstanceValue(row, requirement, backend, mode, consumer) {\n\tconst schema = mode === \"sandbox\" ? requirement.materializedSchema : requirement.schema;\n\tif (row.authKind === \"keystroke\") {\n\t\tif (!row.connectionId) throw new MissingCredentialsError({\n\t\t\tkey: row.appSlug,\n\t\t\tchainAttempted: [\"keystroke\"],\n\t\t\tconsumer\n\t\t});\n\t\tif (requirement.kind === \"oauth_managed\") return materializeComposioOAuthMirror(row, requirement, backend, schema, consumer);\n\t\tif (requirement.kind === \"api_key\") return materializeComposioApiKeySecret(row, backend, schema, consumer);\n\t\tif (mode === \"sandbox\") return backend.resolveKeystrokeSandbox({\n\t\t\tinstanceId: row.id,\n\t\t\tconnectionId: row.connectionId,\n\t\t\tappSlug: row.appSlug,\n\t\t\tschema\n\t\t});\n\t\tconst scopeId = row.scopeType === \"organization\" ? getServerTenantScopeId() : row.scopeId ?? \"\";\n\t\tif (!scopeId) throw new MissingCredentialsError({\n\t\t\tkey: row.appSlug,\n\t\t\tchainAttempted: [\"keystroke\"],\n\t\t\tconsumer\n\t\t});\n\t\tconst value = {\n\t\t\tconnectionId: row.connectionId,\n\t\t\tentityId: row.sharedConnectionId ?? mcpEntityId(row.scopeType, scopeId),\n\t\t\tinstanceId: row.id\n\t\t};\n\t\treturn schema.parse(value);\n\t}\n\tif (row.authKind === \"oauth_managed\") {\n\t\tif (!row.connectionId) throw new MissingCredentialsError({\n\t\t\tkey: row.appSlug,\n\t\t\tchainAttempted: [\"oauth_managed\"],\n\t\t\tconsumer\n\t\t});\n\t\tconst token = await backend.getOAuthAccessToken(row.connectionId);\n\t\tconst tokenField = requirement.tokenField ?? \"accessToken\";\n\t\tconst value = tokenField === \"accessToken\" ? token : { [tokenField]: token.accessToken };\n\t\treturn schema.parse(value);\n\t}\n\treturn backend.resolveApiKey(row.id, schema);\n}\nasync function materializeComposioOAuthMirror(row, requirement, backend, schema, consumer) {\n\tconst composioConnectionId = row.connectionId;\n\tif (!composioConnectionId) throw new MissingCredentialsError({\n\t\tkey: row.appSlug,\n\t\tchainAttempted: [\"keystroke\", \"oauth_mirror\"],\n\t\tconsumer\n\t});\n\tconst token = await backend.getOAuthAccessTokenFromMirror({\n\t\tappSlug: row.appSlug,\n\t\tcomposioConnectionId\n\t});\n\tif (!token) throw new CredentialAccessUnavailableError({\n\t\tappSlug: row.appSlug,\n\t\treason: \"reconnect_required\",\n\t\tconsumer,\n\t\tmessage: `Reconnect the \\`${row.appSlug}\\` credential to use native OAuth (no mirrored access token for Composio connection).`\n\t});\n\tif (isUnusableMirroredAccessToken(token.accessToken)) throw new CredentialAccessUnavailableError({\n\t\tappSlug: row.appSlug,\n\t\treason: \"reconnect_required\",\n\t\tconsumer,\n\t\tmessage: `Reconnect the \\`${row.appSlug}\\` credential to use native OAuth (mirrored token is not a usable provider access token).`\n\t});\n\tconst tokenField = requirement.tokenField ?? \"accessToken\";\n\tconst value = tokenField === \"accessToken\" ? token : { [tokenField]: token.accessToken };\n\treturn schema.parse(value);\n}\n/** Dual-read secrets dual-written onto a Composio keystroke instance (API_KEY / BASIC / …). */\nasync function materializeComposioApiKeySecret(row, backend, schema, consumer) {\n\ttry {\n\t\treturn await backend.resolveApiKey(row.id, schema);\n\t} catch (error) {\n\t\tif (error instanceof MissingCredentialsError) throw new CredentialAccessUnavailableError({\n\t\t\tappSlug: row.appSlug,\n\t\t\treason: \"reconnect_required\",\n\t\t\tconsumer,\n\t\t\tmessage: `Reconnect the \\`${row.appSlug}\\` credential to use native API-key auth (no dual-written secret for Composio connection).`\n\t\t});\n\t\tthrow error;\n\t}\n}\nasync function resolveSelectedInstance(key, instanceId, context, consumer) {\n\tconst row = await selectCredentialInstanceById$1(instanceId);\n\tif (!row || row.appSlug !== key) throw new MissingCredentialsError({\n\t\tkey,\n\t\tchainAttempted: [\"selection\"],\n\t\tconsumer\n\t});\n\tif (!credentialScopeMatchesContext(row.scopeType, row.scopeId, context)) throw new CredentialAccessDeniedError(instanceId);\n\treturn row;\n}\nfunction withTenantScope(context) {\n\treturn context.orgId ? context : {\n\t\t...context,\n\t\torgId: getServerTenantScopeId()\n\t};\n}\nfunction scopeIdForScope(scope, key, context) {\n\tswitch (scope) {\n\t\tcase \"organization\": return context.orgId;\n\t\tcase \"project\": return context.projectId;\n\t\tcase \"user\": return resolveUserId(key, context);\n\t}\n}\nasync function resolveAtScope(key, scopeType, scopeId, consumer) {\n\tconst rows = await selectCredentialInstancesForScope$1(key, scopeType, scopeId);\n\tif (rows.length === 0) return;\n\treturn pickInstance(rows, key, consumer);\n}\nasync function resolveBoundInstance(instanceId, requirement, context, consumer, backend, mode) {\n\tconst row = await selectCredentialInstanceById$1(instanceId);\n\tif (!row || row.appSlug !== requirement.key) throw new MissingCredentialsError({\n\t\tkey: requirement.key,\n\t\tchainAttempted: [\"binding\"],\n\t\tconsumer\n\t});\n\tif (!bindingTenantReachable(row, context)) throw new CredentialAccessDeniedError(instanceId);\n\treturn resolveInstanceValue(row, requirement, backend ?? createCredentialBackend(), mode, consumer);\n}\nfunction bindingTenantReachable(row, context) {\n\tswitch (row.scopeType) {\n\t\tcase \"organization\": return row.scopeId === context.orgId;\n\t\tcase \"project\": return row.scopeId === context.projectId;\n\t\tcase \"user\": return Boolean(row.scopeId);\n\t\tdefault: return false;\n\t}\n}\n/**\n* Resolution order:\n*   1. Platform assignment (consumer-specific, then wildcard).\n*   2. Client selection in `context.selection`.\n*   3. Scope pinned on the requirement (`.scope(\"user\")`).\n*   4. Project default, then org default.\n*/\nasync function resolvePolicy(requirement, context, consumer, backend, mode) {\n\tconst attempted = [];\n\tconst materialBackend = backend ?? createCredentialBackend();\n\tconst scoped = withTenantScope(context);\n\tconst boundId = requirement.kind !== \"keystroke\" ? selectAssignedInstanceId(scoped.assignments, consumer?.id, requirement.key) : void 0;\n\tif (boundId) return resolveBoundInstance(boundId, requirement, scoped, consumer, materialBackend, mode);\n\tif (requirement.kind === \"keystroke\") {\n\t\tconst bound = await resolveKeystrokeInstanceId({\n\t\t\tapp: requirement.key,\n\t\t\tscopes: [],\n\t\t\tassignments: scoped.assignments,\n\t\t\tconsumerId: consumer?.id\n\t\t});\n\t\tif (bound) {\n\t\t\tconst row = await selectCredentialInstanceById$1(bound.instanceId);\n\t\t\tif (!row) throw new MissingCredentialsError({\n\t\t\t\tkey: requirement.key,\n\t\t\t\tchainAttempted: [\"binding\"],\n\t\t\t\tconsumer\n\t\t\t});\n\t\t\treturn resolveInstanceValue(row, requirement, materialBackend, mode, consumer);\n\t\t}\n\t}\n\tconst selectionId = context.selection?.[requirement.key];\n\tif (selectionId) return resolveInstanceValue(await resolveSelectedInstance(requirement.key, selectionId, scoped, consumer), requirement, materialBackend, mode, consumer);\n\tif (requirement.scope) {\n\t\tconst scopeId = scopeIdForScope(requirement.scope, requirement.key, scoped);\n\t\tif (scopeId) {\n\t\t\tattempted.push(requirement.scope);\n\t\t\tconst row = await resolveAtScope(requirement.key, requirement.scope, scopeId, consumer);\n\t\t\tif (row) return resolveInstanceValue(row, requirement, materialBackend, mode, consumer);\n\t\t}\n\t\tthrow new MissingCredentialsError({\n\t\t\tkey: requirement.key,\n\t\t\tchainAttempted: attempted.length > 0 ? attempted : [requirement.scope],\n\t\t\tconsumer\n\t\t});\n\t}\n\tif (requirement.kind === \"keystroke\") {\n\t\tconst scopes = [];\n\t\tif (scoped.projectId) {\n\t\t\tattempted.push(\"project\");\n\t\t\tscopes.push([\"project\", scoped.projectId]);\n\t\t}\n\t\tif (scoped.orgId) {\n\t\t\tattempted.push(\"organization\");\n\t\t\tscopes.push([\"organization\", scoped.orgId]);\n\t\t}\n\t\tconst resolved = await resolveKeystrokeInstanceId({\n\t\t\tapp: requirement.key,\n\t\t\tscopes,\n\t\t\tconsumerId: consumer?.id,\n\t\t\tconsumer\n\t\t});\n\t\tif (resolved) {\n\t\t\tconst row = await selectCredentialInstanceById$1(resolved.instanceId);\n\t\t\tif (row) return resolveInstanceValue(row, requirement, materialBackend, mode, consumer);\n\t\t}\n\t\tthrow new MissingCredentialsError({\n\t\t\tkey: requirement.key,\n\t\t\tchainAttempted: attempted,\n\t\t\tconsumer\n\t\t});\n\t}\n\tif (scoped.projectId) {\n\t\tattempted.push(\"project\");\n\t\tconst row = await resolveAtScope(requirement.key, \"project\", scoped.projectId, consumer);\n\t\tif (row) return resolveInstanceValue(row, requirement, materialBackend, mode, consumer);\n\t}\n\tif (scoped.orgId) {\n\t\tattempted.push(\"organization\");\n\t\tconst row = await resolveAtScope(requirement.key, \"organization\", scoped.orgId, consumer);\n\t\tif (row) return resolveInstanceValue(row, requirement, materialBackend, mode, consumer);\n\t}\n\tthrow new MissingCredentialsError({\n\t\tkey: requirement.key,\n\t\tchainAttempted: attempted,\n\t\tconsumer\n\t});\n}\nasync function resolveCredentialRequirements(options) {\n\tconst resolved = {};\n\tconst requirements = normalizeCredentialList(options.requirements);\n\tconst backend = options.credentialBackend ?? createCredentialBackend();\n\tconst mode = options.materialization ?? \"action\";\n\tfor (const requirement of requirements) resolved[requirement.key] = await resolvePolicy(requirement, options.context, options.consumer, backend, mode);\n\treturn resolved;\n}\nasync function resolveSandboxCredentialRequirements(options) {\n\tconst consumer = options.consumer ?? {\n\t\tkind: \"sandbox\",\n\t\tname: \"sandbox\",\n\t\tid: SANDBOX_CREDENTIAL_CONSUMER_ID\n\t};\n\treturn resolveCredentialRequirements({\n\t\t...options,\n\t\tconsumer,\n\t\tmaterialization: \"sandbox\"\n\t});\n}\n//#endregion\n//#region src/create-credential-resolver.ts\nfunction createCredentialResolver(options) {\n\tconst credentialBackend = options.credentialBackend ?? getProjectCredentialBackend() ?? createCredentialBackend();\n\tfunction buildContext(contextOverride) {\n\t\treturn {\n\t\t\t...options.context,\n\t\t\t...contextOverride,\n\t\t\tselection: {\n\t\t\t\t...options.context.selection,\n\t\t\t\t...contextOverride?.selection\n\t\t\t},\n\t\t\tuserIds: {\n\t\t\t\t...options.context.userIds,\n\t\t\t\t...contextOverride?.userIds\n\t\t\t}\n\t\t};\n\t}\n\treturn {\n\t\tasync resolve(requirements, consumer, contextOverride) {\n\t\t\treturn resolveCredentialRequirements({\n\t\t\t\trequirements,\n\t\t\t\tconsumer,\n\t\t\t\tcredentialBackend,\n\t\t\t\tcontext: buildContext(contextOverride)\n\t\t\t});\n\t\t},\n\t\tasync resolveSandbox(requirements, consumer, contextOverride) {\n\t\t\treturn resolveSandboxCredentialRequirements({\n\t\t\t\trequirements,\n\t\t\t\tconsumer,\n\t\t\t\tcredentialBackend,\n\t\t\t\tcontext: buildContext(contextOverride)\n\t\t\t});\n\t\t}\n\t};\n}\n//#endregion\n//#region src/mcp/resolve-mcp-tools.ts\nfunction translateMcpScopeError(error, key) {\n\tif (error instanceof McpInsufficientScopeError) throw new McpInsufficientScopeCredentialError(key, error.requiredScopes);\n\tthrow error;\n}\nasync function connectWithScopeTranslation(def, resolver) {\n\ttry {\n\t\treturn await connectMcpDefinition(def, await resolveMcpAuth(def, resolver));\n\t} catch (error) {\n\t\ttranslateMcpScopeError(error, def.key);\n\t}\n}\nasync function resolveMcpAuth(def, resolver) {\n\tif (!def.credentials?.length) return;\n\tconst credentials = await resolver.resolve(def.credentials, {\n\t\tkind: \"tool\",\n\t\tname: def.key\n\t});\n\treturn def.auth(credentials);\n}\nasync function resolveMcpTools(def, resolver) {\n\tif (!def.declaredTools?.length) {\n\t\tconst connection = await connectWithScopeTranslation(def, resolver);\n\t\treturn {\n\t\t\ttoolSet: connection.toolSet,\n\t\t\tclose: connection.close\n\t\t};\n\t}\n\tlet connectionPromise;\n\tconst ensureConnected = () => {\n\t\tconnectionPromise ??= connectWithScopeTranslation(def, resolver);\n\t\treturn connectionPromise;\n\t};\n\tconst toolSet = {};\n\tfor (const declared of def.declaredTools) {\n\t\tconst toolName = createToolName(def.key, declared.name);\n\t\ttoolSet[toolName] = tool({\n\t\t\tdescription: declared.description ?? declared.title ?? declared.name,\n\t\t\tinputSchema: jsonSchema(normalizeInputSchema({\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {},\n\t\t\t\t...declared.inputSchema\n\t\t\t})),\n\t\t\texecute: async (input, options) => {\n\t\t\t\tconst nativeTool = (await ensureConnected()).toolSet[toolName];\n\t\t\t\tif (!nativeTool?.execute) throw new Error(`MCP tool \"${declared.name}\" not found on server \"${def.key}\".`);\n\t\t\t\ttry {\n\t\t\t\t\treturn await nativeTool.execute(input, options);\n\t\t\t\t} catch (error) {\n\t\t\t\t\ttranslateMcpScopeError(error, def.key);\n\t\t\t\t}\n\t\t\t},\n\t\t\ttoModelOutput: async (options) => {\n\t\t\t\tconst nativeTool = (await ensureConnected()).toolSet[toolName];\n\t\t\t\tif (nativeTool?.toModelOutput) return nativeTool.toModelOutput(options);\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"json\",\n\t\t\t\t\tvalue: options.output\n\t\t\t\t};\n\t\t\t}\n\t\t});\n\t}\n\treturn {\n\t\ttoolSet,\n\t\tclose: async () => {\n\t\t\tif (connectionPromise) await (await connectionPromise).close();\n\t\t}\n\t};\n}\n//#endregion\n//#region src/mcp/connected-mcp-app.ts\nconst ApiKeyFieldsSchema = z.record(z.string(), z.unknown());\nasync function visibleCredentialRows(rows, canAccessCredential) {\n\tconst visible = [];\n\tfor (const row of rows) if (!canAccessCredential || await canAccessCredential(row)) visible.push(row);\n\treturn visible;\n}\n/** Prefer project-scoped, then organization-scoped, then first visible. */\nfunction pickPreferredCredential(visible, projectId) {\n\tif (projectId) {\n\t\tconst projectScoped = visible.find((row) => row.scopeType === \"project\" && row.scopeId === projectId);\n\t\tif (projectScoped) return projectScoped;\n\t}\n\tconst orgScoped = visible.find((row) => row.scopeType === \"organization\");\n\tif (orgScoped) return orgScoped;\n\treturn visible[0];\n}\nasync function resolveCredentialInstance(appSlug, options) {\n\tconst rows = await selectCredentialInstancesByAppSlug(appSlug);\n\tif (options.credentialId) {\n\t\tconst match = rows.find((row) => row.id === options.credentialId);\n\t\tif (!match) throw new Error(\"Credential not found\");\n\t\tif (options.canAccessCredential && !await options.canAccessCredential(match)) throw new Error(\"Credential not found\");\n\t\treturn match;\n\t}\n\tif (options.credentialSlug) {\n\t\tconst match = pickPreferredCredential(await visibleCredentialRows(rows.filter((row) => row.slug === options.credentialSlug), options.canAccessCredential), options.projectId);\n\t\tif (!match) throw new Error(`No \"${appSlug}\" credential named \"${options.credentialSlug}\" found in scope.`);\n\t\treturn match;\n\t}\n\treturn pickPreferredCredential(await visibleCredentialRows(rows, options.canAccessCredential), options.projectId);\n}\n/** Resolve Bearer / API-key headers for a connected custom MCP app (oauth, api_key, NO_AUTH). */\nasync function resolveConnectedMcpAuthHeaders(app, options = {}) {\n\tif (app.authKind === \"oauth\") {\n\t\tconst instance = await resolveCredentialInstance(app.slug, options);\n\t\tif (!instance) throw new Error(`No connected credential for ${app.slug}. Run \\`keystroke connect ${app.slug}\\` first.`);\n\t\tif (instance.authKind !== \"oauth_managed\" || !instance.connectionId) throw new Error(`Credential for ${app.slug} is not an OAuth connection`);\n\t\tconst { accessToken } = await createLocalCredentialBackend().getOAuthAccessToken(instance.connectionId);\n\t\treturn { Authorization: `Bearer ${accessToken}` };\n\t}\n\tif (app.authKind === \"api_key\") {\n\t\tif (app.credentialScheme === \"NO_AUTH\") return;\n\t\tconst instance = await resolveCredentialInstance(app.slug, options);\n\t\tif (!instance) throw new Error(`No connected credential for ${app.slug}. Run \\`keystroke connect ${app.slug}\\` first.`);\n\t\tconst backend = createLocalCredentialBackend();\n\t\tconst fields = ApiKeyFieldsSchema.parse(await backend.resolveApiKey(instance.id, ApiKeyFieldsSchema));\n\t\tconst token = typeof fields.token === \"string\" && fields.token || typeof fields.apiKey === \"string\" && fields.apiKey || typeof fields.accessToken === \"string\" && fields.accessToken || Object.values(fields).find((value) => typeof value === \"string\");\n\t\tif (!token) throw new Error(`Credential for ${app.slug} has no string secret field`);\n\t\tif (app.credentialScheme === \"API_KEY\") return { \"X-API-Key\": token };\n\t\treturn { Authorization: `Bearer ${token}` };\n\t}\n\tthrow new Error(`Unsupported auth kind for MCP app: ${app.authKind}`);\n}\nfunction mcpToolErrorMessage(result) {\n\tif (typeof result !== \"object\" || result === null || !(\"content\" in result)) return \"MCP tool returned an error.\";\n\tconst content = result.content;\n\tif (!Array.isArray(content)) return \"MCP tool returned an error.\";\n\treturn content.filter((part) => typeof part === \"object\" && part !== null && \"type\" in part && part.type === \"text\" && \"text\" in part && typeof part.text === \"string\").map((part) => part.text.trim()).filter(Boolean).join(\"\\n\") || \"MCP tool returned an error.\";\n}\n/** Call a tool on a connected custom MCP app URL using stored org credentials. */\nasync function callConnectedMcpAppTool(app, tool, args = {}, options = {}) {\n\tif (app.source !== \"mcp\" || !app.url?.trim()) throw new Error(\"App is not an MCP app with a server URL\");\n\tconst headers = await resolveConnectedMcpAuthHeaders(app, options);\n\treturn withMcpReadClient(app.url, async (client) => {\n\t\tconst result = await client.callTool({\n\t\t\tname: tool,\n\t\t\targuments: args\n\t\t});\n\t\tif (result.isError) throw new Error(mcpToolErrorMessage(result));\n\t\treturn result;\n\t}, headers ? { headers } : void 0);\n}\n//#endregion\n//#region src/oauth-state.ts\nconst DEFAULT_STATE_TTL_MS = 600 * 1e3;\nfunction defaultSigningKey() {\n\tconst secret = process.env.CREDENTIALS_ENCRYPTION_KEY?.trim();\n\tif (!secret) throw new Error(\"CREDENTIALS_ENCRYPTION_KEY is required\");\n\treturn secret;\n}\nfunction signPayload(payload, signingKey) {\n\treturn createHmac(\"sha256\", signingKey()).update(payload).digest(\"base64url\");\n}\nfunction createOAuthState(options = {}) {\n\tconst signingKey = options.signingKey ?? defaultSigningKey;\n\tconst payload = options.payload ?? {};\n\tconst payloadSegment = (options.serializePayload ?? (() => \"\"))(payload);\n\tconst id = randomBytes(16).toString(\"hex\");\n\tconst expiresAt = Date.now() + (options.ttlMs ?? DEFAULT_STATE_TTL_MS);\n\tconst signedPayload = payloadSegment ? `${id}.${expiresAt}.${payloadSegment}` : `${id}.${expiresAt}`;\n\treturn {\n\t\tstate: `${signedPayload}.${signPayload(signedPayload, signingKey)}`,\n\t\tpayload,\n\t\tid,\n\t\texpiresAt\n\t};\n}\nfunction verifyOAuthState(options, state) {\n\tif (!state) return null;\n\tconst hasPayload = Boolean(options.deserializePayload);\n\tconst parts = state.split(\".\");\n\tif (parts.length !== (hasPayload ? 4 : 3)) return null;\n\tconst [id, expiresRaw] = parts;\n\tconst signature = parts.at(-1);\n\tif (!id || !expiresRaw || !signature) return null;\n\tconst payloadSegment = hasPayload ? parts[2] ?? \"\" : \"\";\n\tconst expected = signPayload(hasPayload ? `${id}.${expiresRaw}.${payloadSegment}` : `${id}.${expiresRaw}`, options.signingKey ?? defaultSigningKey);\n\tconst signatureBuffer = Buffer.from(signature);\n\tconst expectedBuffer = Buffer.from(expected);\n\tif (signatureBuffer.length !== expectedBuffer.length || !timingSafeEqual(signatureBuffer, expectedBuffer)) return null;\n\tconst expiresAt = Number(expiresRaw);\n\tif (!Number.isFinite(expiresAt) || expiresAt < Date.now()) return null;\n\tif (!hasPayload) return {};\n\treturn options.deserializePayload(payloadSegment);\n}\n//#endregion\n//#region src/mcp-provider.ts\nasync function encodeOAuthState(payload, ttlMs) {\n\tconst { state, id, expiresAt } = createOAuthState({\n\t\tpayload,\n\t\tttlMs\n\t});\n\tawait putOAuthPendingState({\n\t\tid,\n\t\tpayloadCiphertext: encryptCredentialPayload(JSON.stringify(payload)),\n\t\texpiresAt: new Date(expiresAt)\n\t});\n\treturn state;\n}\nasync function decodeOAuthState(state) {\n\tconst verified = verifyOAuthState({}, state);\n\tconst id = state.split(\".\")[0];\n\tif (!verified || !id) throw new Error(\"OAuth state is invalid or expired\");\n\tconst ciphertext = await takeOAuthPendingState(id);\n\tif (!ciphertext) throw new Error(\"OAuth state is invalid or expired\");\n\ttry {\n\t\treturn JSON.parse(decryptCredentialPayload(ciphertext));\n\t} catch {\n\t\tthrow new Error(\"OAuth state is invalid or expired\");\n\t}\n}\nfunction oauthAppMetadata(oauth, mcpUrl, options) {\n\treturn {\n\t\tmcpUrl,\n\t\tauthorizationEndpoint: oauth.authorizationEndpoint,\n\t\ttokenEndpoint: oauth.tokenEndpoint,\n\t\tregistrationEndpoint: oauth.registrationEndpoint,\n\t\tresource: oauth.resource,\n\t\tissuer: oauth.issuer,\n\t\tscopes: oauth.scopes,\n\t\t...options?.tokenEndpointAuthMethod ? { tokenEndpointAuthMethod: options.tokenEndpointAuthMethod } : {},\n\t\t...options?.clientRegistrationMode ? { clientRegistrationMode: options.clientRegistrationMode } : {},\n\t\t...options?.redirectUri ? { redirectUri: options.redirectUri } : {}\n\t};\n}\nfunction oauthClientSecretForStorage(clientSecret) {\n\treturn clientSecret?.trim() ? clientSecret : \"\";\n}\nfunction grantedScopesFromToken(scope, fallbackScopes) {\n\tconst trimmed = scope?.trim();\n\tif (!trimmed) return fallbackScopes;\n\treturn trimmed.split(/\\s+/).filter(Boolean);\n}\nfunction accessTokenExpiresAt(expiresIn) {\n\tif (!expiresIn || expiresIn <= 0) return;\n\treturn new Date(Date.now() + expiresIn * 1e3);\n}\nasync function discoverMcpApp(url) {\n\tconst probe = await probeMcpAuth(url);\n\tconst template = mcpProbeToAppTemplate(probe);\n\tconst serverInfo = await probeMcpServerInfo(url);\n\tconst serverName = probe.oauth?.resourceName?.trim() || serverInfo?.title?.trim() || serverInfo?.name?.trim() || void 0;\n\tconst serverDescription = serverInfo?.description?.trim() || void 0;\n\treturn {\n\t\tdetected: probe.mode === \"oauth\" ? Boolean(probe.oauth) : probe.unauthenticatedStatus !== void 0,\n\t\ttemplate: {\n\t\t\t...template,\n\t\t\t...serverName ? { serverName } : {},\n\t\t\t...serverDescription ? { serverDescription } : {}\n\t\t}\n\t};\n}\nvar McpOAuthConnectError = class extends Error {\n\tphase;\n\tdiagnostics;\n\tconstructor(phase, message, diagnostics = {}) {\n\t\tsuper(message);\n\t\tthis.phase = phase;\n\t\tthis.diagnostics = diagnostics;\n\t\tthis.name = \"McpOAuthConnectError\";\n\t}\n};\nfunction oauthErrorCode(error) {\n\tif (!error || typeof error !== \"object\" || !(\"errorCode\" in error)) return;\n\tconst value = Reflect.get(error, \"errorCode\");\n\treturn typeof value === \"string\" && /^[a-z0-9_]+$/i.test(value) ? value : void 0;\n}\nconst SUPPORTED_TOKEN_AUTH_METHODS = [\n\t\"client_secret_basic\",\n\t\"client_secret_post\",\n\t\"none\"\n];\nfunction requireHttpsUrl(value, label) {\n\tconst url = new URL(value);\n\tif (url.protocol !== \"https:\") throw new Error(`${label} must use HTTPS`);\n\treturn url;\n}\nfunction validateRedirectUri(value) {\n\tconst url = new URL(value);\n\tconst isLocalhost = url.hostname === \"localhost\" || url.hostname === \"127.0.0.1\";\n\tif (url.protocol !== \"https:\" && !(url.protocol === \"http:\" && isLocalhost)) throw new Error(\"OAuth redirect URI must use HTTPS or HTTP localhost\");\n}\nfunction validateMcpResource(mcpUrl, resourceUrl) {\n\tconst serverUrl = new URL(mcpUrl);\n\tif (serverUrl.hash || resourceUrl.hash || resourceUrl.toString() !== serverUrl.toString()) throw new Error(\"MCP protected resource does not identify the requested MCP server\");\n}\nfunction selectTokenEndpointAuthMethod(metadata) {\n\tconst advertised = metadata.token_endpoint_auth_methods_supported;\n\tconst supported = advertised?.length ? advertised : [\"client_secret_basic\"];\n\tconst selected = SUPPORTED_TOKEN_AUTH_METHODS.find((method) => supported.includes(method));\n\tif (!selected) throw new Error(`MCP authorization server only supports unsupported token endpoint authentication methods: ${supported.join(\", \")}`);\n\treturn selected;\n}\nfunction validateAuthorizationCapabilities(metadata) {\n\tif (!metadata.response_types_supported?.includes(\"code\")) throw new Error(\"MCP authorization server does not support the code response type\");\n\tif (metadata.grant_types_supported?.length && !metadata.grant_types_supported.includes(\"authorization_code\")) throw new Error(\"MCP authorization server does not support authorization_code\");\n\tif (!metadata.code_challenge_methods_supported?.includes(\"S256\")) throw new Error(\"MCP authorization server does not advertise PKCE S256 support\");\n}\nfunction validateRegisteredClientInformation(clientInformation, requestedMethod, advertisedMethods) {\n\tconst assignedMethod = clientInformation.token_endpoint_auth_method ?? requestedMethod;\n\tif (!SUPPORTED_TOKEN_AUTH_METHODS.includes(assignedMethod)) throw new Error(`MCP authorization server assigned unsupported token endpoint authentication method: ${assignedMethod}`);\n\tif (!advertisedMethods.includes(assignedMethod)) throw new Error(`MCP authorization server assigned an unadvertised token endpoint authentication method: ${assignedMethod}`);\n\tif (assignedMethod !== \"none\" && !clientInformation.client_secret?.trim()) throw new Error(`MCP authorization server assigned ${assignedMethod} without a client_secret`);\n\treturn {\n\t\t...clientInformation,\n\t\ttoken_endpoint_auth_method: assignedMethod,\n\t\tregistrationMode: \"dcr\"\n\t};\n}\n/**\n* Prefer CIMD (URL client_id) when the AS advertises support and we have an\n* HTTPS metadata URL; otherwise DCR. Localhost HTTP cannot be a CIMD client_id\n* (Notion and other ASes must fetch it), so local/dev without a tunnel falls\n* back to DCR when available.\n*\n* Spec order: pre-registered → CIMD → DCR → manual.\n*/\nasync function resolveMcpOAuthClientInformation(options) {\n\tconst supportsCimd = options.metadata.client_id_metadata_document_supported === true;\n\tconst supportsPublicClient = options.metadata.token_endpoint_auth_methods_supported?.includes(\"none\") === true;\n\tif (supportsCimd && supportsPublicClient && Boolean(options.clientMetadataUrl) && isHttpsUrl(options.clientMetadataUrl) && options.clientMetadataUrl) return {\n\t\tclient_id: options.clientMetadataUrl,\n\t\ttoken_endpoint_auth_method: \"none\",\n\t\tregistrationMode: \"cimd\"\n\t};\n\tif (options.metadata.registration_endpoint) {\n\t\tconst grantTypes = [\"authorization_code\", ...options.metadata.grant_types_supported?.includes(\"refresh_token\") ? [\"refresh_token\"] : []];\n\t\tconst tokenEndpointAuthMethod = selectTokenEndpointAuthMethod(options.metadata);\n\t\tconst currentlySupportedAuthMethods = options.metadata.token_endpoint_auth_methods_supported?.length ? options.metadata.token_endpoint_auth_methods_supported : [\"client_secret_basic\"];\n\t\tconst existing = await getDecryptedOAuthAppBySlug(options.appSlug);\n\t\tif (existing?.provider === \"mcp\" && existing.metadata?.clientRegistrationMode === \"dcr\" && existing.metadata.issuer === options.metadata.issuer && existing.metadata.registrationEndpoint === options.metadata.registration_endpoint && existing.metadata.resource === options.resource && existing.metadata.redirectUri === options.redirectUri && existing.metadata.tokenEndpointAuthMethod && SUPPORTED_TOKEN_AUTH_METHODS.includes(existing.metadata.tokenEndpointAuthMethod) && currentlySupportedAuthMethods.includes(existing.metadata.tokenEndpointAuthMethod)) return {\n\t\t\tclient_id: existing.clientId,\n\t\t\t...existing.clientSecret ? { client_secret: existing.clientSecret } : {},\n\t\t\ttoken_endpoint_auth_method: existing.metadata.tokenEndpointAuthMethod,\n\t\t\tregistrationMode: \"dcr\"\n\t\t};\n\t\tlet providerHttpStatus;\n\t\ttry {\n\t\t\tconst safeFetch = createPublicHttpFetch();\n\t\t\treturn validateRegisteredClientInformation(await registerClient(options.authorizationServerUrl, {\n\t\t\t\tmetadata: options.metadata,\n\t\t\t\tclientMetadata: {\n\t\t\t\t\tclient_name: \"Keystroke\",\n\t\t\t\t\tredirect_uris: [options.redirectUri],\n\t\t\t\t\tgrant_types: grantTypes,\n\t\t\t\t\tresponse_types: [\"code\"],\n\t\t\t\t\ttoken_endpoint_auth_method: tokenEndpointAuthMethod\n\t\t\t\t},\n\t\t\t\tscope: options.scope,\n\t\t\t\tfetchFn: async (input, init) => {\n\t\t\t\t\tconst response = await safeFetch(input, init);\n\t\t\t\t\tproviderHttpStatus = response.status;\n\t\t\t\t\treturn response;\n\t\t\t\t}\n\t\t\t}), tokenEndpointAuthMethod, currentlySupportedAuthMethods);\n\t\t} catch (error) {\n\t\t\tthrow new McpOAuthConnectError(\"client_registration\", providerHttpStatus === 403 ? \"MCP server rejected dynamic client registration; it may require a pre-approved OAuth client\" : \"MCP OAuth client registration failed\", {\n\t\t\t\tcorrelationId: options.correlationId,\n\t\t\t\tauthorizationServerUrl: options.authorizationServerUrl,\n\t\t\t\tregistrationEndpoint: options.metadata.registration_endpoint,\n\t\t\t\tgrantTypes,\n\t\t\t\ttokenEndpointAuthMethod,\n\t\t\t\t...providerHttpStatus ? { providerHttpStatus } : {},\n\t\t\t\t...oauthErrorCode(error) ? { oauthError: oauthErrorCode(error) } : {}\n\t\t\t});\n\t\t}\n\t}\n\tif (supportsCimd) throw new Error(\"Authorization server supports Client ID Metadata Documents, but not Keystroke's public-client authentication or HTTPS metadata URL\");\n\tthrow new Error(\"MCP authorization server does not support Client ID Metadata Documents or Dynamic Client Registration\");\n}\nasync function beginMcpOAuthConnect(options) {\n\tconst appUrl = options.app.url?.trim();\n\tif (!appUrl || options.app.source !== \"mcp\" || options.app.authKind !== \"oauth\") throw new Error(\"App is not a direct MCP OAuth app\");\n\tconst correlationId = crypto.randomUUID();\n\tlet discovered;\n\ttry {\n\t\tvalidateRedirectUri(options.redirectUri);\n\t\trequireHttpsUrl(appUrl, \"MCP server URL\");\n\t\tdiscovered = await discoverMcpOAuthServer(appUrl);\n\t} catch {\n\t\tthrow new McpOAuthConnectError(\"resource_discovery\", \"Failed to discover MCP OAuth protected-resource metadata\", { correlationId });\n\t}\n\tconst metadata = discovered.authorizationServerMetadata;\n\ttry {\n\t\tif (!metadata?.authorization_endpoint || !metadata.token_endpoint) throw new Error(\"MCP server does not expose OAuth authorization metadata\");\n\t\tvalidateAuthorizationCapabilities(metadata);\n\t\trequireHttpsUrl(discovered.authorizationServerUrl, \"OAuth authorization server URL\");\n\t\trequireHttpsUrl(metadata.authorization_endpoint, \"OAuth authorization endpoint\");\n\t\trequireHttpsUrl(metadata.token_endpoint, \"OAuth token endpoint\");\n\t\tif (metadata.registration_endpoint) requireHttpsUrl(metadata.registration_endpoint, \"OAuth registration endpoint\");\n\t} catch {\n\t\tthrow new McpOAuthConnectError(\"authorization_server_discovery\", \"MCP authorization server metadata is incompatible\", {\n\t\t\tcorrelationId,\n\t\t\tauthorizationServerUrl: discovered.authorizationServerUrl\n\t\t});\n\t}\n\tlet resourceUrl;\n\ttry {\n\t\tresourceUrl = requireHttpsUrl(discovered.resourceMetadata.resource, \"MCP protected resource\");\n\t\tif (resourceUrl.hash) throw new Error(\"MCP protected resource must not include a fragment\");\n\t\tvalidateMcpResource(appUrl, resourceUrl);\n\t} catch {\n\t\tthrow new McpOAuthConnectError(\"resource_discovery\", \"MCP protected-resource metadata contains an invalid resource\", { correlationId });\n\t}\n\tconst oauth = {\n\t\tissuer: metadata.issuer,\n\t\tauthorizationEndpoint: metadata.authorization_endpoint,\n\t\ttokenEndpoint: metadata.token_endpoint,\n\t\tregistrationEndpoint: metadata.registration_endpoint,\n\t\tscopes: discovered.challengeScope ? discovered.challengeScope.split(/\\s+/).filter(Boolean) : discovered.resourceMetadata.scopes_supported ?? [],\n\t\tresource: resourceUrl.toString(),\n\t\tresourceName: discovered.resourceMetadata?.resource_name?.trim() || void 0\n\t};\n\tconst requestedScopes = options.input.scopes?.map((value) => value.trim()).filter(Boolean) ?? [];\n\tconst challengedScopes = discovered.challengeScope?.split(/\\s+/).filter(Boolean) ?? [];\n\tconst selectedScopes = challengedScopes.length > 0 ? [...new Set([...challengedScopes, ...requestedScopes])] : requestedScopes.length > 0 ? requestedScopes : discovered.resourceMetadata.scopes_supported ?? [];\n\tconst scope = selectedScopes.length > 0 ? selectedScopes.join(\" \") : void 0;\n\tlet clientInformation;\n\ttry {\n\t\tclientInformation = await resolveMcpOAuthClientInformation({\n\t\t\tappSlug: options.app.slug,\n\t\t\tcorrelationId,\n\t\t\tauthorizationServerUrl: discovered.authorizationServerUrl,\n\t\t\tmetadata,\n\t\t\tresource: resourceUrl.toString(),\n\t\t\tredirectUri: options.redirectUri,\n\t\t\tscope,\n\t\t\tclientMetadataUrl: options.clientMetadataUrl\n\t\t});\n\t} catch (error) {\n\t\tif (error instanceof McpOAuthConnectError) throw error;\n\t\tthrow new McpOAuthConnectError(\"client_registration\", \"MCP authorization server does not support a compatible client registration\", {\n\t\t\tcorrelationId,\n\t\t\tauthorizationServerUrl: discovered.authorizationServerUrl\n\t\t});\n\t}\n\ttry {\n\t\tawait ensureOAuthApp({\n\t\t\tslug: options.app.slug,\n\t\t\tprovider: \"mcp\",\n\t\t\ttokenStrategy: \"refresh\",\n\t\t\tclientId: clientInformation.client_id,\n\t\t\tclientSecret: oauthClientSecretForStorage(clientInformation.client_secret),\n\t\t\tmetadata: oauthAppMetadata(oauth, appUrl, {\n\t\t\t\ttokenEndpointAuthMethod: clientInformation.token_endpoint_auth_method,\n\t\t\t\tclientRegistrationMode: clientInformation.registrationMode,\n\t\t\t\tredirectUri: options.redirectUri\n\t\t\t})\n\t\t});\n\t} catch {\n\t\tthrow new McpOAuthConnectError(\"credential_persistence\", \"Failed to save MCP OAuth client registration\", { correlationId });\n\t}\n\tconst statePayload = {\n\t\tcorrelationId,\n\t\tcodeVerifier: \"\",\n\t\tappSlug: options.app.slug,\n\t\torganizationId: options.organizationId,\n\t\tuserId: options.userId,\n\t\tscopeTargets: {\n\t\t\t...options.scopeTargets,\n\t\t\tprojectNamesById: options.projectNamesById\n\t\t},\n\t\tauthorizationServerUrl: discovered.authorizationServerUrl,\n\t\tresource: oauth.resource,\n\t\toauthMetadata: oauth,\n\t\tauthorizationServerMetadata: metadata,\n\t\tmcpUrl: appUrl,\n\t\tredirectUri: options.redirectUri,\n\t\tclientId: clientInformation.client_id,\n\t\tclientSecret: clientInformation.client_secret,\n\t\ttokenEndpointAuthMethod: clientInformation.token_endpoint_auth_method,\n\t\tclientRegistrationMode: clientInformation.registrationMode,\n\t\tlabel: options.input.label,\n\t\tcredentialInstanceId: options.input.credentialInstanceId\n\t};\n\tlet authorizationUrl;\n\tlet codeVerifier;\n\ttry {\n\t\t({authorizationUrl, codeVerifier} = await startAuthorization(discovered.authorizationServerUrl, {\n\t\t\tmetadata,\n\t\t\tclientInformation,\n\t\t\tredirectUrl: options.redirectUri,\n\t\t\tscope,\n\t\t\tresource: resourceUrl\n\t\t}));\n\t} catch (error) {\n\t\tthrow new McpOAuthConnectError(\"authorization_start\", \"Failed to start MCP authorization\", {\n\t\t\tcorrelationId,\n\t\t\tauthorizationServerUrl: discovered.authorizationServerUrl,\n\t\t\t...oauthErrorCode(error) ? { oauthError: oauthErrorCode(error) } : {}\n\t\t});\n\t}\n\tstatePayload.codeVerifier = codeVerifier;\n\tconst state = await encodeOAuthState(statePayload);\n\tauthorizationUrl.searchParams.set(\"state\", state);\n\treturn { authorizeUrl: authorizationUrl.toString() };\n}\nasync function completeMcpOAuthConnect(options) {\n\tconst { payload } = options;\n\tconst resourceUrl = payload.resource ? new URL(payload.resource) : void 0;\n\tif (!resourceUrl) throw new McpOAuthConnectError(\"authorization_callback\", \"OAuth callback state is missing the MCP resource\", { correlationId: payload.correlationId });\n\tlet tokens;\n\tlet providerHttpStatus;\n\ttry {\n\t\tconst safeFetch = createPublicHttpFetch();\n\t\ttokens = await exchangeAuthorization(payload.authorizationServerUrl, {\n\t\t\tmetadata: payload.authorizationServerMetadata,\n\t\t\tclientInformation: {\n\t\t\t\tclient_id: payload.clientId,\n\t\t\t\t...payload.clientSecret ? { client_secret: payload.clientSecret } : {},\n\t\t\t\t...payload.tokenEndpointAuthMethod ? { token_endpoint_auth_method: payload.tokenEndpointAuthMethod } : {}\n\t\t\t},\n\t\t\tauthorizationCode: options.code,\n\t\t\tcodeVerifier: payload.codeVerifier,\n\t\t\tredirectUri: payload.redirectUri,\n\t\t\tresource: resourceUrl,\n\t\t\tfetchFn: async (input, init) => {\n\t\t\t\tconst response = await safeFetch(input, init);\n\t\t\t\tproviderHttpStatus = response.status;\n\t\t\t\treturn response;\n\t\t\t}\n\t\t});\n\t} catch (error) {\n\t\tthrow new McpOAuthConnectError(\"token_exchange\", \"MCP OAuth token exchange failed\", {\n\t\t\tcorrelationId: payload.correlationId,\n\t\t\tauthorizationServerUrl: payload.authorizationServerUrl,\n\t\t\t...providerHttpStatus ? { providerHttpStatus } : {},\n\t\t\t...oauthErrorCode(error) ? { oauthError: oauthErrorCode(error) } : {}\n\t\t});\n\t}\n\tlet oauthAppId;\n\tlet connectionId;\n\ttry {\n\t\t({id: oauthAppId} = await ensureOAuthApp({\n\t\t\tslug: payload.appSlug,\n\t\t\tprovider: \"mcp\",\n\t\t\ttokenStrategy: \"refresh\",\n\t\t\tclientId: payload.clientId,\n\t\t\tclientSecret: oauthClientSecretForStorage(payload.clientSecret),\n\t\t\tmetadata: oauthAppMetadata(payload.oauthMetadata, payload.mcpUrl, {\n\t\t\t\ttokenEndpointAuthMethod: payload.tokenEndpointAuthMethod,\n\t\t\t\tclientRegistrationMode: payload.clientRegistrationMode,\n\t\t\t\tredirectUri: payload.redirectUri\n\t\t\t})\n\t\t}));\n\t\tconnectionId = await saveOAuthConnection({\n\t\t\tappId: oauthAppId,\n\t\t\texternalId: payload.userId,\n\t\t\taccessToken: tokens.access_token,\n\t\t\trefreshToken: tokens.refresh_token,\n\t\t\taccessTokenExpiresAt: accessTokenExpiresAt(tokens.expires_in),\n\t\t\tgrantedScopes: grantedScopesFromToken(tokens.scope, payload.oauthMetadata.scopes),\n\t\t\tmetadata: { mcpUrl: payload.oauthMetadata.resource }\n\t\t});\n\t\tawait ensureOAuthCredentialInstance({\n\t\t\tcredentialKey: payload.appSlug,\n\t\t\tconnectionId,\n\t\t\taccountLabel: payload.label,\n\t\t\texternalId: payload.userId,\n\t\t\tuserLabel: payload.label,\n\t\t\ttargets: payload.scopeTargets,\n\t\t\tcredentialInstanceId: payload.credentialInstanceId\n\t\t});\n\t} catch {\n\t\tthrow new McpOAuthConnectError(\"credential_persistence\", \"Failed to save the MCP OAuth credential\", { correlationId: payload.correlationId });\n\t}\n\treturn {\n\t\tappSlug: payload.appSlug,\n\t\tconnectionId,\n\t\torganizationId: payload.organizationId\n\t};\n}\n//#endregion\n//#region src/discovery-error.ts\nvar DiscoveryError = class extends Error {\n\tcode;\n\tstatus;\n\tconstructor(message, code, status) {\n\t\tsuper(message);\n\t\tthis.name = \"DiscoveryError\";\n\t\tthis.code = code;\n\t\tthis.status = status;\n\t}\n};\nfunction isDiscoveryError(error) {\n\treturn error instanceof DiscoveryError;\n}\nfunction discoveryErrorFromPublicHttpUrl(error) {\n\tconst message = error.message;\n\tif (/host is not allowed|URL host is not allowed/i.test(message)) return new DiscoveryError(message, \"url_not_allowed\", 400);\n\treturn new DiscoveryError(message, \"invalid_url\", 400);\n}\nfunction discoveryErrorFromFetchFailure(error, fallback) {\n\tconst message = error instanceof Error ? error.message : fallback;\n\tif (/ENOTFOUND|ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENETUNREACH|fetch failed|network error|certificate|SSL|TLS/i.test(message)) return new DiscoveryError(`Could not reach the public URL (${message})`, \"url_unreachable\", 422);\n\treturn new DiscoveryError(message, \"url_unreachable\", 422);\n}\n//#endregion\n//#region src/openapi-provider.ts\nconst MAX_SPEC_BYTES = 5 * 1024 * 1024;\nfunction isRecord$1(value) {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\nfunction isOpenApiSpec(value) {\n\treturn isRecord$1(value) && (typeof value.openapi === \"string\" || typeof value.swagger === \"string\");\n}\nasync function discoverOpenApiApp(url) {\n\tlet response;\n\ttry {\n\t\tresponse = await fetchPublicHttp(url);\n\t} catch (error) {\n\t\tif (error instanceof PublicHttpUrlError$1) throw discoveryErrorFromPublicHttpUrl(error);\n\t\tthrow discoveryErrorFromFetchFailure(error, \"Failed to fetch OpenAPI spec\");\n\t}\n\tif (!response.ok) throw new DiscoveryError(`Failed to fetch OpenAPI spec (${response.status})`, \"upstream_http_error\", 422);\n\tconst contentLength = response.headers.get(\"content-length\");\n\tif (contentLength && Number(contentLength) > MAX_SPEC_BYTES) throw new DiscoveryError(\"OpenAPI spec is too large\", \"spec_too_large\", 422);\n\tconst text = await response.text();\n\tif (text.length > MAX_SPEC_BYTES) throw new DiscoveryError(\"OpenAPI spec is too large\", \"spec_too_large\", 422);\n\tlet parsed;\n\ttry {\n\t\tparsed = JSON.parse(text);\n\t} catch {\n\t\ttry {\n\t\t\tparsed = YAML.parse(text);\n\t\t} catch {\n\t\t\tthrow new DiscoveryError(\"Failed to parse OpenAPI spec as JSON or YAML\", \"spec_parse_error\", 422);\n\t\t}\n\t}\n\tif (!isOpenApiSpec(parsed)) throw new DiscoveryError(\"URL does not contain a valid OpenAPI or Swagger spec\", \"invalid_openapi\", 422);\n\treturn {\n\t\tdetected: true,\n\t\ttemplate: openApiSpecToAppTemplate(parsed, url)\n\t};\n}\n//#endregion\n//#region src/graphql-provider.ts\nconst MAX_RESPONSE_BYTES = 5 * 1024 * 1024;\nconst INTROSPECTION_QUERY = `query IntrospectionQuery {\n  __schema {\n    queryType { name description }\n    mutationType { name description }\n  }\n}`;\nconst USAGE_AUTH_PROBE_QUERY = \"query { __typename }\";\nasync function postGraphql(endpointUrl, query) {\n\tlet response;\n\ttry {\n\t\tresponse = await fetchPublicHttp(endpointUrl, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: {\n\t\t\t\t\"content-type\": \"application/json\",\n\t\t\t\taccept: \"application/json\"\n\t\t\t},\n\t\t\tbody: JSON.stringify({ query })\n\t\t});\n\t} catch (error) {\n\t\tif (error instanceof PublicHttpUrlError$1) throw discoveryErrorFromPublicHttpUrl(error);\n\t\tthrow discoveryErrorFromFetchFailure(error, \"Failed to reach GraphQL endpoint\");\n\t}\n\tconst contentLength = response.headers.get(\"content-length\");\n\tif (contentLength && Number(contentLength) > MAX_RESPONSE_BYTES) throw new DiscoveryError(\"GraphQL introspection response is too large\", \"spec_too_large\", 422);\n\tconst text = await response.text();\n\tif (text.length > MAX_RESPONSE_BYTES) throw new DiscoveryError(\"GraphQL introspection response is too large\", \"spec_too_large\", 422);\n\tlet body;\n\ttry {\n\t\tbody = JSON.parse(text);\n\t} catch {\n\t\tthrow new DiscoveryError(\"GraphQL endpoint did not return JSON\", \"spec_parse_error\", 422);\n\t}\n\treturn {\n\t\tresponse,\n\t\tbody,\n\t\ttext\n\t};\n}\nfunction introspectionDisabled(body) {\n\tif (!isRecord(body) || !Array.isArray(body.errors)) return false;\n\treturn body.errors.some((error) => {\n\t\tif (!isRecord(error)) return false;\n\t\treturn (typeof error.message === \"string\" ? error.message.toLowerCase() : \"\").includes(\"introspection\");\n\t});\n}\nasync function discoverGraphqlApp(url) {\n\tconst endpointUrl = url.trim();\n\tconst { response, body } = await postGraphql(endpointUrl, INTROSPECTION_QUERY);\n\tconst authProbe = inferGraphqlAuthFromProbe(response.status, response.headers.get(\"www-authenticate\"), body);\n\tif (!(isRecord(body) && isRecord(body.data) && isRecord(body.data.__schema))) {\n\t\tif (response.status === 401 || response.status === 403) return {\n\t\t\tdetected: true,\n\t\t\ttemplate: graphqlIntrospectionToAppTemplate({ data: {} }, endpointUrl, authProbe)\n\t\t};\n\t\tif (response.ok && introspectionDisabled(body)) throw new DiscoveryError(\"Introspection is disabled on this endpoint\", \"invalid_openapi\", 422);\n\t\tthrow new DiscoveryError(`Failed to introspect GraphQL endpoint (${response.status})`, \"upstream_http_error\", 422);\n\t}\n\tlet resolvedAuthProbe = authProbe;\n\tif (resolvedAuthProbe === \"none\") {\n\t\tconst usageProbe = await postGraphql(endpointUrl, USAGE_AUTH_PROBE_QUERY);\n\t\tconst usageAuth = inferGraphqlAuthFromProbe(usageProbe.response.status, usageProbe.response.headers.get(\"www-authenticate\"), usageProbe.body);\n\t\tif (usageAuth !== \"none\") resolvedAuthProbe = usageAuth;\n\t}\n\treturn {\n\t\tdetected: true,\n\t\ttemplate: graphqlIntrospectionToAppTemplate(body, endpointUrl, resolvedAuthProbe)\n\t};\n}\n//#endregion\n//#region src/define-mcp.ts\nfunction defineMcp(def) {\n\treturn defineMcp$1(def);\n}\n//#endregion\n//#region src/parse-resolved-credentials.ts\nfunction parseResolvedCredentials(requirements, credentials) {\n\tif (requirements.length === 0) return {};\n\tconst normalized = normalizeCredentialList(requirements);\n\tconst record = credentials !== null && typeof credentials === \"object\" ? credentials : void 0;\n\tconst resolved = {};\n\tfor (const requirement of normalized) {\n\t\tconst value = record?.[requirement.key];\n\t\tif (value === void 0 || value === null) throw new MissingCredentialsError({\n\t\t\tkey: requirement.key,\n\t\t\tchainAttempted: []\n\t\t});\n\t\tconst parsed = requirement.schema.safeParse(value);\n\t\tif (!parsed.success) throw new MissingCredentialsError({\n\t\t\tkey: requirement.key,\n\t\t\tchainAttempted: []\n\t\t});\n\t\tresolved[requirement.key] = parsed.data;\n\t}\n\treturn resolved;\n}\n//#endregion\n//#region src/resolve-action-credentials.ts\n/** Requirement types from contracts — not @keystrokehq/action (avoids credentials → action). */\nasync function resolveActionCredentials(requirements, options) {\n\tif (!requirements.length) return {};\n\tconst resolveCredentials = options.resolveCredentials ?? (options.context ? createCredentialResolver({\n\t\tcontext: options.context,\n\t\toauthAdapter: options.oauthAdapter\n\t}).resolve : void 0);\n\tif (!resolveCredentials) throw new MissingCredentialsError({\n\t\tkey: normalizeCredentialList(requirements)[0].key,\n\t\tchainAttempted: [],\n\t\tconsumer: options.consumer\n\t});\n\treturn parseResolvedCredentials(requirements, await resolveCredentials(requirements, options.consumer, options.contextOverride));\n}\n//#endregion\n//#region src/oauth.ts\nconst stubOAuthTokenAdapter = { async getAccessToken() {\n\tthrow new OAuthNotConfiguredError();\n} };\nfunction createOAuthTokenRefreshRegistry() {\n\tconst handlers = /* @__PURE__ */ new Map();\n\treturn {\n\t\tregister(appKey, refresher) {\n\t\t\thandlers.set(appKey, refresher);\n\t\t},\n\t\tget(appKey) {\n\t\t\treturn handlers.get(appKey);\n\t\t}\n\t};\n}\n//#endregion\n//#region src/backend/oauth-adapter.ts\nfunction createOAuthTokenAdapterFromBackend(backend) {\n\treturn { getAccessToken(connectionId) {\n\t\treturn backend.getOAuthAccessToken(connectionId);\n\t} };\n}\n//#endregion\nexport { CREDENTIAL_SCOPE_TYPES, CredentialAccessDeniedError, CredentialAccessUnavailableError, DiscoveryError, McpInsufficientScopeCredentialError, McpOAuthConnectError, MissingCredentialsError, NeedsSelectionError, OAuthNotConfiguredError, PublicHttpUrlError, beginMcpOAuthConnect, buildAssignmentSet, buildCredentialRunContext, buildRequestAccessDeeplink, callConnectedMcpAppTool, canAssignCredentialInstance, canManageCredentialInstance, captureCredentialToolErrors, completeMcpOAuthConnect, createCredentialBackend, createCredentialResolver, createLocalCredentialBackend, createOAuthState, createOAuthTokenAdapterFromBackend, createOAuthTokenRefreshRegistry, createPlatformCredentialBackend, credentialScopeMatchesContext, credentialScopePrefix, decodeOAuthState, defineMcp, describeCredentialBinding, describeCredentialBindings, discoverGraphqlApp, discoverMcpApp, discoverOpenApiApp, encodeOAuthState, enrichCredentialError, formatCredentialErrorMessage, formatCredentialRef, formatCredentialRefSuggestion, getProjectCredentialBackend, isCredentialError, isDiscoveryError, isWorkerRuntime, loadCredentialAssignments, parseCredentialRef, parseResolvedCredentials, pickMirroredOAuthConnectionId, resolveActionCredentials, resolveAgentConnectContext, resolveConnectedMcpAuthHeaders, resolveCredentialRef, resolveCredentialRequirements, resolveKeystrokeInstanceId, resolveMcpTools, resolveSandboxCredentialRequirements, selectAssignedInstanceId, setProjectCredentialBackend, stubOAuthTokenAdapter, verifyOAuthState, withCredentialAssignments };\n\n//# sourceMappingURL=index.mjs.map","import { r as isWorkflow, t as defineWorkflow } from \"./define-workflow-BBoZgWI5.mjs\";\nimport { z } from \"zod\";\nimport { executeAction, getActionCredentialRequirements, getRegisteredProjectScopeId, getRunSignal, getWorkflowRunHandle, isWithinActionExecution, normalizeCredentialList, registerWorkflowRunGetter, runWithMcpCredentialContext } from \"@keystrokehq/action\";\nimport { BRAIN_MAX_BLOCKS_PER_DOCUMENT, BRAIN_MAX_FILE_BYTES, BRAIN_MAX_INLINE_CONTENT_CHARS, BrainCharacterChunkingSchema, BrainDocumentBlockSchema, BrainDocumentIdSchema, BrainDocumentMetadataSchema, BrainDocumentRevisionSchema, BrainDocumentTitleSchema, BrainEmbeddingContextSchema, BrainFileFormatSchema, BrainReadQuerySchema, BrainReadResponseSchema, BrainReferenceSchema, BrainSearchRequestSchema, BrainSearchResponseSchema, BrainSourceSchema, CHAT_ATTACHMENT_MAX_BYTES, FilePartSchema, ListBrainDocumentsQuerySchema, ListBrainDocumentsResponseSchema, chatAttachmentExtension, chatAttachmentServePath, defineTool, parseBrainReference, stepCompletedOutput, wrapStepCompletedData, zodToStoredJsonSchema } from \"@keystrokehq/shared\";\nimport { captureConsole, withSpan } from \"@keystrokehq/tracing\";\nimport { resolveActionCredentials } from \"@keystrokehq/credentials\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { createHash } from \"node:crypto\";\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/run-timeout-error.ts\nfunction formatTimeoutMs(ms) {\n\tif (ms % 6e4 === 0) {\n\t\tconst minutes = ms / 6e4;\n\t\treturn `${minutes} minute${minutes === 1 ? \"\" : \"s\"}`;\n\t}\n\tif (ms % 1e3 === 0) {\n\t\tconst seconds = ms / 1e3;\n\t\treturn `${seconds} second${seconds === 1 ? \"\" : \"s\"}`;\n\t}\n\treturn `${ms}ms`;\n}\nvar RunTimeoutError = class extends Error {\n\tkind;\n\ttimeoutMs;\n\tconstructor(kind, timeoutMs) {\n\t\tsuper(`${kind} run exceeded ${formatTimeoutMs(timeoutMs)} limit`);\n\t\tthis.name = \"RunTimeoutError\";\n\t\tthis.kind = kind;\n\t\tthis.timeoutMs = timeoutMs;\n\t}\n};\nfunction isRunTimeoutError(error) {\n\treturn error instanceof RunTimeoutError;\n}\n//#endregion\n//#region src/brain.ts\n/**\n* Open a durable, project-authorized Brain handle for the current workflow\n* run. Accepts a base Brain slug (read/write per the project's grant) or a\n* qualified `{brain}:{filter}` reference (read-only, narrowed by the\n* persisted filter).\n*/\nfunction brain(reference) {\n\tif (isWithinActionExecution()) throw new Error(\"brain() cannot run inside an action. Actions are leaf units; orchestrate Brain operations in a workflow.\");\n\tconst runner = getWorkflowRunHandle()?.brainRunner;\n\tif (!runner) throw new Error(\"brain() must run inside a workflow.\");\n\treturn runner(reference);\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/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/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\tlet consumed = this.byCorrelationId.get(event.correlationId);\n\t\t\tif (!consumed) {\n\t\t\t\tconsumed = {\n\t\t\t\t\ttypes: /* @__PURE__ */ new Set(),\n\t\t\t\t\tretryCount: 0\n\t\t\t\t};\n\t\t\t\tthis.byCorrelationId.set(event.correlationId, consumed);\n\t\t\t}\n\t\t\tconst firstOfType = !consumed.types.has(event.type);\n\t\t\tconsumed.types.add(event.type);\n\t\t\tif (event.type === \"step_completed\" && firstOfType) consumed.completedData = event.data;\n\t\t\telse if (event.type === \"step_failed\" && firstOfType) consumed.failedData = event.data;\n\t\t\telse if (event.type === \"step_retrying\") consumed.retryCount += 1;\n\t\t\telse if (event.type === \"sleep_scheduled\" && firstOfType) consumed.sleepResumeAt = event.data?.resumeAt;\n\t\t\telse if (event.type === \"hook_created\" && firstOfType) consumed.hookToken = event.data?.token;\n\t\t\telse if (event.type === \"hook_resumed\" && firstOfType) consumed.hookPayload = event.data?.payload;\n\t\t}\n\t}\n\thasEventType(correlationId, type) {\n\t\treturn this.byCorrelationId.get(correlationId)?.types.has(type) ?? false;\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 consumed = this.byCorrelationId.get(correlationId);\n\t\tif (consumed?.types.has(\"step_failed\")) throw deserializeWorkflowError(consumed.failedData);\n\t\tif (consumed?.types.has(\"step_completed\")) return {\n\t\t\tcompleted: true,\n\t\t\tresult: consumed.completedData\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.byCorrelationId.get(correlationId)?.retryCount ?? 0;\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 resumeAt = this.byCorrelationId.get(correlationId)?.sleepResumeAt;\n\t\treturn resumeAt ? new Date(resumeAt) : void 0;\n\t}\n\tgetHookToken(correlationId) {\n\t\treturn this.byCorrelationId.get(correlationId)?.hookToken;\n\t}\n\tgetHookResult(correlationId) {\n\t\tconst consumed = this.byCorrelationId.get(correlationId);\n\t\tif (!consumed?.types.has(\"hook_resumed\")) return { resolved: false };\n\t\treturn {\n\t\t\tresolved: true,\n\t\t\tpayload: consumed.hookPayload\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};\n}\n/**\n* Correlation-id scope for a sub-workflow body. A sub-workflow runs inline in\n* its parent's replay state, so its steps' structural `callSiteId`s (which are\n* hashed per-file and therefore collide across composed workflows) must be\n* namespaced under the parent step. We push the parent step's correlation key\n* as a path segment; keys become `<parentSegment>/<childKey>`. Held in async\n* context (not on `ReplayState`) so parallel sub-workflows (`Promise.all`) each\n* see their own scope without a shared mutable stack racing.\n*/\nconst stepScopeStorage = new AsyncLocalStorage();\n/** Run `fn` with `segment` appended to the current correlation-id scope. */\nfunction runInStepScope(segment, fn) {\n\tconst parent = stepScopeStorage.getStore() ?? [];\n\treturn stepScopeStorage.run([...parent, segment], fn);\n}\n/** Prefix the active scope onto a step key (`<scope>/<key>`, or `<key>` at top level). */\nfunction scopedKey(key) {\n\tconst scope = stepScopeStorage.getStore();\n\treturn scope && scope.length > 0 ? `${scope.join(\"/\")}/${key}` : key;\n}\n/**\n* Occurrence-independent consumer id (`step:<scopedKey>`) for credential binding,\n* so one assignment covers every execution of a step (loops included) and, unlike\n* the raw `callSiteId`, never collides with a same-positioned step in a parent or\n* sibling sub-workflow.\n*/\nfunction stepConsumerId(callSiteId) {\n\treturn `step:${scopedKey(callSiteId)}`;\n}\n/**\n* Allocate the correlation id for a step: `step:<scopedKey>#<occurrence>`. `key` is\n* the build-injected structural `callSiteId` (so the id matches the canvas graph\n* node 1:1), falling back to the action/agent slug for un-built/test runs, and is\n* prefixed by any active sub-workflow scope. The per-key `#<occurrence>` suffix\n* gives two calls to the same site (e.g. loop iterations) distinct, replay-stable\n* ids, and inserting an unrelated call never shifts the ids of later calls (unlike\n* a single global ordinal). User-authored step ids no longer exist — ids are\n* entirely internal.\n*/\nfunction nextStepCorrelationId(state, key) {\n\tconst effectiveKey = scopedKey(key);\n\tconst occurrence = state.stepOccurrences.get(effectiveKey) ?? 0;\n\tstate.stepOccurrences.set(effectiveKey, occurrence + 1);\n\treturn `step:${effectiveKey}#${occurrence}`;\n}\nfunction createSleep(state) {\n\treturn function sleep(duration, options) {\n\t\tconst correlationId = options?.__site ? nextStepCorrelationId(state, options.__site) : `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 = options?.__site ? nextStepCorrelationId(state, options.__site) : `hook#${state.hookCounter++}`;\n\t\tconst token = options?.token ?? state.consumer.getHookToken(correlationId) ?? `hook_${crypto.randomUUID()}`;\n\t\tconst resumeUrl = state.hookBaseUrl ? `${state.hookBaseUrl}/hooks/${token}/resume` : `/hooks/${token}/resume`;\n\t\tconst schema = options?.schema ? zodToStoredJsonSchema(options.schema) : void 0;\n\t\treturn {\n\t\t\ttoken,\n\t\t\tresumeUrl,\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: schema ? {\n\t\t\t\t\t\ttoken,\n\t\t\t\t\t\tschema\n\t\t\t\t\t} : { 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\t...schema ? { schema } : {}\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.correlationKey ?? options.key);\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\tconst result = stepCompletedOutput(eventLog.resolveData ? await eventLog.resolveData(cached.result) : cached.result);\n\t\treturn options.parseCached ? options.parseCached(result) : 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: wrapStepCompletedData(options.inputForExecution ? options.inputForExecution() : options.input ?? null, 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}\nasync function executeActionWithResolvedCredentials(action, input, options, runOptions, consumerId) {\n\tconst requirements = withCredentialScopeOverride(getActionCredentialRequirements(action), runOptions?.credentialScope);\n\tconst credentials = requirements?.length ? await resolveActionCredentials(requirements, {\n\t\tresolveCredentials: options.resolveCredentials,\n\t\tcontext: options.credentialContext,\n\t\toauthAdapter: options.oauthAdapter,\n\t\tconsumer: {\n\t\t\tkind: \"action\",\n\t\t\tname: action.slug,\n\t\t\tid: consumerId\n\t\t}\n\t}) : {};\n\treturn runWithMcpCredentialContext({\n\t\t...options.mcpCredentialContext,\n\t\tconsumerId\n\t}, () => executeAction(action, input, credentials));\n}\n/** Non-durable action runner for poll sources and other ephemeral orchestration. */\nfunction createDirectActionRunner(options = {}) {\n\treturn (action, input, runOptions) => {\n\t\treturn executeActionWithResolvedCredentials(action, input, options, runOptions, runOptions?.callSiteId ? stepConsumerId(runOptions.callSiteId) : action.slug);\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\tcorrelationKey: runOptions?.callSiteId,\n\t\tmetadataKey: \"actionKey\",\n\t\tinput,\n\t\tparseCached: (cached) => action.output.parse(cached),\n\t\texecute: async (correlationId) => {\n\t\t\treturn executeActionWithResolvedCredentials(action, input, options, runOptions, runOptions?.callSiteId ? stepConsumerId(runOptions.callSiteId) : correlationId);\n\t\t}\n\t});\n}\n//#endregion\n//#region src/run-child-step.ts\n/**\n* Suspends the parent workflow until a queued child reports its terminal\n* outcome. The runtime records `child_dispatched` and later completes or fails\n* this step in the parent's event log; this primitive only owns replay and\n* suspension mechanics.\n*/\nasync function runChildStep(state, options) {\n\tgetRunSignal().throwIfAborted();\n\tconst correlationId = nextStepCorrelationId(state, options.correlationKey ?? options.key);\n\tconst cached = state.consumer.getStepResult(correlationId);\n\tif (cached.completed) {\n\t\tconst result = state.eventLog.resolveData ? await state.eventLog.resolveData(cached.result) : cached.result;\n\t\treturn options.parseCached(result);\n\t}\n\tstate.coordinator.request({\n\t\tkind: \"child\",\n\t\tcorrelationId,\n\t\tdispatched: state.consumer.hasEventType(correlationId, \"child_dispatched\"),\n\t\t...options.child\n\t});\n\treturn createPendingPromise();\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, queueChildren = false) {\n\treturn (agent, input, options) => {\n\t\tconst slug = agent.slug;\n\t\tif (queueChildren) return runChildStep(state, {\n\t\t\tkey: slug,\n\t\t\tcorrelationKey: options?.callSiteId,\n\t\t\tparseCached: (cached) => cached,\n\t\t\tchild: {\n\t\t\t\tchildKind: \"agent\",\n\t\t\t\ttargetId: slug,\n\t\t\t\tinput,\n\t\t\t\t...options?.runPrompt ? { runPrompt: options.runPrompt } : {}\n\t\t\t}\n\t\t});\n\t\treturn runDurableStep(state, {\n\t\t\tkind: \"agent_session\",\n\t\t\tkey: slug,\n\t\t\tcorrelationKey: options?.callSiteId,\n\t\t\tmetadataKey: \"agentKey\",\n\t\t\tinput,\n\t\t\texecute: (_correlationId) => runAgent(agent, input, options?.runPrompt)\n\t\t});\n\t};\n}\n//#endregion\n//#region src/create-brain-step-runner.ts\nconst BrainUploadDocumentResultSchema = z.object({\n\tdocumentId: BrainDocumentIdSchema,\n\toutcome: z.enum([\"ready\", \"unchanged\"]),\n\tversionId: z.string().min(1).nullable(),\n\tmetadataUpdated: z.boolean()\n});\n/** Workflow-facing list options — narrowing comes from the handle, not a `filterSlug` param. */\nconst BrainListOptionsSchema = ListBrainDocumentsQuerySchema.omit({ filterSlug: true });\nconst unsupportedBrainExecutor = async () => {\n\tthrow new Error(\"This workflow host does not support Brains. Brain operations require a hosted project worker.\");\n};\nfunction hash(parts) {\n\tconst digest = createHash(\"sha256\");\n\tfor (const part of parts) {\n\t\tdigest.update(part);\n\t\tdigest.update(\"\\0\");\n\t}\n\treturn digest.digest(\"hex\");\n}\nfunction idempotencyId(runId, correlationId) {\n\treturn hash([\n\t\t\"keystroke.brain.mutation.v1\",\n\t\trunId,\n\t\tcorrelationId\n\t]);\n}\nfunction operationId(runId, correlationId) {\n\treturn hash([\n\t\t\"keystroke.brain.operation.v1\",\n\t\trunId,\n\t\tcorrelationId\n\t]);\n}\nasync function normalizeUploadInput(input) {\n\tconst documentId = BrainDocumentIdSchema.parse(input.documentId);\n\tconst source = BrainSourceSchema.parse(input.source);\n\tconst metadata = input.metadata === void 0 ? void 0 : BrainDocumentMetadataSchema.parse(input.metadata);\n\tconst title = input.title === void 0 ? void 0 : BrainDocumentTitleSchema.parse(input.title);\n\tconst embeddingContext = input.embeddingContext === void 0 ? void 0 : BrainEmbeddingContextSchema.parse(input.embeddingContext);\n\tconst revision = input.revision === void 0 ? void 0 : BrainDocumentRevisionSchema.parse(input.revision);\n\tif ([\n\t\tinput.content !== void 0,\n\t\tinput.blocks !== void 0,\n\t\tinput.file !== void 0\n\t].filter(Boolean).length !== 1) throw new Error(\"Provide exactly one of content, blocks, or file\");\n\tif (input.blocks !== void 0) {\n\t\tif (\"chunking\" in input && input.chunking !== void 0) throw new Error(\"Chunking controls are not allowed with blocks\");\n\t\treturn {\n\t\t\tdocumentId,\n\t\t\tsource,\n\t\t\t...title !== void 0 ? { title } : {},\n\t\t\tblocks: z.array(BrainDocumentBlockSchema).min(1).max(BRAIN_MAX_BLOCKS_PER_DOCUMENT).parse(input.blocks),\n\t\t\t...metadata !== void 0 ? { metadata } : {},\n\t\t\t...embeddingContext !== void 0 ? { embeddingContext } : {},\n\t\t\t...revision !== void 0 ? { revision } : {}\n\t\t};\n\t}\n\tconst chunking = input.chunking === void 0 ? void 0 : BrainCharacterChunkingSchema.parse(input.chunking);\n\tif (input.content !== void 0) {\n\t\tif (input.content.length === 0) throw new Error(\"content must not be empty\");\n\t\tif (input.content.length > BRAIN_MAX_INLINE_CONTENT_CHARS) throw new Error(`content exceeds ${BRAIN_MAX_INLINE_CONTENT_CHARS} characters`);\n\t\treturn {\n\t\t\tdocumentId,\n\t\t\tsource,\n\t\t\t...title !== void 0 ? { title } : {},\n\t\t\tcontent: input.content,\n\t\t\t...metadata !== void 0 ? { metadata } : {},\n\t\t\t...embeddingContext !== void 0 ? { embeddingContext } : {},\n\t\t\t...revision !== void 0 ? { revision } : {},\n\t\t\t...chunking !== void 0 ? { chunking } : {}\n\t\t};\n\t}\n\tconst fileInput = input.file;\n\tif (!fileInput) throw new Error(\"file is required\");\n\tconst binary = fileInput.data;\n\tlet file;\n\tif (binary instanceof Uint8Array) file = binary;\n\telse if (binary instanceof ArrayBuffer) file = new Uint8Array(binary);\n\telse if (typeof Blob !== \"undefined\" && binary instanceof Blob) file = new Uint8Array(await binary.arrayBuffer());\n\telse throw new Error(\"file must be a Uint8Array, ArrayBuffer, or Blob\");\n\tif (file.byteLength === 0) throw new Error(\"file must not be empty\");\n\tif (file.byteLength > BRAIN_MAX_FILE_BYTES) throw new Error(`file exceeds the ${BRAIN_MAX_FILE_BYTES} byte limit`);\n\treturn {\n\t\tdocumentId,\n\t\tsource,\n\t\t...title !== void 0 ? { title } : {},\n\t\tfile: {\n\t\t\tformat: BrainFileFormatSchema.parse(fileInput.format),\n\t\t\tdata: file\n\t\t},\n\t\t...metadata !== void 0 ? { metadata } : {},\n\t\t...embeddingContext !== void 0 ? { embeddingContext } : {},\n\t\t...revision !== void 0 ? { revision } : {},\n\t\t...chunking !== void 0 ? { chunking } : {}\n\t};\n}\nfunction redactedStepInput(request) {\n\tswitch (request.operation) {\n\t\tcase \"uploadDocument\": return {\n\t\t\tbrain: request.brainSlug,\n\t\t\tdocumentId: request.input.documentId,\n\t\t\tinputKind: request.input.file !== void 0 ? \"file\" : request.input.blocks !== void 0 ? \"blocks\" : \"content\"\n\t\t};\n\t\tcase \"updateMetadata\": return {\n\t\t\tbrain: request.brainSlug,\n\t\t\tdocumentId: request.documentId\n\t\t};\n\t\tcase \"delete\": return {\n\t\t\tbrain: request.brainSlug,\n\t\t\tdocumentId: request.documentId\n\t\t};\n\t\tcase \"deleteMany\": return {\n\t\t\tbrain: request.brainSlug,\n\t\t\tdocumentIds: request.documentIds\n\t\t};\n\t\tcase \"list\": return {\n\t\t\tbrain: request.brainSlug,\n\t\t\toptions: request.options\n\t\t};\n\t\tcase \"search\": return {\n\t\t\tbrain: request.brainSlug,\n\t\t\trequest: request.request\n\t\t};\n\t\tcase \"read\": return {\n\t\t\tbrain: request.brainSlug,\n\t\t\tdocumentId: request.documentId,\n\t\t\toptions: request.options\n\t\t};\n\t}\n}\n/**\n* Builds a per-run Brain factory. Every handle method is a durable step.\n*/\nfunction createBrainStepRunner(state, runBrain, workflowSlug) {\n\tconst executeBrain = runBrain ?? unsupportedBrainExecutor;\n\tconst durable = (operation, site, buildRequest, parseCached) => (() => {\n\t\tif (isWithinActionExecution()) throw new Error(\"Brain operations cannot run inside an action. Actions are leaf units; orchestrate Brain operations in a workflow.\");\n\t\tlet stepInput;\n\t\treturn runDurableStep(state, {\n\t\t\tkind: \"brain\",\n\t\t\tkey: `brain.${operation}`,\n\t\t\tcorrelationKey: site ?? `brain.${operation}`,\n\t\t\tmetadataKey: \"brainKey\",\n\t\t\tinputForExecution: () => stepInput,\n\t\t\tparseCached,\n\t\t\texecute: async (correlationId) => {\n\t\t\t\tconst request = buildRequest(correlationId);\n\t\t\t\tstepInput = redactedStepInput(request);\n\t\t\t\treturn parseCached(await executeBrain(request, {\n\t\t\t\t\tworkflowRunId: state.runId,\n\t\t\t\t\tworkflowSlug,\n\t\t\t\t\tcorrelationId\n\t\t\t\t}));\n\t\t\t}\n\t\t});\n\t})();\n\treturn (rawReference) => {\n\t\tconst brainSlug = BrainReferenceSchema.parse(rawReference);\n\t\tconst qualified = parseBrainReference(brainSlug).filterSlug !== null;\n\t\tconst assertWritable = () => {\n\t\t\tif (qualified) throw new Error(`Brain reference \"${brainSlug}\" is a read-only filter; write operations require the base Brain slug`);\n\t\t};\n\t\tconst uploadDocument = async (input, options) => {\n\t\t\tassertWritable();\n\t\t\tconst normalized = await normalizeUploadInput(input);\n\t\t\treturn durable(\"uploadDocument\", options?.__site, (correlationId) => ({\n\t\t\t\toperation: \"uploadDocument\",\n\t\t\t\tbrainSlug,\n\t\t\t\tinput: normalized,\n\t\t\t\tclientIdempotencyId: idempotencyId(state.runId, correlationId)\n\t\t\t}), (cached) => BrainUploadDocumentResultSchema.parse(cached));\n\t\t};\n\t\treturn {\n\t\t\tuploadDocument,\n\t\t\tasync updateMetadata(documentId, metadata, options) {\n\t\t\t\tassertWritable();\n\t\t\t\tawait durable(\"updateMetadata\", options?.__site, (correlationId) => ({\n\t\t\t\t\toperation: \"updateMetadata\",\n\t\t\t\t\tbrainSlug,\n\t\t\t\t\tdocumentId: BrainDocumentIdSchema.parse(documentId),\n\t\t\t\t\tmetadata: BrainDocumentMetadataSchema.parse(metadata),\n\t\t\t\t\tclientIdempotencyId: idempotencyId(state.runId, correlationId)\n\t\t\t\t}), (cached) => z.boolean().parse(cached));\n\t\t\t},\n\t\t\tdelete(documentId, options) {\n\t\t\t\tassertWritable();\n\t\t\t\treturn durable(\"delete\", options?.__site, (correlationId) => ({\n\t\t\t\t\toperation: \"delete\",\n\t\t\t\t\tbrainSlug,\n\t\t\t\t\tdocumentId: BrainDocumentIdSchema.parse(documentId),\n\t\t\t\t\tclientIdempotencyId: idempotencyId(state.runId, correlationId)\n\t\t\t\t}), (cached) => z.boolean().parse(cached));\n\t\t\t},\n\t\t\tdeleteMany(documentIds, options) {\n\t\t\t\tassertWritable();\n\t\t\t\treturn durable(\"deleteMany\", options?.__site, (correlationId) => ({\n\t\t\t\t\toperation: \"deleteMany\",\n\t\t\t\t\tbrainSlug,\n\t\t\t\t\tdocumentIds: z.array(BrainDocumentIdSchema).min(1).parse(documentIds),\n\t\t\t\t\tclientIdempotencyId: idempotencyId(state.runId, correlationId)\n\t\t\t\t}), (cached) => z.array(BrainDocumentIdSchema).parse(cached));\n\t\t\t},\n\t\t\tlist(options) {\n\t\t\t\tconst { __site, ...query } = options ?? {};\n\t\t\t\tconst parsed = BrainListOptionsSchema.parse(query);\n\t\t\t\treturn durable(\"list\", __site, (correlationId) => ({\n\t\t\t\t\toperation: \"list\",\n\t\t\t\t\tbrainSlug,\n\t\t\t\t\toperationId: operationId(state.runId, correlationId),\n\t\t\t\t\toptions: parsed\n\t\t\t\t}), (cached) => ListBrainDocumentsResponseSchema.parse(cached));\n\t\t\t},\n\t\t\tsearch(request, options) {\n\t\t\t\tconst parsed = BrainSearchRequestSchema.parse(request);\n\t\t\t\treturn durable(\"search\", options?.__site, (correlationId) => ({\n\t\t\t\t\toperation: \"search\",\n\t\t\t\t\tbrainSlug,\n\t\t\t\t\toperationId: operationId(state.runId, correlationId),\n\t\t\t\t\trequest: parsed\n\t\t\t\t}), (cached) => BrainSearchResponseSchema.parse(cached));\n\t\t\t},\n\t\t\tread(documentId, options) {\n\t\t\t\tconst { __site, ...query } = options ?? {};\n\t\t\t\tconst parsed = BrainReadQuerySchema.parse(query);\n\t\t\t\treturn durable(\"read\", __site, (correlationId) => ({\n\t\t\t\t\toperation: \"read\",\n\t\t\t\t\tbrainSlug,\n\t\t\t\t\toperationId: operationId(state.runId, correlationId),\n\t\t\t\t\tdocumentId: BrainDocumentIdSchema.parse(documentId),\n\t\t\t\t\toptions: parsed\n\t\t\t\t}), (cached) => BrainReadResponseSchema.parse(cached));\n\t\t\t}\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\tcorrelationKey: opts.callSiteId,\n\t\tmetadataKey: \"llmKey\",\n\t\tinput: {\n\t\t\t...opts.system != null ? { system: opts.system } : {},\n\t\t\tprompt: opts.prompt,\n\t\t\t...opts.model != null ? { model: opts.model } : {}\n\t\t},\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/create-workflow-step-runner.ts\n/**\n* Builds the per-run sub-workflow runner: each `workflow.run(input)` inside a\n* workflow body becomes a durable step keyed by its build-injected `callSiteId`\n* (`step:<callSiteId>#<occurrence>`), falling back to the slug for un-built runs.\n* The sub-workflow's body runs inline in the same replay state (its action/agent/\n* LLM steps and `ctx.sleep`/`ctx.hook` stay durable) but under a correlation-id\n* scope named after this step, so the child's steps never collide with equally\n* positioned steps in the parent. Its validated output is checkpointed so a\n* replay skips the whole sub-workflow once it completes.\n*/\nfunction createWorkflowStepRunner(state, ctx, queueChildren = false) {\n\treturn (workflowUnknown, input, options) => {\n\t\tconst workflow = workflowUnknown;\n\t\tconst parsedInput = workflow.input.parse(input);\n\t\tif (queueChildren) return runChildStep(state, {\n\t\t\tkey: workflow.slug,\n\t\t\tcorrelationKey: options?.callSiteId,\n\t\t\tparseCached: (cached) => workflow.output.parse(cached),\n\t\t\tchild: {\n\t\t\t\tchildKind: \"workflow\",\n\t\t\t\ttargetId: workflow.slug,\n\t\t\t\tinput: parsedInput\n\t\t\t}\n\t\t});\n\t\treturn runDurableStep(state, {\n\t\t\tkind: \"workflow_run\",\n\t\t\tkey: workflow.slug,\n\t\t\tcorrelationKey: options?.callSiteId,\n\t\t\tmetadataKey: \"workflowKey\",\n\t\t\tinput: parsedInput,\n\t\t\tparseCached: (cached) => workflow.output.parse(cached),\n\t\t\texecute: async () => {\n\t\t\t\treturn runInStepScope(options?.callSiteId ?? workflow.slug, async () => {\n\t\t\t\t\tconst output = await workflow.run(parsedInput, ctx);\n\t\t\t\t\treturn workflow.output.parse(output);\n\t\t\t\t});\n\t\t\t}\n\t\t});\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\tbrainRunner: store.brainRunner,\n\t\tllmRunner: store.llmRunner,\n\t\tworkflowRunner: store.workflowRunner\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 events = await eventLog.listReplay(runId);\n\tconst consumer = new EventsConsumer(events);\n\tevents.length = 0;\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 brainRunner = createBrainStepRunner(state, options.runBrain, workflow.slug);\n\tconst ctx = {\n\t\t...options.context,\n\t\trunId,\n\t\tsleep: createSleep(state),\n\t\thook: createHook(state)\n\t};\n\tconst agentRunner = options.runAgent ? createAgentStepRunner(state, options.runAgent, options.queueChildSteps) : void 0;\n\tconst llmRunner = options.runLlm ? createLlmStepRunner(state, options.runLlm) : void 0;\n\tconst workflowRunner = createWorkflowStepRunner(state, ctx, options.queueChildSteps);\n\tconst validatedInput = workflow.input.parse(input);\n\tconst bodyPromise = runWithWorkflowContext({\n\t\tactionRunner,\n\t\tagentRunner,\n\t\tbrainRunner,\n\t\tllmRunner,\n\t\tworkflowRunner,\n\t\trunId\n\t}, () => captureConsole(async () => workflow.run(validatedInput, ctx)));\n\tlet onAbort;\n\tfunction abortRaceOutcome() {\n\t\tif (isRunTimeoutError(signal.reason)) return {\n\t\t\ttype: \"timeout\",\n\t\t\terror: signal.reason\n\t\t};\n\t\treturn { type: \"canceled\" };\n\t}\n\tconst waitForAbort = signal.aborted ? Promise.resolve(abortRaceOutcome()) : new Promise((resolve) => {\n\t\tonAbort = () => resolve(abortRaceOutcome());\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 if (outcome.type === \"timeout\") {\n\t\tbodyPromise.catch(() => {});\n\t\tresult = {\n\t\t\tstatus: \"failed\",\n\t\t\terror: outcome.error,\n\t\t\tfailedCorrelationId: state.failedCorrelationId\n\t\t};\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\tconst { __site, ...rest } = opts;\n\treturn handle.llmRunner({\n\t\tprompt,\n\t\t...rest,\n\t\t...typeof __site === \"string\" ? { callSiteId: __site } : {}\n\t});\n}\n//#endregion\n//#region src/file-store-registry.ts\n/**\n* Cross-module bridge for workflow file storage. The project runtime registers\n* a putObject backed by worker storage; `storeFile` reads it without importing\n* `@keystrokehq/storage` clients from authoring code. Keyed by a global\n* `Symbol.for` so a single slot is shared across bundled copies.\n*/\nconst REGISTRY_KEY = Symbol.for(\"keystroke.fileStore\");\nfunction registry() {\n\tconst globalScope = globalThis;\n\tif (!globalScope[REGISTRY_KEY]) globalScope[REGISTRY_KEY] = {};\n\treturn globalScope[REGISTRY_KEY];\n}\nfunction registerFileStore(store) {\n\tregistry().store = store;\n}\nfunction getRegisteredFileStore() {\n\treturn registry().store;\n}\n//#endregion\n//#region src/replay/payload-offloading-event-log.ts\nconst WORKFLOW_PAYLOAD_REF = \"keystroke.workflow-payload.v1\";\nfunction isWorkflowPayloadRef(value) {\n\treturn typeof value === \"object\" && value !== null && value.type === WORKFLOW_PAYLOAD_REF && typeof value.key === \"string\" && typeof value.byteLength === \"number\";\n}\nfunction payloadKey(event, bytes) {\n\tconst digest = createHash(\"sha256\").update(bytes).digest(\"hex\");\n\treturn `workflow-payloads/${event.runId}/${digest}.json`;\n}\n/**\n* Keeps large completed-step outputs out of replay event rows. Replay loads the\n* small reference and resolves the output only when workflow execution reaches\n* that step.\n*/\nfunction withWorkflowPayloadOffloading(eventLog, store, options = {}) {\n\tconst thresholdBytes = options.thresholdBytes ?? 65536;\n\treturn {\n\t\tasync append(event) {\n\t\t\tif (event.type !== \"step_completed\") return eventLog.append(event);\n\t\t\tconst serialized = JSON.stringify(event.data);\n\t\t\tif (serialized === void 0) return eventLog.append(event);\n\t\t\tconst bytes = new TextEncoder().encode(serialized);\n\t\t\tif (bytes.byteLength <= thresholdBytes) return eventLog.append(event);\n\t\t\tconst key = payloadKey(event, bytes);\n\t\t\tawait store.put(key, bytes);\n\t\t\treturn eventLog.append({\n\t\t\t\t...event,\n\t\t\t\tdata: {\n\t\t\t\t\ttype: WORKFLOW_PAYLOAD_REF,\n\t\t\t\t\tkey,\n\t\t\t\t\tbyteLength: bytes.byteLength\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t\tlistReplay: (runId) => eventLog.listReplay(runId),\n\t\tasync resolveData(data) {\n\t\t\tif (!isWorkflowPayloadRef(data)) return eventLog.resolveData ? eventLog.resolveData(data) : data;\n\t\t\tconst bytes = await store.get(data.key);\n\t\t\treturn JSON.parse(new TextDecoder().decode(bytes));\n\t\t}\n\t};\n}\n/** Enable payload spillover when the host registered readable worker storage. */\nfunction withRegisteredWorkflowPayloadOffloading(eventLog) {\n\tconst store = getRegisteredFileStore();\n\tconst getObject = store?.getObject;\n\tif (!store || !getObject) return eventLog;\n\treturn withWorkflowPayloadOffloading(eventLog, {\n\t\tput: (key, body) => store.putObject({\n\t\t\tkey,\n\t\t\tbody,\n\t\t\tcontentType: \"application/json\"\n\t\t}),\n\t\tget: (key) => getObject(key)\n\t});\n}\n//#endregion\n//#region src/workflow-tool.ts\nlet executor;\nfunction registerWorkflowToolExecutor(fn) {\n\tif (executor) throw new Error(\"workflow tool executor already registered\");\n\texecutor = fn;\n}\nfunction getWorkflowToolExecutor() {\n\tif (!executor) throw new Error(\"workflow tool executor not registered\");\n\treturn executor;\n}\nfunction assertWorkflowToolInput(workflow) {\n\tif (!(\"shape\" in workflow.input) || typeof workflow.input.shape !== \"object\") throw new Error(`Workflow \"${workflow.slug}\" cannot be used as an agent tool: input schema must be a Zod object.`);\n}\nfunction resolveWorkflowTool(workflow, context = {}) {\n\tassertWorkflowToolInput(workflow);\n\tconst key = workflow.slug;\n\tconst description = workflow.description;\n\treturn defineTool({\n\t\tname: key,\n\t\tlabel: key,\n\t\tdescription,\n\t\tparameters: workflow.input,\n\t\tasync execute(toolCallId, params, signal) {\n\t\t\tconst output = await withSpan({\n\t\t\t\tkind: \"tool_call\",\n\t\t\t\tname: key,\n\t\t\t\trefId: toolCallId,\n\t\t\t\tmetadata: {\n\t\t\t\t\ttool: key,\n\t\t\t\t\ttype: \"workflow\"\n\t\t\t\t}\n\t\t\t}, () => getWorkflowToolExecutor()(workflow, params, {\n\t\t\t\tworkflowKey: key,\n\t\t\t\t...context,\n\t\t\t\t...signal ? { signal } : {}\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: 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/store-file.ts\nconst ATTACHMENT_EXT = /^[a-z0-9]+$/;\n/** Same key shape as `chatAttachmentStorageKey` in `@keystrokehq/storage`. */\nfunction chatAttachmentStorageKey(projectId, id, ext) {\n\tconst normalizedExt = ext.replace(/^\\./, \"\").toLowerCase();\n\tif (!ATTACHMENT_EXT.test(normalizedExt)) throw new Error(\"Invalid chat attachment extension\");\n\treturn `chat-attachments/${projectId}/${id}.${normalizedExt}`;\n}\n/**\n* Persist raw bytes into org chat-attachment storage and return a `FilePart` ref\n* that can travel through workflow input / step checkpoints / `agent.prompt({ files })`.\n*\n* Requires worker storage (`registerFileStore`) and a bound project scope.\n* Serve path uses a `workflow` agent-slug placeholder — hydration ignores it.\n* ponytail: web serving of workflow-stored files via the per-agent GET route is not wired.\n*/\nasync function storeFile(data, options) {\n\tconst store = getRegisteredFileStore();\n\tif (!store) throw new Error(\"storeFile requires worker storage (STORAGE_* / KEYSTROKE_WORKSPACES_BUCKET)\");\n\tconst projectId = getRegisteredProjectScopeId() ?? store.projectId;\n\tif (!projectId) throw new Error(\"storeFile requires a bound project scope\");\n\tconst ext = chatAttachmentExtension(options.mediaType);\n\tif (!ext) throw new Error(`Unsupported media type: ${options.mediaType}`);\n\tif (data.byteLength === 0) throw new Error(\"storeFile requires non-empty data\");\n\tif (data.byteLength > CHAT_ATTACHMENT_MAX_BYTES) throw new Error(`File exceeds size limit (${CHAT_ATTACHMENT_MAX_BYTES} bytes): ${data.byteLength}`);\n\tconst storageKey = chatAttachmentStorageKey(projectId, crypto.randomUUID(), ext);\n\tconst url = chatAttachmentServePath(projectId, \"workflow\", storageKey);\n\tawait store.putObject({\n\t\tkey: storageKey,\n\t\tbody: data,\n\t\tcontentType: options.mediaType\n\t});\n\tconst part = {\n\t\ttype: \"file\",\n\t\tmediaType: options.mediaType,\n\t\turl,\n\t\t...options.filename ? { filename: options.filename } : {}\n\t};\n\treturn FilePartSchema.parse(part);\n}\n//#endregion\nexport { MemoryEventLog, RunCanceledError, RunTimeoutError, brain, createActionRunner, createDirectActionRunner, defineWorkflow, deserializeWorkflowError, executeWorkflow, getRegisteredFileStore, isRunCanceledError, isRunTimeoutError, isWorkflow, promptLlm, registerFileStore, registerWorkflowToolExecutor, resolveWorkflowTool, runWithWorkflowContext, serializeWorkflowError, storeFile, withRegisteredWorkflowPayloadOffloading };\n\n//# sourceMappingURL=index.mjs.map","import { CronExpressionParser } from \"cron-parser\";\nimport { z } from \"zod\";\nimport { isWorkflow } from \"@keystrokehq/workflow\";\nimport { jsonSchemaToZod } from \"@keystrokehq/shared\";\n//#region src/cron/cron-schedule.ts\n/**\n* Validates and brands a cron expression. Accepts anything the `cron-parser`\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* Validates and brands a cron expression for poll triggers. Polls may not fire\n* more often than once per minute, so only minute-level schedules are allowed:\n* 5-field expressions and `@daily`-style nicknames. 6-field (seconds)\n* expressions are rejected — use `parseCronSchedule` for cron triggers.\n*/\nconst pollScheduleSchema = cronScheduleSchema.refine(isMinuteLevelCron, \"poll schedule must be a 5-field cron (no seconds) — polls fire at most once per minute\");\n/** Parse/validate a poll schedule (throws on 6-field/seconds expressions). */\nfunction parsePollSchedule(value) {\n\treturn pollScheduleSchema.parse(value);\n}\n/** Nicknames (`@hourly`, …) and 5-field expressions fire at most once per minute. */\nfunction isMinuteLevelCron(schedule) {\n\treturn schedule.startsWith(\"@\") || schedule.split(/\\s+/).length === 5;\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/** Default timezone when none is authored — preserves historical UTC evaluation. */\nconst DEFAULT_TRIGGER_TIMEZONE = \"UTC\";\n/**\n* Validates and brands an IANA timezone (e.g. `America/New_York`). Uses\n* `Intl.DateTimeFormat` so we don't need a timezone database dependency.\n*/\nconst timezoneSchema = z.string().trim().min(1, \"timezone must be a non-empty IANA timezone\").refine(isValidIanaTimezone, \"must be a valid IANA timezone\").brand();\n/** Parse/validate an IANA timezone (throws on failure). */\nfunction parseTimezone(value) {\n\treturn timezoneSchema.parse(value);\n}\nfunction isValidIanaTimezone(value) {\n\ttry {\n\t\tnew Intl.DateTimeFormat(\"en-US\", { timeZone: value });\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Parse a schedule into a `cron-parser` expression (throws on invalid input). */\nfunction parseTriggerSchedule(schedule, timezone = \"UTC\") {\n\treturn parseCronExpression(schedule, void 0, timezone);\n}\n/**\n* The next time the schedule fires at or after `from`.\n*\n* Cron fields are wall-clock times in `timezone` (default UTC). Absolute\n* instants are computed here — do not convert the cron string to UTC at write time.\n*/\nfunction nextTriggerRunAt(schedule, from = /* @__PURE__ */ new Date(), timezone = \"UTC\") {\n\treturn parseCronExpression(schedule, from, timezone).next().toDate();\n}\n/**\n* Single touchpoint for the `cron-parser` library — every parse, validation,\n* and next-run calculation in this package goes through here.\n*/\nfunction parseCronExpression(schedule, currentDate, timezone = \"UTC\") {\n\treturn CronExpressionParser.parse(schedule, {\n\t\tcurrentDate: currentDate ?? /* @__PURE__ */ new Date(),\n\t\ttz: timezone\n\t});\n}\nfunction isParseableCron(value) {\n\ttry {\n\t\tparseCronExpression(value);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n//#endregion\n//#region src/cron-payload.ts\nconst jsonValueSchema = z.lazy(() => z.union([\n\tz.string(),\n\tz.number(),\n\tz.boolean(),\n\tz.null(),\n\tz.array(jsonValueSchema),\n\tz.record(z.string(), jsonValueSchema)\n]));\n/** Runtime schema for an optional static cron payload (JSON only). */\nconst cronPayloadSchema = jsonValueSchema;\n/** Validate a cron payload at define time; throws if not JSON-serializable. */\nfunction parseCronPayload(value) {\n\tconst result = cronPayloadSchema.safeParse(value);\n\tif (!result.success) throw new Error(`defineCronSource payload must be JSON-serializable (string, number, boolean, null, array, or plain object): ${result.error.issues.map((issue) => issue.message).join(\"; \")}`);\n\treturn result.data;\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 requiredTextField = z.string().trim().min(1);\nconst optionalTextField = z.string().trim().min(1).optional();\nconst baseSourceShape = {\n\tslug: slugField,\n\tname: requiredTextField,\n\tdescription: requiredTextField,\n\tattach: z.function()\n};\nconst webhookSourceSchema = z.object({\n\tkind: z.literal(\"webhook\"),\n\t...baseSourceShape,\n\tendpoint: z.string().min(1),\n\tpayload: 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\ttimezone: timezoneSchema.optional(),\n\tpayload: cronPayloadSchema.optional()\n});\nconst pollSourceSchema = z.object({\n\tkind: z.literal(\"poll\"),\n\t...baseSourceShape,\n\tid: z.string().optional(),\n\tschedule: pollScheduleSchema,\n\ttimezone: timezoneSchema.optional(),\n\trun: z.function(),\n\tstateSchema: zodSchema.optional(),\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}\nfunction requireTriggerDisplayText(value, field, label) {\n\tconst trimmed = value?.trim();\n\tif (!trimmed) throw new Error(`${label} requires a non-empty ${field}`);\n\treturn trimmed;\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\tname: source.name,\n\t\tdescription: source.description\n\t};\n}\nfunction triggerMetaFromAttachment(attachment) {\n\treturn {\n\t\tname: attachment.name ?? attachment.source.name,\n\t\tdescription: attachment.description ?? attachment.source.description\n\t};\n}\nfunction triggerMetaRecordFromAttachment(attachment) {\n\treturn triggerMetaFromAttachment(attachment);\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 flattenZodIssues(error) {\n\treturn error.issues.map((issue) => ({\n\t\tpath: issue.path.length > 0 ? issue.path.map(String).join(\".\") : \"(root)\",\n\t\tmessage: issue.message\n\t}));\n}\nfunction formatIssuesDetail(issues) {\n\treturn issues.map((issue) => `${issue.path}: ${issue.message}`).join(\"; \");\n}\nfunction matchShapeAndFilter(shape, filter, payload) {\n\tconst shaped = shape.safeParse(payload);\n\tif (!shaped.success) return {\n\t\tmatched: false,\n\t\tissues: flattenZodIssues(shaped.error)\n\t};\n\tif (filter) {\n\t\tconst filtered = filter.safeParse(shaped.data);\n\t\tif (!filtered.success) return {\n\t\t\tmatched: true,\n\t\t\tdata: shaped.data,\n\t\t\tfilterRejected: true,\n\t\t\tissues: flattenZodIssues(filtered.error)\n\t\t};\n\t}\n\treturn {\n\t\tmatched: true,\n\t\tdata: shaped.data,\n\t\tfilterRejected: false\n\t};\n}\nfunction passesShape(shape, payload) {\n\treturn shape.safeParse(payload).success;\n}\nfunction matchWebhookPayload(raw, schemas) {\n\tconst matches = [];\n\tconst filterRejected = [];\n\tconst unmatched = [];\n\tfor (const schema of schemas) {\n\t\tconst result = matchShapeAndFilter(jsonSchemaToZod(schema.requestSchema), schema.filterSchema ? jsonSchemaToZod(schema.filterSchema) : void 0, raw);\n\t\tif (!result.matched) {\n\t\t\tunmatched.push({\n\t\t\t\tattachmentSlug: schema.attachmentSlug,\n\t\t\t\t...schema.triggerId ? { triggerId: schema.triggerId } : {},\n\t\t\t\tissues: result.issues,\n\t\t\t\treason: \"invalid_payload\"\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst entry = {\n\t\t\tattachmentSlug: schema.attachmentSlug,\n\t\t\t...schema.triggerId ? { triggerId: schema.triggerId } : {},\n\t\t\tdata: result.data\n\t\t};\n\t\tif (result.filterRejected) {\n\t\t\tfilterRejected.push(entry);\n\t\t\tunmatched.push({\n\t\t\t\tattachmentSlug: schema.attachmentSlug,\n\t\t\t\t...schema.triggerId ? { triggerId: schema.triggerId } : {},\n\t\t\t\tissues: result.issues ?? [],\n\t\t\t\treason: \"filter_rejected\"\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tmatches.push(entry);\n\t}\n\treturn {\n\t\tmatches,\n\t\tfilterRejected,\n\t\tunmatched\n\t};\n}\n/** Live Zod validation for webhook `payload` (in-process / authoring paths). */\nfunction passesTriggerMatch(shape, payload) {\n\treturn passesShape(shape, payload);\n}\n//#endregion\n//#region src/sources/webhook-source.ts\nfunction normalizeWebhookEndpoint(endpoint) {\n\treturn endpoint.replace(/^\\/+|\\/+$/g, \"\").replace(/^triggers\\/?/, \"\");\n}\nfunction looseTopLevelObject(schema) {\n\treturn schema instanceof z.ZodObject ? schema.loose() : schema;\n}\n/**\n* ponytail: deployed artifacts keep `@keystrokehq/trigger` external and resolve it from the\n* runtime image, so a runtime rollout re-imports old built code that still calls\n* `defineWebhookSource({ request, filter })`. Map those onto the `payload` API (with the old\n* top-level `.loose()` behavior) so old projects keep booting and matching identically.\n* TODO: remove once all projects have redeployed with `payload`.\n*/\nfunction resolveLegacyWebhookSchemas(options) {\n\tif (options.payload) return { payload: options.payload };\n\tconst legacy = options;\n\tif (!legacy.request) throw new Error(\"defineWebhookSource requires a payload schema\");\n\treturn {\n\t\tpayload: looseTopLevelObject(legacy.request),\n\t\t...legacy.filter ? { legacyFilter: looseTopLevelObject(legacy.filter) } : {}\n\t};\n}\n/**\n* Defines a webhook trigger source — fires its attached workflow when a request\n* hits `/triggers/{endpoint}` and satisfies `payload`.\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* @param options.payload - Zod schema the incoming body must match for the trigger to fire.\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 name = requireTriggerDisplayText(options.name, \"name\", \"defineWebhookSource\");\n\tconst description = requireTriggerDisplayText(options.description, \"description\", \"defineWebhookSource\");\n\tconst { payload, legacyFilter } = resolveLegacyWebhookSchemas(options);\n\tconst source = {\n\t\tkind: \"webhook\",\n\t\tslug: sourceSlug,\n\t\tname,\n\t\tdescription,\n\t\tendpoint,\n\t\tpayload,\n\t\t...legacyFilter ? { filter: legacyFilter } : {},\n\t\tpasses(value) {\n\t\t\treturn passesTriggerMatch(payload, value) && (!legacyFilter || passesTriggerMatch(legacyFilter, value));\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 - Human-readable name shown in the platform.\n* @param options.description - 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* @param options.timezone - Optional IANA timezone (e.g. `America/New_York`).\n*   Cron fields are wall-clock times in this zone. When omitted, UTC.\n* @param options.payload - Optional static JSON payload passed to attachments on\n*   each tick (like a webhook body). When omitted, attachments receive `{}`.\n*   Without a `transform`, the payload must be assignable to the workflow input.\n* @example\n* defineCronSource({ slug: \"morning\", schedule: \"0 9 * * *\" }).attach({ workflow });\n* @example\n* defineCronSource({\n*   slug: \"morning-report\",\n*   schedule: \"0 9 * * *\",\n*   timezone: \"America/New_York\",\n*   payload: { report: \"daily\", region: \"us\" },\n* }).attach({ workflow });\n*/\nfunction defineCronSource(options) {\n\tconst sourceSlug = resolveAuthoringSlug(options, \"defineCronSource\");\n\tconst schedule = parseCronSchedule(options.schedule);\n\tconst timezone = options.timezone === void 0 ? void 0 : parseTimezone(options.timezone);\n\tconst name = requireTriggerDisplayText(options.name, \"name\", \"defineCronSource\");\n\tconst description = requireTriggerDisplayText(options.description, \"description\", \"defineCronSource\");\n\tconst payload = options.payload === void 0 ? void 0 : parseCronPayload(options.payload);\n\tconst source = {\n\t\tkind: \"cron\",\n\t\tslug: sourceSlug,\n\t\tname,\n\t\tdescription,\n\t\tschedule,\n\t\t...timezone !== void 0 ? { timezone } : {},\n\t\t...payload !== void 0 ? { payload } : {},\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\nfunction definePollSource(options) {\n\tconst sourceSlug = resolveAuthoringSlug(options, \"definePollSource\");\n\tconst schedule = parsePollSchedule(options.schedule);\n\tconst timezone = options.timezone === void 0 ? void 0 : parseTimezone(options.timezone);\n\tconst name = requireTriggerDisplayText(options.name, \"name\", \"definePollSource\");\n\tconst description = requireTriggerDisplayText(options.description, \"description\", \"definePollSource\");\n\tif (options.state && options.id) throw new Error(\"definePollSource: `state` and `id` (poll grouping) cannot be used together\");\n\tconst filters = [];\n\tif (options.filter) filters.push(options.filter);\n\tconst source = {\n\t\tkind: \"poll\",\n\t\tslug: sourceSlug,\n\t\tname,\n\t\tdescription,\n\t\tid: options.id,\n\t\tschedule,\n\t\t...timezone !== void 0 ? { timezone } : {},\n\t\trun: options.run,\n\t\tstateSchema: options.state,\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 payload matcher into a JSON Schema stored as webhook\n* `requestSchema` (persisted wire key). Dots in keys are path separators; an empty\n* matcher produces a schema that accepts any JSON object payload.\n*/\nfunction matchToJsonSchema(payload) {\n\tconst schema = emptyObjectSchema();\n\tfor (const [path, value] of Object.entries(payload)) 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 { DEFAULT_TRIGGER_TIMEZONE, TRIGGER_ATTACHMENT, TRIGGER_ATTACHMENT_SIBLINGS, agentKeyFromAgent, agentSlugFromAgent, attachFromSource, attachmentKeyFrom, attachmentSlugFrom, attachmentSlugFromRecord, cronPayloadSchema, cronScheduleSchema, defineCronSource, definePollSource, defineWebhookSource, formatIssuesDetail, interpolatePrompt, isAgentTriggerAttachment, isTriggerAttachment, isWorkflowTriggerAttachment, matchToJsonSchema, matchWebhookPayload, nextTriggerRunAt, normalizeWebhookEndpoint, parseCronPayload, parseCronSchedule, parsePollSchedule, parseTimezone, parseTriggerSchedule, pollScheduleSchema, resolveAgentPrompt, resolveAttachmentInput, resolveAttachmentTransform, resolveAuthoringSlug, resolveCronSchedule, sourceSlugFrom, timezoneSchema, triggerAttachmentsFromExport, triggerMetaFromAttachment, triggerMetaFromSource, triggerMetaRecordFromAttachment, triggerSourceSlugFromAttachmentSlug, triggerTargetSlugFromAttachmentSlug, workflowKeyFromDefinition, workflowSlugFromDefinition };\n\n//# sourceMappingURL=index.mjs.map","import { a as discoverModuleFileEntries, c as walkTypeScriptFiles, i as validateUniqueModuleKeys, l as entryIdFromFile, o as moduleFileKeyFromPath, s as discoverEntries } from \"./discovery-C6Un-m9-.mjs\";\nimport { createRequire } from \"node:module\";\nimport { pathToFileURL } from \"node:url\";\nimport { resolveAppRoot, runWithAppRoot } from \"@keystrokehq/sandbox\";\nimport { dirname, join, relative, sep } from \"node:path\";\nimport { ActionsCatalogShardSchema, AgentManifestShardSchema, PROJECT_MANIFEST_REL_PATH, PromptResponseSchema, ROUTE_MANIFEST_REL_PATH, STORED_JSON_SCHEMA_TARGET, TriggerManifestShardSchema, WorkflowManifestFlowShardSchema, WorkflowManifestMetaShardSchema, getOpenApiJsonSchema, jsonSchemaToZod, normalizeCredentialList, parseProjectManifest, parseStoredRouteManifest, zodToStoredJsonSchema, zodToStoredJsonSchema as zodToStoredJsonSchema$1 } from \"@keystrokehq/shared\";\nimport { isApp } from \"@keystrokehq/app\";\nimport { getActionCredentialRequirements, isAction, normalizeCredentialList as normalizeCredentialList$1 } from \"@keystrokehq/action\";\nimport { createHash } from \"node:crypto\";\nimport { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from \"node:fs\";\nimport { validateAgentModelIds } from \"@keystrokehq/agent/validate-models\";\nimport { buildWorkflowCanvasGraph } from \"@keystrokehq/workflow-canvas\";\nimport { attachmentSlugFromRecord, attachmentSlugFromRecord as attachmentSlugFromRecord$1, cronPayloadSchema, isAgentTriggerAttachment, isWorkflowTriggerAttachment, sourceSlugFrom, triggerAttachmentsFromExport, triggerMetaFromAttachment } from \"@keystrokehq/trigger\";\nimport { z } from \"zod\";\nimport ts from \"typescript\";\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\tif (!value.name?.trim()) throw new Error(`${filePath} agent must include a non-empty name`);\n\tif (!value.description?.trim()) throw new Error(`${filePath} agent must include a non-empty description`);\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\n/**\n* List agent module files without importing them. Key comes from the file path\n* (slug convention: `agents/{slug}.ts` or `agents/{slug}/agent.ts`).\n*/\nasync function discoverAgentEntries(agentsDir) {\n\treturn (await discoverEntries(agentsDir, {\n\t\tnestedEntry: \"agent\",\n\t\tformatKey: (id) => id,\n\t\tduplicateLabel: \"agent module file\"\n\t})).map(({ key, filePath, moduleFile }) => ({\n\t\tkey,\n\t\troute: agentRouteFromKey(key),\n\t\tfilePath,\n\t\tmoduleFile\n\t}));\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/credentials/requirement-summary.ts\n/**\n* Reduce a definition's `.credentials` list to the deploy-time summaries the\n* workflow-canvas credential overlay needs (`key` / `kind` / pinned `scope`).\n* The Zod schema is intentionally dropped — only the resolution metadata ships.\n*/\nfunction credentialRequirementSummaries(list) {\n\tif (!list?.length) return [];\n\treturn normalizeCredentialList$1(list).map((requirement) => ({\n\t\tkey: requirement.key,\n\t\tkind: requirement.kind,\n\t\t...requirement.scope ? { scope: requirement.scope } : {}\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}\nfunction toolCredentialRequirements(tool) {\n\tconst record = tool;\n\tif (isManifestAction(tool)) return getManifestActionCredentialRequirements(tool);\n\treturn \"credentials\" in record && Array.isArray(record.credentials) ? record.credentials : void 0;\n}\n/**\n* Credential requirements per tool slug — the agent's credential consumer key.\n* Powers the workflow-canvas credential overlay for agent nodes (which resolve\n* per tool, not per call site).\n*/\nfunction collectAgentToolRequirements(agent) {\n\tconst byTool = {};\n\tfor (const tool of agent.tools ?? []) {\n\t\tif (isApp(tool)) {\n\t\t\tbyTool[tool.slug] = [{\n\t\t\t\tkey: tool.credential.key,\n\t\t\t\tkind: tool.credential.kind\n\t\t\t}];\n\t\t\tfor (const registered of tool.actions) {\n\t\t\t\tconst slug = registered.action.slug;\n\t\t\t\tconst requirements = toolCredentialRequirements(registered.action);\n\t\t\t\tif (!slug || !requirements?.length) continue;\n\t\t\t\tbyTool[slug] = normalizeCredentialList(requirements).map((requirement) => ({\n\t\t\t\t\tkey: requirement.key,\n\t\t\t\t\tkind: requirement.kind,\n\t\t\t\t\t...requirement.scope ? { scope: requirement.scope } : {}\n\t\t\t\t}));\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tconst slug = actionSlug(tool);\n\t\tconst requirements = toolCredentialRequirements(tool);\n\t\tif (!slug || !requirements?.length) continue;\n\t\tbyTool[slug] = normalizeCredentialList(requirements).map((requirement) => ({\n\t\t\tkey: requirement.key,\n\t\t\tkind: requirement.kind,\n\t\t\t...requirement.scope ? { scope: requirement.scope } : {}\n\t\t}));\n\t}\n\treturn byTool;\n}\n/** Sandbox credential requirements declared on `agent.sandbox.credentials`. */\nfunction collectAgentSandboxRequirements(agent) {\n\treturn credentialRequirementSummaries(agent.sandbox?.credentials);\n}\n/** App-kind slugs required by the agent's tools and sandbox (same as `credential_instances.app_slug`). */\nfunction collectAgentAppSlugs(agent) {\n\tconst slugs = /* @__PURE__ */ new Set();\n\tfor (const tool of agent.tools ?? []) {\n\t\tif (isApp(tool)) {\n\t\t\tslugs.add(tool.slug);\n\t\t\tcontinue;\n\t\t}\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\tfor (const requirement of collectAgentSandboxRequirements(agent)) slugs.add(requirement.key);\n\treturn [...slugs].sort();\n}\nfunction collectAgentToolSlugs(agent) {\n\tconst slugs = [];\n\tfor (const tool of agent.tools ?? []) {\n\t\tif (isApp(tool)) {\n\t\t\tslugs.push(tool.slug);\n\t\t\tfor (const registered of tool.actions) slugs.push(registered.action.slug);\n\t\t\tcontinue;\n\t\t}\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\tconst toolRequirements = collectAgentToolRequirements(agent);\n\tconst sandboxRequirements = collectAgentSandboxRequirements(agent);\n\tconst sandboxSetup = agent.sandbox?.setup?.map((c) => c.trim()).filter(Boolean);\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\t...agent.compactionModel !== void 0 ? { compactionModel: agent.compactionModel } : {},\n\t\tsystemPrompt: agent.systemPrompt,\n\t\ttoolCount: agent.tools?.length ?? 0,\n\t\tcredentialCount: countAgentCredentials(agent),\n\t\tsandboxMode: agent.sandbox?.mode ?? \"in-process\",\n\t\tbrainSlugs: agent.brains ?? [],\n\t\tappSlugs: collectAgentAppSlugs(agent),\n\t\ttoolSlugs: collectAgentToolSlugs(agent),\n\t\t...Object.keys(toolRequirements).length ? { toolRequirements } : {},\n\t\t...sandboxRequirements.length ? { sandboxRequirements } : {},\n\t\t...sandboxSetup?.length ? { sandboxSetup } : {}\n\t};\n}\n//#endregion\n//#region src/actions/discover.ts\nfunction resolveActionFromModule(mod, filePath) {\n\tif (isAction(mod.default)) return mod.default;\n\tconst named = Object.values(mod).filter(isAction);\n\tif (named.length === 1) return named[0];\n\tif (named.length > 1) throw new Error(`${filePath} exports multiple actions; use one action per file`);\n\tthrow new Error(`${filePath} must export defineAction(...) (default or single named export)`);\n}\nasync function importActionDefinition(filePath, options) {\n\tconst appRoot = resolveAppRoot(filePath);\n\tconst href = pathToFileURL(filePath).href;\n\treturn runWithAppRoot(appRoot, async () => {\n\t\treturn resolveActionFromModule(await (options?.reload ? import(`${href}?keystroke=${Date.now()}`) : import(href)), filePath);\n\t});\n}\nasync function discoverActions(actionsDir, options) {\n\tconst files = await discoverModuleFileEntries(actionsDir, {\n\t\tnestedEntry: \"action\",\n\t\tduplicateLabel: \"action module file\"\n\t});\n\treturn Promise.all(files.map(async ({ filePath, moduleFile }) => {\n\t\tconst definition = await importActionDefinition(filePath, options);\n\t\tconst key = definition.slug.trim();\n\t\tif (!key) throw new Error(`${filePath} action must define a non-empty slug`);\n\t\treturn {\n\t\t\tkey,\n\t\t\tfilePath,\n\t\t\tmoduleFile,\n\t\t\tdefinition\n\t\t};\n\t}));\n}\n//#endregion\n//#region src/actions/action-manifest-entry.ts\n/** Single source of truth for the `kind: \"action\"` route-manifest entry shape. */\nfunction actionManifestEntry(action, options) {\n\tconst requirements = credentialRequirementSummaries(getActionCredentialRequirements(action));\n\treturn {\n\t\tkind: \"action\",\n\t\tslug: action.slug,\n\t\tmoduleFile: options.moduleFile,\n\t\tname: action.name,\n\t\tdescription: action.description,\n\t\t...options.appSlug ? { appSlug: options.appSlug } : {},\n\t\tinputSchema: options.inputSchema,\n\t\toutputSchema: options.outputSchema,\n\t\t...requirements.length ? { requirements } : {}\n\t};\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/validate.ts\nfunction discoveredSlug(attachment) {\n\treturn attachment.slug;\n}\nfunction validateTriggerAttachments(attachments) {\n\tconst pollRoutes = /* @__PURE__ */ new Map();\n\tfor (const attachment of attachments) {\n\t\tconst source = attachment.attachment.source;\n\t\tconst slug = discoveredSlug(attachment);\n\t\tif (source.kind === \"poll\") {\n\t\t\tconst sourceSlug = sourceSlugFrom(source);\n\t\t\tconst route = pollRouteFromSourceSlug(sourceSlug);\n\t\t\tconst existingPoll = pollRoutes.get(route);\n\t\t\tif (existingPoll) throw new Error(`Poll route ${route} is declared by both \"${existingPoll}\" and \"${sourceSlug}\"`);\n\t\t\tpollRoutes.set(route, sourceSlug);\n\t\t\tconst groupRoute = pollGroupRouteFromId(source.id ?? sourceSlug);\n\t\t\tif (pollRoutes.has(groupRoute)) throw new Error(`Poll group route ${groupRoute} conflicts with a poll attachment route`);\n\t\t\tif (!source.schedule.trim()) throw new Error(`Trigger attachment \"${slug}\" has an empty poll schedule`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (source.kind === \"cron\") {\n\t\t\tif (!source.schedule.trim()) throw new Error(`Trigger attachment \"${slug}\" has an empty cron schedule`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!source.endpoint.trim()) throw new Error(`Trigger attachment \"${slug}\" has an empty webhook endpoint`);\n\t\tconst route = webhookRouteFromEndpoint(source.endpoint);\n\t\tif (pollRoutes.has(route)) throw new Error(`Webhook route ${route} conflicts with a poll trigger route`);\n\t}\n}\nfunction workflowKeyForAttachment(attachment, workflows) {\n\tif (!isWorkflowTriggerAttachment(attachment.attachment)) throw new Error(`Trigger attachment \"${discoveredSlug(attachment)}\" is not a workflow attachment`);\n\tconst workflowKey = attachment.attachment.workflow.slug;\n\tconst matched = workflows.find((entry) => entry.key === workflowKey);\n\tif (!matched) throw new Error(`Trigger attachment \"${discoveredSlug(attachment)}\" references an unknown workflow`);\n\treturn matched.key;\n}\nfunction agentKeyForAttachment(attachment, agents) {\n\tif (!isAgentTriggerAttachment(attachment.attachment)) throw new Error(`Trigger attachment \"${discoveredSlug(attachment)}\" is not an agent attachment`);\n\tconst agentKey = attachment.attachment.agent.slug;\n\tconst matched = agents.find((entry) => entry.key === agentKey);\n\tif (!matched) throw new Error(`Trigger attachment \"${discoveredSlug(attachment)}\" references an unknown agent`);\n\treturn matched.key;\n}\nfunction validateAttachmentTargets(attachments, workflows, agents) {\n\tfor (const attachment of attachments) {\n\t\tif (isWorkflowTriggerAttachment(attachment.attachment)) {\n\t\t\tworkflowKeyForAttachment(attachment, workflows);\n\t\t\tcontinue;\n\t\t}\n\t\tagentKeyForAttachment(attachment, agents);\n\t}\n}\n/** @deprecated Use validateAttachmentTargets */\nfunction validateAttachmentWorkflowKeys(attachments, workflows) {\n\tfor (const attachment of attachments) if (isWorkflowTriggerAttachment(attachment.attachment)) workflowKeyForAttachment(attachment, workflows);\n}\nfunction validateUniqueAttachmentSlugs(attachments) {\n\tconst bySlug = /* @__PURE__ */ new Map();\n\tfor (const attachment of attachments) {\n\t\tconst slug = discoveredSlug(attachment);\n\t\tconst existing = bySlug.get(slug);\n\t\tif (existing) throw new Error(`Duplicate trigger attachment slug \"${slug}\" (${existing}, ${attachment.filePath})`);\n\t\tbySlug.set(slug, attachment.filePath);\n\t}\n}\nfunction sourceConfigSignature(source) {\n\tif (source.kind === \"webhook\") return `webhook:${source.endpoint}`;\n\tif (source.kind === \"cron\") return `cron:${source.schedule}`;\n\treturn `poll:${source.id ?? source.slug}:${source.schedule}`;\n}\nfunction validateUniqueTriggerSourceSlugs(attachments) {\n\tconst bySourceSlug = /* @__PURE__ */ new Map();\n\tfor (const attachment of attachments) {\n\t\tconst source = attachment.attachment.source;\n\t\tconst sourceSlug = sourceSlugFrom(source);\n\t\tconst signature = sourceConfigSignature(source);\n\t\tconst existing = bySourceSlug.get(sourceSlug);\n\t\tif (existing && existing.signature !== signature) throw new Error(`Conflicting trigger source slug \"${sourceSlug}\" with differing config (${existing.filePath}, ${attachment.filePath})`);\n\t\tif (!existing) bySourceSlug.set(sourceSlug, {\n\t\t\tfilePath: attachment.filePath,\n\t\t\tsignature\n\t\t});\n\t}\n}\n/** @deprecated Use {@link validateUniqueAttachmentSlugs}. */\nconst validateUniqueAttachmentKeys = validateUniqueAttachmentSlugs;\n/** @deprecated Use {@link validateUniqueTriggerSourceSlugs}. */\nconst validateUniqueTriggerKeys = validateUniqueTriggerSourceSlugs;\n//#endregion\n//#region src/validate-project-modules.ts\n/** Build/deploy manifest invariants — not re-run at runtime bootstrap. */\nfunction validateProjectModules(input) {\n\tvalidateTriggerAttachments(input.attachments);\n\tvalidatePollGroups(buildPollGroups(input.attachments));\n\tvalidateUniqueTriggerSourceSlugs(input.attachments);\n\tvalidateUniqueAttachmentSlugs(input.attachments);\n\tvalidateAttachmentTargets(input.attachments, input.workflows, input.agents);\n\tvalidateUniqueModuleKeys([\n\t\t...input.agents.map((entry) => ({\n\t\t\tkind: \"agent\",\n\t\t\tkey: entry.key,\n\t\t\tfilePath: entry.filePath\n\t\t})),\n\t\t...input.workflows.map((workflow) => ({\n\t\t\tkind: \"workflow\",\n\t\t\tkey: workflow.key,\n\t\t\tfilePath: workflow.filePath\n\t\t})),\n\t\t...input.attachments.map((attachment) => ({\n\t\t\tkind: \"trigger\",\n\t\t\tkey: attachment.slug,\n\t\t\tfilePath: attachment.filePath\n\t\t}))\n\t]);\n}\n//#endregion\n//#region src/skills/discover-manifest-entries.ts\nconst SKIP_DIRS$1 = new Set([\".git\", \"node_modules\"]);\nfunction toPosix$2(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 entry of readdirSync(dir).sort()) {\n\t\tconst absolute = join(dir, entry);\n\t\tconst stats = statSync(absolute);\n\t\tif (stats.isDirectory()) {\n\t\t\tif (SKIP_DIRS$1.has(entry)) continue;\n\t\t\twalkSkillFiles(root, absolute, out);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!stats.isFile() || entry !== \"SKILL.md\") continue;\n\t\tconst moduleFile = toPosix$2(relative(root, absolute));\n\t\tconst slug = toPosix$2(relative(join(root, \"src\", \"skills\"), absolute)).replace(/\\/?SKILL\\.md$/, \"\");\n\t\tif (!slug) continue;\n\t\tconst frontmatter = parseSkillFrontmatter(readFileSync(absolute, \"utf8\"));\n\t\tconst name = frontmatter.name?.trim();\n\t\tconst description = frontmatter.description?.trim();\n\t\tif (!name || !description) throw new Error(`${moduleFile} skill frontmatter must include non-empty name and description`);\n\t\tout.push({\n\t\t\tslug,\n\t\t\tname,\n\t\t\tdescription,\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\nconst EXPORT_FIX = \"Use plain structural Zod only (objects, strings, literals, unions). Remap or validate in .attach({ transform }) or at the top of run() instead.\";\nfunction zodDef(schema) {\n\treturn schema._zod?.def;\n}\n/** Finds code-based Zod nodes that cannot be faithfully exported to JSON Schema. */\nfunction findNonExportableSchemaNode(schema, path = \"schema\") {\n\tconst def = zodDef(schema);\n\tif (!def) return;\n\tif (def.type === \"transform\") return `${path} uses .transform()`;\n\tif (def.checks?.some((check) => check._zod?.def?.type === \"custom\")) return `${path} uses .refine() or .superRefine()`;\n\tif (def.type === \"pipe\") {\n\t\tif (def.in && zodDef(def.in)?.type === \"transform\") return `${path} uses .preprocess()`;\n\t\tconst inIssue = def.in ? findNonExportableSchemaNode(def.in, `${path}.pipe(in)`) : void 0;\n\t\tif (inIssue) return inIssue;\n\t\tconst outIssue = def.out ? findNonExportableSchemaNode(def.out, `${path}.pipe(out)`) : void 0;\n\t\tif (outIssue) return outIssue;\n\t}\n\tif (def.shape) for (const [key, child] of Object.entries(def.shape)) {\n\t\tconst issue = findNonExportableSchemaNode(child, `${path}.${key}`);\n\t\tif (issue) return issue;\n\t}\n\tif (def.element) {\n\t\tconst issue = findNonExportableSchemaNode(def.element, `${path}[]`);\n\t\tif (issue) return issue;\n\t}\n\tif (def.options) for (const [index, option] of def.options.entries()) {\n\t\tconst issue = findNonExportableSchemaNode(option, `${path}[${index}]`);\n\t\tif (issue) return issue;\n\t}\n\tif (def.left) {\n\t\tconst issue = findNonExportableSchemaNode(def.left, `${path}.left`);\n\t\tif (issue) return issue;\n\t}\n\tif (def.right) {\n\t\tconst issue = findNonExportableSchemaNode(def.right, `${path}.right`);\n\t\tif (issue) return issue;\n\t}\n\tif (def.valueType) {\n\t\tconst issue = findNonExportableSchemaNode(def.valueType, `${path}.value`);\n\t\tif (issue) return issue;\n\t}\n\tif (def.items) for (const [index, item] of def.items.entries()) {\n\t\tconst issue = findNonExportableSchemaNode(item, `${path}[${index}]`);\n\t\tif (issue) return issue;\n\t}\n\tif (def.rest) {\n\t\tconst issue = findNonExportableSchemaNode(def.rest, `${path}.rest`);\n\t\tif (issue) return issue;\n\t}\n}\nfunction formatSchemaExportError(cause) {\n\treturn /* @__PURE__ */ new Error(`Cannot export schema to JSON Schema: ${cause}. ${EXPORT_FIX}`);\n}\nfunction applyAdditionalProperties(json, allowAdditionalProperties) {\n\tif (!allowAdditionalProperties) return json;\n\tconst visit = (node) => {\n\t\tif (!node || typeof node !== \"object\" || Array.isArray(node)) return;\n\t\tconst record = node;\n\t\tif (record.type === \"object\") record.additionalProperties = true;\n\t\tfor (const value of Object.values(record)) visit(value);\n\t};\n\tvisit(json);\n\treturn json;\n}\n/**\n* Export a Zod schema to the stored OpenAPI 3.0 JSON Schema wire format.\n* Inverse: `jsonSchemaToZod` from `@keystrokehq/shared`.\n*/\nfunction schemaToJson(schema, options = {}) {\n\tconst stored = getOpenApiJsonSchema(schema);\n\tif (stored) return applyAdditionalProperties(structuredClone(stored), options.allowAdditionalProperties);\n\tconst issue = findNonExportableSchemaNode(schema);\n\tif (issue) throw formatSchemaExportError(issue);\n\ttry {\n\t\treturn zodToStoredJsonSchema$1(schema, options);\n\t} catch (error) {\n\t\tthrow formatSchemaExportError(error instanceof Error ? error.message : String(error));\n\t}\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\t...entry.compactionModel !== void 0 ? { compactionModel: entry.compactionModel } : {},\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\t...entry.sandboxMode ? { sandboxMode: entry.sandboxMode } : {},\n\t\t\t\tbrainSlugs: entry.brainSlugs,\n\t\t\t\tappSlugs: entry.appSlugs,\n\t\t\t\ttoolSlugs: entry.toolSlugs,\n\t\t\t\t...entry.toolRequirements ? { toolRequirements: entry.toolRequirements } : {},\n\t\t\t\t...entry.sandboxRequirements?.length ? { sandboxRequirements: entry.sandboxRequirements } : {},\n\t\t\t\t...entry.sandboxSetup?.length ? { sandboxSetup: entry.sandboxSetup } : {}\n\t\t\t});\n\t\t\tbreak;\n\t\tcase \"action\":\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\t...entry.appSlug !== void 0 ? { appSlug: entry.appSlug } : {},\n\t\t\t\tname: entry.name,\n\t\t\t\tdescription: entry.description,\n\t\t\t\tinputSchema: entry.inputSchema,\n\t\t\t\toutputSchema: entry.outputSchema,\n\t\t\t\t...entry.requirements ? { requirements: entry.requirements } : {}\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\tresponseSchema: schemaToJson(entry.response),\n\t\t\t\t...entry.flowGraph ? {\n\t\t\t\t\tflowGraph: entry.flowGraph,\n\t\t\t\t\tflowGraphSourceHash: entry.flowGraphSourceHash,\n\t\t\t\t\t...entry.flowGraphHash ? { flowGraphHash: entry.flowGraphHash } : {}\n\t\t\t\t} : {}\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\t...entry.sourceHash ? { sourceHash: entry.sourceHash } : {},\n\t\t\t\tattachmentSchemas: Object.fromEntries(Object.entries(entry.attachmentSchemas).map(([attachmentSlug, schemas]) => [attachmentSlug, { requestSchema: schemaToJson(schemas.request, { allowAdditionalProperties: true }) }])),\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\t...entry.sourceHash ? { sourceHash: entry.sourceHash } : {},\n\t\t\t\tschedule: entry.schedule,\n\t\t\t\t...entry.timezone ? { timezone: entry.timezone } : {},\n\t\t\t\tname: entry.name,\n\t\t\t\tdescription: 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\t...entry.timezone ? { timezone: entry.timezone } : {}\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/modular/paths.ts\n/** `dist/.keystroke` absolute path for a project root. */\nfunction keystrokeMetaDir(projectRoot) {\n\treturn join(projectRoot, \"dist\", \".keystroke\");\n}\nfunction projectManifestAbsPath(projectRoot) {\n\treturn join(projectRoot, PROJECT_MANIFEST_REL_PATH);\n}\n/** Shard path relative to `dist/.keystroke/`. */\nfunction agentShardRelPath(slug) {\n\treturn `modules/agents/${slug}.json`;\n}\nfunction workflowMetaShardRelPath(slug) {\n\treturn `modules/workflows/${slug}.json`;\n}\nfunction workflowFlowShardRelPath(slug) {\n\treturn `modules/workflows/${slug}.flow.json`;\n}\nfunction triggerShardRelPath(id) {\n\treturn `modules/triggers/${id}.json`;\n}\nconst ACTIONS_CATALOG_REL = \"catalogs/actions.json\";\n/**\n* Stable trigger module id from a `moduleFile` path\n* (`src/triggers/foo/trigger.ts` → `foo`, `src/triggers/bar.ts` → `bar`).\n*/\nfunction triggerIdFromModuleFile(moduleFile) {\n\tlet rest = moduleFile.replace(/\\\\/g, \"/\").replace(/^(src\\/)?triggers\\//, \"\").replace(/\\.(ts|mjs|js)$/, \"\");\n\tif (rest.endsWith(\"/trigger\")) rest = rest.slice(0, -8);\n\treturn rest || \"trigger\";\n}\n//#endregion\n//#region src/modular/compose.ts\nfunction readJson(absPath) {\n\treturn JSON.parse(readFileSync(absPath, \"utf8\"));\n}\nfunction tryReadProjectManifest(projectRoot) {\n\tconst path = projectManifestAbsPath(projectRoot);\n\tif (!existsSync(path)) return;\n\treturn parseProjectManifest(readJson(path));\n}\n/**\n* Compose modular shards under an absolute `dist/.keystroke` directory into a\n* flat v2 `StoredRouteManifest` for existing runtime/DB consumers.\n*/\nfunction composeStoredRouteManifestFromKeystrokeDir(keystrokeDir, manifest) {\n\tconst index = manifest ?? parseProjectManifest(readJson(join(keystrokeDir, \"manifest.json\")));\n\tconst entries = [{ kind: \"health\" }];\n\tfor (const ref of index.modules) {\n\t\tconst shardPath = join(keystrokeDir, ref.path);\n\t\tif (!existsSync(shardPath)) throw new Error(`Missing manifest shard: ${ref.path}`);\n\t\tif (ref.kind === \"agent\") {\n\t\t\tentries.push(AgentManifestShardSchema.parse(readJson(shardPath)));\n\t\t\tcontinue;\n\t\t}\n\t\tif (ref.kind === \"workflow\") {\n\t\t\tconst meta = WorkflowManifestMetaShardSchema.parse(readJson(shardPath));\n\t\t\tif (ref.flowPath) {\n\t\t\t\tconst flowAbs = join(keystrokeDir, ref.flowPath);\n\t\t\t\tif (!existsSync(flowAbs)) throw new Error(`Missing workflow flow shard: ${ref.flowPath}`);\n\t\t\t\tconst flow = WorkflowManifestFlowShardSchema.parse(readJson(flowAbs));\n\t\t\t\tentries.push({\n\t\t\t\t\t...meta,\n\t\t\t\t\t...flow\n\t\t\t\t});\n\t\t\t} else entries.push(meta);\n\t\t\tcontinue;\n\t\t}\n\t\tconst triggerShard = TriggerManifestShardSchema.parse(readJson(shardPath));\n\t\tentries.push(...triggerShard.entries);\n\t}\n\tconst actionsAbs = join(keystrokeDir, index.actionsCatalogPath);\n\tif (existsSync(actionsAbs)) {\n\t\tconst catalog = ActionsCatalogShardSchema.parse(readJson(actionsAbs));\n\t\tentries.push(...catalog.entries);\n\t}\n\treturn {\n\t\tversion: 2,\n\t\tentries,\n\t\tskills: index.skills,\n\t\t...index.integrations ? { integrations: index.integrations } : {}\n\t};\n}\n/**\n* Compose modular on-disk shards into a flat v2 `StoredRouteManifest` for\n* existing consumers. Prefer this when `manifest.json` is present.\n*/\nfunction composeStoredRouteManifestFromModular(projectRoot, manifest = tryReadProjectManifest(projectRoot)) {\n\tif (!manifest) throw new Error(`dist/.keystroke/manifest.json not found under ${projectRoot}`);\n\treturn composeStoredRouteManifestFromKeystrokeDir(keystrokeMetaDir(projectRoot), manifest);\n}\n//#endregion\n//#region src/modular/hash.ts\n/** sha256 hex of raw bytes. */\nfunction sha256Bytes(data) {\n\treturn createHash(\"sha256\").update(data).digest(\"hex\");\n}\n/** sha256 of a file, or undefined when missing. */\nfunction sha256File(absPath) {\n\tif (!existsSync(absPath)) return;\n\treturn sha256Bytes(readFileSync(absPath));\n}\nconst SKIP_DIRS = new Set([\".git\", \"node_modules\"]);\n/** Content hash of every file under a directory (skills/files packs). */\nfunction hashDirectoryContents(dirPath) {\n\tconst hash = createHash(\"sha256\");\n\tif (!statSync(dirPath, { throwIfNoEntry: false })?.isDirectory()) return hash.digest(\"hex\");\n\tconst walk = (current) => {\n\t\tfor (const name of readdirSync(current).sort()) {\n\t\t\tif (SKIP_DIRS.has(name)) continue;\n\t\t\tconst abs = join(current, name);\n\t\t\tconst st = statSync(abs);\n\t\t\tif (st.isDirectory()) {\n\t\t\t\twalk(abs);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!st.isFile()) continue;\n\t\t\thash.update(relative(dirPath, abs).replace(/\\\\/g, \"/\"));\n\t\t\thash.update(\"\\0\");\n\t\t\thash.update(readFileSync(abs));\n\t\t\thash.update(\"\\0\");\n\t\t}\n\t};\n\twalk(dirPath);\n\treturn hash.digest(\"hex\");\n}\n/**\n* Hash for a primitive meta shard: prefer source file contents when `moduleFile`\n* points at a readable project `.ts`; otherwise hash the serialized shard body.\n*/\nfunction contentHashForModule(input) {\n\tif (input.moduleFile.endsWith(\".ts\")) {\n\t\tconst fromSource = sha256File(join(input.projectRoot, input.moduleFile));\n\t\tif (fromSource) return fromSource;\n\t}\n\treturn sha256Bytes(input.shardJson);\n}\n/** Fingerprint of `@keystrokehq/*` deps — invalidates the actions catalog. */\nfunction integrationPackagesFingerprint(projectRoot) {\n\tconst hash = createHash(\"sha256\");\n\tconst packageJsonPath = join(projectRoot, \"package.json\");\n\tif (!existsSync(packageJsonPath)) return hash.digest(\"hex\");\n\tconst raw = readFileSync(packageJsonPath, \"utf8\");\n\thash.update(raw);\n\tlet dependencies = {};\n\ttry {\n\t\tdependencies = JSON.parse(raw).dependencies ?? {};\n\t} catch {\n\t\treturn hash.digest(\"hex\");\n\t}\n\tconst require = createRequire(packageJsonPath);\n\tfor (const name of Object.keys(dependencies).sort()) {\n\t\tif (!name.startsWith(\"@keystrokehq/\")) continue;\n\t\ttry {\n\t\t\tconst resolved = require.resolve(`${name}/package.json`);\n\t\t\thash.update(name);\n\t\t\thash.update(\"\\0\");\n\t\t\thash.update(readFileSync(resolved, \"utf8\"));\n\t\t\thash.update(\"\\0\");\n\t\t} catch {\n\t\t\thash.update(name);\n\t\t\thash.update(\"\\0missing\\0\");\n\t\t}\n\t}\n\treturn hash.digest(\"hex\");\n}\n/** Fingerprint of project `src/actions` (or custom srcDir/actions). */\nfunction projectActionsFingerprint(projectRoot, srcDir = \"src\") {\n\treturn hashDirectoryContents(join(projectRoot, srcDir, \"actions\"));\n}\n/**\n* Catalog invalidation key: integration packages + project action sources.\n* Changing only a project action must miss emit cache.\n*/\nfunction actionsCatalogFingerprint(projectRoot, srcDir = \"src\") {\n\treturn sha256Bytes(`${integrationPackagesFingerprint(projectRoot)}\\0${projectActionsFingerprint(projectRoot, srcDir)}`);\n}\n//#endregion\n//#region src/modular/split.ts\nfunction compactJson(value) {\n\treturn `${JSON.stringify(value)}\\n`;\n}\nfunction isAction$1(entry) {\n\treturn entry.kind === \"action\";\n}\nfunction isAgent(entry) {\n\treturn entry.kind === \"agent\";\n}\nfunction isWorkflow(entry) {\n\treturn entry.kind === \"workflow\";\n}\nfunction isTriggerEntry(entry) {\n\treturn entry.kind === \"trigger-webhook\" || entry.kind === \"trigger-poll\" || entry.kind === \"trigger-poll-group\" || entry.kind === \"cron-schedule\";\n}\n/**\n* Split a flat v2 stored manifest into modular shard files + thin project index.\n*/\nfunction splitStoredRouteManifest(input) {\n\tconst files = /* @__PURE__ */ new Map();\n\tconst modules = [];\n\tfor (const entry of input.stored.entries) {\n\t\tif (!isAgent(entry)) continue;\n\t\tconst shard = entry;\n\t\tconst path = agentShardRelPath(entry.slug);\n\t\tconst shardJson = compactJson(shard);\n\t\tfiles.set(path, shardJson);\n\t\tmodules.push({\n\t\t\tkind: \"agent\",\n\t\t\tid: entry.slug,\n\t\t\tpath,\n\t\t\tcontentHash: contentHashForModule({\n\t\t\t\tprojectRoot: input.projectRoot,\n\t\t\t\tmoduleFile: entry.moduleFile,\n\t\t\t\tshardJson\n\t\t\t})\n\t\t});\n\t}\n\tfor (const entry of input.stored.entries) {\n\t\tif (!isWorkflow(entry)) continue;\n\t\tconst meta = {\n\t\t\tkind: \"workflow\",\n\t\t\tslug: entry.slug,\n\t\t\tname: entry.name,\n\t\t\tdescription: entry.description,\n\t\t\tsubscribable: entry.subscribable,\n\t\t\tmoduleFile: entry.moduleFile,\n\t\t\trequestSchema: entry.requestSchema,\n\t\t\t...entry.responseSchema ? { responseSchema: entry.responseSchema } : {}\n\t\t};\n\t\tconst metaPath = workflowMetaShardRelPath(entry.slug);\n\t\tconst metaJson = compactJson(meta);\n\t\tfiles.set(metaPath, metaJson);\n\t\tconst ref = {\n\t\t\tkind: \"workflow\",\n\t\t\tid: entry.slug,\n\t\t\tpath: metaPath,\n\t\t\tcontentHash: contentHashForModule({\n\t\t\t\tprojectRoot: input.projectRoot,\n\t\t\t\tmoduleFile: entry.moduleFile,\n\t\t\t\tshardJson: metaJson\n\t\t\t})\n\t\t};\n\t\tif (entry.flowGraph && entry.flowGraphSourceHash && entry.flowGraphHash) {\n\t\t\tconst flow = {\n\t\t\t\tflowGraph: entry.flowGraph,\n\t\t\t\tflowGraphSourceHash: entry.flowGraphSourceHash,\n\t\t\t\tflowGraphHash: entry.flowGraphHash\n\t\t\t};\n\t\t\tconst flowPath = workflowFlowShardRelPath(entry.slug);\n\t\t\tfiles.set(flowPath, compactJson(flow));\n\t\t\tref.flowPath = flowPath;\n\t\t\tref.flowHash = entry.flowGraphSourceHash;\n\t\t}\n\t\tmodules.push(ref);\n\t}\n\tconst triggersByModule = /* @__PURE__ */ new Map();\n\tfor (const entry of input.stored.entries) {\n\t\tif (!isTriggerEntry(entry)) continue;\n\t\tconst id = triggerIdFromModuleFile(entry.moduleFile);\n\t\tconst group = triggersByModule.get(id) ?? [];\n\t\tgroup.push(entry);\n\t\ttriggersByModule.set(id, group);\n\t}\n\tfor (const [id, entries] of [...triggersByModule.entries()].sort(([a], [b]) => a.localeCompare(b))) {\n\t\tconst shard = { entries };\n\t\tconst path = triggerShardRelPath(id);\n\t\tconst shardJson = compactJson(shard);\n\t\tfiles.set(path, shardJson);\n\t\tconst moduleFile = entries[0].moduleFile;\n\t\tmodules.push({\n\t\t\tkind: \"trigger\",\n\t\t\tid,\n\t\t\tpath,\n\t\t\tcontentHash: contentHashForModule({\n\t\t\t\tprojectRoot: input.projectRoot,\n\t\t\t\tmoduleFile,\n\t\t\t\tshardJson\n\t\t\t})\n\t\t});\n\t}\n\tconst actionsJson = compactJson({ entries: input.stored.entries.filter(isAction$1) });\n\tfiles.set(ACTIONS_CATALOG_REL, actionsJson);\n\tconst manifest = {\n\t\tversion: 3,\n\t\tmodules,\n\t\tskills: input.stored.skills,\n\t\t...input.stored.integrations ? { integrations: input.stored.integrations } : {},\n\t\tactionsCatalogPath: ACTIONS_CATALOG_REL,\n\t\tactionsCatalogHash: input.actionsCatalogHash\n\t};\n\tfiles.set(\"manifest.json\", compactJson(manifest));\n\treturn {\n\t\tfiles,\n\t\tmanifest\n\t};\n}\n//#endregion\n//#region src/modular/persist.ts\nfunction listRelFiles(dir, base = dir) {\n\tif (!existsSync(dir)) return [];\n\tconst out = [];\n\tfor (const name of readdirSync(dir)) {\n\t\tconst abs = join(dir, name);\n\t\tif (statSync(abs).isDirectory()) out.push(...listRelFiles(abs, base));\n\t\telse out.push(relative(base, abs).replace(/\\\\/g, \"/\"));\n\t}\n\treturn out;\n}\n/**\n* Write modular shards + thin `manifest.json`. Skips files whose bytes match.\n* Does **not** write legacy `route-manifest.json` (removes it if present).\n*/\nfunction persistModularRouteManifest(projectRoot, stored) {\n\tconst { files, manifest } = splitStoredRouteManifest({\n\t\tprojectRoot,\n\t\tstored,\n\t\tactionsCatalogHash: actionsCatalogFingerprint(projectRoot)\n\t});\n\tconst metaRoot = keystrokeMetaDir(projectRoot);\n\tmkdirSync(metaRoot, { recursive: true });\n\tconst wroteFiles = [];\n\tconst skippedFiles = [];\n\tconst keep = new Set(files.keys());\n\tfor (const [rel, contents] of files) {\n\t\tconst abs = join(metaRoot, rel);\n\t\tif (existsSync(abs) && readFileSync(abs, \"utf8\") === contents) {\n\t\t\tskippedFiles.push(rel);\n\t\t\tcontinue;\n\t\t}\n\t\tmkdirSync(dirname(abs), { recursive: true });\n\t\twriteFileSync(abs, contents);\n\t\twroteFiles.push(rel);\n\t}\n\tfor (const existing of listRelFiles(metaRoot)) {\n\t\tif (existing === \"manifest.json\" || existing === \"assets.mjs\" || existing.endsWith(\".map\")) continue;\n\t\tif (existing === \"route-manifest.json\") {\n\t\t\trmSync(join(metaRoot, existing), { force: true });\n\t\t\tcontinue;\n\t\t}\n\t\tif (!keep.has(existing) && (existing.startsWith(\"modules/\") || existing.startsWith(\"catalogs/\"))) rmSync(join(metaRoot, existing), { force: true });\n\t}\n\treturn {\n\t\twroteFiles,\n\t\tskippedFiles,\n\t\tmanifest\n\t};\n}\nfunction collectDistEntryIds(distKindDir, nestedEntry) {\n\tif (!existsSync(distKindDir)) return [];\n\tconst ids = [];\n\tconst walk = (dir) => {\n\t\tfor (const name of readdirSync(dir)) {\n\t\t\tconst abs = join(dir, name);\n\t\t\tif (statSync(abs).isDirectory()) {\n\t\t\t\twalk(abs);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!name.endsWith(\".mjs\")) continue;\n\t\t\tconst id = entryIdFromFile(distKindDir, abs, { nestedEntry });\n\t\t\tif (id) ids.push(id);\n\t\t}\n\t};\n\twalk(distKindDir);\n\treturn ids.sort();\n}\nfunction expectedModuleKeys(projectRoot) {\n\tconst dist = join(projectRoot, \"dist\");\n\tconst keys = [];\n\tfor (const id of collectDistEntryIds(join(dist, \"agents\"), \"agent\")) keys.push(`agent:${id}`);\n\tfor (const id of collectDistEntryIds(join(dist, \"workflows\"), \"workflow\")) keys.push(`workflow:${id}`);\n\tfor (const id of collectDistEntryIds(join(dist, \"triggers\"), \"trigger\")) keys.push(`trigger:${id}`);\n\treturn keys.sort();\n}\nfunction listPackIds(dirPath) {\n\tif (!statSync(dirPath, { throwIfNoEntry: false })?.isDirectory()) return [];\n\treturn readdirSync(dirPath).filter((name) => {\n\t\ttry {\n\t\t\treturn statSync(join(dirPath, name)).isDirectory();\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}).sort();\n}\nfunction assetsIndexStillFresh(projectRoot) {\n\tconst indexPath = join(projectRoot, \"dist\", \".keystroke\", \"assets\", \"index.json\");\n\tconst skillIds = listPackIds(join(projectRoot, \"src\", \"skills\"));\n\tconst fileIds = listPackIds(join(projectRoot, \"src\", \"files\"));\n\tif (!existsSync(indexPath)) return skillIds.length === 0 && fileIds.length === 0;\n\tlet index;\n\ttry {\n\t\tindex = JSON.parse(readFileSync(indexPath, \"utf8\"));\n\t} catch {\n\t\treturn false;\n\t}\n\tconst indexedSkills = index.skills.map((ref) => ref.id).sort();\n\tconst indexedFiles = index.files.map((ref) => ref.id).sort();\n\tif (indexedSkills.length !== skillIds.length || indexedSkills.some((id, i) => id !== skillIds[i]) || indexedFiles.length !== fileIds.length || indexedFiles.some((id, i) => id !== fileIds[i])) return false;\n\tfor (const ref of index.skills) if (hashDirectoryContents(join(projectRoot, \"src\", \"skills\", ref.id)) !== ref.contentHash) return false;\n\tfor (const ref of index.files) if (hashDirectoryContents(join(projectRoot, \"src\", \"files\", ref.id)) !== ref.contentHash) return false;\n\treturn true;\n}\n/**\n* True when every module/actions hash in the on-disk index still matches current\n* sources — emit can skip rebuilding entirely.\n*/\nfunction isModularManifestEmitCacheHit(projectRoot) {\n\tconst existing = tryReadProjectManifest(projectRoot);\n\tif (!existing) return false;\n\tconst metaRoot = keystrokeMetaDir(projectRoot);\n\tif (!existsSync(join(metaRoot, existing.actionsCatalogPath))) return false;\n\tif (existing.actionsCatalogHash !== actionsCatalogFingerprint(projectRoot)) return false;\n\tif (!assetsIndexStillFresh(projectRoot)) return false;\n\tconst indexed = existing.modules.map((ref) => `${ref.kind}:${ref.id}`).sort();\n\tconst expected = expectedModuleKeys(projectRoot);\n\tif (indexed.length !== expected.length || indexed.some((key, i) => key !== expected[i])) return false;\n\tfor (const ref of existing.modules) {\n\t\tconst shardAbs = join(metaRoot, ref.path);\n\t\tif (!existsSync(shardAbs)) return false;\n\t\tlet moduleFile;\n\t\ttry {\n\t\t\tconst body = JSON.parse(readFileSync(shardAbs, \"utf8\"));\n\t\t\tmoduleFile = body.moduleFile ?? body.entries?.[0]?.moduleFile;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t\tif (!moduleFile?.endsWith(\".ts\")) return false;\n\t\tconst sourceHash = sha256File(join(projectRoot, moduleFile));\n\t\tif (!sourceHash || sourceHash !== ref.contentHash) return false;\n\t\tif (ref.kind === \"workflow\") {\n\t\t\tif (ref.flowPath && !existsSync(join(metaRoot, ref.flowPath))) return false;\n\t\t\tif (ref.flowHash && ref.flowHash !== sourceHash) return false;\n\t\t}\n\t}\n\treturn true;\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\tif (!value.name?.trim()) throw new Error(`${filePath} workflow must include a non-empty name`);\n\tif (!value.description?.trim()) throw new Error(`${filePath} workflow must include a non-empty description`);\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 requiredTextField = z.string().trim().min(1);\nconst optionalTextField = z.string().trim().min(1).optional();\nconst baseSourceShape = {\n\tslug: slugField,\n\tname: requiredTextField,\n\tdescription: requiredTextField,\n\tattach: z.function()\n};\nconst webhookSourceSchema = z.object({\n\tkind: z.literal(\"webhook\"),\n\t...baseSourceShape,\n\tendpoint: z.string().min(1),\n\tpayload: 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\ttimezone: z.string().trim().min(1).optional(),\n\tpayload: cronPayloadSchema.optional()\n});\nconst pollSourceSchema = z.object({\n\tkind: z.literal(\"poll\"),\n\t...baseSourceShape,\n\tid: z.string().optional(),\n\tschedule: cronScheduleSchema,\n\ttimezone: z.string().trim().min(1).optional(),\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 isBrandedTriggerAttachment(value) {\n\treturn typeof value === \"object\" && value !== null && TRIGGER_ATTACHMENT in value && value[TRIGGER_ATTACHMENT] === true;\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}\nfunction validateManifestTriggerAttachment(value, filePath) {\n\tif (!isBrandedTriggerAttachment(value)) throw new Error(`${filePath} must default-export a trigger attachment from .attach({ workflow }) or .attach({ agent, prompt })`);\n\tconst result = triggerAttachmentCoreSchema.safeParse(value);\n\tif (!result.success) throw new Error(`${filePath}: invalid trigger attachment: ${formatIssues(result.error.issues)}`);\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\treturn (await Promise.all(files.map(async ({ filePath, moduleFile }) => {\n\t\treturn (await importTriggerAttachments(filePath, options)).map((attachment) => ({\n\t\t\tslug: attachmentSlugFromRecord$1(attachment),\n\t\t\tfilePath,\n\t\t\tmoduleFile,\n\t\t\tattachment\n\t\t}));\n\t}))).flat();\n}\nfunction validateImportedTriggerAttachment(def, filePath) {\n\treturn validateManifestTriggerAttachment(def, filePath);\n}\nasync function loadTriggerModuleDefault(filePath, options) {\n\tconst appRoot = resolveAppRoot(filePath);\n\tconst href = pathToFileURL(filePath).href;\n\treturn runWithAppRoot(appRoot, async () => {\n\t\treturn (await (options?.reload ? import(`${href}?keystroke=${Date.now()}`) : import(href))).default;\n\t});\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/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\tconst triggerId = typeof binding.options.triggerId === \"string\" ? binding.options.triggerId : void 0;\n\t\treturn [{\n\t\t\tattachmentSlug: binding.discovered.slug,\n\t\t\t...triggerId ? { triggerId } : {},\n\t\t\tpayload: source.payload,\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\t...entry.triggerId ? { triggerId: entry.triggerId } : {},\n\t\trequestSchema: schemaToJson(entry.payload, { allowAdditionalProperties: true }),\n\t\t...entry.filter ? { filterSchema: schemaToJson(entry.filter, { allowAdditionalProperties: true }) } : {}\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.payload] : [];\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, { request: entry.payload }]));\n}\n//#endregion\n//#region src/workflows/discover.ts\n/**\n* List workflow module files without importing them. Key comes from the file path.\n*/\nasync function discoverWorkflowEntries(workflowsDir) {\n\treturn (await discoverEntries(workflowsDir, {\n\t\tnestedEntry: \"workflow\",\n\t\tformatKey: (id) => id,\n\t\tduplicateLabel: \"workflow module file\"\n\t})).map(({ key, filePath, moduleFile }) => ({\n\t\tkey,\n\t\troute: workflowRouteFromKey(key),\n\t\tfilePath,\n\t\tmoduleFile\n\t}));\n}\nfunction validateImportedWorkflowDefinition(def, filePath) {\n\treturn validateManifestWorkflow(def, filePath);\n}\nasync function importWorkflowDefinition(filePath, options) {\n\tconst appRoot = resolveAppRoot(filePath);\n\tconst href = pathToFileURL(filePath).href;\n\treturn runWithAppRoot(appRoot, async () => {\n\t\treturn validateImportedWorkflowDefinition((await (options?.reload ? import(`${href}?keystroke=${Date.now()}`) : import(href))).default, filePath);\n\t});\n}\nasync function discoverWorkflows(workflowsDir, options) {\n\tconst entries = await discoverWorkflowEntries(workflowsDir);\n\treturn Promise.all(entries.map(async (entry) => {\n\t\tconst definition = await importWorkflowDefinition(entry.filePath, options);\n\t\treturn {\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}\n//#endregion\n//#region src/workflows/resolve-step-slug.ts\nfunction toPosix$1(path) {\n\treturn path.split(\"\\\\\").join(\"/\");\n}\nfunction buildSymbolImportMap(source, fileName) {\n\tconst sourceFile = ts.createSourceFile(fileName, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n\tconst map = /* @__PURE__ */ new Map();\n\tfor (const statement of sourceFile.statements) {\n\t\tif (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) continue;\n\t\tconst specifier = statement.moduleSpecifier.text;\n\t\tconst clause = statement.importClause;\n\t\tif (!clause) continue;\n\t\tif (clause.name) map.set(clause.name.text, {\n\t\t\tspecifier,\n\t\t\texportName: \"default\"\n\t\t});\n\t\tif (clause.namedBindings && ts.isNamedImports(clause.namedBindings)) for (const element of clause.namedBindings.elements) {\n\t\t\tconst exportName = (element.propertyName ?? element.name).text;\n\t\t\tmap.set(element.name.text, {\n\t\t\t\tspecifier,\n\t\t\t\texportName\n\t\t\t});\n\t\t}\n\t}\n\treturn map;\n}\nfunction resolveRelativeModuleFile(projectRoot, workflowModuleFile, specifier) {\n\tif (!specifier.startsWith(\".\")) return;\n\tconst workflowDir = dirname(join(projectRoot, workflowModuleFile));\n\tconst candidates = [\n\t\tjoin(workflowDir, specifier),\n\t\t`${join(workflowDir, specifier)}.ts`,\n\t\tjoin(workflowDir, `${specifier}.ts`),\n\t\tjoin(workflowDir, specifier, \"index.ts\")\n\t];\n\tfor (const candidate of candidates) if (existsSync(candidate)) return toPosix$1(relative(projectRoot, candidate));\n}\nfunction toResolvedStepSlug(entry) {\n\treturn {\n\t\tslug: entry.slug,\n\t\tname: entry.name,\n\t\tdescription: entry.description\n\t};\n}\n/** Build a deploy-time slug resolver from a workflow file's imports + definition registry. */\nfunction createResolveSlugFn(projectRoot, workflowModuleFile, workflowSource, registryByModuleFile, integrationRegistry) {\n\tconst importMap = buildSymbolImportMap(workflowSource, workflowModuleFile);\n\treturn (importName) => {\n\t\tconst imported = importMap.get(importName);\n\t\tif (!imported) return;\n\t\tconst { specifier, exportName } = imported;\n\t\tif (specifier.startsWith(\".\")) {\n\t\t\tconst moduleFile = resolveRelativeModuleFile(projectRoot, workflowModuleFile, specifier);\n\t\t\tif (!moduleFile) return;\n\t\t\tconst entry = registryByModuleFile.get(moduleFile);\n\t\t\treturn entry ? toResolvedStepSlug(entry) : void 0;\n\t\t}\n\t\tconst entry = integrationRegistry?.get(`${specifier}#${exportName}`);\n\t\treturn entry ? toResolvedStepSlug(entry) : void 0;\n\t};\n}\nfunction buildSlugRegistry(entries) {\n\treturn new Map(entries.map((entry) => [entry.moduleFile, entry]));\n}\n//#endregion\n//#region src/actions/discover-integration-actions.ts\n/** The framework package — never treated as an integration action source. */\nconst FRAMEWORK_PACKAGE = \"@keystrokehq/keystroke\";\n/**\n* Map an integration import specifier to its app slug.\n*\n* `@keystrokehq/slackbot/actions` → `slackbot`, `@keystrokehq/github` → `github`.\n* Returns `undefined` for the framework package and any non-`@keystrokehq` scope.\n*/\nfunction integrationAppSlugFromSpecifier(specifier) {\n\tif (specifier === FRAMEWORK_PACKAGE || specifier.startsWith(`${FRAMEWORK_PACKAGE}/`)) return;\n\treturn /^@keystrokehq\\/([^/]+)(?:\\/.*)?$/.exec(specifier)?.[1];\n}\n/**\n* The integration action subpath convention (`@keystrokehq/<app>/actions`). We only\n* import these — the real authoring convention — to avoid loading whole packages.\n*/\nfunction isIntegrationActionsSpecifier(specifier) {\n\treturn /^@keystrokehq\\/[^/]+\\/actions$/.test(specifier) && specifier !== FRAMEWORK_PACKAGE;\n}\n/** Map each integration `/actions` specifier imported by a file to the exports it uses. */\nfunction collectIntegrationImports(source, fileName) {\n\tconst sourceFile = ts.createSourceFile(fileName, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);\n\tconst bySpecifier = /* @__PURE__ */ new Map();\n\tfor (const statement of sourceFile.statements) {\n\t\tif (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) continue;\n\t\tconst specifier = statement.moduleSpecifier.text;\n\t\tif (!isIntegrationActionsSpecifier(specifier)) continue;\n\t\tconst usage = bySpecifier.get(specifier) ?? {\n\t\t\tnames: /* @__PURE__ */ new Set(),\n\t\t\timportsAll: false\n\t\t};\n\t\tconst clause = statement.importClause;\n\t\tif (clause?.name) usage.names.add(\"default\");\n\t\tconst bindings = clause?.namedBindings;\n\t\tif (bindings) if (ts.isNamespaceImport(bindings)) usage.importsAll = true;\n\t\telse for (const element of bindings.elements) usage.names.add(element.propertyName?.text ?? element.name.text);\n\t\tbySpecifier.set(specifier, usage);\n\t}\n\treturn bySpecifier;\n}\n/**\n* Discover actions imported from integration packages (`@keystrokehq/<app>/actions`)\n* by the project's workflow/agent source files.\n*\n* Each `/actions` subpath is resolved from the project's `node_modules`, dynamically\n* imported, and its action exports enumerated. Best-effort: a missing or broken\n* integration package never fails the manifest build — it is logged and skipped.\n*/\nasync function discoverIntegrationActions(projectRoot, sourceFiles, options) {\n\tconst usageBySpecifier = /* @__PURE__ */ new Map();\n\tfor (const sourceFile of sourceFiles) {\n\t\tlet source;\n\t\ttry {\n\t\t\tsource = readFileSync(join(projectRoot, sourceFile), \"utf8\");\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const [specifier, usage] of collectIntegrationImports(source, sourceFile)) {\n\t\t\tconst existing = usageBySpecifier.get(specifier) ?? {\n\t\t\t\tnames: /* @__PURE__ */ new Set(),\n\t\t\t\timportsAll: false\n\t\t\t};\n\t\t\tfor (const name of usage.names) existing.names.add(name);\n\t\t\texisting.importsAll = existing.importsAll || usage.importsAll;\n\t\t\tusageBySpecifier.set(specifier, existing);\n\t\t}\n\t}\n\tconst entries = [];\n\tconst registry = /* @__PURE__ */ new Map();\n\tconst seenSlugs = new Set(options?.existingSlugs);\n\tconst require = createRequire(join(projectRoot, \"package.json\"));\n\tconst discovered = await Promise.all([...usageBySpecifier].map(async ([specifier, usage]) => {\n\t\tconst appSlug = integrationAppSlugFromSpecifier(specifier);\n\t\tif (!appSlug) return null;\n\t\ttry {\n\t\t\tconst resolvedPath = require.resolve(specifier);\n\t\t\tconst href = pathToFileURL(resolvedPath).href;\n\t\t\tconst mod = await runWithAppRoot(resolveAppRoot(resolvedPath), async () => await import(href));\n\t\t\tconst localEntries = [];\n\t\t\tconst localRegistry = [];\n\t\t\tfor (const [exportName, value] of Object.entries(mod)) {\n\t\t\t\tif (!isAction(value)) continue;\n\t\t\t\tif (!usage.importsAll && !usage.names.has(exportName)) continue;\n\t\t\t\tconst definition = value;\n\t\t\t\tlocalRegistry.push([`${specifier}#${exportName}`, {\n\t\t\t\t\tslug: definition.slug,\n\t\t\t\t\tname: definition.name,\n\t\t\t\t\tdescription: definition.description\n\t\t\t\t}]);\n\t\t\t\tlocalEntries.push(actionManifestEntry(definition, {\n\t\t\t\t\tmoduleFile: specifier,\n\t\t\t\t\tappSlug,\n\t\t\t\t\tinputSchema: schemaToJson(definition.input),\n\t\t\t\t\toutputSchema: schemaToJson(definition.output)\n\t\t\t\t}));\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tlocalEntries,\n\t\t\t\tlocalRegistry\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tconsole.warn(`[manifest] skipped integration actions for ${specifier}: ${message}`);\n\t\t\treturn null;\n\t\t}\n\t}));\n\tfor (const result of discovered) {\n\t\tif (!result) continue;\n\t\tfor (const [key, entry] of result.localRegistry) registry.set(key, entry);\n\t\tfor (const entry of result.localEntries) {\n\t\t\tif (seenSlugs.has(entry.slug)) continue;\n\t\t\tseenSlugs.add(entry.slug);\n\t\t\tentries.push(entry);\n\t\t}\n\t}\n\treturn {\n\t\tentries,\n\t\tregistry\n\t};\n}\n//#endregion\n//#region src/triggers/manifest-attachments.ts\nfunction triggerManifestAttachments(attachments) {\n\treturn attachments.map((attachment) => isWorkflowTriggerAttachment(attachment.attachment) ? {\n\t\tid: attachment.slug,\n\t\ttargetKind: \"workflow\",\n\t\ttargetSlug: attachment.attachment.workflow.slug\n\t} : {\n\t\tid: attachment.slug,\n\t\ttargetKind: \"agent\",\n\t\ttargetSlug: attachment.attachment.agent.slug\n\t});\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\tactionsDir: join(distBase, \"actions\"),\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* Run the deploy-time AST producer over a workflow's source file to attach its\n* control-flow skeleton + a content hash (for staleness). Best-effort: skips\n* when the resolved moduleFile is not a readable `.ts` source (e.g. dist-only\n* builds) or the source has no recognizable workflow, and never fails the build.\n*/\nfunction produceWorkflowFlowGraph(projectRoot, moduleFile, options) {\n\tif (!moduleFile.endsWith(\".ts\")) return;\n\tconst absolute = join(projectRoot, moduleFile);\n\tif (!existsSync(absolute)) return;\n\ttry {\n\t\tconst source = readFileSync(absolute, \"utf8\");\n\t\tconst flowGraph = buildWorkflowCanvasGraph(source, {\n\t\t\tfileName: moduleFile,\n\t\t\tresolveSlug: options?.slugRegistry ? createResolveSlugFn(projectRoot, moduleFile, source, options.slugRegistry, options.integrationRegistry) : void 0\n\t\t});\n\t\tif (!flowGraph) return;\n\t\treturn {\n\t\t\tflowGraph,\n\t\t\tflowGraphSourceHash: createHash(\"sha256\").update(source).digest(\"hex\"),\n\t\t\tflowGraphHash: createHash(\"sha256\").update(JSON.stringify(flowGraph)).digest(\"hex\")\n\t\t};\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tconsole.warn(`[manifest] skipped workflow flow graph for ${moduleFile}: ${message}`);\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 slugRegistryEntries = [];\n\t\tconst srcRoot = join(projectRoot, \"src\");\n\t\tconst integrationPromise = Promise.all([walkTypeScriptFiles(join(srcRoot, \"agents\")), walkTypeScriptFiles(join(srcRoot, \"workflows\"))]).then(([agentSources, workflowSources]) => discoverIntegrationActions(projectRoot, [...agentSources, ...workflowSources].map((file) => relative(projectRoot, file).split(sep).join(\"/\"))));\n\t\tconst [agentEntries, workflows, attachments] = await Promise.all([\n\t\t\tdiscoverAgentEntries(dirs.agentsDir),\n\t\t\tdiscoverWorkflows(dirs.workflowsDir, reload),\n\t\t\tdiscoverTriggerAttachments(dirs.triggersDir, reload)\n\t\t]);\n\t\tvalidateProjectModules({\n\t\t\tagents: agentEntries,\n\t\t\tworkflows,\n\t\t\tattachments\n\t\t});\n\t\tconst loadedAgents = await Promise.all(agentEntries.map(async (entry) => ({\n\t\t\tentry,\n\t\t\tagent: await importAgentDefinition(entry.filePath, reload)\n\t\t})));\n\t\tawait validateAgentModelIds(loadedAgents.flatMap(({ agent }) => agent.compactionModel ? [agent.model, agent.compactionModel] : [agent.model]));\n\t\tconst resolvedAgents = [];\n\t\tfor (const { entry, agent } of loadedAgents) {\n\t\t\tconst moduleFile = await sourcePaths.resolve(\"agents\", \"agent\", dirs.agentsDir, entry.filePath);\n\t\t\tresolvedAgents.push({\n\t\t\t\tagent,\n\t\t\t\tmoduleFile\n\t\t\t});\n\t\t\tslugRegistryEntries.push({\n\t\t\t\tslug: agent.slug,\n\t\t\t\tname: agent.name,\n\t\t\t\tdescription: agent.description,\n\t\t\t\tmoduleFile\n\t\t\t});\n\t\t}\n\t\tconst actions = await discoverActions(dirs.actionsDir, reload);\n\t\tconst resolvedActions = [];\n\t\tfor (const action of actions) {\n\t\t\tconst moduleFile = await sourcePaths.resolve(\"actions\", \"action\", dirs.actionsDir, action.filePath);\n\t\t\tresolvedActions.push({\n\t\t\t\taction,\n\t\t\t\tmoduleFile\n\t\t\t});\n\t\t\tslugRegistryEntries.push({\n\t\t\t\tslug: action.definition.slug,\n\t\t\t\tname: action.definition.name,\n\t\t\t\tdescription: action.definition.description,\n\t\t\t\tmoduleFile\n\t\t\t});\n\t\t}\n\t\tconst resolvedWorkflows = [];\n\t\tfor (const workflow of workflows) {\n\t\t\tconst moduleFile = await sourcePaths.resolve(\"workflows\", \"workflow\", dirs.workflowsDir, workflow.filePath);\n\t\t\tresolvedWorkflows.push({\n\t\t\t\tworkflow,\n\t\t\t\tmoduleFile\n\t\t\t});\n\t\t\tslugRegistryEntries.push({\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\tmoduleFile\n\t\t\t});\n\t\t}\n\t\tconst slugRegistry = buildSlugRegistry(slugRegistryEntries);\n\t\tconst integrationDiscovered = await integrationPromise;\n\t\tconst existingSlugs = new Set(slugRegistryEntries.map((entry) => entry.slug));\n\t\tconst integration = {\n\t\t\tregistry: integrationDiscovered.registry,\n\t\t\tentries: integrationDiscovered.entries.filter((entry) => !existingSlugs.has(entry.slug))\n\t\t};\n\t\tfor (const { agent, moduleFile } of resolvedAgents) manifest.push(agentManifestEntry(agent, { moduleFile }));\n\t\tfor (const { action, moduleFile } of resolvedActions) manifest.push(actionManifestEntry(action.definition, {\n\t\t\tmoduleFile,\n\t\t\tinputSchema: schemaToJson(action.definition.input),\n\t\t\toutputSchema: schemaToJson(action.definition.output)\n\t\t}));\n\t\tfor (const entry of integration.entries) manifest.push(entry);\n\t\tfor (const { workflow, moduleFile } of resolvedWorkflows) manifest.push({\n\t\t\tkind: \"workflow\",\n\t\t\tslug: workflow.definition.slug,\n\t\t\tname: workflow.definition.name,\n\t\t\tdescription: workflow.definition.description,\n\t\t\tsubscribable: workflow.definition.subscription?.mode === \"subscribable\",\n\t\t\tmoduleFile,\n\t\t\trequest: workflow.definition.input,\n\t\t\tresponse: workflow.definition.output,\n\t\t\t...produceWorkflowFlowGraph(projectRoot, moduleFile, {\n\t\t\t\tslugRegistry,\n\t\t\t\tintegrationRegistry: integration.registry\n\t\t\t})\n\t\t});\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: triggerManifestAttachments(group),\n\t\t\t\tmoduleFile,\n\t\t\t\t...sourceHash ? { sourceHash } : {},\n\t\t\t\tschedule: source.schedule,\n\t\t\t\t...source.timezone ? { timezone: source.timezone } : {},\n\t\t\t\t...source.payload !== void 0 ? { payload: source.payload } : {},\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: triggerManifestAttachments(group),\n\t\t\t\tmoduleFile,\n\t\t\t\t...sourceHash ? { sourceHash } : {},\n\t\t\t\tschedule: source.schedule,\n\t\t\t\t...source.timezone ? { timezone: source.timezone } : {},\n\t\t\t\t...meta,\n\t\t\t\tresponse: PromptResponseSchema\n\t\t\t});\n\t\t}\n\t\tconst webhooksByTrigger = /* @__PURE__ */ new Map();\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 triggerSlug = sourceSlugFrom(source);\n\t\t\tconst group = webhooksByTrigger.get(triggerSlug) ?? [];\n\t\t\tgroup.push(discovered);\n\t\t\twebhooksByTrigger.set(triggerSlug, group);\n\t\t}\n\t\tfor (const [, group] of webhooksByTrigger) {\n\t\t\tconst first = group[0];\n\t\t\tconst source = first.attachment.source;\n\t\t\tif (source.kind !== \"webhook\") continue;\n\t\t\tconst { moduleFile, sourceHash } = await sourcePaths.resolveSource(\"triggers\", \"trigger\", dirs.triggersDir, first.filePath);\n\t\t\tconst bindings = group.map((discovered) => ({\n\t\t\t\tdiscovered,\n\t\t\t\toptions: {\n\t\t\t\t\texecution: { attachmentSlug: discovered.slug },\n\t\t\t\t\tattachmentSlug: discovered.slug\n\t\t\t\t}\n\t\t\t}));\n\t\t\tconst attachmentMeta = Object.fromEntries(group.map((row) => {\n\t\t\t\tconst meta = triggerMetaFromAttachment(row.attachment);\n\t\t\t\treturn [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: triggerManifestAttachments(group),\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\tattachmentMeta,\n\t\t\t\tresponse: PromptResponseSchema\n\t\t\t});\n\t\t}\n\t\treturn parseStoredRouteManifest(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/** Emit modular `dist/.keystroke/manifest.json` + shards (no legacy flat write). */\nasync function emitStoredRouteManifestForProject(projectRoot) {\n\tif (isModularManifestEmitCacheHit(projectRoot)) return;\n\tpersistModularRouteManifest(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\t...entry.timezone ? { timezone: entry.timezone } : {}\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\t...entry.timezone ? { timezone: entry.timezone } : {}\n\t\t});\n\t}\n\treturn schedules;\n}\n//#endregion\n//#region src/load-route-manifest.ts\nfunction routeManifestPathForProjectRoot(projectRoot) {\n\tconst modular = join(projectRoot, PROJECT_MANIFEST_REL_PATH);\n\tif (existsSync(modular)) return modular;\n\treturn join(projectRoot, ROUTE_MANIFEST_REL_PATH);\n}\n/**\n* Load the project catalog as a flat v2 manifest.\n* Prefers modular `manifest.json` (+ shards); falls back to legacy flat file.\n*/\nfunction readRouteManifest(projectRoot) {\n\tif (tryReadProjectManifest(projectRoot)) return composeStoredRouteManifestFromModular(projectRoot);\n\tconst legacyPath = join(projectRoot, ROUTE_MANIFEST_REL_PATH);\n\tif (!existsSync(legacyPath)) throw new Error(`${PROJECT_MANIFEST_REL_PATH} (or legacy ${ROUTE_MANIFEST_REL_PATH}) not found — run keystroke build to emit the manifest`);\n\tconst raw = readFileSync(legacyPath, \"utf8\");\n\treturn parseStoredRouteManifest(JSON.parse(raw));\n}\n//#endregion\n//#region src/persist.ts\n/** @deprecated Prefer `persistModularRouteManifest` — kept as an alias for call sites. */\nfunction persistStoredRouteManifest(projectRoot, manifest) {\n\tpersistModularRouteManifest(projectRoot, manifest);\n}\n//#endregion\n//#region src/modular/compose-from-map.ts\nfunction readRequired(readJson, path) {\n\tconst value = readJson(path);\n\tif (value === void 0) throw new Error(`Missing manifest shard: ${path}`);\n\treturn value;\n}\n/**\n* Compose a flat v2 `StoredRouteManifest` from modular shards via a sync reader.\n* When `includeFlowGraphs` is false, workflow entries omit flowGraph fields (registry/promote).\n* When `onlyWorkflowFlowSlug` is set, only that workflow gets its flow shard merged.\n*/\nfunction composeStoredRouteManifestFromShardReader(index, readJson, options) {\n\tconst includeFlowGraphs = options?.includeFlowGraphs ?? true;\n\tconst onlySlug = options?.onlyWorkflowFlowSlug;\n\tconst entries = [{ kind: \"health\" }];\n\tfor (const ref of index.modules) {\n\t\tif (ref.kind === \"agent\") {\n\t\t\tentries.push(AgentManifestShardSchema.parse(readRequired(readJson, ref.path)));\n\t\t\tcontinue;\n\t\t}\n\t\tif (ref.kind === \"workflow\") {\n\t\t\tconst meta = WorkflowManifestMetaShardSchema.parse(readRequired(readJson, ref.path));\n\t\t\tif (includeFlowGraphs && Boolean(ref.flowPath) && (onlySlug === void 0 || onlySlug === ref.id) && ref.flowPath) {\n\t\t\t\tconst flow = WorkflowManifestFlowShardSchema.parse(readRequired(readJson, ref.flowPath));\n\t\t\t\tentries.push({\n\t\t\t\t\t...meta,\n\t\t\t\t\t...flow\n\t\t\t\t});\n\t\t\t} else entries.push(meta);\n\t\t\tcontinue;\n\t\t}\n\t\tconst triggerShard = TriggerManifestShardSchema.parse(readRequired(readJson, ref.path));\n\t\tentries.push(...triggerShard.entries);\n\t}\n\tconst catalog = ActionsCatalogShardSchema.parse(readRequired(readJson, index.actionsCatalogPath));\n\tentries.push(...catalog.entries);\n\treturn {\n\t\tversion: 2,\n\t\tentries,\n\t\tskills: index.skills,\n\t\t...index.integrations ? { integrations: index.integrations } : {}\n\t};\n}\n/** Registry / promote view — meta shards only (no flowGraphs). */\nfunction composeRegistryManifestFromShardReader(index, readJson) {\n\treturn composeStoredRouteManifestFromShardReader(index, readJson, { includeFlowGraphs: false });\n}\n/**\n* Canvas / overview bundle: one workflow with flowGraph + companion meta entries\n* (actions, agents, other workflow metas without their flows).\n*/\nfunction workflowCanvasBundleFromShardReader(index, slug, readJson) {\n\tconst ref = index.modules.find((module) => module.kind === \"workflow\" && module.id === slug);\n\tif (!ref) throw new Error(`Workflow \"${slug}\" not found in project manifest`);\n\tconst meta = WorkflowManifestMetaShardSchema.parse(readRequired(readJson, ref.path));\n\tif (!ref.flowPath) throw new Error(`Workflow \"${slug}\" has no flow shard`);\n\tconst flow = WorkflowManifestFlowShardSchema.parse(readRequired(readJson, ref.flowPath));\n\tconst workflow = {\n\t\t...meta,\n\t\t...flow\n\t};\n\tconst companions = [];\n\tfor (const module of index.modules) {\n\t\tif (module.kind === \"agent\") {\n\t\t\tcompanions.push(AgentManifestShardSchema.parse(readRequired(readJson, module.path)));\n\t\t\tcontinue;\n\t\t}\n\t\tif (module.kind === \"workflow\" && module.id !== slug) companions.push(WorkflowManifestMetaShardSchema.parse(readRequired(readJson, module.path)));\n\t}\n\tconst catalog = ActionsCatalogShardSchema.parse(readRequired(readJson, index.actionsCatalogPath));\n\tcompanions.push(...catalog.entries);\n\treturn {\n\t\tworkflow,\n\t\tcompanions\n\t};\n}\n/** Workflow meta shard only (requestSchema / forms) — no flowGraph. */\nfunction workflowMetaFromShardReader(index, slug, readJson) {\n\tconst ref = index.modules.find((module) => module.kind === \"workflow\" && module.id === slug);\n\tif (!ref) throw new Error(`Workflow \"${slug}\" not found in project manifest`);\n\treturn WorkflowManifestMetaShardSchema.parse(readRequired(readJson, ref.path));\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\nexport { STORED_JSON_SCHEMA_TARGET, actionsCatalogFingerprint, agentKeyForAttachment, agentManifestEntry, agentRouteFromKey, attachmentSlugFromRecord, buildPollGroups, buildStoredRouteManifestForProject, buildStoredRouteManifestFromContext, buildWebhookBindingsByRoute, collectAgentAppSlugs, collectAgentToolSlugs, composeRegistryManifestFromShardReader, composeStoredRouteManifestFromKeystrokeDir, composeStoredRouteManifestFromModular, composeStoredRouteManifestFromShardReader, contentHashForModule, countAgentCredentials, discoverAgentEntries, discoverEntries, discoverModuleFileEntries, discoverSkillManifestEntries, discoverTriggerAttachments, discoverWorkflowEntries, discoverWorkflows, emitStoredRouteManifestForProject, entryIdFromFile, findWebhookManifestEntryByEndpoint, findWebhookManifestEntryByPath, findWorkflowManifestEntry, hashDirectoryContents, importAgentDefinition, importTriggerAttachment, importTriggerAttachments, importWorkflowDefinition, integrationPackagesFingerprint, isModularManifestEmitCacheHit, jsonSchemaToZod, matchesPollRunTarget, moduleFileKeyFromPath, persistModularRouteManifest, persistStoredRouteManifest, pollGroupId, pollGroupRouteFromId, pollRouteFromKey, pollRouteFromSourceSlug, projectActionsFingerprint, readRouteManifest, routeManifestPathForProjectRoot, schedulesFromManifest, schemaToJson, serializeRouteManifest, sha256Bytes, sha256File, splitStoredRouteManifest, toStoredRouteManifest, triggerManifestAttachments, tryReadProjectManifest, validateAttachmentTargets, validateAttachmentWorkflowKeys, validateImportedTriggerAttachment, validateImportedWorkflowDefinition, validatePollGroups, validateProjectModules, validateTriggerAttachments, validateUniqueAttachmentKeys, validateUniqueAttachmentSlugs, validateUniqueModuleKeys, validateUniqueTriggerKeys, validateUniqueTriggerSourceSlugs, walkTypeScriptFiles, webhookAttachmentSchemasFromBindings, webhookManifestAttachmentSchemasFromBindings, webhookMatchSchemaForBindings, webhookRouteFromEndpoint, workflowCanvasBundleFromShardReader, workflowKeyForAttachment, workflowMetaFromShardReader, workflowRouteFromKey, zodToStoredJsonSchema };\n\n//# sourceMappingURL=index.mjs.map"],"x_google_ignoreList":[1,2,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,34,35,36,37,38,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,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299,300,301,302,303,304,305,306,307,308,309,310,311,312,313,314,315,316,317,318,319,320,321,322,323,324,325,326,327],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,MAAMA,YAAU,IAAI,kBAAkB;AACtC,SAAS,sBAAsB;CAC9B,OAAOA,UAAQ,SAAS;AACzB;;;;;AAqBA,SAAS,gBAAgB,OAAO;CAC/B,IAAI,CAAC,SAAS,OAAO,UAAU,UAAU,OAAO;CAChD,MAAM,SAAS,WAAW,KAAK;CAC/B,IAAI,WAAW,KAAK,MAAM,WAAW,KAAK,UAAU,OAAO,SAAS,MAAM,OAAO;CACjF,IAAI,UAAU,SAAS,OAAO,MAAM,SAAS;MACxC,MAAM,SAAS,gBAAgB,MAAM,SAAS,mBAAmB,MAAM,SAAS,oBAAoB,MAAM,SAAS,mBAAmB,OAAO;CAAA;CAElJ,OAAO;AACR;AACA,SAAS,WAA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AAS,YAAY,OAAO,OAAO,WAAW;AACpE;;;AChBA,MAAM,yBAAyB;AACJC,QAAU,UAAU,OAAO,UAAU,YAAY,uBAAuB,KAAK,KAAK,GAAG,+BAA+B;;;ACC/I,MAAM,mBAAmB,IAAI,IAAI;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAC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