@keystrokehq/keystroke 1.0.13 → 1.0.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/action.cjs +1 -1
- package/dist/action.mjs +1 -1
- package/dist/agent.cjs +119 -12
- package/dist/agent.cjs.map +1 -1
- package/dist/agent.d.cts +1 -1
- package/dist/agent.d.mts +1 -1
- package/dist/agent.mjs +119 -12
- package/dist/agent.mjs.map +1 -1
- package/dist/app.cjs +1 -1
- package/dist/app.mjs +1 -1
- package/dist/client.cjs +1 -1
- package/dist/client.mjs +1 -1
- package/dist/config.d.cts +2 -2
- package/dist/config.d.cts.map +1 -1
- package/dist/config.d.mts +2 -2
- package/dist/config.d.mts.map +1 -1
- package/dist/credentials.cjs +1 -1
- package/dist/credentials.mjs +1 -1
- package/dist/{dist-DtejauR-.mjs → dist-BWGuF7Bi.mjs} +22 -9
- package/dist/dist-BWGuF7Bi.mjs.map +1 -0
- package/dist/{dist-C5UmW-zB.cjs → dist-CDMCEgV0.cjs} +22 -9
- package/dist/dist-CDMCEgV0.cjs.map +1 -0
- package/dist/{dist-DpZL1LE1.cjs → dist-CIXPxH8Y.cjs} +7 -3
- package/dist/dist-CIXPxH8Y.cjs.map +1 -0
- package/dist/{dist-DSbrc1sP.mjs → dist-DESn8Gyx.mjs} +3 -3
- package/dist/{dist-DSbrc1sP.mjs.map → dist-DESn8Gyx.mjs.map} +1 -1
- package/dist/{dist-Zh8nB_45.cjs → dist-jju5p8QW.cjs} +3 -3
- package/dist/{dist-Zh8nB_45.cjs.map → dist-jju5p8QW.cjs.map} +1 -1
- package/dist/{dist-D53HZMV9.mjs → dist-qrlBz5eZ.mjs} +7 -3
- package/dist/dist-qrlBz5eZ.mjs.map +1 -0
- package/dist/{index-Ohwnfidc.d.cts → index-BQEzTb7P.d.cts} +3 -3
- package/dist/index-BQEzTb7P.d.cts.map +1 -0
- package/dist/index-BTz2OMAM.d.cts.map +1 -1
- package/dist/index-Cq2F2XdS.d.mts.map +1 -1
- package/dist/index-WT4ULMiw.d.cts.map +1 -1
- package/dist/index-WT4ULMiw.d.mts.map +1 -1
- package/dist/{index-DdAOmbQc.d.mts → index-ub0OqZXh.d.mts} +3 -3
- package/dist/index-ub0OqZXh.d.mts.map +1 -0
- package/dist/{mistral-tahkZ8Hu.mjs → mistral-B3AiRi15.mjs} +2 -2
- package/dist/{mistral-tahkZ8Hu.mjs.map → mistral-B3AiRi15.mjs.map} +1 -1
- package/dist/{mistral-6XMKgah3.cjs → mistral-HS6Ekkp2.cjs} +2 -2
- package/dist/{mistral-6XMKgah3.cjs.map → mistral-HS6Ekkp2.cjs.map} +1 -1
- package/dist/{sse-CSbz_aIR.mjs → sse-DISKrIFa.mjs} +2 -2
- package/dist/{sse-CSbz_aIR.mjs.map → sse-DISKrIFa.mjs.map} +1 -1
- package/dist/{sse-PotOG2Pc.cjs → sse-ELfo0nZE.cjs} +2 -2
- package/dist/{sse-PotOG2Pc.cjs.map → sse-ELfo0nZE.cjs.map} +1 -1
- package/dist/trigger.cjs +135 -35
- package/dist/trigger.cjs.map +1 -1
- package/dist/trigger.d.cts +88 -21
- package/dist/trigger.d.cts.map +1 -1
- package/dist/trigger.d.mts +88 -21
- package/dist/trigger.d.mts.map +1 -1
- package/dist/trigger.mjs +122 -36
- package/dist/trigger.mjs.map +1 -1
- package/dist/workflow.cjs +1 -1
- package/dist/workflow.mjs +1 -1
- package/package.json +3 -3
- package/dist/dist-C5UmW-zB.cjs.map +0 -1
- package/dist/dist-D53HZMV9.mjs.map +0 -1
- package/dist/dist-DpZL1LE1.cjs.map +0 -1
- package/dist/dist-DtejauR-.mjs.map +0 -1
- package/dist/index-DdAOmbQc.d.mts.map +0 -1
- package/dist/index-Ohwnfidc.d.cts.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"dist-D53HZMV9.mjs","names":["ForeignKeyBuilder","ForeignKey","uniqueKeyName","ForeignKeyBuilder","uniqueKeyName","customType","integer","numeric","real","text","InlineForeignKeys","IndexBuilderOn","IndexBuilder","Index","index","uniqueIndex","primaryKey","PrimaryKeyBuilder","PrimaryKey","handle","getDatabaseHandle","getDbFromContext","buildPgSchema","buildSqliteSchema","text","integer","uniqueIndex","text$1","integer$1","uniqueIndex$1","index","index$1","tableRegistry","schema","getDb","eq$1","scopedAnd","and$1","max$1","ALGORITHM","IV_LENGTH","resolveEncryptionKey","schema","v3Schema","v4Schema","z","Ajv","crypto","z","fs","fs","path","path","process","createToolDescription","text","text$1","integer$1","index","index$1","integer","text","integer","index","text$1","integer$1","index$1","uniqueIndex","uniqueIndex$1","primaryKey","primaryKey$1","eq$1","and$1","decryptCredentialPayload$1","encryptCredentialPayload$1","selectCredentialInstanceById$2","selectCredentialInstancesForScope$2"],"sources":["../../../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/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/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/sql/expressions/conditions.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/expressions/select.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/functions/aggregate.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","../../tracing/dist/index.mjs","../../database/dist/index.mjs","../../../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/types.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/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/Options.js","../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/Refs.js","../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/errorMessages.js","../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/getRelativePath.js","../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/parsers/any.js","../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/parsers/array.js","../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js","../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js","../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/parsers/branded.js","../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/parsers/catch.js","../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/parsers/date.js","../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/parsers/default.js","../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/parsers/effects.js","../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/parsers/enum.js","../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js","../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/parsers/literal.js","../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/parsers/string.js","../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/parsers/record.js","../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/parsers/map.js","../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js","../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/parsers/never.js","../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/parsers/null.js","../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/parsers/union.js","../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js","../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/parsers/number.js","../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/parsers/object.js","../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/parsers/optional.js","../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js","../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/parsers/promise.js","../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/parsers/set.js","../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js","../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js","../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js","../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js","../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/selectParser.js","../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/parseDef.js","../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.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/pkce-challenge@5.0.1/node_modules/pkce-challenge/dist/index.node.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/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/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/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js","../../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/windows.js","../../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/mode.js","../../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js","../../../node_modules/.pnpm/which@2.0.2/node_modules/which/which.js","../../../node_modules/.pnpm/path-key@3.1.1/node_modules/path-key/index.js","../../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js","../../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/escape.js","../../../node_modules/.pnpm/shebang-regex@3.0.0/node_modules/shebang-regex/index.js","../../../node_modules/.pnpm/shebang-command@2.0.0/node_modules/shebang-command/index.js","../../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js","../../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js","../../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/enoent.js","../../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/index.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js","../../mcp/dist/index.mjs","../../platform-database/dist/auth-verifications-D-no86bc.mjs","../../platform-database/dist/index.mjs","../../credentials/dist/store-BokhwcCi.mjs","../../secrets/dist/index.mjs","../../credentials/dist/index.mjs"],"sourcesContent":["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 { 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\";\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 { Column } from \"../../column.js\";\nimport { is } from \"../../entity.js\";\nimport { Table } from \"../../table.js\";\nimport {\n isDriverValueEncoder,\n isSQLWrapper,\n Param,\n Placeholder,\n SQL,\n sql,\n StringChunk,\n View\n} from \"../sql.js\";\nfunction bindIfParam(value, column) {\n if (isDriverValueEncoder(column) && !isSQLWrapper(value) && !is(value, Param) && !is(value, Placeholder) && !is(value, Column) && !is(value, Table) && !is(value, View)) {\n return new Param(value, column);\n }\n return value;\n}\nconst eq = (left, right) => {\n return sql`${left} = ${bindIfParam(right, left)}`;\n};\nconst ne = (left, right) => {\n return sql`${left} <> ${bindIfParam(right, left)}`;\n};\nfunction and(...unfilteredConditions) {\n const conditions = unfilteredConditions.filter(\n (c) => c !== void 0\n );\n if (conditions.length === 0) {\n return void 0;\n }\n if (conditions.length === 1) {\n return new SQL(conditions);\n }\n return new SQL([\n new StringChunk(\"(\"),\n sql.join(conditions, new StringChunk(\" and \")),\n new StringChunk(\")\")\n ]);\n}\nfunction or(...unfilteredConditions) {\n const conditions = unfilteredConditions.filter(\n (c) => c !== void 0\n );\n if (conditions.length === 0) {\n return void 0;\n }\n if (conditions.length === 1) {\n return new SQL(conditions);\n }\n return new SQL([\n new StringChunk(\"(\"),\n sql.join(conditions, new StringChunk(\" or \")),\n new StringChunk(\")\")\n ]);\n}\nfunction not(condition) {\n return sql`not ${condition}`;\n}\nconst gt = (left, right) => {\n return sql`${left} > ${bindIfParam(right, left)}`;\n};\nconst gte = (left, right) => {\n return sql`${left} >= ${bindIfParam(right, left)}`;\n};\nconst lt = (left, right) => {\n return sql`${left} < ${bindIfParam(right, left)}`;\n};\nconst lte = (left, right) => {\n return sql`${left} <= ${bindIfParam(right, left)}`;\n};\nfunction inArray(column, values) {\n if (Array.isArray(values)) {\n if (values.length === 0) {\n return sql`false`;\n }\n return sql`${column} in ${values.map((v) => bindIfParam(v, column))}`;\n }\n return sql`${column} in ${bindIfParam(values, column)}`;\n}\nfunction notInArray(column, values) {\n if (Array.isArray(values)) {\n if (values.length === 0) {\n return sql`true`;\n }\n return sql`${column} not in ${values.map((v) => bindIfParam(v, column))}`;\n }\n return sql`${column} not in ${bindIfParam(values, column)}`;\n}\nfunction isNull(value) {\n return sql`${value} is null`;\n}\nfunction isNotNull(value) {\n return sql`${value} is not null`;\n}\nfunction exists(subquery) {\n return sql`exists ${subquery}`;\n}\nfunction notExists(subquery) {\n return sql`not exists ${subquery}`;\n}\nfunction between(column, min, max) {\n return sql`${column} between ${bindIfParam(min, column)} and ${bindIfParam(\n max,\n column\n )}`;\n}\nfunction notBetween(column, min, max) {\n return sql`${column} not between ${bindIfParam(\n min,\n column\n )} and ${bindIfParam(max, column)}`;\n}\nfunction like(column, value) {\n return sql`${column} like ${value}`;\n}\nfunction notLike(column, value) {\n return sql`${column} not like ${value}`;\n}\nfunction ilike(column, value) {\n return sql`${column} ilike ${value}`;\n}\nfunction notIlike(column, value) {\n return sql`${column} not ilike ${value}`;\n}\nfunction arrayContains(column, values) {\n if (Array.isArray(values)) {\n if (values.length === 0) {\n throw new Error(\"arrayContains requires at least one value\");\n }\n const array = sql`${bindIfParam(values, column)}`;\n return sql`${column} @> ${array}`;\n }\n return sql`${column} @> ${bindIfParam(values, column)}`;\n}\nfunction arrayContained(column, values) {\n if (Array.isArray(values)) {\n if (values.length === 0) {\n throw new Error(\"arrayContained requires at least one value\");\n }\n const array = sql`${bindIfParam(values, column)}`;\n return sql`${column} <@ ${array}`;\n }\n return sql`${column} <@ ${bindIfParam(values, column)}`;\n}\nfunction arrayOverlaps(column, values) {\n if (Array.isArray(values)) {\n if (values.length === 0) {\n throw new Error(\"arrayOverlaps requires at least one value\");\n }\n const array = sql`${bindIfParam(values, column)}`;\n return sql`${column} && ${array}`;\n }\n return sql`${column} && ${bindIfParam(values, column)}`;\n}\nexport {\n and,\n arrayContained,\n arrayContains,\n arrayOverlaps,\n between,\n bindIfParam,\n eq,\n exists,\n gt,\n gte,\n ilike,\n inArray,\n isNotNull,\n isNull,\n like,\n lt,\n lte,\n ne,\n not,\n notBetween,\n notExists,\n notIlike,\n notInArray,\n notLike,\n or\n};\n//# sourceMappingURL=conditions.js.map","import { sql } from \"../sql.js\";\nfunction asc(column) {\n return sql`${column} asc`;\n}\nfunction desc(column) {\n return sql`${column} desc`;\n}\nexport {\n asc,\n desc\n};\n//# sourceMappingURL=select.js.map","import { Column } from \"../../column.js\";\nimport { is } from \"../../entity.js\";\nimport { sql } from \"../sql.js\";\nfunction count(expression) {\n return sql`count(${expression || sql.raw(\"*\")})`.mapWith(Number);\n}\nfunction countDistinct(expression) {\n return sql`count(distinct ${expression})`.mapWith(Number);\n}\nfunction avg(expression) {\n return sql`avg(${expression})`.mapWith(String);\n}\nfunction avgDistinct(expression) {\n return sql`avg(distinct ${expression})`.mapWith(String);\n}\nfunction sum(expression) {\n return sql`sum(${expression})`.mapWith(String);\n}\nfunction sumDistinct(expression) {\n return sql`sum(distinct ${expression})`.mapWith(String);\n}\nfunction max(expression) {\n return sql`max(${expression})`.mapWith(is(expression, Column) ? expression : String);\n}\nfunction min(expression) {\n return sql`min(${expression})`.mapWith(is(expression, Column) ? expression : String);\n}\nexport {\n avg,\n avgDistinct,\n count,\n countDistinct,\n max,\n min,\n sum,\n sumDistinct\n};\n//# sourceMappingURL=aggregate.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 { AsyncLocalStorage } from \"node:async_hooks\";\n//#region src/config.ts\nlet sink;\nfunction configureTracing(options) {\n\tsink = options.sink;\n}\nfunction getTracingSink() {\n\treturn sink;\n}\nfunction resetTracingForTests() {\n\tsink = void 0;\n}\n//#endregion\n//#region src/context.ts\nconst traceContextStorage = new AsyncLocalStorage();\nfunction getTraceContext() {\n\treturn traceContextStorage.getStore();\n}\nfunction runWithTraceContext(context, fn) {\n\treturn traceContextStorage.run(context, fn);\n}\n//#endregion\n//#region src/serialize.ts\nfunction formatConsoleArg(value) {\n\tif (typeof value === \"string\") return value;\n\tif (value instanceof Error) return value.stack ?? value.message;\n\ttry {\n\t\treturn JSON.stringify(value);\n\t} catch {\n\t\treturn String(value);\n\t}\n}\nfunction serializeConsoleArgs(args) {\n\tif (args.length === 0) return { message: \"\" };\n\tconst [first, ...rest] = args;\n\tconst message = formatConsoleArg(first);\n\tif (rest.length === 0) return { message };\n\tif (rest.length === 1) return {\n\t\tmessage,\n\t\tdata: rest[0]\n\t};\n\treturn {\n\t\tmessage,\n\t\tdata: rest\n\t};\n}\nfunction summarizePayload(payload) {\n\tif (payload === void 0) return;\n\ttry {\n\t\tconst serialized = JSON.stringify(payload);\n\t\tif (serialized.length <= 500) return payload;\n\t\treturn {\n\t\t\ttruncated: true,\n\t\t\tlength: serialized.length,\n\t\t\tpreview: serialized.slice(0, 500)\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\ttruncated: true,\n\t\t\tpreview: String(payload).slice(0, 500)\n\t\t};\n\t}\n}\n//#endregion\n//#region src/console.ts\nconst CONSOLE_LEVELS = [\n\t\"log\",\n\t\"debug\",\n\t\"info\",\n\t\"warn\",\n\t\"error\"\n];\nfunction mapConsoleLevel(level) {\n\tif (level === \"log\") return \"info\";\n\treturn level;\n}\nasync function captureConsole(fn) {\n\tconst originals = /* @__PURE__ */ new Map();\n\tfor (const level of CONSOLE_LEVELS) {\n\t\toriginals.set(level, console[level].bind(console));\n\t\tconsole[level] = (...args) => {\n\t\t\toriginals.get(level)?.(...args);\n\t\t\tconst sink = getTracingSink();\n\t\t\tconst context = getTraceContext();\n\t\t\tif (!sink || !context) return;\n\t\t\tconst { message, data } = serializeConsoleArgs(args);\n\t\t\tsink.appendLog({\n\t\t\t\ttraceId: context.traceId,\n\t\t\t\tspanId: context.spanId,\n\t\t\t\tlevel: mapConsoleLevel(level),\n\t\t\t\tmessage,\n\t\t\t\tdata,\n\t\t\t\tsource: \"console\",\n\t\t\t\tcreatedAt: /* @__PURE__ */ new Date()\n\t\t\t});\n\t\t};\n\t}\n\ttry {\n\t\treturn await fn();\n\t} finally {\n\t\tfor (const level of CONSOLE_LEVELS) {\n\t\t\tconst original = originals.get(level);\n\t\t\tif (original) console[level] = original;\n\t\t}\n\t}\n}\n//#endregion\n//#region src/log.ts\nasync function logSystem(level, message, data) {\n\tconst sink = getTracingSink();\n\tconst context = getTraceContext();\n\tif (!sink || !context) return;\n\tawait sink.appendLog({\n\t\ttraceId: context.traceId,\n\t\tspanId: context.spanId,\n\t\tlevel,\n\t\tmessage,\n\t\tdata,\n\t\tsource: \"system\",\n\t\tcreatedAt: /* @__PURE__ */ new Date()\n\t});\n}\n//#endregion\n//#region src/span.ts\nfunction serializeSpanError(error) {\n\tif (error instanceof Error) return {\n\t\tname: error.name,\n\t\tmessage: error.message\n\t};\n\treturn { message: String(error) };\n}\nasync function withSpan(input, fn) {\n\tconst sink = getTracingSink();\n\tif (!sink) return await fn();\n\tconst parent = getTraceContext();\n\tconst spanId = input.spanId ?? crypto.randomUUID();\n\tconst traceId = input.traceId ?? parent?.traceId ?? spanId;\n\tconst parentSpanId = input.parentSpanId ?? parent?.spanId;\n\tconst startedAt = /* @__PURE__ */ new Date();\n\tawait sink.openSpan({\n\t\tid: spanId,\n\t\ttraceId,\n\t\tparentSpanId,\n\t\tkind: input.kind,\n\t\trefId: input.refId,\n\t\tname: input.name,\n\t\tmetadata: input.metadata,\n\t\tstartedAt\n\t});\n\tconst context = {\n\t\ttraceId,\n\t\tspanId,\n\t\tparentSpanId\n\t};\n\ttry {\n\t\tconst result = await runWithTraceContext(context, () => fn());\n\t\tawait sink.closeSpan(spanId, \"ok\", /* @__PURE__ */ new Date());\n\t\treturn result;\n\t} catch (error) {\n\t\tawait sink.closeSpan(spanId, \"error\", /* @__PURE__ */ new Date(), serializeSpanError(error));\n\t\tthrow error;\n\t}\n}\nfunction isSpanActive() {\n\treturn getTraceContext() !== void 0;\n}\n//#endregion\nexport { captureConsole, configureTracing, getTraceContext, isSpanActive, logSystem, resetTracingForTests, runWithTraceContext, summarizePayload, withSpan };\n\n//# sourceMappingURL=index.mjs.map","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport pg, { Pool } from \"pg\";\nimport { drizzle } from \"drizzle-orm/node-postgres\";\nimport { doublePrecision, index, integer, jsonb, pgTable, text, timestamp, uniqueIndex } from \"drizzle-orm/pg-core\";\nimport { index as index$1, integer as integer$1, real, sqliteTable, text as text$1, uniqueIndex as uniqueIndex$1 } from \"drizzle-orm/sqlite-core\";\nimport { and, and as and$1, asc, count, desc, eq, eq as eq$1, gt, inArray, inArray as inArray$1, isNotNull, isNull, lt, lte, max, max as max$1, ne, notInArray, or, sql, sql as sql$1 } from \"drizzle-orm\";\nimport { existsSync, mkdirSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport SqliteClient from \"better-sqlite3\";\nimport { drizzle as drizzle$1 } from \"drizzle-orm/better-sqlite3\";\nimport { readMigrationFiles } from \"drizzle-orm/migrator\";\nimport { fileURLToPath } from \"node:url\";\nimport { migrate } from \"drizzle-orm/better-sqlite3/migrator\";\nimport { getTraceContext } from \"@keystrokehq/tracing\";\nimport { createCipheriv, createDecipheriv, createHash, randomBytes } from \"node:crypto\";\nimport { buildCredentialInstanceLabel, deriveCredentialInstanceSlug, displayCredentialAppName, resolveUniqueCredentialInstanceLabel } from \"@keystrokehq/shared\";\n//#region \\0rolldown/runtime.js\nvar __defProp = Object.defineProperty;\nvar __exportAll = (all, no_symbols) => {\n\tlet target = {};\n\tfor (var name in all) __defProp(target, name, {\n\t\tget: all[name],\n\t\tenumerable: true\n\t});\n\tif (!no_symbols) __defProp(target, Symbol.toStringTag, { value: \"Module\" });\n\treturn target;\n};\n//#endregion\n//#region src/config/constants.ts\n/** Used when `DATABASE_URL` is unset and `initDatabase({ url })` is omitted. */\nconst DEFAULT_DATABASE_URL = \"file:./data/dev.db\";\nconst tenantScopeStorage = new AsyncLocalStorage();\nfunction runWithTenantScope(tenantId, fn) {\n\treturn tenantScopeStorage.run(tenantId, fn);\n}\nfunction getServerTenantScopeId() {\n\treturn tenantScopeStorage.getStore() ?? process.env.TENANT_ID?.trim() ?? \"default\";\n}\n//#endregion\n//#region src/config/project-scope.ts\n/** Default project id for local single-project dev. */\nconst DEFAULT_PROJECT_ID = \"default\";\nconst projectScopeStorage = new AsyncLocalStorage();\nfunction runWithProjectScope(projectId, fn) {\n\treturn projectScopeStorage.run(projectId, fn);\n}\nfunction getBoundProjectScopeId() {\n\treturn projectScopeStorage.getStore();\n}\nfunction getProjectScopeId() {\n\treturn getBoundProjectScopeId() ?? \"default\";\n}\n//#endregion\n//#region src/config/postgres-url.ts\nconst POSTGRES_ENV_KEYS = [\n\t\"POSTGRES_HOST\",\n\t\"POSTGRES_PORT\",\n\t\"POSTGRES_DB\",\n\t\"POSTGRES_USER\",\n\t\"POSTGRES_PASSWORD\"\n];\nfunction readEnv(env, key) {\n\treturn env[key]?.trim() || void 0;\n}\nfunction readPostgresSsl(env) {\n\tconst value = readEnv(env, \"POSTGRES_SSL\")?.toLowerCase();\n\treturn value === \"true\" || value === \"1\" || value === \"yes\";\n}\nfunction readPostgresSslFromUrl(url) {\n\ttry {\n\t\tconst sslmode = new URL(url.replace(/^postgresql:/i, \"postgres:\")).searchParams.get(\"sslmode\")?.toLowerCase();\n\t\treturn sslmode === \"require\" || sslmode === \"verify-ca\" || sslmode === \"verify-full\";\n\t} catch {\n\t\treturn false;\n\t}\n}\nfunction resolvePostgresSsl(env, url) {\n\treturn readPostgresSsl(env) || (url ? readPostgresSslFromUrl(url) : false);\n}\nfunction resolvePostgresBranch(env) {\n\tconst explicit = env.POSTGRES_BRANCH?.trim();\n\tif (explicit) return explicit;\n\tconst platformUser = readEnv(env, \"POSTGRES_USER\") ?? readPostgresUserFromDatabaseUrl(readEnv(env, \"DATABASE_URL\"));\n\tif (!platformUser?.includes(\".\")) return;\n\treturn platformUser.slice(platformUser.lastIndexOf(\".\") + 1) || void 0;\n}\nfunction readPostgresUserFromDatabaseUrl(url) {\n\tif (!url || !/^postgres(ql)?:\\/\\//i.test(url)) return;\n\ttry {\n\t\tconst parsed = new URL(url.replace(/^postgresql:/i, \"postgres:\"));\n\t\treturn decodeURIComponent(parsed.username);\n\t} catch {\n\t\treturn;\n\t}\n}\nfunction applyPostgresSslMode(url) {\n\tconst parsed = new URL(url.replace(/^postgresql:/i, \"postgres:\"));\n\tif (!parsed.searchParams.has(\"sslmode\")) parsed.searchParams.set(\"sslmode\", \"require\");\n\treturn parsed.toString().replace(/^postgres:/i, \"postgresql:\");\n}\nfunction missingPostgresEnvKeys(env) {\n\treturn POSTGRES_ENV_KEYS.filter((key) => readEnv(env, key) === void 0);\n}\n/** Append POSTGRES_BRANCH to bare role names for providers that use user.branch connections. */\nfunction qualifyConnectionUser(user, env = process.env) {\n\tif (user.includes(\".\")) return user;\n\tconst branch = resolvePostgresBranch(env);\n\tif (!branch) return user;\n\treturn `${user}.${branch}`;\n}\nfunction buildPostgresUrl(config) {\n\tconst user = encodeURIComponent(config.user);\n\tconst password = encodeURIComponent(config.password);\n\tconst auth = config.password ? `${user}:${password}` : user;\n\tconst database = encodeURIComponent(config.database).replace(/%2F/g, \"/\");\n\tconst url = `postgresql://${auth}@${config.host}:${config.port}/${database}`;\n\treturn config.ssl ? applyPostgresSslMode(url) : url;\n}\nfunction parsePostgresUrl(url) {\n\tconst parsed = new URL(url.replace(/^postgresql:/i, \"postgres:\"));\n\tconst database = decodeURIComponent(parsed.pathname.replace(/^\\//, \"\"));\n\tif (!database) throw new Error(`Postgres URL is missing database name: ${url}`);\n\treturn {\n\t\thost: parsed.hostname,\n\t\tport: parsed.port ? Number(parsed.port) : 5432,\n\t\tdatabase,\n\t\tuser: decodeURIComponent(parsed.username),\n\t\tpassword: decodeURIComponent(parsed.password)\n\t};\n}\nfunction resolvePostgresConfigFromPostgresEnv(env) {\n\tif (missingPostgresEnvKeys(env).length > 0) return;\n\tconst port = Number(readEnv(env, \"POSTGRES_PORT\"));\n\tif (!Number.isFinite(port)) throw new Error(`Invalid POSTGRES_PORT: ${env.POSTGRES_PORT}`);\n\treturn {\n\t\thost: readEnv(env, \"POSTGRES_HOST\"),\n\t\tport,\n\t\tdatabase: readEnv(env, \"POSTGRES_DB\"),\n\t\tuser: readEnv(env, \"POSTGRES_USER\"),\n\t\tpassword: readEnv(env, \"POSTGRES_PASSWORD\"),\n\t\tssl: readPostgresSsl(env)\n\t};\n}\n/** Requires POSTGRES_* env vars or a postgres DATABASE_URL. */\nfunction resolvePostgresConfigFromEnv(env = process.env) {\n\tconst direct = readEnv(env, \"DATABASE_URL\");\n\tif (direct && /^postgres(ql)?:\\/\\//i.test(direct)) return {\n\t\t...parsePostgresUrl(direct),\n\t\tssl: resolvePostgresSsl(env, direct)\n\t};\n\tconst config = resolvePostgresConfigFromPostgresEnv(env);\n\tif (!config) throw new Error(`Missing required Postgres env vars: ${missingPostgresEnvKeys(env).join(\", \")}`);\n\treturn config;\n}\n/** Requires POSTGRES_* env vars or a postgres DATABASE_URL. */\nfunction resolvePostgresUrlFromEnv(env = process.env) {\n\tconst ssl = readPostgresSsl(env);\n\tconst direct = readEnv(env, \"DATABASE_URL\");\n\tif (direct && /^postgres(ql)?:\\/\\//i.test(direct)) return ssl ? applyPostgresSslMode(direct) : direct;\n\treturn buildPostgresUrl(resolvePostgresConfigFromEnv(env));\n}\n/**\n* Project runtime — POSTGRES_* only (same env shape as hosted workers).\n* Returns undefined when unset; initDatabase falls back to sqlite DEFAULT_DATABASE_URL.\n* Optional DATABASE_SEARCH_PATH sets the tenant schema search_path.\n*/\nfunction resolveProjectDatabaseUrlFromEnv(env = process.env) {\n\tconst config = resolvePostgresConfigFromPostgresEnv(env);\n\treturn config ? buildPostgresUrl(config) : void 0;\n}\n/** @deprecated Prefer resolveProjectDatabaseUrlFromEnv (project) or resolvePostgresUrlFromEnv (platform). */\nfunction resolveDatabaseUrlFromEnv(env = process.env) {\n\treturn resolveProjectDatabaseUrlFromEnv(env);\n}\n//#endregion\n//#region src/client/request-context.ts\nconst requestHandle = new AsyncLocalStorage();\nfunction getRequestDatabaseHandle() {\n\treturn requestHandle.getStore();\n}\nfunction runWithRequestDatabaseHandle(handle, fn) {\n\treturn requestHandle.run(handle, fn);\n}\n//#endregion\n//#region src/client/context.ts\nlet handle;\nfunction isDatabaseInitialized() {\n\treturn getRequestDatabaseHandle() !== void 0 || handle !== void 0;\n}\nfunction getDatabaseHandle() {\n\tconst scoped = getRequestDatabaseHandle();\n\tif (scoped) return scoped;\n\tif (!handle) throw new Error(\"Database not initialized. Call initDatabase() before getDb().\");\n\treturn handle;\n}\nfunction setDatabaseHandle(next) {\n\thandle = next;\n}\nfunction getDefaultDatabaseHandle() {\n\treturn handle;\n}\nfunction getDbFromContext() {\n\treturn getDatabaseHandle().db;\n}\n//#endregion\n//#region src/schema/bundle.ts\nfunction buildPgSchema(registry) {\n\treturn Object.fromEntries(Object.entries(registry).map(([name, { pg }]) => [name, pg]));\n}\nfunction buildSqliteSchema(registry) {\n\treturn Object.fromEntries(Object.entries(registry).map(([name, { sqlite }]) => [name, sqlite]));\n}\n//#endregion\n//#region src/schema/tables/agents.ts\nconst agents = pgTable(\"agents\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\tslug: text(\"slug\").notNull(),\n\tname: text(\"name\"),\n\tdescription: text(\"description\"),\n\troute: text(\"route\").notNull(),\n\tmoduleFile: text(\"module_file\").notNull(),\n\tmodel: text(\"model\").notNull(),\n\tsystemPrompt: text(\"system_prompt\").notNull(),\n\ttoolCount: integer(\"tool_count\"),\n\tcredentialCount: integer(\"credential_count\"),\n\tappSlugs: jsonb(\"app_slugs\").$type(),\n\tregisteredAt: timestamp(\"registered_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tdeletedAt: timestamp(\"deleted_at\", { withTimezone: true })\n}, (table) => [uniqueIndex(\"agents_project_id_slug_idx\").on(table.projectId, table.slug), uniqueIndex(\"agents_project_id_route_idx\").on(table.projectId, table.route)]);\nconst agentsSqlite = sqliteTable(\"agents\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\tslug: text$1(\"slug\").notNull(),\n\tname: text$1(\"name\"),\n\tdescription: text$1(\"description\"),\n\troute: text$1(\"route\").notNull(),\n\tmoduleFile: text$1(\"module_file\").notNull(),\n\tmodel: text$1(\"model\").notNull(),\n\tsystemPrompt: text$1(\"system_prompt\").notNull(),\n\ttoolCount: integer$1(\"tool_count\"),\n\tcredentialCount: integer$1(\"credential_count\"),\n\tappSlugs: text$1(\"app_slugs\", { mode: \"json\" }).$type(),\n\tregisteredAt: integer$1(\"registered_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tdeletedAt: integer$1(\"deleted_at\", { mode: \"timestamp_ms\" })\n}, (table) => [uniqueIndex$1(\"agents_project_id_slug_idx\").on(table.projectId, table.slug), uniqueIndex$1(\"agents_project_id_route_idx\").on(table.projectId, table.route)]);\n//#endregion\n//#region src/schema/tables/agent-sessions.ts\nconst agentSessions = pgTable(\"agent_sessions\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\tagentId: text(\"agent_id\").notNull().references(() => agents.id),\n\tsourceKind: text(\"source_kind\").$type().notNull().default(\"api\"),\n\tsourceId: text(\"source_id\"),\n\tparentSpanId: text(\"parent_span_id\"),\n\tranByUserId: text(\"ran_by_user_id\"),\n\ttitle: text(\"title\"),\n\tcanceledAt: timestamp(\"canceled_at\", { withTimezone: true }),\n\ttotalDurationMs: integer(\"total_duration_ms\").notNull().default(0),\n\tliveMessage: jsonb(\"live_message\"),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tdeletedAt: timestamp(\"deleted_at\", { withTimezone: true })\n}, (table) => [index(\"agent_sessions_agent_updated_idx\").on(table.agentId, table.updatedAt)]);\nconst agentSessionsSqlite = sqliteTable(\"agent_sessions\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\tagentId: text$1(\"agent_id\").notNull().references(() => agentsSqlite.id),\n\tsourceKind: text$1(\"source_kind\").$type().notNull().default(\"api\"),\n\tsourceId: text$1(\"source_id\"),\n\tparentSpanId: text$1(\"parent_span_id\"),\n\tranByUserId: text$1(\"ran_by_user_id\"),\n\ttitle: text$1(\"title\"),\n\tcanceledAt: integer$1(\"canceled_at\", { mode: \"timestamp_ms\" }),\n\ttotalDurationMs: integer$1(\"total_duration_ms\").notNull().default(0),\n\tliveMessage: text$1(\"live_message\", { mode: \"json\" }),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tdeletedAt: integer$1(\"deleted_at\", { mode: \"timestamp_ms\" })\n}, (table) => [index$1(\"agent_sessions_agent_updated_idx\").on(table.agentId, table.updatedAt)]);\n//#endregion\n//#region src/schema/tables/agent-events.ts\nconst agentEvents = pgTable(\"agent_events\", {\n\tid: text(\"id\").primaryKey(),\n\tsessionId: text(\"session_id\").notNull().references(() => agentSessions.id),\n\tseq: integer(\"seq\").notNull(),\n\teventType: text(\"event_type\").notNull(),\n\tpayload: jsonb(\"payload\").notNull(),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tdeletedAt: timestamp(\"deleted_at\", { withTimezone: true })\n});\nconst agentEventsSqlite = sqliteTable(\"agent_events\", {\n\tid: text$1(\"id\").primaryKey(),\n\tsessionId: text$1(\"session_id\").notNull().references(() => agentSessionsSqlite.id),\n\tseq: integer$1(\"seq\").notNull(),\n\teventType: text$1(\"event_type\").notNull(),\n\tpayload: text$1(\"payload\", { mode: \"json\" }).notNull(),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tdeletedAt: integer$1(\"deleted_at\", { mode: \"timestamp_ms\" })\n});\n//#endregion\n//#region src/schema/tables/usage-records.ts\nconst usageRecords = pgTable(\"usage_records\", {\n\tid: text(\"id\").primaryKey(),\n\trunId: text(\"run_id\").notNull(),\n\trunKind: text(\"run_kind\").$type().notNull(),\n\tkind: text(\"kind\").notNull(),\n\tlabel: text(\"label\").notNull(),\n\tquantity: integer(\"quantity\"),\n\tunit: text(\"unit\"),\n\tamount: doublePrecision(\"amount\").notNull(),\n\tmetadata: jsonb(\"metadata\"),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull()\n}, (table) => [index(\"usage_records_run_run_kind_idx\").on(table.runId, table.runKind), index(\"usage_records_kind_idx\").on(table.kind)]);\nconst usageRecordsSqlite = sqliteTable(\"usage_records\", {\n\tid: text$1(\"id\").primaryKey(),\n\trunId: text$1(\"run_id\").notNull(),\n\trunKind: text$1(\"run_kind\").$type().notNull(),\n\tkind: text$1(\"kind\").notNull(),\n\tlabel: text$1(\"label\").notNull(),\n\tquantity: integer$1(\"quantity\"),\n\tunit: text$1(\"unit\"),\n\tamount: real(\"amount\").notNull(),\n\tmetadata: text$1(\"metadata\", { mode: \"json\" }),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [index$1(\"usage_records_run_run_kind_idx\").on(table.runId, table.runKind), index$1(\"usage_records_kind_idx\").on(table.kind)]);\n//#endregion\n//#region src/schema/tables/trigger-attachments.ts\nconst triggerAttachments = pgTable(\"trigger_attachments\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\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\tmoduleFile: text(\"module_file\").notNull(),\n\tsource: jsonb(\"source\").$type().notNull(),\n\torigin: text(\"origin\").$type().notNull().default(\"project\"),\n\tprompt: text(\"prompt\"),\n\tlifecycle: jsonb(\"lifecycle\").$type(),\n\tcreatedBySessionId: text(\"created_by_session_id\"),\n\tregisteredAt: timestamp(\"registered_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tdeletedAt: timestamp(\"deleted_at\", { withTimezone: true })\n}, (table) => [uniqueIndex(\"trigger_attachments_project_id_slug_idx\").on(table.projectId, table.slug)]);\nconst triggerAttachmentsSqlite = sqliteTable(\"trigger_attachments\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\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\tmoduleFile: text$1(\"module_file\").notNull(),\n\tsource: text$1(\"source\", { mode: \"json\" }).$type().notNull(),\n\torigin: text$1(\"origin\").$type().notNull().default(\"project\"),\n\tprompt: text$1(\"prompt\"),\n\tlifecycle: text$1(\"lifecycle\", { mode: \"json\" }).$type(),\n\tcreatedBySessionId: text$1(\"created_by_session_id\"),\n\tregisteredAt: integer$1(\"registered_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tdeletedAt: integer$1(\"deleted_at\", { mode: \"timestamp_ms\" })\n}, (table) => [uniqueIndex$1(\"trigger_attachments_project_id_slug_idx\").on(table.projectId, table.slug)]);\n//#endregion\n//#region src/schema/tables/trigger-schedules.ts\nconst triggerSchedules = pgTable(\"trigger_schedules\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\tattachmentSlug: text(\"attachment_slug\").notNull(),\n\tkind: text(\"kind\").$type().notNull(),\n\tschedule: text(\"schedule\").notNull(),\n\tnextRunAt: timestamp(\"next_run_at\", { withTimezone: true }).notNull(),\n\tenabled: integer(\"enabled\").notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [uniqueIndex(\"trigger_schedules_project_id_attachment_slug_idx\").on(table.projectId, table.attachmentSlug), index(\"trigger_schedules_next_run_at_idx\").on(table.nextRunAt, table.enabled)]);\nconst triggerSchedulesSqlite = sqliteTable(\"trigger_schedules\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\tattachmentSlug: text$1(\"attachment_slug\").notNull(),\n\tkind: text$1(\"kind\").$type().notNull(),\n\tschedule: text$1(\"schedule\").notNull(),\n\tnextRunAt: integer$1(\"next_run_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tenabled: integer$1(\"enabled\").notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [uniqueIndex$1(\"trigger_schedules_project_id_attachment_slug_idx\").on(table.projectId, table.attachmentSlug), index$1(\"trigger_schedules_next_run_at_idx\").on(table.nextRunAt, table.enabled)]);\n//#endregion\n//#region src/schema/tables/trigger-runs.ts\nconst triggerRuns = pgTable(\"trigger_runs\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\tattachmentId: text(\"attachment_id\").notNull().references(() => triggerAttachments.id),\n\tsourcePath: text(\"source_path\"),\n\ttriggerType: text(\"trigger_type\").$type().notNull(),\n\tpayload: jsonb(\"payload\"),\n\ttriggeredAt: timestamp(\"triggered_at\", { withTimezone: true }).notNull()\n});\nconst triggerRunsSqlite = sqliteTable(\"trigger_runs\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\tattachmentId: text$1(\"attachment_id\").notNull().references(() => triggerAttachmentsSqlite.id),\n\tsourcePath: text$1(\"source_path\"),\n\ttriggerType: text$1(\"trigger_type\").$type().notNull(),\n\tpayload: text$1(\"payload\", { mode: \"json\" }),\n\ttriggeredAt: integer$1(\"triggered_at\", { mode: \"timestamp_ms\" }).notNull()\n});\n//#endregion\n//#region src/schema/tables/workflow-subscriptions.ts\nconst workflowSubscriptions = pgTable(\"workflow_subscriptions\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\tworkflowSlug: text(\"workflow_slug\").notNull(),\n\tuserId: text(\"user_id\").notNull(),\n\tenabled: integer(\"enabled\").notNull(),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [uniqueIndex(\"workflow_subscriptions_project_workflow_user\").on(table.projectId, table.workflowSlug, table.userId)]);\nconst workflowSubscriptionsSqlite = sqliteTable(\"workflow_subscriptions\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\tworkflowSlug: text$1(\"workflow_slug\").notNull(),\n\tuserId: text$1(\"user_id\").notNull(),\n\tenabled: integer$1(\"enabled\", { mode: \"boolean\" }).notNull(),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [uniqueIndex$1(\"workflow_subscriptions_project_workflow_user\").on(table.projectId, table.workflowSlug, table.userId)]);\n//#endregion\n//#region src/schema/tables/workflow-runs.ts\nconst workflowRuns = pgTable(\"workflow_runs\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\tworkflowSlug: text(\"workflow_slug\").notNull(),\n\tattachmentId: text(\"attachment_id\").references(() => triggerAttachments.id),\n\tsubscriptionId: text(\"subscription_id\").references(() => workflowSubscriptions.id),\n\ttriggerRunId: text(\"trigger_run_id\").references(() => triggerRuns.id),\n\tparentWorkflowRunId: text(\"parent_workflow_run_id\"),\n\tparentSpanId: text(\"parent_span_id\"),\n\tsourceKind: text(\"source_kind\").$type().notNull().default(\"api\"),\n\tsourceId: text(\"source_id\"),\n\tranByUserId: text(\"ran_by_user_id\"),\n\tstatus: text(\"status\").$type().notNull(),\n\ttrigger: text(\"trigger\").$type().notNull(),\n\ttriggeredAt: timestamp(\"triggered_at\", { withTimezone: true }).notNull(),\n\tstartedAt: timestamp(\"started_at\", { withTimezone: true }),\n\tfinishedAt: timestamp(\"finished_at\", { withTimezone: true }),\n\tinput: jsonb(\"input\"),\n\toutput: jsonb(\"output\"),\n\terror: jsonb(\"error\")\n}, (table) => [index(\"workflow_runs_project_workflow_triggered_idx\").on(table.projectId, table.workflowSlug, table.triggeredAt)]);\nconst workflowRunsSqlite = sqliteTable(\"workflow_runs\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\tworkflowSlug: text$1(\"workflow_slug\").notNull(),\n\tattachmentId: text$1(\"attachment_id\").references(() => triggerAttachmentsSqlite.id),\n\tsubscriptionId: text$1(\"subscription_id\").references(() => workflowSubscriptionsSqlite.id),\n\ttriggerRunId: text$1(\"trigger_run_id\").references(() => triggerRunsSqlite.id),\n\tparentWorkflowRunId: text$1(\"parent_workflow_run_id\"),\n\tparentSpanId: text$1(\"parent_span_id\"),\n\tsourceKind: text$1(\"source_kind\").$type().notNull().default(\"api\"),\n\tsourceId: text$1(\"source_id\"),\n\tranByUserId: text$1(\"ran_by_user_id\"),\n\tstatus: text$1(\"status\").$type().notNull(),\n\ttrigger: text$1(\"trigger\").$type().notNull(),\n\ttriggeredAt: integer$1(\"triggered_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tstartedAt: integer$1(\"started_at\", { mode: \"timestamp_ms\" }),\n\tfinishedAt: integer$1(\"finished_at\", { mode: \"timestamp_ms\" }),\n\tinput: text$1(\"input\", { mode: \"json\" }),\n\toutput: text$1(\"output\", { mode: \"json\" }),\n\terror: text$1(\"error\", { mode: \"json\" })\n}, (table) => [index$1(\"workflow_runs_project_workflow_triggered_idx\").on(table.projectId, table.workflowSlug, table.triggeredAt)]);\n//#endregion\n//#region src/schema/tables/workflow-events.ts\n/**\n* Append-only durable execution log. One row per workflow lifecycle transition.\n* Replay reads these in `seq` order and short-circuits already-completed primitives.\n*/\nconst workflowEvents = pgTable(\"workflow_events\", {\n\tid: text(\"id\").primaryKey(),\n\trunId: text(\"run_id\").notNull().references(() => workflowRuns.id),\n\tprojectId: text(\"project_id\").notNull(),\n\tseq: integer(\"seq\").notNull(),\n\ttype: text(\"type\").$type().notNull(),\n\tcorrelationId: text(\"correlation_id\"),\n\tdata: jsonb(\"data\"),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull()\n}, (table) => [\n\tuniqueIndex(\"workflow_events_run_id_seq_unique\").on(table.runId, table.seq),\n\tindex(\"workflow_events_run_id_type_idx\").on(table.runId, table.type),\n\tindex(\"workflow_events_correlation_id_idx\").on(table.correlationId)\n]);\nconst workflowEventsSqlite = sqliteTable(\"workflow_events\", {\n\tid: text$1(\"id\").primaryKey(),\n\trunId: text$1(\"run_id\").notNull().references(() => workflowRunsSqlite.id),\n\tprojectId: text$1(\"project_id\").notNull(),\n\tseq: integer$1(\"seq\").notNull(),\n\ttype: text$1(\"type\").$type().notNull(),\n\tcorrelationId: text$1(\"correlation_id\"),\n\tdata: text$1(\"data\", { mode: \"json\" }),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [\n\tuniqueIndex$1(\"workflow_events_run_id_seq_unique\").on(table.runId, table.seq),\n\tindex$1(\"workflow_events_run_id_type_idx\").on(table.runId, table.type),\n\tindex$1(\"workflow_events_correlation_id_idx\").on(table.correlationId)\n]);\n//#endregion\n//#region src/schema/tables/workflow-hooks.ts\nconst workflowHooks = pgTable(\"workflow_hooks\", {\n\thookId: text(\"hook_id\").primaryKey(),\n\trunId: text(\"run_id\").notNull().references(() => workflowRuns.id),\n\tprojectId: text(\"project_id\").notNull(),\n\ttoken: text(\"token\").notNull(),\n\tcorrelationId: text(\"correlation_id\").notNull(),\n\tstatus: text(\"status\").$type().notNull(),\n\tpayload: jsonb(\"payload\"),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tresumedAt: timestamp(\"resumed_at\", { withTimezone: true })\n}, (table) => [uniqueIndex(\"workflow_hooks_token_unique\").on(table.token), index(\"workflow_hooks_run_id_idx\").on(table.runId)]);\nconst workflowHooksSqlite = sqliteTable(\"workflow_hooks\", {\n\thookId: text$1(\"hook_id\").primaryKey(),\n\trunId: text$1(\"run_id\").notNull().references(() => workflowRunsSqlite.id),\n\tprojectId: text$1(\"project_id\").notNull(),\n\ttoken: text$1(\"token\").notNull(),\n\tcorrelationId: text$1(\"correlation_id\").notNull(),\n\tstatus: text$1(\"status\").$type().notNull(),\n\tpayload: text$1(\"payload\", { mode: \"json\" }),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tresumedAt: integer$1(\"resumed_at\", { mode: \"timestamp_ms\" })\n}, (table) => [uniqueIndex$1(\"workflow_hooks_token_unique\").on(table.token), index$1(\"workflow_hooks_run_id_idx\").on(table.runId)]);\n//#endregion\n//#region src/schema/tables/credential-instances.ts\nconst credentialInstances = pgTable(\"credential_instances\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\tappSlug: text(\"app_slug\").notNull(),\n\tslug: text(\"slug\").notNull(),\n\tname: text(\"name\"),\n\tscopeType: text(\"scope_type\").$type().notNull(),\n\tscopeId: text(\"scope_id\"),\n\tlabel: text(\"label\"),\n\tisDefault: integer(\"is_default\").notNull(),\n\tauthKind: text(\"auth_kind\").$type().notNull(),\n\tciphertext: text(\"ciphertext\"),\n\tconnectionId: text(\"connection_id\"),\n\t/** MCP entity id that owns connection_id when multiple scopes share one connection. */\n\tsharedConnectionId: text(\"shared_connection_id\"),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [uniqueIndex(\"credential_instances_project_scope_slug_unique\").on(table.projectId, table.scopeType, table.scopeId, table.slug), index(\"credential_instances_project_app_slug_scope_idx\").on(table.projectId, table.appSlug, table.scopeType, table.scopeId)]);\nconst credentialInstancesSqlite = sqliteTable(\"credential_instances\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\tappSlug: text$1(\"app_slug\").notNull(),\n\tslug: text$1(\"slug\").notNull(),\n\tname: text$1(\"name\"),\n\tscopeType: text$1(\"scope_type\").$type().notNull(),\n\tscopeId: text$1(\"scope_id\"),\n\tlabel: text$1(\"label\"),\n\tisDefault: integer$1(\"is_default\", { mode: \"boolean\" }).notNull(),\n\tauthKind: text$1(\"auth_kind\").$type().notNull(),\n\tciphertext: text$1(\"ciphertext\"),\n\tconnectionId: text$1(\"connection_id\"),\n\t/** MCP entity id that owns connection_id when multiple scopes share one connection. */\n\tsharedConnectionId: text$1(\"shared_connection_id\"),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [uniqueIndex$1(\"credential_instances_project_scope_slug_unique\").on(table.projectId, table.scopeType, table.scopeId, table.slug), index$1(\"credential_instances_project_app_slug_scope_idx\").on(table.projectId, table.appSlug, table.scopeType, table.scopeId)]);\n//#endregion\n//#region src/schema/tables/credential-assignments.ts\nconst credentialAssignments = pgTable(\"credential_assignments\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\ttargetType: text(\"target_type\").$type().notNull(),\n\ttargetKey: text(\"target_key\").notNull(),\n\t/** '*' = wildcard; else runtime consumer id (step correlation id or tool slug). */\n\tconsumerId: text(\"consumer_id\").notNull(),\n\tcredentialSlug: text(\"credential_slug\").notNull(),\n\tinstanceId: text(\"instance_id\").notNull(),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [uniqueIndex(\"credential_assignments_project_target_consumer_slug\").on(table.projectId, table.targetType, table.targetKey, table.consumerId, table.credentialSlug), index(\"credential_assignments_project_target_idx\").on(table.projectId, table.targetType, table.targetKey)]);\nconst credentialAssignmentsSqlite = sqliteTable(\"credential_assignments\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\ttargetType: text$1(\"target_type\").$type().notNull(),\n\ttargetKey: text$1(\"target_key\").notNull(),\n\tconsumerId: text$1(\"consumer_id\").notNull(),\n\tcredentialSlug: text$1(\"credential_slug\").notNull(),\n\tinstanceId: text$1(\"instance_id\").notNull(),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [uniqueIndex$1(\"credential_assignments_project_target_consumer_slug\").on(table.projectId, table.targetType, table.targetKey, table.consumerId, table.credentialSlug), index$1(\"credential_assignments_project_target_idx\").on(table.projectId, table.targetType, table.targetKey)]);\n//#endregion\n//#region src/schema/tables/jobs.ts\nconst jobs = pgTable(\"jobs\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\tkind: text(\"kind\").$type().notNull(),\n\ttargetId: text(\"target_id\").notNull(),\n\trunId: text(\"run_id\").notNull(),\n\ttrigger: text(\"trigger\").$type().notNull(),\n\tpayload: jsonb(\"payload\"),\n\tstatus: text(\"status\").$type().notNull(),\n\tscheduledAt: timestamp(\"scheduled_at\", { withTimezone: true }).notNull(),\n\tattempt: integer(\"attempt\").notNull(),\n\tmaxAttempts: integer(\"max_attempts\").notNull(),\n\tleasedBy: text(\"leased_by\"),\n\tleaseExpiresAt: timestamp(\"lease_expires_at\", { withTimezone: true }),\n\tcompletedAt: timestamp(\"completed_at\", { withTimezone: true }),\n\terror: jsonb(\"error\")\n});\nconst jobsSqlite = sqliteTable(\"jobs\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\tkind: text$1(\"kind\").$type().notNull(),\n\ttargetId: text$1(\"target_id\").notNull(),\n\trunId: text$1(\"run_id\").notNull(),\n\ttrigger: text$1(\"trigger\").$type().notNull(),\n\tpayload: text$1(\"payload\", { mode: \"json\" }),\n\tstatus: text$1(\"status\").$type().notNull(),\n\tscheduledAt: integer$1(\"scheduled_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tattempt: integer$1(\"attempt\").notNull(),\n\tmaxAttempts: integer$1(\"max_attempts\").notNull(),\n\tleasedBy: text$1(\"leased_by\"),\n\tleaseExpiresAt: integer$1(\"lease_expires_at\", { mode: \"timestamp_ms\" }),\n\tcompletedAt: integer$1(\"completed_at\", { mode: \"timestamp_ms\" }),\n\terror: text$1(\"error\", { mode: \"json\" })\n});\n//#endregion\n//#region src/schema/tables/gateway-attachments.ts\nconst gatewayAttachments = pgTable(\"gateway_attachments\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\tslug: text(\"slug\").notNull(),\n\tagentSlug: text(\"agent_slug\").notNull(),\n\tmoduleFile: text(\"module_file\"),\n\tplatform: text(\"platform\").notNull(),\n\tteamId: text(\"team_id\"),\n\tchannelId: text(\"channel_id\").notNull(),\n\tsource: jsonb(\"source\").$type().notNull(),\n\tregisteredAt: timestamp(\"registered_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tdeletedAt: timestamp(\"deleted_at\", { withTimezone: true })\n}, (table) => [uniqueIndex(\"gateway_attachments_project_id_slug_idx\").on(table.projectId, table.slug), uniqueIndex(\"gateway_attachments_project_platform_channel_active\").on(table.projectId, table.platform, table.channelId).where(sql`${table.deletedAt} is null`)]);\nconst gatewayAttachmentsSqlite = sqliteTable(\"gateway_attachments\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\tslug: text$1(\"slug\").notNull(),\n\tagentSlug: text$1(\"agent_slug\").notNull(),\n\tmoduleFile: text$1(\"module_file\"),\n\tplatform: text$1(\"platform\").notNull(),\n\tteamId: text$1(\"team_id\"),\n\tchannelId: text$1(\"channel_id\").notNull(),\n\tsource: text$1(\"source\", { mode: \"json\" }).$type().notNull(),\n\tregisteredAt: integer$1(\"registered_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tdeletedAt: integer$1(\"deleted_at\", { mode: \"timestamp_ms\" })\n}, (table) => [uniqueIndex$1(\"gateway_attachments_project_id_slug_idx\").on(table.projectId, table.slug), uniqueIndex$1(\"gateway_attachments_project_platform_channel_active\").on(table.projectId, table.platform, table.channelId).where(sql`${table.deletedAt} is null`)]);\nfunction gatewayAttachmentKeyForChannel(platform, channelId) {\n\treturn `${platform}:${channelId}`;\n}\n//#endregion\n//#region src/schema/tables/gateway-thread-sessions.ts\nconst gatewayThreadSessions = pgTable(\"gateway_thread_sessions\", {\n\tthreadId: text(\"thread_id\").primaryKey(),\n\tagentId: text(\"agent_id\").notNull().references(() => agents.id),\n\tsessionId: text(\"session_id\").notNull().references(() => agentSessions.id),\n\tattachmentId: text(\"attachment_id\").notNull().references(() => gatewayAttachments.id),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n});\nconst gatewayThreadSessionsSqlite = sqliteTable(\"gateway_thread_sessions\", {\n\tthreadId: text$1(\"thread_id\").primaryKey(),\n\tagentId: text$1(\"agent_id\").notNull().references(() => agentsSqlite.id),\n\tsessionId: text$1(\"session_id\").notNull().references(() => agentSessionsSqlite.id),\n\tattachmentId: text$1(\"attachment_id\").notNull().references(() => gatewayAttachmentsSqlite.id),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n});\n//#endregion\n//#region src/schema/tables/trace-spans.ts\nconst traceSpans = pgTable(\"trace_spans\", {\n\tid: text(\"id\").primaryKey(),\n\ttraceId: text(\"trace_id\").notNull(),\n\tparentSpanId: text(\"parent_span_id\"),\n\tkind: text(\"kind\").$type().notNull(),\n\trefId: text(\"ref_id\").notNull(),\n\tname: text(\"name\").notNull(),\n\tstatus: text(\"status\").$type().notNull(),\n\tstartedAt: timestamp(\"started_at\", { withTimezone: true }).notNull(),\n\tfinishedAt: timestamp(\"finished_at\", { withTimezone: true }),\n\tmetadata: jsonb(\"metadata\"),\n\terror: jsonb(\"error\")\n});\nconst traceSpansSqlite = sqliteTable(\"trace_spans\", {\n\tid: text$1(\"id\").primaryKey(),\n\ttraceId: text$1(\"trace_id\").notNull(),\n\tparentSpanId: text$1(\"parent_span_id\"),\n\tkind: text$1(\"kind\").$type().notNull(),\n\trefId: text$1(\"ref_id\").notNull(),\n\tname: text$1(\"name\").notNull(),\n\tstatus: text$1(\"status\").$type().notNull(),\n\tstartedAt: integer$1(\"started_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tfinishedAt: integer$1(\"finished_at\", { mode: \"timestamp_ms\" }),\n\tmetadata: text$1(\"metadata\", { mode: \"json\" }),\n\terror: text$1(\"error\", { mode: \"json\" })\n});\n//#endregion\n//#region src/schema/tables/trace-logs.ts\nconst traceLogs = pgTable(\"trace_logs\", {\n\tid: text(\"id\").primaryKey(),\n\ttraceId: text(\"trace_id\").notNull(),\n\tspanId: text(\"span_id\").notNull().references(() => traceSpans.id),\n\tseq: integer(\"seq\").notNull(),\n\tlevel: text(\"level\").$type().notNull(),\n\tmessage: text(\"message\").notNull(),\n\tdata: jsonb(\"data\"),\n\tsource: text(\"source\").$type().notNull(),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull()\n}, (table) => [index(\"trace_logs_trace_id_seq_idx\").on(table.traceId, table.seq), index(\"trace_logs_span_id_seq_idx\").on(table.spanId, table.seq)]);\nconst traceLogsSqlite = sqliteTable(\"trace_logs\", {\n\tid: text$1(\"id\").primaryKey(),\n\ttraceId: text$1(\"trace_id\").notNull(),\n\tspanId: text$1(\"span_id\").notNull().references(() => traceSpansSqlite.id),\n\tseq: integer$1(\"seq\").notNull(),\n\tlevel: text$1(\"level\").$type().notNull(),\n\tmessage: text$1(\"message\").notNull(),\n\tdata: text$1(\"data\", { mode: \"json\" }),\n\tsource: text$1(\"source\").$type().notNull(),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [index$1(\"trace_logs_trace_id_seq_idx\").on(table.traceId, table.seq), index$1(\"trace_logs_span_id_seq_idx\").on(table.spanId, table.seq)]);\n//#endregion\n//#region src/schema/tables/skills.ts\nconst skills = pgTable(\"skills\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\tslug: text(\"slug\").notNull(),\n\tname: text(\"name\"),\n\tdescription: text(\"description\"),\n\tmoduleFile: text(\"module_file\").notNull(),\n\tregisteredAt: timestamp(\"registered_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tdeletedAt: timestamp(\"deleted_at\", { withTimezone: true })\n}, (table) => [uniqueIndex(\"skills_project_id_slug_idx\").on(table.projectId, table.slug)]);\nconst skillsSqlite = sqliteTable(\"skills\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\tslug: text$1(\"slug\").notNull(),\n\tname: text$1(\"name\"),\n\tdescription: text$1(\"description\"),\n\tmoduleFile: text$1(\"module_file\").notNull(),\n\tregisteredAt: integer$1(\"registered_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tdeletedAt: integer$1(\"deleted_at\", { mode: \"timestamp_ms\" })\n}, (table) => [uniqueIndex$1(\"skills_project_id_slug_idx\").on(table.projectId, table.slug)]);\n//#endregion\n//#region src/schema/tables/workflows.ts\nconst workflows = pgTable(\"workflows\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\tslug: text(\"slug\").notNull(),\n\tname: text(\"name\"),\n\tdescription: text(\"description\"),\n\tmoduleFile: text(\"module_file\").notNull(),\n\tsubscribable: integer(\"subscribable\").notNull(),\n\tregisteredAt: timestamp(\"registered_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tdeletedAt: timestamp(\"deleted_at\", { withTimezone: true })\n}, (table) => [uniqueIndex(\"workflows_project_id_slug_idx\").on(table.projectId, table.slug)]);\nconst workflowsSqlite = sqliteTable(\"workflows\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\tslug: text$1(\"slug\").notNull(),\n\tname: text$1(\"name\"),\n\tdescription: text$1(\"description\"),\n\tmoduleFile: text$1(\"module_file\").notNull(),\n\tsubscribable: integer$1(\"subscribable\", { mode: \"boolean\" }).notNull(),\n\tregisteredAt: integer$1(\"registered_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tdeletedAt: integer$1(\"deleted_at\", { mode: \"timestamp_ms\" })\n}, (table) => [uniqueIndex$1(\"workflows_project_id_slug_idx\").on(table.projectId, table.slug)]);\n//#endregion\n//#region src/schema/tables/resource-activity.ts\nconst resourceActivity = pgTable(\"resource_activity\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull(),\n\tuserId: text(\"user_id\").notNull(),\n\tresourceKind: text(\"resource_kind\").notNull(),\n\tresourceId: text(\"resource_id\").notNull(),\n\tlastOpenedAt: timestamp(\"last_opened_at\", { withTimezone: true }).notNull()\n}, (table) => [uniqueIndex(\"resource_activity_project_user_kind_resource\").on(table.projectId, table.userId, table.resourceKind, table.resourceId), index(\"resource_activity_user_last_opened_at\").on(table.userId, table.lastOpenedAt)]);\nconst resourceActivitySqlite = sqliteTable(\"resource_activity\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull(),\n\tuserId: text$1(\"user_id\").notNull(),\n\tresourceKind: text$1(\"resource_kind\").notNull(),\n\tresourceId: text$1(\"resource_id\").notNull(),\n\tlastOpenedAt: integer$1(\"last_opened_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [uniqueIndex$1(\"resource_activity_project_user_kind_resource\").on(table.projectId, table.userId, table.resourceKind, table.resourceId), index$1(\"resource_activity_user_last_opened_at\").on(table.userId, table.lastOpenedAt)]);\n//#endregion\n//#region src/schema/registrations.ts\n/**\n* Project server tables — Postgres (hosted) or SQLite (local dev).\n*/\nconst tableRegistry = {\n\tagents: {\n\t\tpg: agents,\n\t\tsqlite: agentsSqlite\n\t},\n\tagentSessions: {\n\t\tpg: agentSessions,\n\t\tsqlite: agentSessionsSqlite\n\t},\n\tagentEvents: {\n\t\tpg: agentEvents,\n\t\tsqlite: agentEventsSqlite\n\t},\n\tusageRecords: {\n\t\tpg: usageRecords,\n\t\tsqlite: usageRecordsSqlite\n\t},\n\ttriggerAttachments: {\n\t\tpg: triggerAttachments,\n\t\tsqlite: triggerAttachmentsSqlite\n\t},\n\ttriggerSchedules: {\n\t\tpg: triggerSchedules,\n\t\tsqlite: triggerSchedulesSqlite\n\t},\n\ttriggerRuns: {\n\t\tpg: triggerRuns,\n\t\tsqlite: triggerRunsSqlite\n\t},\n\tworkflowRuns: {\n\t\tpg: workflowRuns,\n\t\tsqlite: workflowRunsSqlite\n\t},\n\tworkflowEvents: {\n\t\tpg: workflowEvents,\n\t\tsqlite: workflowEventsSqlite\n\t},\n\tworkflowHooks: {\n\t\tpg: workflowHooks,\n\t\tsqlite: workflowHooksSqlite\n\t},\n\tcredentialInstances: {\n\t\tpg: credentialInstances,\n\t\tsqlite: credentialInstancesSqlite\n\t},\n\tcredentialAssignments: {\n\t\tpg: credentialAssignments,\n\t\tsqlite: credentialAssignmentsSqlite\n\t},\n\tjobs: {\n\t\tpg: jobs,\n\t\tsqlite: jobsSqlite\n\t},\n\tgatewayAttachments: {\n\t\tpg: gatewayAttachments,\n\t\tsqlite: gatewayAttachmentsSqlite\n\t},\n\tgatewayThreadSessions: {\n\t\tpg: gatewayThreadSessions,\n\t\tsqlite: gatewayThreadSessionsSqlite\n\t},\n\ttraceSpans: {\n\t\tpg: traceSpans,\n\t\tsqlite: traceSpansSqlite\n\t},\n\ttraceLogs: {\n\t\tpg: traceLogs,\n\t\tsqlite: traceLogsSqlite\n\t},\n\tskills: {\n\t\tpg: skills,\n\t\tsqlite: skillsSqlite\n\t},\n\tworkflows: {\n\t\tpg: workflows,\n\t\tsqlite: workflowsSqlite\n\t},\n\tworkflowSubscriptions: {\n\t\tpg: workflowSubscriptions,\n\t\tsqlite: workflowSubscriptionsSqlite\n\t},\n\tresourceActivity: {\n\t\tpg: resourceActivity,\n\t\tsqlite: resourceActivitySqlite\n\t}\n};\nconst schema = buildPgSchema(tableRegistry);\nbuildSqliteSchema(tableRegistry);\n//#endregion\n//#region src/schema/pg.ts\nvar pg_exports = /* @__PURE__ */ __exportAll({\n\tagentEvents: () => agentEvents,\n\tagentSessions: () => agentSessions,\n\tagents: () => agents,\n\tcredentialAssignments: () => credentialAssignments,\n\tcredentialInstances: () => credentialInstances,\n\tgatewayAttachments: () => gatewayAttachments,\n\tgatewayThreadSessions: () => gatewayThreadSessions,\n\tjobs: () => jobs,\n\tresourceActivity: () => resourceActivity,\n\tschema: () => schema,\n\tskills: () => skills,\n\ttraceLogs: () => traceLogs,\n\ttraceSpans: () => traceSpans,\n\ttriggerAttachments: () => triggerAttachments,\n\ttriggerRuns: () => triggerRuns,\n\ttriggerSchedules: () => triggerSchedules,\n\tusageRecords: () => usageRecords,\n\tworkflowEvents: () => workflowEvents,\n\tworkflowHooks: () => workflowHooks,\n\tworkflowRuns: () => workflowRuns,\n\tworkflowSubscriptions: () => workflowSubscriptions,\n\tworkflows: () => workflows\n});\n//#endregion\n//#region src/connection/pg/db.ts\n/** Inferred from `schema` — `getDb()` and query files use this type. */\nfunction createPgDb(pool) {\n\treturn drizzle(pool, { schema });\n}\n//#endregion\n//#region src/connection/pg/search-path.ts\nconst SCHEMA_IDENT = /^[a-zA-Z_][a-zA-Z0-9_]*$/;\n/** Drizzle __drizzle_migrations schema — tenant path when set, else public (platform). */\nfunction resolveMigrationsSchema(searchPath) {\n\treturn searchPath ? primarySearchPathSchema(searchPath) : \"public\";\n}\n/** First schema in a comma-separated search_path (the tenant / app schema). */\nfunction primarySearchPathSchema(searchPath) {\n\tconst schema = searchPath.split(\",\")[0]?.trim();\n\tif (!schema || !SCHEMA_IDENT.test(schema)) throw new Error(`Invalid search_path: ${searchPath}`);\n\treturn schema;\n}\nfunction parseSearchPathFromUrl(url) {\n\ttry {\n\t\tconst parsed = new URL(url.replace(/^postgresql:/, \"postgres:\"));\n\t\tconst direct = parsed.searchParams.get(\"search_path\");\n\t\tif (direct) return direct;\n\t\tconst options = parsed.searchParams.get(\"options\");\n\t\tif (!options) return;\n\t\treturn decodeURIComponent(options).match(/search_path[= ]([^,\\s]+(?:,\\s*[^,\\s]+)*)/i)?.[1]?.trim();\n\t} catch {\n\t\treturn;\n\t}\n}\nfunction urlHasSearchPath(url) {\n\treturn parseSearchPathFromUrl(url) !== void 0;\n}\nfunction resolveSearchPath(url, override) {\n\tconst explicit = override?.trim() || process.env.DATABASE_SEARCH_PATH?.trim();\n\tif (explicit) {\n\t\tprimarySearchPathSchema(explicit);\n\t\treturn explicit;\n\t}\n\treturn parseSearchPathFromUrl(url);\n}\n/** Ensures libpq sets search_path at connect time (avoids pool connect-handler races). */\nfunction appendSearchPathToUrl(url, searchPath) {\n\tif (urlHasSearchPath(url)) return url;\n\tprimarySearchPathSchema(searchPath);\n\tconst option = encodeURIComponent(`-c search_path=${searchPath}`);\n\treturn `${url}${url.includes(\"?\") ? \"&\" : \"?\"}options=${option}`;\n}\n//#endregion\n//#region src/connection/pg/index.ts\nfunction createPgConnection(options) {\n\tconst searchPath = resolveSearchPath(options.url, options.searchPath);\n\tconst pool = new Pool({\n\t\tconnectionString: options.url,\n\t\tmax: options.max ?? 10,\n\t\tconnectionTimeoutMillis: 5e3,\n\t\tidleTimeoutMillis: 3e4,\n\t\tkeepAlive: true\n\t});\n\treturn {\n\t\tdialect: \"postgres\",\n\t\tdb: createPgDb(pool),\n\t\tpool,\n\t\tsearchPath,\n\t\tclose: () => pool.end()\n\t};\n}\n//#endregion\n//#region src/connection/sqlite/configure.ts\n/** Pragmas for on-disk sqlite (WAL, FKs, busy timeout). No-op for `:memory:`. */\nfunction configureSqlite(client, path) {\n\tif (path === \":memory:\" || path.startsWith(\":memory:\")) {\n\t\tclient.pragma(\"foreign_keys = ON\");\n\t\treturn;\n\t}\n\tclient.pragma(\"journal_mode = WAL\");\n\tclient.pragma(\"synchronous = NORMAL\");\n\tclient.pragma(\"foreign_keys = ON\");\n\tclient.pragma(\"busy_timeout = 5000\");\n}\n//#endregion\n//#region src/connection/sqlite/resolve-path.ts\nfunction resolveSqlitePath(url) {\n\tif (url === \":memory:\" || url.startsWith(\":memory:\")) return url;\n\tif (url.startsWith(\"file:\")) return url.slice(5);\n\tif (url.startsWith(\"sqlite:\")) return url.slice(7);\n\treturn url;\n}\n//#endregion\n//#region src/connection/sqlite/index.ts\nfunction createSqliteConnection(options) {\n\tconst path = resolveSqlitePath(options.url);\n\tif (path !== \":memory:\" && !path.startsWith(\":memory:\")) mkdirSync(dirname(path), { recursive: true });\n\tconst client = new SqliteClient(path);\n\tconfigureSqlite(client, path);\n\treturn {\n\t\tdialect: \"sqlite\",\n\t\tdb: drizzle$1(client, { schema: pg_exports }),\n\t\tclose: () => client.close()\n\t};\n}\n//#endregion\n//#region src/connection/pg/cancel-channel.ts\n/** Postgres LISTEN/NOTIFY pub/sub for a single cancel channel (lowercase identifier, max 63 chars). */\nfunction createPostgresCancelChannel(connectionString, channel) {\n\treturn {\n\t\tasync publishCancel(runId) {\n\t\t\tconst client = new pg.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 pg.Client({ connectionString });\n\t\t\tawait client.connect();\n\t\t\tawait client.query(`LISTEN ${channel}`);\n\t\t\tconst onNotification = (message) => {\n\t\t\t\tif (message.payload) handler(message.payload);\n\t\t\t};\n\t\t\tclient.on(\"notification\", onNotification);\n\t\t\treturn async () => {\n\t\t\t\tclient.off(\"notification\", onNotification);\n\t\t\t\tawait client.query(`UNLISTEN ${channel}`);\n\t\t\t\tawait client.end();\n\t\t\t};\n\t\t}\n\t};\n}\n//#endregion\n//#region src/connection/index.ts\nfunction createConnection(options) {\n\tif (options.dialect === \"postgres\") return createPgConnection({\n\t\turl: options.url,\n\t\tmax: options.max,\n\t\tsearchPath: options.searchPath\n\t});\n\treturn createSqliteConnection({ url: options.url });\n}\n//#endregion\n//#region src/dialect/infer.ts\nfunction inferDialect(url, override) {\n\tif (override) return override;\n\tconst lower = url.toLowerCase();\n\tif (lower.startsWith(\"postgres://\") || lower.startsWith(\"postgresql://\")) return \"postgres\";\n\tif (lower.startsWith(\"file:\") || lower.startsWith(\"sqlite:\") || lower === \":memory:\" || lower.startsWith(\":memory:\")) return \"sqlite\";\n\tif (!url.includes(\"://\")) return \"sqlite\";\n\tthrow new Error(`Could not infer database dialect from DATABASE_URL. Set dialect explicitly (got: ${url})`);\n}\n//#endregion\n//#region src/client/pool-cache.ts\nconst MAX_CACHED_POOLS = 20;\nconst IDLE_EVICT_MS = 6e4;\nconst EVICT_INTERVAL_MS = 3e4;\nconst cache = /* @__PURE__ */ new Map();\nlet evictTimer;\nfunction cacheKey(url, searchPath, max) {\n\treturn `${url}\\0${searchPath ?? \"\"}\\0${max ?? \"\"}`;\n}\nfunction touch(entry) {\n\tentry.lastUsedAt = Date.now();\n}\nfunction ensureEvictTimer() {\n\tif (evictTimer) return;\n\tevictTimer = setInterval(() => {\n\t\tevictIdlePools();\n\t}, EVICT_INTERVAL_MS);\n\tevictTimer.unref?.();\n}\nasync function closeEntry(key, entry) {\n\tcache.delete(key);\n\tawait entry.handle.close();\n}\nasync function evictIdlePools() {\n\tconst now = Date.now();\n\tfor (const [key, entry] of cache) if (entry.refs === 0 && now - entry.lastUsedAt >= IDLE_EVICT_MS) await closeEntry(key, entry);\n}\nasync function evictLeastRecentlyUsedIdle() {\n\tlet oldestKey;\n\tlet oldestUsedAt = Number.POSITIVE_INFINITY;\n\tfor (const [key, entry] of cache) if (entry.refs === 0 && entry.lastUsedAt < oldestUsedAt) {\n\t\toldestKey = key;\n\t\toldestUsedAt = entry.lastUsedAt;\n\t}\n\tif (!oldestKey) return false;\n\tconst entry = cache.get(oldestKey);\n\tif (!entry) return false;\n\tawait closeEntry(oldestKey, entry);\n\treturn true;\n}\nasync function acquireProjectDatabasePool(options) {\n\tconst dialect = inferDialect(options.url);\n\tif (dialect !== \"postgres\") {\n\t\tconst searchPath = resolveSearchPath(options.url, options.searchPath);\n\t\treturn createConnection({\n\t\t\turl: options.url,\n\t\t\tdialect,\n\t\t\tmax: options.max,\n\t\t\tsearchPath\n\t\t});\n\t}\n\tconst searchPath = resolveSearchPath(options.url, options.searchPath);\n\tconst max = options.max ?? 5;\n\tconst key = cacheKey(options.url, searchPath, max);\n\tlet entry = cache.get(key);\n\tif (!entry) {\n\t\twhile (cache.size >= MAX_CACHED_POOLS) if (!await evictLeastRecentlyUsedIdle()) break;\n\t\tentry = {\n\t\t\thandle: createConnection({\n\t\t\t\turl: options.url,\n\t\t\t\tdialect,\n\t\t\t\tmax,\n\t\t\t\tsearchPath\n\t\t\t}),\n\t\t\trefs: 0,\n\t\t\tlastUsedAt: Date.now()\n\t\t};\n\t\tcache.set(key, entry);\n\t\tensureEvictTimer();\n\t}\n\tentry.refs += 1;\n\ttouch(entry);\n\treturn entry.handle;\n}\nfunction releaseProjectDatabasePool(options) {\n\tif (inferDialect(options.url) !== \"postgres\") return;\n\tconst searchPath = resolveSearchPath(options.url, options.searchPath);\n\tconst max = options.max ?? 5;\n\tconst key = cacheKey(options.url, searchPath, max);\n\tconst entry = cache.get(key);\n\tif (!entry) return;\n\tentry.refs = Math.max(0, entry.refs - 1);\n\ttouch(entry);\n}\nasync function closeAllProjectDatabasePools() {\n\tconst entries = [...cache.entries()];\n\tcache.clear();\n\tif (evictTimer) {\n\t\tclearInterval(evictTimer);\n\t\tevictTimer = void 0;\n\t}\n\tawait Promise.all(entries.map(([, entry]) => entry.handle.close()));\n}\n//#endregion\n//#region src/client/close.ts\nasync function closeDatabase() {\n\tif (getRequestDatabaseHandle()) throw new Error(\"closeDatabase() cannot be called inside runWithProjectDatabase()\");\n\tawait closeAllProjectDatabasePools();\n\tconst handle = getDefaultDatabaseHandle();\n\tif (!handle) return;\n\tawait handle.close();\n\tsetDatabaseHandle(void 0);\n}\n//#endregion\n//#region src/migrate/adapt-pg-migrations.ts\n/** Drizzle-kit emits REFERENCES \"public\".\"table\" — strip public so search_path applies. */\nfunction adaptPgMigrationsForSearchPath(migrations) {\n\treturn migrations.map((migration) => ({\n\t\t...migration,\n\t\tsql: migration.sql.map((statement) => statement.replace(/REFERENCES \"public\"\\./gi, \"REFERENCES \"))\n\t}));\n}\n//#endregion\n//#region src/migrate/load-migrations.ts\nfunction loadMigrations(migrationsFolder, embedded) {\n\tif (existsSync(join(migrationsFolder, \"meta\", \"_journal.json\"))) return readMigrationFiles({ migrationsFolder });\n\treturn embedded.map((migration) => ({\n\t\t...migration,\n\t\tsql: [...migration.sql]\n\t}));\n}\n//#endregion\n//#region src/migrate/migrate-pg.ts\nasync function migratePgDatabase(db, config, migrations) {\n\tconst migrator = db;\n\tawait migrator.dialect.migrate(migrations, migrator.session, config);\n}\n//#endregion\n//#region src/migrate/resolve-folder.ts\nfunction resolvePackageRoot() {\n\tlet dir = dirname(fileURLToPath(import.meta.url));\n\tfor (;;) {\n\t\tif (existsSync(join(dir, \"drizzle\", \"sqlite\", \"meta\", \"_journal.json\")) || existsSync(join(dir, \"drizzle\", \"pg\", \"meta\", \"_journal.json\"))) return dir;\n\t\tconst parent = dirname(dir);\n\t\tif (parent === dir) break;\n\t\tdir = parent;\n\t}\n\tthrow new Error(\"Could not resolve @keystrokehq/database package root for migrations\");\n}\nfunction fallbackFolder(...segments) {\n\treturn join(dirname(fileURLToPath(import.meta.url)), ...segments);\n}\nfunction resolveMigrationsFolder(dialect, override) {\n\tif (override) return override;\n\ttry {\n\t\treturn join(resolvePackageRoot(), \"drizzle\", dialect === \"postgres\" ? \"pg\" : \"sqlite\");\n\t} catch {\n\t\treturn fallbackFolder(\"drizzle\", dialect === \"postgres\" ? \"pg\" : \"sqlite\");\n\t}\n}\n//#endregion\n//#region src/migrate/migrations.pg.generated.ts\nconst pgMigrations = [\n\t{\n\t\t\"sql\": [\n\t\t\t\"CREATE TABLE \\\"agent_events\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"session_id\\\" text NOT NULL,\\n\t\\\"seq\\\" integer NOT NULL,\\n\t\\\"event_type\\\" text NOT NULL,\\n\t\\\"payload\\\" jsonb NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"deleted_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"agent_sessions\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"agent_id\\\" text NOT NULL,\\n\t\\\"source_kind\\\" text DEFAULT 'api' NOT NULL,\\n\t\\\"source_id\\\" text,\\n\t\\\"parent_span_id\\\" text,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"deleted_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"agents\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"name\\\" text,\\n\t\\\"description\\\" text,\\n\t\\\"route\\\" text NOT NULL,\\n\t\\\"module_file\\\" text NOT NULL,\\n\t\\\"model\\\" text NOT NULL,\\n\t\\\"system_prompt\\\" text NOT NULL,\\n\t\\\"tool_count\\\" integer,\\n\t\\\"credential_count\\\" integer,\\n\t\\\"registered_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"deleted_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"credential_instances\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"scope_type\\\" text NOT NULL,\\n\t\\\"scope_id\\\" text,\\n\t\\\"label\\\" text,\\n\t\\\"is_default\\\" integer NOT NULL,\\n\t\\\"auth_kind\\\" text NOT NULL,\\n\t\\\"ciphertext\\\" text,\\n\t\\\"connection_id\\\" text,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"gateway_attachments\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"agent_slug\\\" text NOT NULL,\\n\t\\\"module_file\\\" text,\\n\t\\\"platform\\\" text NOT NULL,\\n\t\\\"team_id\\\" text,\\n\t\\\"channel_id\\\" text NOT NULL,\\n\t\\\"source\\\" jsonb NOT NULL,\\n\t\\\"registered_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"deleted_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"gateway_thread_sessions\\\" (\\n\t\\\"thread_id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"agent_id\\\" text NOT NULL,\\n\t\\\"session_id\\\" text NOT NULL,\\n\t\\\"attachment_id\\\" text NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"jobs\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"kind\\\" text NOT NULL,\\n\t\\\"target_id\\\" text NOT NULL,\\n\t\\\"run_id\\\" text NOT NULL,\\n\t\\\"trigger\\\" text NOT NULL,\\n\t\\\"payload\\\" jsonb,\\n\t\\\"status\\\" text NOT NULL,\\n\t\\\"scheduled_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"attempt\\\" integer NOT NULL,\\n\t\\\"max_attempts\\\" integer NOT NULL,\\n\t\\\"leased_by\\\" text,\\n\t\\\"lease_expires_at\\\" timestamp with time zone,\\n\t\\\"completed_at\\\" timestamp with time zone,\\n\t\\\"error\\\" jsonb\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"oauth_apps\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"provider\\\" text NOT NULL,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"token_strategy\\\" text NOT NULL,\\n\t\\\"client_id_ciphertext\\\" text NOT NULL,\\n\t\\\"client_secret_ciphertext\\\" text NOT NULL,\\n\t\\\"signing_secret_ciphertext\\\" text,\\n\t\\\"redirect_uri\\\" text,\\n\t\\\"metadata\\\" jsonb,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"oauth_connections\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"app_id\\\" text NOT NULL,\\n\t\\\"external_id\\\" text NOT NULL,\\n\t\\\"access_token_ciphertext\\\" text NOT NULL,\\n\t\\\"refresh_token_ciphertext\\\" text,\\n\t\\\"access_token_expires_at\\\" timestamp with time zone,\\n\t\\\"granted_scopes\\\" jsonb,\\n\t\\\"metadata\\\" jsonb,\\n\t\\\"connected_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"resource_activity\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"user_id\\\" text NOT NULL,\\n\t\\\"resource_kind\\\" text NOT NULL,\\n\t\\\"resource_id\\\" text NOT NULL,\\n\t\\\"last_opened_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"secret_values\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"ref_kind\\\" text NOT NULL,\\n\t\\\"ref_id\\\" text NOT NULL,\\n\t\\\"field\\\" text NOT NULL,\\n\t\\\"ciphertext\\\" text NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"skills\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"name\\\" text,\\n\t\\\"description\\\" text,\\n\t\\\"module_file\\\" text NOT NULL,\\n\t\\\"registered_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"deleted_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"trace_logs\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"trace_id\\\" text NOT NULL,\\n\t\\\"span_id\\\" text NOT NULL,\\n\t\\\"seq\\\" integer NOT NULL,\\n\t\\\"level\\\" text NOT NULL,\\n\t\\\"message\\\" text NOT NULL,\\n\t\\\"data\\\" jsonb,\\n\t\\\"source\\\" text NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"trace_spans\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"trace_id\\\" text NOT NULL,\\n\t\\\"parent_span_id\\\" text,\\n\t\\\"kind\\\" text NOT NULL,\\n\t\\\"ref_id\\\" text NOT NULL,\\n\t\\\"name\\\" text NOT NULL,\\n\t\\\"status\\\" text NOT NULL,\\n\t\\\"started_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"finished_at\\\" timestamp with time zone,\\n\t\\\"metadata\\\" jsonb,\\n\t\\\"error\\\" jsonb\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"trigger_attachments\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"target_kind\\\" text DEFAULT 'workflow' NOT NULL,\\n\t\\\"workflow_slug\\\" text,\\n\t\\\"agent_slug\\\" text,\\n\t\\\"module_file\\\" text NOT NULL,\\n\t\\\"source\\\" jsonb NOT NULL,\\n\t\\\"origin\\\" text DEFAULT 'project' NOT NULL,\\n\t\\\"prompt\\\" text,\\n\t\\\"lifecycle\\\" jsonb,\\n\t\\\"created_by_session_id\\\" text,\\n\t\\\"registered_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"deleted_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"trigger_runs\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"attachment_id\\\" text NOT NULL,\\n\t\\\"source_path\\\" text,\\n\t\\\"trigger_type\\\" text NOT NULL,\\n\t\\\"payload\\\" jsonb,\\n\t\\\"triggered_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"trigger_schedules\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"attachment_slug\\\" text NOT NULL,\\n\t\\\"kind\\\" text NOT NULL,\\n\t\\\"schedule\\\" text NOT NULL,\\n\t\\\"next_run_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"enabled\\\" integer NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"workflow_events\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"run_id\\\" text NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"seq\\\" integer NOT NULL,\\n\t\\\"type\\\" text NOT NULL,\\n\t\\\"correlation_id\\\" text,\\n\t\\\"data\\\" jsonb,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"workflow_hooks\\\" (\\n\t\\\"hook_id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"run_id\\\" text NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"token\\\" text NOT NULL,\\n\t\\\"correlation_id\\\" text NOT NULL,\\n\t\\\"status\\\" text NOT NULL,\\n\t\\\"payload\\\" jsonb,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"resumed_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"workflow_runs\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"workflow_slug\\\" text NOT NULL,\\n\t\\\"attachment_id\\\" text,\\n\t\\\"subscription_id\\\" text,\\n\t\\\"trigger_run_id\\\" text,\\n\t\\\"parent_workflow_run_id\\\" text,\\n\t\\\"parent_span_id\\\" text,\\n\t\\\"source_kind\\\" text DEFAULT 'api' NOT NULL,\\n\t\\\"source_id\\\" text,\\n\t\\\"status\\\" text NOT NULL,\\n\t\\\"trigger\\\" text NOT NULL,\\n\t\\\"triggered_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"started_at\\\" timestamp with time zone,\\n\t\\\"finished_at\\\" timestamp with time zone,\\n\t\\\"input\\\" jsonb,\\n\t\\\"output\\\" jsonb,\\n\t\\\"error\\\" jsonb\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"workflow_subscriptions\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"workflow_slug\\\" text NOT NULL,\\n\t\\\"user_id\\\" text NOT NULL,\\n\t\\\"enabled\\\" integer NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"workflows\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"name\\\" text,\\n\t\\\"description\\\" text,\\n\t\\\"module_file\\\" text NOT NULL,\\n\t\\\"subscribable\\\" integer NOT NULL,\\n\t\\\"registered_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"deleted_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nALTER TABLE \\\"agent_events\\\" ADD CONSTRAINT \\\"agent_events_session_id_agent_sessions_id_fk\\\" FOREIGN KEY (\\\"session_id\\\") REFERENCES \\\"public\\\".\\\"agent_sessions\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"agent_sessions\\\" ADD CONSTRAINT \\\"agent_sessions_agent_id_agents_id_fk\\\" FOREIGN KEY (\\\"agent_id\\\") REFERENCES \\\"public\\\".\\\"agents\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"gateway_thread_sessions\\\" ADD CONSTRAINT \\\"gateway_thread_sessions_agent_id_agents_id_fk\\\" FOREIGN KEY (\\\"agent_id\\\") REFERENCES \\\"public\\\".\\\"agents\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"gateway_thread_sessions\\\" ADD CONSTRAINT \\\"gateway_thread_sessions_session_id_agent_sessions_id_fk\\\" FOREIGN KEY (\\\"session_id\\\") REFERENCES \\\"public\\\".\\\"agent_sessions\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"gateway_thread_sessions\\\" ADD CONSTRAINT \\\"gateway_thread_sessions_attachment_id_gateway_attachments_id_fk\\\" FOREIGN KEY (\\\"attachment_id\\\") REFERENCES \\\"public\\\".\\\"gateway_attachments\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"oauth_connections\\\" ADD CONSTRAINT \\\"oauth_connections_app_id_oauth_apps_id_fk\\\" FOREIGN KEY (\\\"app_id\\\") REFERENCES \\\"public\\\".\\\"oauth_apps\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"trace_logs\\\" ADD CONSTRAINT \\\"trace_logs_span_id_trace_spans_id_fk\\\" FOREIGN KEY (\\\"span_id\\\") REFERENCES \\\"public\\\".\\\"trace_spans\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"trigger_runs\\\" ADD CONSTRAINT \\\"trigger_runs_attachment_id_trigger_attachments_id_fk\\\" FOREIGN KEY (\\\"attachment_id\\\") REFERENCES \\\"public\\\".\\\"trigger_attachments\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"workflow_events\\\" ADD CONSTRAINT \\\"workflow_events_run_id_workflow_runs_id_fk\\\" FOREIGN KEY (\\\"run_id\\\") REFERENCES \\\"public\\\".\\\"workflow_runs\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"workflow_hooks\\\" ADD CONSTRAINT \\\"workflow_hooks_run_id_workflow_runs_id_fk\\\" FOREIGN KEY (\\\"run_id\\\") REFERENCES \\\"public\\\".\\\"workflow_runs\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"workflow_runs\\\" ADD CONSTRAINT \\\"workflow_runs_attachment_id_trigger_attachments_id_fk\\\" FOREIGN KEY (\\\"attachment_id\\\") REFERENCES \\\"public\\\".\\\"trigger_attachments\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"workflow_runs\\\" ADD CONSTRAINT \\\"workflow_runs_subscription_id_workflow_subscriptions_id_fk\\\" FOREIGN KEY (\\\"subscription_id\\\") REFERENCES \\\"public\\\".\\\"workflow_subscriptions\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"workflow_runs\\\" ADD CONSTRAINT \\\"workflow_runs_trigger_run_id_trigger_runs_id_fk\\\" FOREIGN KEY (\\\"trigger_run_id\\\") REFERENCES \\\"public\\\".\\\"trigger_runs\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nCREATE INDEX \\\"agent_sessions_agent_updated_idx\\\" ON \\\"agent_sessions\\\" USING btree (\\\"agent_id\\\",\\\"updated_at\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"agents_project_id_slug_idx\\\" ON \\\"agents\\\" USING btree (\\\"project_id\\\",\\\"slug\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"agents_project_id_route_idx\\\" ON \\\"agents\\\" USING btree (\\\"project_id\\\",\\\"route\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"credential_instances_project_slug_scope_label_unique\\\" ON \\\"credential_instances\\\" USING btree (\\\"project_id\\\",\\\"slug\\\",\\\"scope_type\\\",\\\"scope_id\\\",\\\"label\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"credential_instances_project_slug_scope_idx\\\" ON \\\"credential_instances\\\" USING btree (\\\"project_id\\\",\\\"slug\\\",\\\"scope_type\\\",\\\"scope_id\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"gateway_attachments_project_id_slug_idx\\\" ON \\\"gateway_attachments\\\" USING btree (\\\"project_id\\\",\\\"slug\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"gateway_attachments_project_platform_channel_active\\\" ON \\\"gateway_attachments\\\" USING btree (\\\"project_id\\\",\\\"platform\\\",\\\"channel_id\\\") WHERE \\\"gateway_attachments\\\".\\\"deleted_at\\\" is null;\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"oauth_apps_project_id_slug_idx\\\" ON \\\"oauth_apps\\\" USING btree (\\\"project_id\\\",\\\"slug\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"oauth_connections_app_external_unique\\\" ON \\\"oauth_connections\\\" USING btree (\\\"app_id\\\",\\\"external_id\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"resource_activity_project_user_kind_resource\\\" ON \\\"resource_activity\\\" USING btree (\\\"project_id\\\",\\\"user_id\\\",\\\"resource_kind\\\",\\\"resource_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"resource_activity_user_last_opened_at\\\" ON \\\"resource_activity\\\" USING btree (\\\"user_id\\\",\\\"last_opened_at\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"secret_values_ref_unique\\\" ON \\\"secret_values\\\" USING btree (\\\"project_id\\\",\\\"ref_kind\\\",\\\"ref_id\\\",\\\"field\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"secret_values_ref_idx\\\" ON \\\"secret_values\\\" USING btree (\\\"project_id\\\",\\\"ref_kind\\\",\\\"ref_id\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"skills_project_id_slug_idx\\\" ON \\\"skills\\\" USING btree (\\\"project_id\\\",\\\"slug\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"trace_logs_trace_id_seq_idx\\\" ON \\\"trace_logs\\\" USING btree (\\\"trace_id\\\",\\\"seq\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"trace_logs_span_id_seq_idx\\\" ON \\\"trace_logs\\\" USING btree (\\\"span_id\\\",\\\"seq\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"trigger_attachments_project_id_slug_idx\\\" ON \\\"trigger_attachments\\\" USING btree (\\\"project_id\\\",\\\"slug\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"trigger_schedules_project_id_attachment_slug_idx\\\" ON \\\"trigger_schedules\\\" USING btree (\\\"project_id\\\",\\\"attachment_slug\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"trigger_schedules_next_run_at_idx\\\" ON \\\"trigger_schedules\\\" USING btree (\\\"next_run_at\\\",\\\"enabled\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"workflow_events_run_id_seq_unique\\\" ON \\\"workflow_events\\\" USING btree (\\\"run_id\\\",\\\"seq\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"workflow_events_run_id_type_idx\\\" ON \\\"workflow_events\\\" USING btree (\\\"run_id\\\",\\\"type\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"workflow_events_correlation_id_idx\\\" ON \\\"workflow_events\\\" USING btree (\\\"correlation_id\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"workflow_hooks_token_unique\\\" ON \\\"workflow_hooks\\\" USING btree (\\\"token\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"workflow_hooks_run_id_idx\\\" ON \\\"workflow_hooks\\\" USING btree (\\\"run_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"workflow_runs_project_workflow_triggered_idx\\\" ON \\\"workflow_runs\\\" USING btree (\\\"project_id\\\",\\\"workflow_slug\\\",\\\"triggered_at\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"workflow_subscriptions_project_workflow_user\\\" ON \\\"workflow_subscriptions\\\" USING btree (\\\"project_id\\\",\\\"workflow_slug\\\",\\\"user_id\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"workflows_project_id_slug_idx\\\" ON \\\"workflows\\\" USING btree (\\\"project_id\\\",\\\"slug\\\");\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1781213647873,\n\t\t\"hash\": \"03d99ea3c47d7b7f9a3b73a9b767c82a29394e5b2c53868e55061bf0bed93e0b\"\n\t},\n\t{\n\t\t\"sql\": [\"ALTER TABLE \\\"agent_sessions\\\" ADD COLUMN \\\"ran_by_user_id\\\" text;\", \"\\nALTER TABLE \\\"workflow_runs\\\" ADD COLUMN \\\"ran_by_user_id\\\" text;\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1781243850513,\n\t\t\"hash\": \"3f3eb52271a724ca488bfd6b2aba9095265455c55dee2a5d76d16c8698801906\"\n\t},\n\t{\n\t\t\"sql\": [\"ALTER TABLE \\\"agent_sessions\\\" ADD COLUMN \\\"canceled_at\\\" timestamp with time zone;\\n\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 17813e8,\n\t\t\"hash\": \"3dbe010bde8652bd58886b33d5d8c449e7213ef66a6235c365598dc978802d71\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"CREATE TABLE \\\"agent_runs\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"session_id\\\" text NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"agent_id\\\" text NOT NULL,\\n\t\\\"run_index\\\" integer NOT NULL,\\n\t\\\"source_kind\\\" text DEFAULT 'api' NOT NULL,\\n\t\\\"source_id\\\" text,\\n\t\\\"ran_by_user_id\\\" text,\\n\t\\\"status\\\" text NOT NULL,\\n\t\\\"error\\\" jsonb,\\n\t\\\"started_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"finished_at\\\" timestamp with time zone,\\n\t\\\"total_cost_usd\\\" double precision,\\n\t\\\"total_tokens\\\" integer,\\n\t\\\"models_used\\\" jsonb,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"deleted_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"usage_records\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"run_id\\\" text NOT NULL,\\n\t\\\"run_kind\\\" text NOT NULL,\\n\t\\\"kind\\\" text NOT NULL,\\n\t\\\"label\\\" text NOT NULL,\\n\t\\\"quantity\\\" integer,\\n\t\\\"unit\\\" text,\\n\t\\\"amount\\\" double precision NOT NULL,\\n\t\\\"metadata\\\" jsonb,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nALTER TABLE \\\"agent_events\\\" ADD COLUMN \\\"run_id\\\" text;\",\n\t\t\t\"\\nALTER TABLE \\\"agent_runs\\\" ADD CONSTRAINT \\\"agent_runs_session_id_agent_sessions_id_fk\\\" FOREIGN KEY (\\\"session_id\\\") REFERENCES \\\"public\\\".\\\"agent_sessions\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"agent_runs\\\" ADD CONSTRAINT \\\"agent_runs_agent_id_agents_id_fk\\\" FOREIGN KEY (\\\"agent_id\\\") REFERENCES \\\"public\\\".\\\"agents\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\",\n\t\t\t\"\\nCREATE INDEX \\\"agent_runs_session_run_index_idx\\\" ON \\\"agent_runs\\\" USING btree (\\\"session_id\\\",\\\"run_index\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"agent_runs_agent_started_idx\\\" ON \\\"agent_runs\\\" USING btree (\\\"agent_id\\\",\\\"started_at\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"agent_runs_project_started_idx\\\" ON \\\"agent_runs\\\" USING btree (\\\"project_id\\\",\\\"started_at\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"usage_records_run_run_kind_idx\\\" ON \\\"usage_records\\\" USING btree (\\\"run_id\\\",\\\"run_kind\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"usage_records_kind_idx\\\" ON \\\"usage_records\\\" USING btree (\\\"kind\\\");\",\n\t\t\t\"\\nALTER TABLE \\\"agent_events\\\" ADD CONSTRAINT \\\"agent_events_run_id_agent_runs_id_fk\\\" FOREIGN KEY (\\\"run_id\\\") REFERENCES \\\"public\\\".\\\"agent_runs\\\"(\\\"id\\\") ON DELETE no action ON UPDATE no action;\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1781568153484,\n\t\t\"hash\": \"e40c228590351e229ed0fb39e8e3045e2b68368363675b2f147a694c6437a80e\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"ALTER TABLE IF EXISTS \\\"agent_runs\\\" DISABLE ROW LEVEL SECURITY;\",\n\t\t\t\"\\nDROP TABLE IF EXISTS \\\"agent_runs\\\" CASCADE;\",\n\t\t\t\"\\nALTER TABLE \\\"agent_sessions\\\" ADD COLUMN IF NOT EXISTS \\\"total_duration_ms\\\" integer DEFAULT 0 NOT NULL;\",\n\t\t\t\"\\nALTER TABLE \\\"agent_events\\\" DROP COLUMN IF EXISTS \\\"run_id\\\";\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1781630388181,\n\t\t\"hash\": \"b995f6f4e5f1147c20ea90cd26877d7154ff1b1625adba277507268c2a8c35f6\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"DROP TABLE \\\"oauth_apps\\\" CASCADE;\",\n\t\t\t\"\\nDROP TABLE \\\"oauth_connections\\\" CASCADE;\",\n\t\t\t\"\\nDROP TABLE \\\"secret_values\\\" CASCADE;\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1781941661795,\n\t\t\"hash\": \"3816998a2a2c7ead79cacfb64281fd415220473dee9512192b05b8cb57516f74\"\n\t},\n\t{\n\t\t\"sql\": [\"ALTER TABLE \\\"credential_instances\\\" ADD COLUMN \\\"shared_connection_id\\\" text;\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1782243320892,\n\t\t\"hash\": \"ec36b70bcd148a39ac4f55789348aee32315070e7d8b75aff61a9cee1d245721\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"ALTER TABLE \\\"agent_sessions\\\" ADD COLUMN \\\"title\\\" text;\",\n\t\t\t\"\\nALTER TABLE \\\"agent_sessions\\\" ADD COLUMN \\\"live_message\\\" jsonb;\",\n\t\t\t\"\\nALTER TABLE \\\"agents\\\" ADD COLUMN \\\"credential_keys\\\" jsonb;\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1782280074442,\n\t\t\"hash\": \"6174d3625965c6921bc20d51f67cc841b3e96b0d1c3777508a6969a2f2622f25\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"ALTER TABLE \\\"agents\\\" RENAME COLUMN \\\"credential_keys\\\" TO \\\"app_slugs\\\";\",\n\t\t\t\"\\nCREATE TABLE \\\"credential_assignments\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"target_type\\\" text NOT NULL,\\n\t\\\"target_key\\\" text NOT NULL,\\n\t\\\"consumer_id\\\" text NOT NULL,\\n\t\\\"credential_slug\\\" text NOT NULL,\\n\t\\\"instance_id\\\" text NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"credential_assignments_project_target_consumer_slug\\\" ON \\\"credential_assignments\\\" USING btree (\\\"project_id\\\",\\\"target_type\\\",\\\"target_key\\\",\\\"consumer_id\\\",\\\"credential_slug\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"credential_assignments_project_target_idx\\\" ON \\\"credential_assignments\\\" USING btree (\\\"project_id\\\",\\\"target_type\\\",\\\"target_key\\\");\",\n\t\t\t\"\\nALTER TABLE \\\"credential_instances\\\" RENAME COLUMN \\\"slug\\\" TO \\\"app_slug\\\";\",\n\t\t\t\"\\nALTER TABLE \\\"credential_instances\\\" ADD COLUMN \\\"slug\\\" text;\",\n\t\t\t\"\\nALTER TABLE \\\"credential_instances\\\" ADD COLUMN \\\"name\\\" text;\",\n\t\t\t\"\\nUPDATE \\\"credential_instances\\\" SET \\\"name\\\" = \\\"label\\\";\",\n\t\t\t\"\\nUPDATE \\\"credential_instances\\\" SET \\\"slug\\\" = CASE WHEN \\\"is_default\\\" = 1 THEN \\\"app_slug\\\" ELSE \\\"app_slug\\\" || '-' || substr(\\\"id\\\", 1, 8) END;\",\n\t\t\t\"\\nALTER TABLE \\\"credential_instances\\\" ALTER COLUMN \\\"slug\\\" SET NOT NULL;\",\n\t\t\t\"\\nDROP INDEX \\\"credential_instances_project_slug_scope_label_unique\\\";\",\n\t\t\t\"\\nDROP INDEX \\\"credential_instances_project_slug_scope_idx\\\";\",\n\t\t\t\"\\nCREATE INDEX \\\"credential_instances_project_app_slug_scope_idx\\\" ON \\\"credential_instances\\\" USING btree (\\\"project_id\\\",\\\"app_slug\\\",\\\"scope_type\\\",\\\"scope_id\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"credential_instances_project_scope_slug_unique\\\" ON \\\"credential_instances\\\" USING btree (\\\"project_id\\\",\\\"scope_type\\\",\\\"scope_id\\\",\\\"slug\\\");\\n\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 17826e8,\n\t\t\"hash\": \"ee310c8ce64fdc1b17cff8f138fee267eb1b1676262e58dae6e4c7e505295b4a\"\n\t}\n];\n//#endregion\n//#region src/migrate/run.ts\nasync function runMigrations(handle, migrationsFolder) {\n\tif (handle.dialect === \"postgres\") {\n\t\tconst config = {\n\t\t\tmigrationsFolder,\n\t\t\tmigrationsSchema: resolveMigrationsSchema(handle.searchPath)\n\t\t};\n\t\tconst loaded = loadMigrations(migrationsFolder, pgMigrations);\n\t\tconst migrations = handle.searchPath ? adaptPgMigrationsForSearchPath(loaded) : loaded;\n\t\tawait migratePgDatabase(handle.db, config, migrations);\n\t\treturn;\n\t}\n\tmigrate(handle.db, { migrationsFolder });\n}\n//#endregion\n//#region src/client/init.ts\nfunction resolveUrl(url) {\n\tif (url) return url;\n\tconst envUrl = process.env.DATABASE_URL?.trim();\n\tif (envUrl && inferDialect(envUrl) === \"sqlite\") return envUrl;\n\treturn resolveProjectDatabaseUrlFromEnv(process.env) ?? \"file:./data/dev.db\";\n}\nasync function initDatabase(options = {}) {\n\tif (isDatabaseInitialized()) return;\n\tconst url = resolveUrl(options.url);\n\tconst dialect = inferDialect(url, options.dialect);\n\tconst searchPath = resolveSearchPath(url, options.searchPath);\n\tconst next = createConnection({\n\t\turl,\n\t\tdialect,\n\t\tmax: options.max,\n\t\tsearchPath\n\t});\n\tsetDatabaseHandle(next);\n\tif (options.migrate ?? true) await runMigrations(next, resolveMigrationsFolder(dialect, options.migrationsFolder));\n}\n//#endregion\n//#region src/client/project-database.ts\n/** Bind a Postgres handle for the org's shared runtime schema (all projects in the org). */\nasync function runWithProjectDatabase(options, fn) {\n\tconst poolOptions = {\n\t\turl: options.url,\n\t\tsearchPath: options.searchPath,\n\t\tmax: options.max\n\t};\n\tconst handle = await acquireProjectDatabasePool(poolOptions);\n\tconst closeOnRelease = inferDialect(options.url) !== \"postgres\";\n\treturn runWithRequestDatabaseHandle(handle, async () => {\n\t\ttry {\n\t\t\treturn await fn();\n\t\t} finally {\n\t\t\tif (closeOnRelease) await handle.close();\n\t\t\telse releaseProjectDatabasePool(poolOptions);\n\t\t}\n\t});\n}\n//#endregion\n//#region src/queries/_internal.ts\n/** Internal: only `queries/**` may call this. */\nfunction getDb() {\n\treturn getDbFromContext();\n}\n//#endregion\n//#region src/queries/agents/list-active.ts\n/**\n* List every active agent in the bound org schema (all projects). Not project\n* scoped — the org database schema is itself the tenant boundary.\n*/\nasync function listActiveAgents(options) {\n\tconst db = getDb();\n\tif (options?.projectIds !== void 0 && options.projectIds.length === 0) return [];\n\tconst conditions = [isNull(agents.deletedAt)];\n\tif (options?.projectIds !== void 0) conditions.push(inArray$1(agents.projectId, options.projectIds));\n\treturn db.select().from(agents).where(and$1(...conditions)).orderBy(desc(agents.updatedAt));\n}\n//#endregion\n//#region src/queries/_internal/project-scope.ts\nfunction eqProjectScope(table) {\n\treturn eq$1(table.projectId, getProjectScopeId());\n}\nfunction scopedAnd(table, ...conditions) {\n\treturn and$1(eqProjectScope(table), ...conditions);\n}\nfunction projectScopeId() {\n\treturn getProjectScopeId();\n}\n/** Use with left joins on workflowRuns/triggerRuns/agentSessions keyed by trace or ref id. */\nfunction traceRootProjectScopeFilter() {\n\treturn or(eq$1(workflowRuns.projectId, getProjectScopeId()), eq$1(triggerRuns.projectId, getProjectScopeId()), eq$1(agentSessions.projectId, getProjectScopeId()));\n}\n//#endregion\n//#region src/queries/agents/select.ts\nasync function selectAgentBySlug(slug) {\n\treturn (await getDb().select().from(agents).where(scopedAnd(agents, eq$1(agents.slug, slug))).limit(1))[0];\n}\nasync function selectActiveAgentByRoute(route) {\n\treturn (await getDb().select({\n\t\tid: agents.id,\n\t\tslug: agents.slug\n\t}).from(agents).where(scopedAnd(agents, eq$1(agents.route, route), isNull(agents.deletedAt))).limit(1))[0];\n}\n/** Fetch active agents by id from the bound org schema (all projects). */\nasync function selectActiveAgentsByIds(ids) {\n\tif (ids.length === 0) return [];\n\treturn getDb().select().from(agents).where(and$1(inArray$1(agents.id, ids), isNull(agents.deletedAt)));\n}\n/** Fetch a single active agent by id from the bound org schema (all projects). */\nasync function selectActiveAgentById(id) {\n\treturn (await getDb().select().from(agents).where(and$1(eq$1(agents.id, id), isNull(agents.deletedAt))).limit(1))[0];\n}\n//#endregion\n//#region src/queries/agents/resolve-project-id.ts\n/** The agent row is the source of truth for which project it belongs to. */\nasync function resolveAgentProjectId(agentId) {\n\tconst agent = await selectActiveAgentById(agentId);\n\tif (!agent) throw new Error(`Agent not found: ${agentId}`);\n\treturn agent.projectId;\n}\n//#endregion\n//#region src/queries/agents/write.ts\nasync function insertAgent(values) {\n\tawait getDb().insert(agents).values({\n\t\t...values,\n\t\tprojectId: projectScopeId()\n\t});\n}\nasync function updateAgentById(id, values) {\n\tawait getDb().update(agents).set(values).where(scopedAnd(agents, eq$1(agents.id, id)));\n}\nasync function softDeleteAllAgents(now) {\n\tawait getDb().update(agents).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(agents, isNull(agents.deletedAt)));\n}\nasync function softDeleteAgentsNotInSlugs(slugs, now) {\n\tawait getDb().update(agents).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(agents, isNull(agents.deletedAt), notInArray(agents.slug, slugs)));\n}\n//#endregion\n//#region src/agents/cursor.ts\nfunction encodeAgentSessionCursor(cursor) {\n\treturn Buffer.from(JSON.stringify({\n\t\tupdatedAt: cursor.updatedAt.toISOString(),\n\t\tid: cursor.id\n\t})).toString(\"base64url\");\n}\nfunction decodeAgentSessionCursor(value) {\n\ttry {\n\t\tconst parsed = JSON.parse(Buffer.from(value, \"base64url\").toString(\"utf8\"));\n\t\tif (typeof parsed.updatedAt !== \"string\" || typeof parsed.id !== \"string\") return null;\n\t\tconst updatedAt = new Date(parsed.updatedAt);\n\t\tif (Number.isNaN(updatedAt.getTime())) return null;\n\t\treturn {\n\t\t\tupdatedAt,\n\t\t\tid: parsed.id\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\n//#endregion\n//#region src/queries/agent-sessions/index.ts\nasync function insertAgentSession(values) {\n\tawait getDb().insert(agentSessions).values({\n\t\t...values,\n\t\tsourceKind: values.sourceKind ?? \"api\",\n\t\tsourceId: values.sourceId ?? null,\n\t\tranByUserId: values.ranByUserId ?? null,\n\t\tprojectId: projectScopeId()\n\t});\n}\nasync function selectActiveAgentSession(sessionId) {\n\treturn (await getDb().select().from(agentSessions).where(scopedAnd(agentSessions, eq$1(agentSessions.id, sessionId), isNull(agentSessions.deletedAt))).limit(1))[0];\n}\nasync function selectAgentSessionById(sessionId) {\n\treturn selectActiveAgentSession(sessionId);\n}\nasync function listAgentSessionsBySourceIds(options) {\n\tif (options.sourceIds.length === 0) return /* @__PURE__ */ new Map();\n\tconst rows = await getDb().select().from(agentSessions).where(scopedAnd(agentSessions, eq$1(agentSessions.sourceKind, options.sourceKind), inArray$1(agentSessions.sourceId, options.sourceIds), isNull(agentSessions.deletedAt)));\n\tconst bySourceId = /* @__PURE__ */ new Map();\n\tfor (const row of rows) if (row.sourceId) bySourceId.set(row.sourceId, row);\n\treturn bySourceId;\n}\nasync function selectAgentSessionForAgent(agentSlug, sessionId) {\n\treturn (await getDb().select({ session: agentSessions }).from(agentSessions).innerJoin(agents, eq$1(agents.id, agentSessions.agentId)).where(and$1(eq$1(agents.slug, agentSlug), eq$1(agents.projectId, projectScopeId()), eq$1(agentSessions.id, sessionId), isNull(agentSessions.deletedAt))).limit(1))[0]?.session;\n}\nasync function touchAgentSession(sessionId, updatedAt) {\n\tawait getDb().update(agentSessions).set({ updatedAt }).where(scopedAnd(agentSessions, eq$1(agentSessions.id, sessionId), isNull(agentSessions.deletedAt)));\n}\nasync function updateAgentSessionTitle(sessionId, title) {\n\tawait getDb().update(agentSessions).set({ title }).where(scopedAnd(agentSessions, eq$1(agentSessions.id, sessionId), isNull(agentSessions.deletedAt)));\n}\nasync function addAgentSessionDuration(sessionId, deltaMs) {\n\tif (deltaMs <= 0) return;\n\tawait getDb().update(agentSessions).set({ totalDurationMs: sql$1`${agentSessions.totalDurationMs} + ${deltaMs}` }).where(scopedAnd(agentSessions, eq$1(agentSessions.id, sessionId), isNull(agentSessions.deletedAt)));\n}\nfunction cursorBefore$2(cursor) {\n\treturn or(lt(agentSessions.updatedAt, cursor.updatedAt), and$1(eq$1(agentSessions.updatedAt, cursor.updatedAt), lt(agentSessions.id, cursor.id)));\n}\nasync function listAgentSessionRowsPaginated(options) {\n\tconst db = getDb();\n\tconst conditions = [\n\t\teq$1(agents.slug, options.agentSlug),\n\t\teq$1(agents.projectId, projectScopeId()),\n\t\tisNull(agentSessions.deletedAt)\n\t];\n\tif (options.source) conditions.push(eq$1(agentSessions.sourceKind, options.source));\n\tif (options.cursor) {\n\t\tconst decoded = decodeAgentSessionCursor(options.cursor);\n\t\tif (!decoded) throw new Error(\"Invalid cursor\");\n\t\tconditions.push(cursorBefore$2(decoded));\n\t}\n\tconst limit = options.limit + 1;\n\tconst sessions = (await db.select({ session: agentSessions }).from(agentSessions).innerJoin(agents, eq$1(agents.id, agentSessions.agentId)).where(and$1(...conditions)).orderBy(desc(agentSessions.updatedAt), desc(agentSessions.id)).limit(limit)).map((row) => row.session);\n\tconst hasMore = sessions.length > options.limit;\n\tconst page = hasMore ? sessions.slice(0, options.limit) : sessions;\n\tconst last = page.at(-1);\n\treturn {\n\t\trows: page,\n\t\tnextCursor: hasMore && last ? encodeAgentSessionCursor({\n\t\t\tupdatedAt: last.updatedAt,\n\t\t\tid: last.id\n\t\t}) : null\n\t};\n}\nasync function cancelAgentSessionRow(sessionId, canceledAt) {\n\treturn (await getDb().update(agentSessions).set({\n\t\tcanceledAt,\n\t\tupdatedAt: canceledAt\n\t}).where(scopedAnd(agentSessions, eq$1(agentSessions.id, sessionId), isNull(agentSessions.deletedAt), isNull(agentSessions.canceledAt))).returning())[0];\n}\n/**\n* Reactivates a session for a new run by clearing a prior cancellation. Cancellation\n* is per-run: a session is a multi-turn conversation, so a new prompt must not be blocked\n* (or perpetually shown as \"canceled\") just because an earlier turn was canceled. No-ops\n* when the session was not canceled.\n*/\nasync function clearAgentSessionCancellation(sessionId) {\n\tawait getDb().update(agentSessions).set({ canceledAt: null }).where(scopedAnd(agentSessions, eq$1(agentSessions.id, sessionId), isNull(agentSessions.deletedAt), isNotNull(agentSessions.canceledAt)));\n}\nasync function updateSessionLiveMessage(sessionId, message) {\n\tawait getDb().update(agentSessions).set({ liveMessage: message }).where(scopedAnd(agentSessions, eq$1(agentSessions.id, sessionId), isNull(agentSessions.deletedAt)));\n}\nasync function clearSessionLiveMessage(sessionId) {\n\tawait getDb().update(agentSessions).set({ liveMessage: null }).where(scopedAnd(agentSessions, eq$1(agentSessions.id, sessionId), isNull(agentSessions.deletedAt)));\n}\nasync function selectSessionLiveMessage(sessionId) {\n\treturn (await getDb().select({ liveMessage: agentSessions.liveMessage }).from(agentSessions).where(scopedAnd(agentSessions, eq$1(agentSessions.id, sessionId), isNull(agentSessions.deletedAt))).limit(1))[0]?.liveMessage;\n}\n//#endregion\n//#region src/queries/agent-events/index.ts\nasync function maxSeqForSession(sessionId) {\n\treturn (await getDb().select({ value: max$1(agentEvents.seq) }).from(agentEvents).innerJoin(agentSessions, eq$1(agentSessions.id, agentEvents.sessionId)).where(scopedAnd(agentSessions, eq$1(agentEvents.sessionId, sessionId), isNull(agentEvents.deletedAt))))[0]?.value ?? 0;\n}\nasync function insertAgentEvent(values) {\n\tawait getDb().insert(agentEvents).values(values);\n}\nasync function listMessagePayloads(sessionId, messageEventType) {\n\treturn (await listMessageEventsForSession(sessionId, messageEventType)).map((row) => row.payload);\n}\nasync function listMessageEventsForSession(sessionId, messageEventType, options) {\n\tconst db = getDb();\n\tconst sinceSeq = options?.sinceSeq;\n\treturn await db.select({\n\t\tpayload: agentEvents.payload,\n\t\tcreatedAt: agentEvents.createdAt,\n\t\tseq: agentEvents.seq\n\t}).from(agentEvents).innerJoin(agentSessions, eq$1(agentSessions.id, agentEvents.sessionId)).where(scopedAnd(agentSessions, eq$1(agentEvents.sessionId, sessionId), eq$1(agentEvents.eventType, messageEventType), isNull(agentEvents.deletedAt), sinceSeq != null && sinceSeq > 0 ? gt(agentEvents.seq, sinceSeq) : void 0)).orderBy(asc(agentEvents.seq));\n}\nasync function countMessageEventsForSession(sessionId, messageEventType) {\n\tconst rows = await getDb().select({ count: sql$1`count(*)` }).from(agentEvents).innerJoin(agentSessions, eq$1(agentSessions.id, agentEvents.sessionId)).where(scopedAnd(agentSessions, eq$1(agentEvents.sessionId, sessionId), eq$1(agentEvents.eventType, messageEventType), isNull(agentEvents.deletedAt)));\n\treturn Number(rows[0]?.count ?? 0);\n}\nasync function listAgentEventsForSession(sessionId) {\n\treturn (await getDb().select({ event: agentEvents }).from(agentEvents).innerJoin(agentSessions, eq$1(agentSessions.id, agentEvents.sessionId)).where(scopedAnd(agentSessions, eq$1(agentEvents.sessionId, sessionId), isNull(agentEvents.deletedAt))).orderBy(asc(agentEvents.seq))).map((row) => row.event);\n}\n//#endregion\n//#region src/queries/usage-records/index.ts\nasync function insertUsageRecord(values) {\n\tawait getDb().insert(usageRecords).values({\n\t\t...values,\n\t\tquantity: values.quantity ?? null,\n\t\tunit: values.unit ?? null,\n\t\tmetadata: values.metadata ?? null\n\t});\n}\nasync function listUsageRecordsForRun(runId, runKind) {\n\treturn getDb().select().from(usageRecords).where(and$1(eq$1(usageRecords.runId, runId), eq$1(usageRecords.runKind, runKind))).orderBy(asc(usageRecords.createdAt), asc(usageRecords.id));\n}\nasync function listUsageRecordsForRuns(runIds, runKind) {\n\tif (runIds.length === 0) return [];\n\treturn getDb().select().from(usageRecords).where(and$1(inArray$1(usageRecords.runId, runIds), eq$1(usageRecords.runKind, runKind))).orderBy(asc(usageRecords.createdAt), asc(usageRecords.id));\n}\n//#endregion\n//#region src/queries/trigger-attachments/index.ts\nasync function selectTriggerAttachmentBySlug(slug) {\n\treturn (await getDb().select().from(triggerAttachments).where(scopedAnd(triggerAttachments, eq$1(triggerAttachments.slug, slug))).limit(1))[0];\n}\nasync function selectTriggerAttachmentById(id) {\n\treturn (await getDb().select().from(triggerAttachments).where(scopedAnd(triggerAttachments, eq$1(triggerAttachments.id, id))).limit(1))[0];\n}\nasync function insertTriggerAttachment(values) {\n\tawait getDb().insert(triggerAttachments).values({\n\t\t...values,\n\t\tprojectId: projectScopeId()\n\t});\n}\nasync function updateTriggerAttachmentById(id, values) {\n\tawait getDb().update(triggerAttachments).set(values).where(scopedAnd(triggerAttachments, eq$1(triggerAttachments.id, id)));\n}\nasync function softDeleteAllTriggerAttachments(now) {\n\tawait getDb().update(triggerAttachments).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(triggerAttachments, isNull(triggerAttachments.deletedAt), eq$1(triggerAttachments.origin, \"project\")));\n}\nasync function softDeleteTriggerAttachmentsNotInSlugs(slugs, now) {\n\tawait getDb().update(triggerAttachments).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(triggerAttachments, isNull(triggerAttachments.deletedAt), eq$1(triggerAttachments.origin, \"project\"), notInArray(triggerAttachments.slug, slugs)));\n}\nasync function getTriggerAttachmentBySlug(slug) {\n\treturn selectTriggerAttachmentBySlug(slug);\n}\nasync function listActiveTriggerAttachments() {\n\treturn getDb().select().from(triggerAttachments).where(scopedAnd(triggerAttachments, isNull(triggerAttachments.deletedAt), eq$1(triggerAttachments.origin, \"project\")));\n}\nasync function selectWebhookTriggerAttachments() {\n\treturn (await getDb().select().from(triggerAttachments).where(scopedAnd(triggerAttachments, isNull(triggerAttachments.deletedAt)))).filter((row) => row.source.kind === \"webhook\");\n}\nasync function selectEphemeralTriggerAttachmentsByAgentSlug(agentSlug) {\n\treturn getDb().select().from(triggerAttachments).where(scopedAnd(triggerAttachments, isNull(triggerAttachments.deletedAt), eq$1(triggerAttachments.origin, \"ephemeral\"), eq$1(triggerAttachments.agentSlug, agentSlug)));\n}\nasync function selectTriggerAttachmentsByAgentSlug(agentSlug) {\n\treturn getDb().select().from(triggerAttachments).where(scopedAnd(triggerAttachments, isNull(triggerAttachments.deletedAt), eq$1(triggerAttachments.agentSlug, agentSlug)));\n}\nasync function selectEphemeralTriggerAttachments() {\n\treturn getDb().select().from(triggerAttachments).where(scopedAnd(triggerAttachments, isNull(triggerAttachments.deletedAt), eq$1(triggerAttachments.origin, \"ephemeral\")));\n}\n//#endregion\n//#region src/queries/trigger-schedules/index.ts\nfunction enabledValue(enabled) {\n\treturn enabled ? 1 : 0;\n}\nasync function selectTriggerScheduleBySlug(attachmentSlug) {\n\treturn (await getDb().select().from(triggerSchedules).where(scopedAnd(triggerSchedules, eq$1(triggerSchedules.attachmentSlug, attachmentSlug))).limit(1))[0];\n}\nasync function upsertTriggerSchedule(values) {\n\tconst db = getDb();\n\tconst existing = await selectTriggerScheduleBySlug(values.attachmentSlug);\n\tconst now = values.updatedAt;\n\tif (existing) {\n\t\tawait db.update(triggerSchedules).set({\n\t\t\tkind: values.kind,\n\t\t\tschedule: values.schedule,\n\t\t\tnextRunAt: values.nextRunAt,\n\t\t\tenabled: enabledValue(values.enabled),\n\t\t\tupdatedAt: now\n\t\t}).where(scopedAnd(triggerSchedules, eq$1(triggerSchedules.attachmentSlug, values.attachmentSlug)));\n\t\treturn;\n\t}\n\tawait db.insert(triggerSchedules).values({\n\t\tid: crypto.randomUUID(),\n\t\tattachmentSlug: values.attachmentSlug,\n\t\tkind: values.kind,\n\t\tschedule: values.schedule,\n\t\tnextRunAt: values.nextRunAt,\n\t\tenabled: enabledValue(values.enabled),\n\t\tupdatedAt: now,\n\t\tprojectId: projectScopeId()\n\t});\n}\nasync function setTriggerScheduleEnabled(attachmentSlug, enabled, now) {\n\tawait getDb().update(triggerSchedules).set({\n\t\tenabled: enabledValue(enabled),\n\t\tupdatedAt: now\n\t}).where(scopedAnd(triggerSchedules, eq$1(triggerSchedules.attachmentSlug, attachmentSlug)));\n}\nasync function disableAllTriggerSchedules(now) {\n\tawait getDb().update(triggerSchedules).set({\n\t\tenabled: 0,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(triggerSchedules, eq$1(triggerSchedules.enabled, 1)));\n}\nasync function disableTriggerSchedulesNotInSlugs(attachmentKeys, now) {\n\tawait getDb().update(triggerSchedules).set({\n\t\tenabled: 0,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(triggerSchedules, eq$1(triggerSchedules.enabled, 1), notInArray(triggerSchedules.attachmentSlug, attachmentKeys)));\n}\nasync function listEnabledTriggerSchedules() {\n\treturn getDb().select().from(triggerSchedules).where(scopedAnd(triggerSchedules, eq$1(triggerSchedules.enabled, 1))).orderBy(asc(triggerSchedules.attachmentSlug));\n}\nasync function claimDueTriggerSchedules(now, resolveNextRunAt, limit = 10) {\n\tconst db = getDb();\n\tif (getDatabaseHandle().dialect === \"postgres\") return db.transaction(async (tx) => {\n\t\tconst due = await tx.select().from(triggerSchedules).where(scopedAnd(triggerSchedules, eq$1(triggerSchedules.enabled, 1), lte(triggerSchedules.nextRunAt, now))).orderBy(asc(triggerSchedules.nextRunAt)).limit(limit);\n\t\tconst claimed = [];\n\t\tfor (const row of due) {\n\t\t\tconst nextRunAt = resolveNextRunAt(row.schedule);\n\t\t\tconst [updated] = await tx.update(triggerSchedules).set({\n\t\t\t\tnextRunAt,\n\t\t\t\tupdatedAt: now\n\t\t\t}).where(scopedAnd(triggerSchedules, eq$1(triggerSchedules.attachmentSlug, row.attachmentSlug), lte(triggerSchedules.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(triggerSchedules).where(scopedAnd(triggerSchedules, eq$1(triggerSchedules.enabled, 1), lte(triggerSchedules.nextRunAt, now))).orderBy(asc(triggerSchedules.nextRunAt)).limit(limit);\n\tconst claimed = [];\n\tfor (const row of due) {\n\t\tconst nextRunAt = resolveNextRunAt(row.schedule);\n\t\tawait db.update(triggerSchedules).set({\n\t\t\tnextRunAt,\n\t\t\tupdatedAt: now\n\t\t}).where(scopedAnd(triggerSchedules, eq$1(triggerSchedules.attachmentSlug, row.attachmentSlug), lte(triggerSchedules.nextRunAt, now)));\n\t\tconst updated = await selectTriggerScheduleBySlug(row.attachmentSlug);\n\t\tif (updated && updated.nextRunAt.getTime() === nextRunAt.getTime()) claimed.push(updated);\n\t}\n\treturn claimed;\n}\nasync function claimDueTriggerSchedulesForOrg(now, resolveNextRunAt, limit = 10) {\n\tconst db = getDb();\n\tif (getDatabaseHandle().dialect === \"postgres\") return db.transaction(async (tx) => {\n\t\tconst due = await tx.select().from(triggerSchedules).where(and$1(eq$1(triggerSchedules.enabled, 1), lte(triggerSchedules.nextRunAt, now))).orderBy(asc(triggerSchedules.nextRunAt)).limit(limit);\n\t\tconst claimed = [];\n\t\tfor (const row of due) {\n\t\t\tconst nextRunAt = resolveNextRunAt(row.schedule);\n\t\t\tconst [updated] = await tx.update(triggerSchedules).set({\n\t\t\t\tnextRunAt,\n\t\t\t\tupdatedAt: now\n\t\t\t}).where(and$1(eq$1(triggerSchedules.attachmentSlug, row.attachmentSlug), eq$1(triggerSchedules.projectId, row.projectId), lte(triggerSchedules.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(triggerSchedules).where(and$1(eq$1(triggerSchedules.enabled, 1), lte(triggerSchedules.nextRunAt, now))).orderBy(asc(triggerSchedules.nextRunAt)).limit(limit);\n\tconst claimed = [];\n\tfor (const row of due) {\n\t\tconst nextRunAt = resolveNextRunAt(row.schedule);\n\t\tawait db.update(triggerSchedules).set({\n\t\t\tnextRunAt,\n\t\t\tupdatedAt: now\n\t\t}).where(and$1(eq$1(triggerSchedules.attachmentSlug, row.attachmentSlug), eq$1(triggerSchedules.projectId, row.projectId), lte(triggerSchedules.nextRunAt, now)));\n\t\tconst schedule = (await db.select().from(triggerSchedules).where(and$1(eq$1(triggerSchedules.attachmentSlug, row.attachmentSlug), eq$1(triggerSchedules.projectId, row.projectId))).limit(1))[0];\n\t\tif (schedule && schedule.nextRunAt.getTime() === nextRunAt.getTime()) claimed.push(schedule);\n\t}\n\treturn claimed;\n}\nasync function listTriggerSchedulesBySlugs(attachmentKeys) {\n\tif (attachmentKeys.length === 0) return [];\n\treturn getDb().select().from(triggerSchedules).where(scopedAnd(triggerSchedules, inArray$1(triggerSchedules.attachmentSlug, attachmentKeys)));\n}\n//#endregion\n//#region src/workflows/cursor.ts\nfunction encodeWorkflowRunCursor(cursor) {\n\treturn Buffer.from(JSON.stringify({\n\t\ttriggeredAt: cursor.triggeredAt.toISOString(),\n\t\tid: cursor.id\n\t})).toString(\"base64url\");\n}\nfunction decodeWorkflowRunCursor(value) {\n\ttry {\n\t\tconst parsed = JSON.parse(Buffer.from(value, \"base64url\").toString(\"utf8\"));\n\t\tif (typeof parsed.triggeredAt !== \"string\" || typeof parsed.id !== \"string\") return null;\n\t\tconst triggeredAt = new Date(parsed.triggeredAt);\n\t\tif (Number.isNaN(triggeredAt.getTime())) return null;\n\t\treturn {\n\t\t\ttriggeredAt,\n\t\t\tid: parsed.id\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\n//#endregion\n//#region src/workflows/serialize.ts\nfunction toIso(value) {\n\tif (!value) return null;\n\treturn value.toISOString();\n}\nfunction workflowRunSummaryFromRow(row) {\n\treturn {\n\t\tid: row.id,\n\t\tstatus: row.status,\n\t\ttrigger: row.trigger,\n\t\ttriggeredAt: row.triggeredAt.toISOString(),\n\t\tstartedAt: toIso(row.startedAt),\n\t\tfinishedAt: toIso(row.finishedAt),\n\t\ttriggerRunId: row.triggerRunId ?? null,\n\t\tattachmentId: row.attachmentId ?? null,\n\t\tsourceKind: row.sourceKind,\n\t\tsourceId: row.sourceId ?? null\n\t};\n}\nfunction workflowRunRecordFromRow(row) {\n\treturn {\n\t\tid: row.id,\n\t\tworkflowSlug: row.workflowSlug,\n\t\tstatus: row.status,\n\t\ttrigger: row.trigger,\n\t\ttriggeredAt: row.triggeredAt.toISOString(),\n\t\tstartedAt: toIso(row.startedAt),\n\t\tfinishedAt: toIso(row.finishedAt),\n\t\tsourceKind: row.sourceKind,\n\t\tsourceId: row.sourceId ?? null,\n\t\ttriggerRunId: row.triggerRunId ?? null,\n\t\tattachmentId: row.attachmentId ?? null,\n\t\tparentWorkflowRunId: row.parentWorkflowRunId ?? null,\n\t\tparentSpanId: row.parentSpanId ?? null,\n\t\tinput: row.input ?? null,\n\t\toutput: row.output ?? null,\n\t\terror: row.error ?? null\n\t};\n}\nfunction triggerRunDetailFromRow(row, attachmentSlug) {\n\treturn {\n\t\tid: row.id,\n\t\tattachmentId: row.attachmentId,\n\t\tattachmentSlug,\n\t\ttriggerType: row.triggerType,\n\t\tsourcePath: row.sourcePath ?? null,\n\t\tpayload: row.payload ?? null,\n\t\ttriggeredAt: row.triggeredAt.toISOString()\n\t};\n}\nfunction workflowStepRunFromEvent(row) {\n\treturn {\n\t\tid: row.id,\n\t\tactionKey: row.correlationId ?? row.id,\n\t\toutput: row.data ?? null,\n\t\tcompletedAt: row.createdAt.toISOString()\n\t};\n}\nfunction traceSpanToJson(span) {\n\treturn {\n\t\t...span,\n\t\tstartedAt: span.startedAt.toISOString(),\n\t\tfinishedAt: toIso(span.finishedAt)\n\t};\n}\nfunction traceLogToJson(log) {\n\treturn {\n\t\t...log,\n\t\tcreatedAt: log.createdAt.toISOString()\n\t};\n}\nfunction traceResponseToJson(trace) {\n\treturn {\n\t\ttraceId: trace.traceId,\n\t\ttrigger: trace.trigger,\n\t\tgateway: trace.gateway,\n\t\tspans: trace.spans.map(traceSpanToJson),\n\t\tlogs: trace.logs.map(traceLogToJson)\n\t};\n}\n//#endregion\n//#region src/queries/workflow-runs/index.ts\nasync function insertWorkflowRun(values) {\n\tawait getDb().insert(workflowRuns).values({\n\t\t...values,\n\t\tsourceKind: values.sourceKind ?? \"api\",\n\t\tsourceId: values.sourceId ?? null,\n\t\tranByUserId: values.ranByUserId ?? null,\n\t\tprojectId: projectScopeId()\n\t});\n}\nasync function markWorkflowRunRunningRow(id, startedAt) {\n\tawait getDb().update(workflowRuns).set({\n\t\tstatus: \"running\",\n\t\tstartedAt,\n\t\terror: null,\n\t\tfinishedAt: null\n\t}).where(scopedAnd(workflowRuns, eq$1(workflowRuns.id, id)));\n}\nasync function setWorkflowRunStatusRow(id, status) {\n\tawait getDb().update(workflowRuns).set({ status }).where(scopedAnd(workflowRuns, eq$1(workflowRuns.id, id)));\n}\nasync function selectWorkflowRunById(id) {\n\treturn (await getDb().select().from(workflowRuns).where(scopedAnd(workflowRuns, eq$1(workflowRuns.id, id))).limit(1))[0];\n}\n/** Resolve the owning project for a run id across the whole org schema. */\nasync function resolveWorkflowRunProjectId(runId) {\n\tconst rows = await getDb().select({ projectId: workflowRuns.projectId }).from(workflowRuns).where(eq$1(workflowRuns.id, runId)).limit(1);\n\tif (!rows[0]) throw new Error(`Workflow run not found: ${runId}`);\n\treturn rows[0].projectId;\n}\nasync function completeWorkflowRunRow(id, output, finishedAt) {\n\tawait getDb().update(workflowRuns).set({\n\t\tstatus: \"completed\",\n\t\toutput,\n\t\tfinishedAt,\n\t\terror: null\n\t}).where(scopedAnd(workflowRuns, eq$1(workflowRuns.id, id), ne(workflowRuns.status, \"canceled\")));\n}\nasync function failWorkflowRunRow(id, error, finishedAt) {\n\tawait getDb().update(workflowRuns).set({\n\t\tstatus: \"failed\",\n\t\terror,\n\t\tfinishedAt\n\t}).where(scopedAnd(workflowRuns, eq$1(workflowRuns.id, id), ne(workflowRuns.status, \"canceled\")));\n}\nconst CANCELABLE_WORKFLOW_STATUSES = [\n\t\"pending\",\n\t\"running\",\n\t\"sleeping\",\n\t\"waiting_hook\"\n];\nasync function cancelWorkflowRunRow(id, finishedAt) {\n\treturn (await getDb().update(workflowRuns).set({\n\t\tstatus: \"canceled\",\n\t\tfinishedAt\n\t}).where(scopedAnd(workflowRuns, eq$1(workflowRuns.id, id), inArray$1(workflowRuns.status, CANCELABLE_WORKFLOW_STATUSES))).returning())[0];\n}\nasync function listWorkflowRunsByWorkflowSlug(workflowSlug) {\n\treturn getDb().select().from(workflowRuns).where(scopedAnd(workflowRuns, eq$1(workflowRuns.workflowSlug, workflowSlug)));\n}\nasync function listWorkflowRunsByTriggerRunId(triggerRunId) {\n\treturn getDb().select().from(workflowRuns).where(scopedAnd(workflowRuns, eq$1(workflowRuns.triggerRunId, triggerRunId)));\n}\nasync function listWorkflowRunsByTriggerRunIds(triggerRunIds) {\n\tif (triggerRunIds.length === 0) return /* @__PURE__ */ new Map();\n\tconst rows = await getDb().select().from(workflowRuns).where(scopedAnd(workflowRuns, inArray$1(workflowRuns.triggerRunId, triggerRunIds)));\n\tconst byTriggerRunId = /* @__PURE__ */ new Map();\n\tfor (const row of rows) if (row.triggerRunId) byTriggerRunId.set(row.triggerRunId, row);\n\treturn byTriggerRunId;\n}\nasync function selectWorkflowRunForWorkflow(workflowSlug, runId) {\n\treturn (await getDb().select().from(workflowRuns).where(scopedAnd(workflowRuns, eq$1(workflowRuns.id, runId), eq$1(workflowRuns.workflowSlug, workflowSlug))).limit(1))[0];\n}\nfunction cursorBefore$1(cursor) {\n\treturn or(lt(workflowRuns.triggeredAt, cursor.triggeredAt), and$1(eq$1(workflowRuns.triggeredAt, cursor.triggeredAt), lt(workflowRuns.id, cursor.id)));\n}\nasync function listWorkflowRunsPaginated(options) {\n\tconst db = getDb();\n\tconst conditions = [eq$1(workflowRuns.workflowSlug, options.workflowSlug)];\n\tif (options.status) conditions.push(eq$1(workflowRuns.status, options.status));\n\tif (options.trigger) conditions.push(eq$1(workflowRuns.trigger, options.trigger));\n\tif (options.cursor) {\n\t\tconst decoded = decodeWorkflowRunCursor(options.cursor);\n\t\tif (!decoded) throw new Error(\"Invalid cursor\");\n\t\tconditions.push(cursorBefore$1(decoded));\n\t}\n\tconst limit = options.limit + 1;\n\tconst rows = await db.select().from(workflowRuns).where(scopedAnd(workflowRuns, ...conditions)).orderBy(desc(workflowRuns.triggeredAt), desc(workflowRuns.id)).limit(limit);\n\tconst hasMore = rows.length > options.limit;\n\tconst page = hasMore ? rows.slice(0, options.limit) : rows;\n\tconst last = page.at(-1);\n\treturn {\n\t\titems: page.map(workflowRunSummaryFromRow),\n\t\tnextCursor: hasMore && last ? encodeWorkflowRunCursor({\n\t\t\ttriggeredAt: last.triggeredAt,\n\t\t\tid: last.id\n\t\t}) : null\n\t};\n}\n//#endregion\n//#region src/queries/workflow-events/index.ts\nasync function selectMaxEventSeq(runId) {\n\tconst rows = await getDb().select({ value: max$1(workflowEvents.seq) }).from(workflowEvents).where(scopedAnd(workflowEvents, eq$1(workflowEvents.runId, runId)));\n\treturn Number(rows[0]?.value ?? -1);\n}\n/**\n* Append one event. Allocates the next per-run `seq` (max+1) and is idempotent\n* when an explicit `id` is supplied. Returns true when a row was inserted.\n*/\nasync function appendWorkflowEvent(values) {\n\tconst db = getDb();\n\tconst id = values.id ?? crypto.randomUUID();\n\tconst seq = await selectMaxEventSeq(values.runId) + 1;\n\treturn (await db.insert(workflowEvents).values({\n\t\tid,\n\t\trunId: values.runId,\n\t\tprojectId: projectScopeId(),\n\t\tseq,\n\t\ttype: values.type,\n\t\tcorrelationId: values.correlationId ?? null,\n\t\tdata: values.data ?? null,\n\t\tcreatedAt: /* @__PURE__ */ new Date()\n\t}).onConflictDoNothing({ target: workflowEvents.id }).returning({ id: workflowEvents.id })).length > 0;\n}\nasync function listReplayEvents(runId) {\n\treturn getDb().select().from(workflowEvents).where(scopedAnd(workflowEvents, eq$1(workflowEvents.runId, runId))).orderBy(asc(workflowEvents.seq));\n}\n/** Completed step events for a run, in execution order — backs the run-detail steps view. */\nasync function listStepCompletedEvents(runId) {\n\treturn getDb().select().from(workflowEvents).where(scopedAnd(workflowEvents, eq$1(workflowEvents.runId, runId), eq$1(workflowEvents.type, \"step_completed\"))).orderBy(asc(workflowEvents.seq));\n}\n//#endregion\n//#region src/queries/workflow-hooks/index.ts\n/** Idempotent on `token` so replays don't create duplicate hook rows. */\nasync function insertWorkflowHook(values) {\n\tawait getDb().insert(workflowHooks).values({\n\t\thookId: values.hookId,\n\t\trunId: values.runId,\n\t\tprojectId: projectScopeId(),\n\t\ttoken: values.token,\n\t\tcorrelationId: values.correlationId,\n\t\tstatus: \"waiting\",\n\t\tpayload: values.payload ?? null,\n\t\tcreatedAt: /* @__PURE__ */ new Date(),\n\t\tresumedAt: null\n\t}).onConflictDoNothing({ target: workflowHooks.token });\n}\nasync function selectWorkflowHookByToken(token) {\n\treturn (await getDb().select().from(workflowHooks).where(scopedAnd(workflowHooks, eq$1(workflowHooks.token, token))).limit(1))[0];\n}\nasync function markWorkflowHookResumed(hookId, payload) {\n\tawait getDb().update(workflowHooks).set({\n\t\tstatus: \"resumed\",\n\t\tpayload,\n\t\tresumedAt: /* @__PURE__ */ new Date()\n\t}).where(scopedAnd(workflowHooks, eq$1(workflowHooks.hookId, hookId)));\n}\n//#endregion\n//#region src/triggers/cursor.ts\nfunction encodeTriggerRunCursor(cursor) {\n\treturn Buffer.from(JSON.stringify({\n\t\ttriggeredAt: cursor.triggeredAt.toISOString(),\n\t\tid: cursor.id\n\t})).toString(\"base64url\");\n}\nfunction decodeTriggerRunCursor(value) {\n\ttry {\n\t\tconst parsed = JSON.parse(Buffer.from(value, \"base64url\").toString(\"utf8\"));\n\t\tif (typeof parsed.triggeredAt !== \"string\" || typeof parsed.id !== \"string\") return null;\n\t\tconst triggeredAt = new Date(parsed.triggeredAt);\n\t\tif (Number.isNaN(triggeredAt.getTime())) return null;\n\t\treturn {\n\t\t\ttriggeredAt,\n\t\t\tid: parsed.id\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\n//#endregion\n//#region src/triggers/serialize.ts\nfunction triggerRunSummaryFromRow(row, options) {\n\treturn {\n\t\tid: row.id,\n\t\ttriggerType: row.triggerType,\n\t\ttriggeredAt: row.triggeredAt.toISOString(),\n\t\tsourcePath: row.sourcePath ?? null,\n\t\tworkflowRun: options?.workflowRun ? {\n\t\t\tid: options.workflowRun.id,\n\t\t\tstatus: options.workflowRun.status,\n\t\t\tworkflowSlug: options.workflowRun.workflowSlug\n\t\t} : null,\n\t\tagentSession: options?.agentSession && options.agentSlug ? {\n\t\t\tid: options.agentSession.id,\n\t\t\tagentSlug: options.agentSlug\n\t\t} : null\n\t};\n}\nfunction triggerRunRecordFromRow(row, attachmentSlug) {\n\treturn {\n\t\tid: row.id,\n\t\tattachmentId: row.attachmentId,\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}\n//#endregion\n//#region src/queries/trigger-runs/index.ts\nasync function insertTriggerRun(values) {\n\tawait getDb().insert(triggerRuns).values({\n\t\t...values,\n\t\tprojectId: projectScopeId()\n\t});\n}\nasync function selectTriggerRunById(id) {\n\treturn (await getDb().select().from(triggerRuns).where(scopedAnd(triggerRuns, eq$1(triggerRuns.id, id))).limit(1))[0];\n}\nasync function selectTriggerRunForAttachment(attachmentId, runId) {\n\treturn (await getDb().select().from(triggerRuns).where(scopedAnd(triggerRuns, eq$1(triggerRuns.id, runId), eq$1(triggerRuns.attachmentId, attachmentId))).limit(1))[0];\n}\nfunction cursorBefore(cursor) {\n\treturn or(lt(triggerRuns.triggeredAt, cursor.triggeredAt), and$1(eq$1(triggerRuns.triggeredAt, cursor.triggeredAt), lt(triggerRuns.id, cursor.id)));\n}\nasync function listTriggerRunRowsPaginated(options) {\n\tconst db = getDb();\n\tconst conditions = [eq$1(triggerRuns.attachmentId, options.attachmentId)];\n\tif (options.triggerType) conditions.push(eq$1(triggerRuns.triggerType, options.triggerType));\n\tif (options.cursor) {\n\t\tconst decoded = decodeTriggerRunCursor(options.cursor);\n\t\tif (!decoded) throw new Error(\"Invalid cursor\");\n\t\tconditions.push(cursorBefore(decoded));\n\t}\n\tconst limit = options.limit + 1;\n\tconst rows = await db.select().from(triggerRuns).where(scopedAnd(triggerRuns, ...conditions)).orderBy(desc(triggerRuns.triggeredAt), desc(triggerRuns.id)).limit(limit);\n\tconst hasMore = rows.length > options.limit;\n\tconst page = hasMore ? rows.slice(0, options.limit) : rows;\n\tconst last = page.at(-1);\n\tconst workflowRunsByTriggerRunId = await listWorkflowRunsByTriggerRunIds(page.map((row) => row.id));\n\treturn {\n\t\titems: page.map((row) => triggerRunSummaryFromRow(row, { workflowRun: 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}\n//#endregion\n//#region src/queries/jobs/index.ts\nconst DEFAULT_LEASE_MS = 300 * 1e3;\nasync function insertJob(values) {\n\tawait getDb().insert(jobs).values({\n\t\t...values,\n\t\tprojectId: projectScopeId()\n\t});\n}\nasync function claimPendingJob(workerId, leaseExpiresAt, now) {\n\tconst db = getDb();\n\tconst job = (await db.select().from(jobs).where(scopedAnd(jobs, eq$1(jobs.status, \"pending\"), lte(jobs.scheduledAt, now))).orderBy(asc(jobs.scheduledAt)).limit(1))[0];\n\tif (!job) return;\n\tawait db.update(jobs).set({\n\t\tstatus: \"leased\",\n\t\tleasedBy: workerId,\n\t\tleaseExpiresAt\n\t}).where(scopedAnd(jobs, eq$1(jobs.id, job.id), eq$1(jobs.status, \"pending\")));\n\tconst claimed = await selectJobById(job.id);\n\tif (claimed?.status !== \"leased\" || claimed.leasedBy !== workerId) return;\n\treturn claimed;\n}\nasync function claimNextJobRow(workerId, leaseMs = DEFAULT_LEASE_MS) {\n\tconst db = getDb();\n\tconst dialect = getDatabaseHandle().dialect;\n\tconst now = /* @__PURE__ */ new Date();\n\tconst leaseExpiresAt = new Date(now.getTime() + leaseMs);\n\tif (dialect === \"postgres\") return db.transaction(async (tx) => {\n\t\tconst job = (await tx.select().from(jobs).where(scopedAnd(jobs, eq$1(jobs.status, \"pending\"), lte(jobs.scheduledAt, now))).orderBy(asc(jobs.scheduledAt)).limit(1))[0];\n\t\tif (!job) return;\n\t\tawait tx.update(jobs).set({\n\t\t\tstatus: \"leased\",\n\t\t\tleasedBy: workerId,\n\t\t\tleaseExpiresAt\n\t\t}).where(scopedAnd(jobs, eq$1(jobs.id, job.id)));\n\t\treturn {\n\t\t\t...job,\n\t\t\tstatus: \"leased\",\n\t\t\tleasedBy: workerId,\n\t\t\tleaseExpiresAt\n\t\t};\n\t});\n\treturn claimPendingJob(workerId, leaseExpiresAt, now);\n}\nasync function markJobRunning(id) {\n\tawait getDb().update(jobs).set({ status: \"running\" }).where(scopedAnd(jobs, eq$1(jobs.id, id)));\n}\nasync function completeJobRow(id, completedAt) {\n\tawait getDb().update(jobs).set({\n\t\tstatus: \"completed\",\n\t\tcompletedAt,\n\t\terror: null\n\t}).where(scopedAnd(jobs, eq$1(jobs.id, id)));\n}\nasync function failJobRow(id, error, completedAt) {\n\tawait getDb().update(jobs).set({\n\t\tstatus: \"failed\",\n\t\terror,\n\t\tcompletedAt\n\t}).where(scopedAnd(jobs, eq$1(jobs.id, id)));\n}\nasync function requeueExpiredLeases(now = /* @__PURE__ */ new Date()) {\n\tconst db = getDb();\n\tconst expired = await db.select({ id: jobs.id }).from(jobs).where(scopedAnd(jobs, inArray$1(jobs.status, [\"leased\", \"running\"]), isNotNull(jobs.leaseExpiresAt), lt(jobs.leaseExpiresAt, now)));\n\tif (expired.length === 0) return 0;\n\tawait db.update(jobs).set({\n\t\tstatus: \"pending\",\n\t\tleasedBy: null,\n\t\tleaseExpiresAt: null\n\t}).where(scopedAnd(jobs, inArray$1(jobs.id, expired.map((row) => row.id))));\n\treturn expired.length;\n}\nasync function selectJobById(id) {\n\treturn (await getDb().select().from(jobs).where(scopedAnd(jobs, eq$1(jobs.id, id))).limit(1))[0];\n}\nasync function selectJobByRunId(runId) {\n\treturn (await getDb().select().from(jobs).where(scopedAnd(jobs, eq$1(jobs.runId, runId))).limit(1))[0];\n}\nasync function resetJobForRetry(id, scheduledAt, attempt) {\n\tawait getDb().update(jobs).set({\n\t\tstatus: \"pending\",\n\t\tscheduledAt,\n\t\tattempt,\n\t\tleasedBy: null,\n\t\tleaseExpiresAt: null,\n\t\tcompletedAt: null,\n\t\terror: null\n\t}).where(scopedAnd(jobs, eq$1(jobs.id, id)));\n}\n//#endregion\n//#region src/queries/gateway-attachments/index.ts\nasync function selectGatewayAttachmentBySlug(slug) {\n\treturn (await getDb().select().from(gatewayAttachments).where(scopedAnd(gatewayAttachments, eq$1(gatewayAttachments.slug, slug))).limit(1))[0];\n}\nasync function selectGatewayAttachmentById(id) {\n\treturn (await getDb().select().from(gatewayAttachments).where(scopedAnd(gatewayAttachments, eq$1(gatewayAttachments.id, id))).limit(1))[0];\n}\n/** Thrown when a channel is already bound by a different project in the same organization. */\nvar GatewayChannelConflictError = class extends Error {\n\tplatform;\n\tchannelId;\n\townerProjectId;\n\tconstructor(platform, channelId, ownerProjectId) {\n\t\tsuper(`Channel ${channelId} is already bound to another project in this organization`);\n\t\tthis.platform = platform;\n\t\tthis.channelId = channelId;\n\t\tthis.ownerProjectId = ownerProjectId;\n\t\tthis.name = \"GatewayChannelConflictError\";\n\t}\n};\n/** Project-unscoped active binding for a channel — used to enforce org-unique channel ownership. */\nasync function getActiveOrgGatewayAttachmentByChannel(platform, channelId) {\n\treturn (await getDb().select().from(gatewayAttachments).where(and$1(eq$1(gatewayAttachments.platform, platform), eq$1(gatewayAttachments.channelId, channelId), isNull(gatewayAttachments.deletedAt))).limit(1))[0];\n}\n/** Project-unscoped binding for a Slack workspace channel. */\nasync function getActiveOrgGatewayAttachmentByTeamAndChannel(platform, teamId, channelId) {\n\treturn (await getDb().select().from(gatewayAttachments).where(and$1(eq$1(gatewayAttachments.platform, platform), eq$1(gatewayAttachments.teamId, teamId), eq$1(gatewayAttachments.channelId, channelId), isNull(gatewayAttachments.deletedAt))).limit(1))[0];\n}\nasync function getActiveGatewayAttachmentByChannel(platform, channelId) {\n\treturn (await getDb().select().from(gatewayAttachments).where(scopedAnd(gatewayAttachments, eq$1(gatewayAttachments.platform, platform), eq$1(gatewayAttachments.channelId, channelId), isNull(gatewayAttachments.deletedAt))).limit(1))[0];\n}\nasync function listActiveGatewayAttachments() {\n\treturn getDb().select().from(gatewayAttachments).where(scopedAnd(gatewayAttachments, isNull(gatewayAttachments.deletedAt)));\n}\n/**\n* Project-unscoped: every active attachment for a platform across all projects in the current org\n* schema, joined to its agent's registry id. Used by the platform ingress, which routes by channel\n* before a project scope is known. A single query avoids per-attachment agent lookups.\n*/\nasync function listActiveOrgGatewayBindingsByPlatform(platform) {\n\treturn getDb().select({\n\t\tattachmentId: gatewayAttachments.id,\n\t\tslug: gatewayAttachments.slug,\n\t\tagentSlug: gatewayAttachments.agentSlug,\n\t\tagentId: agents.id,\n\t\tchannelId: gatewayAttachments.channelId,\n\t\tteamId: gatewayAttachments.teamId,\n\t\tsource: gatewayAttachments.source,\n\t\tprojectId: gatewayAttachments.projectId\n\t}).from(gatewayAttachments).innerJoin(agents, and$1(eq$1(agents.projectId, gatewayAttachments.projectId), eq$1(agents.slug, gatewayAttachments.agentSlug), isNull(agents.deletedAt))).where(and$1(eq$1(gatewayAttachments.platform, platform), isNull(gatewayAttachments.deletedAt)));\n}\nasync function listActiveGatewayAttachmentsByAgentSlug(agentSlug) {\n\treturn getDb().select().from(gatewayAttachments).where(scopedAnd(gatewayAttachments, eq$1(gatewayAttachments.agentSlug, agentSlug), isNull(gatewayAttachments.deletedAt)));\n}\nasync function softDeleteGatewayAttachmentsForAgentPlatformTeam(agentSlug, platform, teamId, now) {\n\tconst db = getDb();\n\tconst targets = (await listActiveGatewayAttachmentsByAgentSlug(agentSlug)).filter((row) => row.platform === platform && (teamId === null ? row.teamId == null : row.teamId === teamId));\n\tif (targets.length === 0) return 0;\n\tfor (const row of targets) await db.update(gatewayAttachments).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(gatewayAttachments, eq$1(gatewayAttachments.id, row.id)));\n\treturn targets.length;\n}\nasync function listActiveGatewayAttachmentsByPlatform(platform) {\n\treturn getDb().select().from(gatewayAttachments).where(scopedAnd(gatewayAttachments, eq$1(gatewayAttachments.platform, platform), isNull(gatewayAttachments.deletedAt)));\n}\nasync function insertGatewayAttachment(values) {\n\tawait getDb().insert(gatewayAttachments).values({\n\t\t...values,\n\t\tprojectId: projectScopeId()\n\t});\n}\nasync function updateGatewayAttachmentById(id, values) {\n\tawait getDb().update(gatewayAttachments).set(values).where(scopedAnd(gatewayAttachments, eq$1(gatewayAttachments.id, id)));\n}\nasync function softDeleteGatewayAttachmentByChannel(platform, channelId, now) {\n\tconst existing = await getActiveGatewayAttachmentByChannel(platform, channelId);\n\tif (!existing) return false;\n\tawait getDb().update(gatewayAttachments).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(gatewayAttachments, eq$1(gatewayAttachments.id, existing.id)));\n\treturn true;\n}\nasync function upsertGatewayAttachmentByChannel(options) {\n\tconst now = /* @__PURE__ */ new Date();\n\tconst slug = gatewayAttachmentKeyForChannel(options.platform, options.channelId);\n\tconst existing = await getActiveGatewayAttachmentByChannel(options.platform, options.channelId);\n\tif (existing) {\n\t\tawait updateGatewayAttachmentById(existing.id, {\n\t\t\tagentSlug: options.agentSlug,\n\t\t\tmoduleFile: \"\",\n\t\t\tplatform: options.platform,\n\t\t\tteamId: options.teamId ?? existing.teamId,\n\t\t\tchannelId: options.channelId,\n\t\t\tsource: options.source,\n\t\t\tupdatedAt: now,\n\t\t\tdeletedAt: null\n\t\t});\n\t\tconst updated = await selectGatewayAttachmentById(existing.id);\n\t\tif (!updated) throw new Error(\"Failed to load gateway attachment after update\");\n\t\treturn updated;\n\t}\n\tconst orgOwned = await getActiveOrgGatewayAttachmentByChannel(options.platform, options.channelId);\n\tif (orgOwned && orgOwned.projectId !== projectScopeId()) throw new GatewayChannelConflictError(options.platform, options.channelId, orgOwned.projectId);\n\tconst softDeleted = await selectGatewayAttachmentBySlug(slug);\n\tif (softDeleted && softDeleted.deletedAt) {\n\t\tawait updateGatewayAttachmentById(softDeleted.id, {\n\t\t\tagentSlug: options.agentSlug,\n\t\t\tmoduleFile: \"\",\n\t\t\tplatform: options.platform,\n\t\t\tteamId: options.teamId ?? softDeleted.teamId,\n\t\t\tchannelId: options.channelId,\n\t\t\tsource: options.source,\n\t\t\tupdatedAt: now,\n\t\t\tdeletedAt: null\n\t\t});\n\t\tconst revived = await selectGatewayAttachmentById(softDeleted.id);\n\t\tif (!revived) throw new Error(\"Failed to load gateway attachment after revive\");\n\t\treturn revived;\n\t}\n\tconst id = crypto.randomUUID();\n\tawait insertGatewayAttachment({\n\t\tid,\n\t\tslug,\n\t\tagentSlug: options.agentSlug,\n\t\tmoduleFile: \"\",\n\t\tplatform: options.platform,\n\t\tteamId: options.teamId ?? null,\n\t\tchannelId: options.channelId,\n\t\tsource: options.source,\n\t\tregisteredAt: now,\n\t\tupdatedAt: now,\n\t\tdeletedAt: null\n\t});\n\tconst inserted = await selectGatewayAttachmentById(id);\n\tif (!inserted) throw new Error(\"Failed to load gateway attachment after insert\");\n\treturn inserted;\n}\nasync function getGatewayAttachmentBySlug(slug) {\n\treturn selectGatewayAttachmentBySlug(slug);\n}\n//#endregion\n//#region src/queries/gateway-thread-sessions/index.ts\nasync function selectGatewayThreadSessionByThreadId(threadId) {\n\treturn (await getDb().select({ session: gatewayThreadSessions }).from(gatewayThreadSessions).innerJoin(gatewayAttachments, eq$1(gatewayAttachments.id, gatewayThreadSessions.attachmentId)).where(scopedAnd(gatewayAttachments, eq$1(gatewayThreadSessions.threadId, threadId))).limit(1))[0]?.session;\n}\nasync function selectGatewayThreadSessionBySessionId(sessionId) {\n\treturn (await getDb().select({ session: gatewayThreadSessions }).from(gatewayThreadSessions).innerJoin(gatewayAttachments, eq$1(gatewayAttachments.id, gatewayThreadSessions.attachmentId)).where(scopedAnd(gatewayAttachments, eq$1(gatewayThreadSessions.sessionId, sessionId))).limit(1))[0]?.session;\n}\nasync function upsertGatewayThreadSession(values) {\n\tawait getDb().insert(gatewayThreadSessions).values(values).onConflictDoUpdate({\n\t\ttarget: gatewayThreadSessions.threadId,\n\t\tset: {\n\t\t\tagentId: values.agentId,\n\t\t\tsessionId: values.sessionId,\n\t\t\tattachmentId: values.attachmentId,\n\t\t\tupdatedAt: values.updatedAt\n\t\t}\n\t});\n}\n//#endregion\n//#region src/queries/workflows/list-active.ts\n/**\n* List every active workflow in the bound org schema (all projects). Not project\n* scoped — the org database schema is itself the tenant boundary.\n*/\nasync function listActiveWorkflows(options) {\n\tconst db = getDb();\n\tif (options?.projectIds !== void 0 && options.projectIds.length === 0) return [];\n\tconst conditions = [isNull(workflows.deletedAt)];\n\tif (options?.projectIds !== void 0) conditions.push(inArray$1(workflows.projectId, options.projectIds));\n\treturn db.select().from(workflows).where(and$1(...conditions)).orderBy(desc(workflows.updatedAt));\n}\n//#endregion\n//#region src/queries/workflows/select.ts\nasync function selectWorkflowBySlug(slug) {\n\treturn (await getDb().select().from(workflows).where(scopedAnd(workflows, eq$1(workflows.slug, slug))).limit(1))[0];\n}\nasync function selectActiveWorkflowBySlug(slug) {\n\treturn (await getDb().select().from(workflows).where(scopedAnd(workflows, eq$1(workflows.slug, slug), isNull(workflows.deletedAt))).limit(1))[0];\n}\n/** Fetch active workflows by id from the bound org schema (all projects). */\nasync function selectActiveWorkflowsByIds(ids) {\n\tif (ids.length === 0) return [];\n\treturn getDb().select().from(workflows).where(and$1(inArray$1(workflows.id, ids), isNull(workflows.deletedAt)));\n}\n/** Fetch a single active workflow by id from the bound org schema (all projects). */\nasync function selectActiveWorkflowById(id) {\n\treturn (await getDb().select().from(workflows).where(and$1(eq$1(workflows.id, id), isNull(workflows.deletedAt))).limit(1))[0];\n}\n//#endregion\n//#region src/queries/workflows/write.ts\nasync function insertWorkflow(values) {\n\tawait getDb().insert(workflows).values({\n\t\t...values,\n\t\tprojectId: projectScopeId(),\n\t\tsubscribable: values.subscribable ? 1 : 0\n\t});\n}\nasync function updateWorkflowById(id, values) {\n\tawait getDb().update(workflows).set({\n\t\tname: values.name,\n\t\tdescription: values.description,\n\t\tmoduleFile: values.moduleFile,\n\t\tsubscribable: values.subscribable ? 1 : 0,\n\t\tupdatedAt: values.updatedAt,\n\t\tdeletedAt: values.deletedAt\n\t}).where(scopedAnd(workflows, eq$1(workflows.id, id)));\n}\nasync function softDeleteAllWorkflows(now) {\n\tawait getDb().update(workflows).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(workflows, isNull(workflows.deletedAt)));\n}\nasync function softDeleteWorkflowsNotInSlugs(slugs, now) {\n\tawait getDb().update(workflows).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(workflows, isNull(workflows.deletedAt), notInArray(workflows.slug, slugs)));\n}\n//#endregion\n//#region src/queries/skills/list-active.ts\n/**\n* List every active skill in the bound org schema (all projects). Not project\n* scoped — the org database schema is itself the tenant boundary.\n*/\nasync function listActiveSkills(options) {\n\tconst db = getDb();\n\tif (options?.projectIds !== void 0 && options.projectIds.length === 0) return [];\n\tconst conditions = [isNull(skills.deletedAt)];\n\tif (options?.projectIds !== void 0) conditions.push(inArray$1(skills.projectId, options.projectIds));\n\treturn db.select().from(skills).where(and$1(...conditions)).orderBy(desc(skills.updatedAt));\n}\n//#endregion\n//#region src/queries/skills/select.ts\nasync function selectSkillBySlug(slug) {\n\treturn (await getDb().select().from(skills).where(scopedAnd(skills, eq$1(skills.slug, slug))).limit(1))[0];\n}\n/** Fetch active skills by id from the bound org schema (all projects). */\nasync function selectActiveSkillsByIds(ids) {\n\tif (ids.length === 0) return [];\n\treturn getDb().select().from(skills).where(and$1(inArray$1(skills.id, ids), isNull(skills.deletedAt)));\n}\n/** Fetch a single active skill by id from the bound org schema (all projects). */\nasync function selectActiveSkillById(id) {\n\treturn (await getDb().select().from(skills).where(and$1(eq$1(skills.id, id), isNull(skills.deletedAt))).limit(1))[0];\n}\n//#endregion\n//#region src/queries/skills/write.ts\nasync function insertSkill(values) {\n\tawait getDb().insert(skills).values({\n\t\t...values,\n\t\tprojectId: projectScopeId()\n\t});\n}\nasync function updateSkillById(id, values) {\n\tawait getDb().update(skills).set({\n\t\tname: values.name,\n\t\tdescription: values.description,\n\t\tmoduleFile: values.moduleFile,\n\t\tupdatedAt: values.updatedAt,\n\t\tdeletedAt: values.deletedAt\n\t}).where(scopedAnd(skills, eq$1(skills.id, id)));\n}\nasync function softDeleteAllSkills(now) {\n\tawait getDb().update(skills).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(skills, isNull(skills.deletedAt)));\n}\nasync function softDeleteSkillsNotInSlugs(slugs, now) {\n\tawait getDb().update(skills).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(scopedAnd(skills, isNull(skills.deletedAt), notInArray(skills.slug, slugs)));\n}\n//#endregion\n//#region src/queries/workflow-subscriptions/index.ts\nasync function selectWorkflowSubscriptionById(id) {\n\treturn (await getDb().select().from(workflowSubscriptions).where(scopedAnd(workflowSubscriptions, eq$1(workflowSubscriptions.id, id))).limit(1))[0];\n}\nasync function selectWorkflowSubscriptionByWorkflowAndUser(workflowSlug, userId) {\n\treturn (await getDb().select().from(workflowSubscriptions).where(scopedAnd(workflowSubscriptions, eq$1(workflowSubscriptions.workflowSlug, workflowSlug), eq$1(workflowSubscriptions.userId, userId))).limit(1))[0];\n}\nasync function listWorkflowSubscriptionsByWorkflowSlug(workflowSlug) {\n\treturn getDb().select().from(workflowSubscriptions).where(scopedAnd(workflowSubscriptions, eq$1(workflowSubscriptions.workflowSlug, workflowSlug)));\n}\nasync function listEnabledWorkflowSubscriptionsByWorkflowSlug(workflowSlug) {\n\treturn getDb().select().from(workflowSubscriptions).where(scopedAnd(workflowSubscriptions, eq$1(workflowSubscriptions.workflowSlug, workflowSlug), eq$1(workflowSubscriptions.enabled, 1)));\n}\nasync function insertWorkflowSubscription(values) {\n\tawait getDb().insert(workflowSubscriptions).values({\n\t\t...values,\n\t\tprojectId: projectScopeId(),\n\t\tenabled: values.enabled ? 1 : 0\n\t});\n}\nasync function updateWorkflowSubscriptionById(id, values) {\n\tawait getDb().update(workflowSubscriptions).set({\n\t\tenabled: values.enabled ? 1 : 0,\n\t\tupdatedAt: values.updatedAt\n\t}).where(scopedAnd(workflowSubscriptions, eq$1(workflowSubscriptions.id, id)));\n}\nasync function deleteWorkflowSubscriptionById(id) {\n\tif (!await selectWorkflowSubscriptionById(id)) return false;\n\tawait getDb().delete(workflowSubscriptions).where(scopedAnd(workflowSubscriptions, eq$1(workflowSubscriptions.id, id)));\n\treturn true;\n}\n//#endregion\n//#region src/queries/resource-activity/index.ts\nasync function selectResourceActivityByUserAndResource(input) {\n\treturn (await getDb().select().from(resourceActivity).where(and$1(eq$1(resourceActivity.projectId, input.projectId), eq$1(resourceActivity.userId, input.userId), eq$1(resourceActivity.resourceKind, input.resourceKind), eq$1(resourceActivity.resourceId, input.resourceId))).limit(1))[0];\n}\nasync function touchResourceActivity(input) {\n\tconst now = /* @__PURE__ */ new Date();\n\tconst existing = await selectResourceActivityByUserAndResource(input);\n\tconst db = getDb();\n\tif (existing) {\n\t\tawait db.update(resourceActivity).set({ lastOpenedAt: now }).where(eq$1(resourceActivity.id, existing.id));\n\t\treturn;\n\t}\n\tawait db.insert(resourceActivity).values({\n\t\tid: crypto.randomUUID(),\n\t\tprojectId: input.projectId,\n\t\tuserId: input.userId,\n\t\tresourceKind: input.resourceKind,\n\t\tresourceId: input.resourceId,\n\t\tlastOpenedAt: now\n\t});\n}\nasync function listRecentResourceActivity(userId, limit) {\n\treturn getDb().select().from(resourceActivity).where(eq$1(resourceActivity.userId, userId)).orderBy(desc(resourceActivity.lastOpenedAt)).limit(limit);\n}\n//#endregion\n//#region src/queries/resource-last-run/index.ts\n/**\n* Last run per workflow id from the bound org schema.\n*\n* Runs are keyed by (projectId, workflowSlug), so join onto the workflows\n* registry to resolve ids. Account pages span all projects in the org, so this\n* intentionally does not use the ALS project scope — the join already matches\n* each run to its own project's workflow row.\n*/\nasync function selectWorkflowLastRunAtByIds(workflowIds) {\n\tif (workflowIds.length === 0) return /* @__PURE__ */ new Map();\n\tconst rows = await getDb().select({\n\t\tworkflowId: workflows.id,\n\t\tlastRunAt: max(workflowRuns.triggeredAt)\n\t}).from(workflowRuns).innerJoin(workflows, and(eq(workflows.projectId, workflowRuns.projectId), eq(workflows.slug, workflowRuns.workflowSlug))).where(inArray(workflows.id, workflowIds)).groupBy(workflows.id);\n\tconst result = /* @__PURE__ */ new Map();\n\tfor (const row of rows) if (row.lastRunAt) result.set(row.workflowId, row.lastRunAt);\n\treturn result;\n}\n/**\n* Last session activity per agent id from the bound org schema.\n*\n* Agent ids are unique within the org schema, so no project scope filter is\n* needed (and the ALS scope is not bound on account routes anyway).\n*/\nasync function selectAgentLastRunAtByIds(agentIds) {\n\tif (agentIds.length === 0) return /* @__PURE__ */ new Map();\n\tconst rows = await getDb().select({\n\t\tagentId: agentSessions.agentId,\n\t\tlastRunAt: max(agentSessions.updatedAt)\n\t}).from(agentSessions).where(inArray(agentSessions.agentId, agentIds)).groupBy(agentSessions.agentId);\n\tconst result = /* @__PURE__ */ new Map();\n\tfor (const row of rows) if (row.lastRunAt) result.set(row.agentId, row.lastRunAt);\n\treturn result;\n}\n//#endregion\n//#region src/queries/project-metrics/select-resource-counts.ts\n/**\n* Active resource counts grouped by project id across the bound org schema. Not\n* project scoped — the org database schema is itself the tenant boundary.\n*/\nasync function selectProjectResourceCounts(options) {\n\tif (options?.projectIds !== void 0 && options.projectIds.length === 0) return {};\n\tconst db = getDb();\n\tconst projectIds = options?.projectIds;\n\tconst agentConditions = [isNull(agents.deletedAt)];\n\tconst workflowConditions = [isNull(workflows.deletedAt)];\n\tconst skillConditions = [isNull(skills.deletedAt)];\n\tconst credentialConditions = [eq$1(credentialInstances.scopeType, \"project\")];\n\tif (projectIds !== void 0) {\n\t\tagentConditions.push(inArray$1(agents.projectId, projectIds));\n\t\tworkflowConditions.push(inArray$1(workflows.projectId, projectIds));\n\t\tskillConditions.push(inArray$1(skills.projectId, projectIds));\n\t\tcredentialConditions.push(inArray$1(credentialInstances.projectId, projectIds));\n\t}\n\tconst [agentRows, workflowRows, skillRows, credentialRows] = await Promise.all([\n\t\tdb.select({\n\t\t\tprojectId: agents.projectId,\n\t\t\tcount: count()\n\t\t}).from(agents).where(and$1(...agentConditions)).groupBy(agents.projectId),\n\t\tdb.select({\n\t\t\tprojectId: workflows.projectId,\n\t\t\tcount: count()\n\t\t}).from(workflows).where(and$1(...workflowConditions)).groupBy(workflows.projectId),\n\t\tdb.select({\n\t\t\tprojectId: skills.projectId,\n\t\t\tcount: count()\n\t\t}).from(skills).where(and$1(...skillConditions)).groupBy(skills.projectId),\n\t\tdb.select({\n\t\t\tprojectId: credentialInstances.projectId,\n\t\t\tcount: count()\n\t\t}).from(credentialInstances).where(and$1(...credentialConditions)).groupBy(credentialInstances.projectId)\n\t]);\n\tconst metrics = {};\n\tconst ensure = (projectId) => {\n\t\tlet entry = metrics[projectId];\n\t\tif (!entry) {\n\t\t\tentry = {\n\t\t\t\tagentCount: 0,\n\t\t\t\tworkflowCount: 0,\n\t\t\t\tskillCount: 0,\n\t\t\t\tcredentialCount: 0\n\t\t\t};\n\t\t\tmetrics[projectId] = entry;\n\t\t}\n\t\treturn entry;\n\t};\n\tfor (const row of agentRows) ensure(row.projectId).agentCount = Number(row.count);\n\tfor (const row of workflowRows) ensure(row.projectId).workflowCount = Number(row.count);\n\tfor (const row of skillRows) ensure(row.projectId).skillCount = Number(row.count);\n\tfor (const row of credentialRows) ensure(row.projectId).credentialCount = Number(row.count);\n\treturn metrics;\n}\n//#endregion\n//#region src/agents/serialize.ts\nfunction agentSessionStatusFromSpan(span, messageCount, canceledAt) {\n\tif (canceledAt) return \"canceled\";\n\tif (span) {\n\t\tif (span.status === \"running\") return \"running\";\n\t\tif (span.status === \"error\") return \"failed\";\n\t\treturn \"completed\";\n\t}\n\treturn messageCount > 0 ? \"completed\" : \"running\";\n}\nfunction agentSessionSummaryFromParts(options) {\n\treturn {\n\t\tid: options.row.id,\n\t\tstatus: options.status,\n\t\tsource: options.row.sourceKind,\n\t\tsourceId: options.row.sourceId ?? null,\n\t\ttitle: options.row.title ?? null,\n\t\tranByUserName: options.ranByUserName ?? null,\n\t\tgatewayPlatform: options.gatewayPlatform ?? null,\n\t\ttriggerType: options.triggerType ?? null,\n\t\tcreatedAt: options.row.createdAt.toISOString(),\n\t\tupdatedAt: options.row.updatedAt.toISOString(),\n\t\tmessageCount: options.messageCount\n\t};\n}\nfunction agentSessionRecordFromParts(options) {\n\treturn {\n\t\tid: options.row.id,\n\t\tagentSlug: options.agentSlug,\n\t\tstatus: options.status,\n\t\tsource: options.row.sourceKind,\n\t\tsourceId: options.row.sourceId ?? null,\n\t\tcreatedAt: options.row.createdAt.toISOString(),\n\t\tupdatedAt: options.row.updatedAt.toISOString(),\n\t\tparentSpanId: options.row.parentSpanId ?? null,\n\t\tmessageCount: options.messageCount,\n\t\terror: options.error,\n\t\ttotalDurationMs: options.row.totalDurationMs\n\t};\n}\nfunction gatewaySessionDetailFromParts(gateway, attachmentSlug) {\n\treturn {\n\t\tthreadId: gateway.threadId,\n\t\tattachmentId: gateway.attachmentId,\n\t\tattachmentSlug\n\t};\n}\nfunction agentEventFromRow(row) {\n\treturn {\n\t\tid: row.id,\n\t\tsessionId: row.sessionId,\n\t\tseq: row.seq,\n\t\teventType: row.eventType,\n\t\tpayload: row.payload,\n\t\tcreatedAt: row.createdAt.toISOString()\n\t};\n}\nfunction sessionErrorFromSpan(span) {\n\tif (!span || span.status !== \"error\") return null;\n\treturn span.error ?? null;\n}\n//#endregion\n//#region src/agents/types.ts\nconst MESSAGE_EVENT_TYPE = \"message\";\n//#endregion\n//#region src/tracing/sink.ts\nconst FLUSH_INTERVAL_MS = 50;\nconst FLUSH_BATCH_SIZE = 100;\nfunction createDatabaseTracingSink() {\n\tconst pending = [];\n\tconst seqByTrace = /* @__PURE__ */ new Map();\n\tlet flushTimer;\n\tasync function flushNow() {\n\t\tif (flushTimer) {\n\t\t\tclearTimeout(flushTimer);\n\t\t\tflushTimer = void 0;\n\t\t}\n\t\tif (pending.length === 0) return;\n\t\tawait insertTraceLogs(pending.splice(0, pending.length));\n\t}\n\tfunction scheduleFlush() {\n\t\tif (flushTimer) return;\n\t\tflushTimer = setTimeout(() => {\n\t\t\tflushTimer = void 0;\n\t\t\tflushNow().catch((error) => {\n\t\t\t\tconsole.error(\"[tracing] failed to flush logs:\", error);\n\t\t\t});\n\t\t}, FLUSH_INTERVAL_MS);\n\t}\n\tasync function nextSeq(traceId) {\n\t\tconst cached = seqByTrace.get(traceId);\n\t\tif (cached !== void 0) {\n\t\t\tconst next = cached + 1;\n\t\t\tseqByTrace.set(traceId, next);\n\t\t\treturn next;\n\t\t}\n\t\tconst next = await maxTraceLogSeq(traceId) + 1;\n\t\tseqByTrace.set(traceId, next);\n\t\treturn next;\n\t}\n\treturn {\n\t\tasync openSpan(span) {\n\t\t\tawait insertTraceSpan({\n\t\t\t\tid: span.id,\n\t\t\t\ttraceId: span.traceId,\n\t\t\t\tparentSpanId: span.parentSpanId ?? null,\n\t\t\t\tkind: span.kind,\n\t\t\t\trefId: span.refId,\n\t\t\t\tname: span.name,\n\t\t\t\tstatus: \"running\",\n\t\t\t\tstartedAt: span.startedAt,\n\t\t\t\tmetadata: span.metadata ?? null\n\t\t\t});\n\t\t},\n\t\tasync closeSpan(spanId, status, finishedAt, error) {\n\t\t\tawait updateTraceSpanStatus(spanId, status, finishedAt, error);\n\t\t\tawait flushNow();\n\t\t},\n\t\tasync appendLog(entry) {\n\t\t\tconst seq = await nextSeq(entry.traceId);\n\t\t\tpending.push({\n\t\t\t\tid: crypto.randomUUID(),\n\t\t\t\ttraceId: entry.traceId,\n\t\t\t\tspanId: entry.spanId,\n\t\t\t\tseq,\n\t\t\t\tlevel: entry.level,\n\t\t\t\tmessage: entry.message,\n\t\t\t\tdata: entry.data,\n\t\t\t\tsource: entry.source,\n\t\t\t\tcreatedAt: entry.createdAt\n\t\t\t});\n\t\t\tif (pending.length >= FLUSH_BATCH_SIZE) {\n\t\t\t\tawait flushNow();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tscheduleFlush();\n\t\t},\n\t\tflushNow\n\t};\n}\n//#endregion\n//#region src/tracing/index.ts\nfunction triggerFromSpans(spans) {\n\tconst triggerSpan = spans.find((span) => span.kind === \"trigger_run\");\n\tif (!triggerSpan?.metadata || typeof triggerSpan.metadata !== \"object\") return null;\n\tconst metadata = triggerSpan.metadata;\n\treturn {\n\t\ttriggerType: String(metadata.triggerType ?? \"unknown\"),\n\t\ttriggerRunId: triggerSpan.refId,\n\t\tworkflowSlug: typeof metadata.workflowSlug === \"string\" ? metadata.workflowSlug : void 0,\n\t\tagentSlug: typeof metadata.agentSlug === \"string\" ? metadata.agentSlug : void 0,\n\t\tattachmentId: typeof metadata.attachmentId === \"string\" ? metadata.attachmentId : null,\n\t\tattachmentSlug: typeof metadata.attachmentSlug === \"string\" ? metadata.attachmentSlug : null,\n\t\troute: typeof metadata.route === \"string\" ? metadata.route : void 0,\n\t\tsourcePath: typeof metadata.sourcePath === \"string\" ? metadata.sourcePath : null\n\t};\n}\nfunction gatewayFromSpans(spans) {\n\tconst gatewaySpan = spans.find((span) => span.kind === \"gateway_event\");\n\tif (!gatewaySpan?.metadata || typeof gatewaySpan.metadata !== \"object\") return null;\n\tconst metadata = gatewaySpan.metadata;\n\tif (typeof metadata.gatewayAttachmentId !== \"string\" || typeof metadata.gatewayAttachmentKey !== \"string\") return null;\n\treturn {\n\t\tgatewayAttachmentId: metadata.gatewayAttachmentId,\n\t\tgatewayAttachmentKey: metadata.gatewayAttachmentKey,\n\t\tthreadId: typeof metadata.threadId === \"string\" ? metadata.threadId : void 0,\n\t\tchannelId: typeof metadata.channelId === \"string\" ? metadata.channelId : void 0,\n\t\tmode: typeof metadata.mode === \"string\" ? metadata.mode : void 0\n\t};\n}\nasync function getTraceForWorkflowRun(workflowRunId) {\n\tconst run = await selectWorkflowRunById(workflowRunId);\n\tif (!run) return null;\n\tlet traceId = workflowRunId;\n\tif (run.triggerRunId) traceId = run.triggerRunId;\n\telse {\n\t\tconst workflowSpan = await selectTraceSpanByRefId(workflowRunId);\n\t\tif (workflowSpan) traceId = workflowSpan.traceId;\n\t}\n\tconst spans = await listTraceSpansByTraceId(traceId);\n\tconst logs = await listTraceLogsByTraceId(traceId);\n\treturn {\n\t\ttraceId,\n\t\ttrigger: triggerFromSpans(spans),\n\t\tgateway: gatewayFromSpans(spans),\n\t\tspans,\n\t\tlogs\n\t};\n}\nasync function getTraceForTriggerRun(triggerRunId) {\n\tconst spans = await listTraceSpansByTraceId(triggerRunId);\n\tif (spans.length === 0) return null;\n\tconst logs = await listTraceLogsByTraceId(triggerRunId);\n\treturn {\n\t\ttraceId: triggerRunId,\n\t\ttrigger: triggerFromSpans(spans),\n\t\tgateway: gatewayFromSpans(spans),\n\t\tspans,\n\t\tlogs\n\t};\n}\nasync function getTraceForAgentSession(sessionId) {\n\tconst traceId = (await selectTraceSpanByRefId(sessionId))?.traceId ?? sessionId;\n\tconst spans = await listTraceSpansByTraceId(traceId);\n\tconst logs = await listTraceLogsByTraceId(traceId);\n\tif (spans.length === 0 && logs.length === 0) return null;\n\treturn {\n\t\ttraceId,\n\t\ttrigger: triggerFromSpans(spans),\n\t\tgateway: gatewayFromSpans(spans),\n\t\tspans,\n\t\tlogs\n\t};\n}\n//#endregion\n//#region src/agents/session-api.ts\nasync function resolveGatewayPlatform(row) {\n\tif (row.sourceKind !== \"gateway\" || !row.sourceId) return null;\n\treturn (await selectGatewayAttachmentById(row.sourceId))?.platform ?? null;\n}\nasync function resolveTriggerType(row) {\n\tif (row.sourceKind !== \"trigger\" || !row.sourceId) return null;\n\treturn (await selectTriggerRunById(row.sourceId))?.triggerType ?? null;\n}\nasync function enrichSessionRow(row) {\n\tconst [span, gateway, messageCount] = await Promise.all([\n\t\tselectLatestAgentSessionSpanByRefId(row.id),\n\t\tselectGatewayThreadSessionBySessionId(row.id),\n\t\tcountMessageEventsForSession(row.id, MESSAGE_EVENT_TYPE)\n\t]);\n\treturn {\n\t\tspan,\n\t\tgateway,\n\t\tmessageCount,\n\t\tstatus: agentSessionStatusFromSpan(span, messageCount, row.canceledAt)\n\t};\n}\nasync function buildAgentSessionSummary(row, options) {\n\tconst enriched = await enrichSessionRow(row);\n\tconst [gatewayPlatform, triggerType, ranByUserName] = await Promise.all([\n\t\tresolveGatewayPlatform(row),\n\t\tresolveTriggerType(row),\n\t\trow.ranByUserId && options?.resolveUserName ? options.resolveUserName(row.ranByUserId) : Promise.resolve(null)\n\t]);\n\treturn agentSessionSummaryFromParts({\n\t\trow,\n\t\tstatus: enriched.status,\n\t\tmessageCount: enriched.messageCount,\n\t\tgatewayPlatform,\n\t\ttriggerType,\n\t\tranByUserName\n\t});\n}\nasync function listAgentSessionsPaginated(options) {\n\tconst items = [];\n\tlet cursor = options.cursor;\n\tlet nextCursor = null;\n\twhile (items.length < options.limit) {\n\t\tconst page = await listAgentSessionRowsPaginated({\n\t\t\tagentSlug: options.agentSlug,\n\t\t\tlimit: options.limit,\n\t\t\tcursor,\n\t\t\tsource: options.source\n\t\t});\n\t\tfor (const row of page.rows) {\n\t\t\tconst summary = await buildAgentSessionSummary(row, { resolveUserName: options.resolveUserName });\n\t\t\tif (options.status && summary.status !== options.status) continue;\n\t\t\titems.push(summary);\n\t\t\tif (items.length >= options.limit) {\n\t\t\t\tnextCursor = page.nextCursor;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (items.length >= options.limit || !page.nextCursor) {\n\t\t\tif (items.length < options.limit) nextCursor = null;\n\t\t\tbreak;\n\t\t}\n\t\tcursor = page.nextCursor;\n\t}\n\treturn {\n\t\titems,\n\t\tnextCursor\n\t};\n}\nasync function buildAgentSessionDetail(options) {\n\tconst row = await selectAgentSessionForAgent(options.agentSlug, options.sessionId);\n\tif (!row) return null;\n\tconst enriched = await enrichSessionRow(row);\n\tconst includeGateway = options.include.includes(\"gateway\");\n\tconst includeMessages = options.include.includes(\"messages\");\n\tconst includeEvents = options.include.includes(\"events\");\n\tconst includeTrace = options.include.includes(\"trace\");\n\tlet gateway = null;\n\tif (includeGateway && enriched.gateway) {\n\t\tconst attachment = await selectGatewayAttachmentById(enriched.gateway.attachmentId);\n\t\tgateway = gatewaySessionDetailFromParts(enriched.gateway, attachment?.slug ?? null);\n\t}\n\tconst messages = includeMessages ? await listMessagePayloads(row.id, MESSAGE_EVENT_TYPE) : [];\n\tconst events = includeEvents ? (await listAgentEventsForSession(row.id)).map(agentEventFromRow) : [];\n\tlet trace = null;\n\tif (includeTrace) {\n\t\tconst traceData = await getTraceForAgentSession(row.id);\n\t\ttrace = traceData ? traceResponseToJson(traceData) : null;\n\t}\n\treturn {\n\t\tsession: agentSessionRecordFromParts({\n\t\t\trow,\n\t\t\tagentSlug: options.agentSlug,\n\t\t\tstatus: enriched.status,\n\t\t\tmessageCount: enriched.messageCount,\n\t\t\terror: sessionErrorFromSpan(enriched.span)\n\t\t}),\n\t\tgateway,\n\t\tmessages,\n\t\tevents,\n\t\ttrace\n\t};\n}\nfunction messagePayloadWithSentAt(payload, createdAt, seq) {\n\treturn {\n\t\t...typeof payload === \"object\" && payload !== null && !Array.isArray(payload) ? payload : { content: payload },\n\t\tsentAt: createdAt.toISOString(),\n\t\tseq\n\t};\n}\n/**\n* Returns the persisted chat state for a session. `messages` is the full\n* transcript by default, or only events with `seq > sinceSeq` when a cursor is\n* supplied — the chat UI polls with its highest seen seq so each poll ships only\n* new turns plus the (separate, transient) `live` streaming message. Each\n* message carries its `seq` so the client can advance the cursor and key the row.\n*/\nasync function buildAgentSessionChatState(sessionId, options) {\n\tconst row = await selectActiveAgentSession(sessionId);\n\tif (!row) return null;\n\tconst enriched = await enrichSessionRow(row);\n\tconst [messageEvents, live] = await Promise.all([listMessageEventsForSession(row.id, MESSAGE_EVENT_TYPE, { sinceSeq: options?.sinceSeq }), selectSessionLiveMessage(row.id)]);\n\tconst messages = messageEvents.map(({ payload, createdAt, seq }) => messagePayloadWithSentAt(payload, createdAt, seq));\n\treturn {\n\t\tstatus: enriched.status,\n\t\tmessages,\n\t\tlive: live ?? null\n\t};\n}\n//#endregion\n//#region src/workflows/run-detail.ts\nasync function buildWorkflowRunDetail(options) {\n\tconst row = await selectWorkflowRunForWorkflow(options.workflowSlug, options.runId);\n\tif (!row) return null;\n\tconst includeTrigger = options.include.includes(\"trigger\");\n\tconst includeSteps = options.include.includes(\"steps\");\n\tconst includeTrace = options.include.includes(\"trace\");\n\tlet trigger = null;\n\tif (includeTrigger && row.triggerRunId) {\n\t\tconst triggerRun = await selectTriggerRunById(row.triggerRunId);\n\t\tif (triggerRun) trigger = triggerRunDetailFromRow(triggerRun, (await selectTriggerAttachmentById(triggerRun.attachmentId))?.slug ?? null);\n\t}\n\tconst steps = includeSteps ? (await listStepCompletedEvents(row.id)).map(workflowStepRunFromEvent) : [];\n\tlet trace = null;\n\tif (includeTrace) {\n\t\tconst traceData = await getTraceForWorkflowRun(row.id);\n\t\ttrace = traceData ? traceResponseToJson(traceData) : null;\n\t}\n\treturn {\n\t\trun: workflowRunRecordFromRow(row),\n\t\ttrigger,\n\t\tsteps,\n\t\ttrace\n\t};\n}\n//#endregion\n//#region src/history/helpers.ts\nfunction titleCaseResourceName(slug, explicitName) {\n\tif (explicitName?.trim()) return explicitName.trim();\n\tconst normalized = slug.split(/[/_-]+/).filter(Boolean).join(\" \");\n\tif (!normalized) return slug;\n\treturn normalized.replace(/\\b\\w/g, (char) => char.toUpperCase());\n}\nfunction triggerLabelFromRaw(raw) {\n\tif (raw === \"api\") return \"API\";\n\treturn raw.charAt(0).toUpperCase() + raw.slice(1);\n}\nfunction timeInQueueMsBetween(triggeredAt, startedAt) {\n\tif (!startedAt) return null;\n\treturn Math.max(0, startedAt.getTime() - triggeredAt.getTime());\n}\nfunction buildHistoryUsage(records, durationMs) {\n\tconst grouped = /* @__PURE__ */ new Map();\n\tfor (const record of records) {\n\t\tconst key = `${record.kind}:${record.label}`;\n\t\tconst existing = grouped.get(key);\n\t\tif (existing) existing.amountUsd += record.amountUsd;\n\t\telse grouped.set(key, {\n\t\t\tlabel: record.label,\n\t\t\tamountUsd: record.amountUsd\n\t\t});\n\t}\n\tconst lineItems = [...grouped.entries()].map(([id, item]) => ({\n\t\tid,\n\t\tlabel: item.label,\n\t\tamountUsd: item.amountUsd\n\t}));\n\treturn {\n\t\trunDurationMs: durationMs,\n\t\tlineItems,\n\t\ttotalExcludingDurationUsd: lineItems.reduce((sum, item) => sum + item.amountUsd, 0)\n\t};\n}\n//#endregion\n//#region src/history/trace-messages.ts\nfunction metadataRecord(metadata) {\n\tif (metadata && typeof metadata === \"object\" && !Array.isArray(metadata)) return metadata;\n\treturn {};\n}\nfunction attachMessagesToAgentSessionSpans(spans, messages) {\n\tconst sessionSpans = spans.filter((span) => span.kind === \"agent_session\").sort((left, right) => Date.parse(left.startedAt) - Date.parse(right.startedAt));\n\tif (sessionSpans.length === 0) return spans;\n\tconst sortedMessages = [...messages].sort((left, right) => left.createdAt.getTime() - right.createdAt.getTime());\n\tconst messagesBySpanId = /* @__PURE__ */ new Map();\n\tfor (let index = 0; index < sessionSpans.length; index += 1) {\n\t\tconst span = sessionSpans[index];\n\t\tconst windowStartMs = Date.parse(span.startedAt);\n\t\tconst windowEndMs = index + 1 < sessionSpans.length ? Date.parse(sessionSpans[index + 1].startedAt) : Number.POSITIVE_INFINITY;\n\t\tconst slice = sortedMessages.filter((message) => {\n\t\t\tconst createdAtMs = message.createdAt.getTime();\n\t\t\treturn createdAtMs >= windowStartMs && createdAtMs < windowEndMs;\n\t\t}).map((message) => message.payload);\n\t\tmessagesBySpanId.set(span.id, slice);\n\t}\n\treturn spans.map((span) => {\n\t\tif (span.kind !== \"agent_session\") return span;\n\t\tconst { messages: _stale, ...rest } = metadataRecord(span.metadata);\n\t\treturn {\n\t\t\t...span,\n\t\t\tmetadata: {\n\t\t\t\t...rest,\n\t\t\t\tmessages: messagesBySpanId.get(span.id) ?? []\n\t\t\t}\n\t\t};\n\t});\n}\n//#endregion\n//#region src/history/serialize.ts\nfunction workflowTriggerRaw(run) {\n\tif (run.sourceKind === \"gateway\") return \"gateway\";\n\treturn run.trigger;\n}\nfunction agentTriggerRaw(session) {\n\treturn session.sourceKind;\n}\nfunction workflowTriggerRawFromParts(run, override) {\n\treturn override ?? workflowTriggerRaw(run);\n}\nfunction agentTriggerRawFromParts(session, override) {\n\treturn override ?? agentTriggerRaw(session);\n}\nfunction durationMsBetween(startedAt, finishedAt) {\n\tif (!startedAt || !finishedAt) return null;\n\treturn Math.max(0, finishedAt.getTime() - startedAt.getTime());\n}\nfunction historyRunFromWorkflow(parts) {\n\tconst { run, workflow, stepCount } = parts;\n\tconst resourceKey = run.workflowSlug;\n\tconst resourceId = workflow?.id ?? run.workflowSlug;\n\tconst resourceName = titleCaseResourceName(resourceKey, workflow?.name);\n\tconst status = run.status;\n\tconst startedAt = run.startedAt ?? run.triggeredAt;\n\tconst triggerRaw = workflowTriggerRawFromParts(run, parts.triggerRaw);\n\treturn {\n\t\tid: run.id,\n\t\tkind: \"workflow\",\n\t\ttraceId: run.triggerRunId ?? run.id,\n\t\tprojectId: run.projectId,\n\t\tresourceKey,\n\t\tresourceId,\n\t\tresourceName,\n\t\tstatus,\n\t\ttriggeredAt: run.triggeredAt.toISOString(),\n\t\ttimeInQueueMs: timeInQueueMsBetween(run.triggeredAt, run.startedAt),\n\t\tstartedAt: startedAt.toISOString(),\n\t\tfinishedAt: run.finishedAt?.toISOString() ?? null,\n\t\tdurationMs: durationMsBetween(startedAt, run.finishedAt),\n\t\ttriggerLabel: triggerLabelFromRaw(triggerRaw),\n\t\ttriggerRaw,\n\t\tranByUserId: run.ranByUserId ?? null,\n\t\tmodelsUsed: parts.modelsUsed ?? [],\n\t\totherServicesUsed: parts.otherServicesUsed ?? [],\n\t\ttotalCostUsd: parts.totalCostUsd ?? 0,\n\t\tstepCount\n\t};\n}\nfunction historyRunFromAgent(parts) {\n\tconst { session, agent, status, messageCount } = parts;\n\tconst resourceKey = agent.slug;\n\tconst triggerRaw = agentTriggerRawFromParts(session, parts.triggerRaw);\n\tconst startedAt = session.createdAt;\n\tconst finishedAt = status === \"running\" ? null : session.canceledAt ?? session.updatedAt;\n\treturn {\n\t\tid: session.id,\n\t\tkind: \"agent\",\n\t\ttraceId: session.id,\n\t\tprojectId: session.projectId,\n\t\tresourceKey,\n\t\tresourceId: agent.id,\n\t\tresourceName: titleCaseResourceName(resourceKey, agent.name),\n\t\tstatus,\n\t\ttriggeredAt: session.createdAt.toISOString(),\n\t\ttimeInQueueMs: null,\n\t\tstartedAt: startedAt.toISOString(),\n\t\tfinishedAt: finishedAt?.toISOString() ?? null,\n\t\tdurationMs: parts.totalDurationMs ?? 0,\n\t\ttriggerLabel: triggerLabelFromRaw(triggerRaw),\n\t\ttriggerRaw,\n\t\tranByUserId: session.ranByUserId ?? null,\n\t\tmodelsUsed: parts.modelsUsed ?? [],\n\t\totherServicesUsed: parts.otherServicesUsed ?? [],\n\t\ttotalCostUsd: parts.totalCostUsd ?? 0,\n\t\tmessageCount\n\t};\n}\nfunction mapTrace(trace, messageEvents = []) {\n\treturn {\n\t\ttraceId: trace.traceId,\n\t\ttrigger: trace.trigger ? {\n\t\t\ttriggerType: trace.trigger.triggerType,\n\t\t\ttriggerRunId: trace.trigger.triggerRunId,\n\t\t\t...trace.trigger.workflowSlug ? { workflowKey: trace.trigger.workflowSlug } : {},\n\t\t\t...trace.trigger.agentSlug ? { agentKey: trace.trigger.agentSlug } : {},\n\t\t\tattachmentId: trace.trigger.attachmentId ?? null,\n\t\t\tattachmentKey: trace.trigger.attachmentSlug ?? null,\n\t\t\troute: trace.trigger.route,\n\t\t\tsourcePath: trace.trigger.sourcePath ?? null\n\t\t} : null,\n\t\tgateway: trace.gateway,\n\t\tspans: attachMessagesToAgentSessionSpans(trace.spans, messageEvents),\n\t\tlogs: trace.logs\n\t};\n}\nasync function buildHistoryWorkflowRunDetail(workflowSlug, runId) {\n\tconst detail = await buildWorkflowRunDetail({\n\t\tworkflowSlug,\n\t\trunId,\n\t\tinclude: [\n\t\t\t\"trigger\",\n\t\t\t\"steps\",\n\t\t\t\"trace\"\n\t\t]\n\t});\n\tif (!detail) return null;\n\tconst durationMs = durationMsBetween(detail.run.startedAt ? new Date(detail.run.startedAt) : null, detail.run.finishedAt ? new Date(detail.run.finishedAt) : null);\n\tconst usageRecords = await listUsageRecordsForRun(runId, \"workflow\");\n\treturn {\n\t\tkind: \"workflow\",\n\t\trun: {\n\t\t\tid: detail.run.id,\n\t\t\tworkflowKey: detail.run.workflowSlug,\n\t\t\tstatus: detail.run.status,\n\t\t\ttrigger: detail.run.trigger,\n\t\t\ttriggeredAt: detail.run.triggeredAt,\n\t\t\tstartedAt: detail.run.startedAt,\n\t\t\tfinishedAt: detail.run.finishedAt,\n\t\t\tinput: detail.run.input,\n\t\t\toutput: detail.run.output,\n\t\t\terror: detail.run.error\n\t\t},\n\t\ttrigger: detail.trigger ? {\n\t\t\tid: detail.trigger.id,\n\t\t\tattachmentKey: detail.trigger.attachmentSlug,\n\t\t\ttriggerType: detail.trigger.triggerType,\n\t\t\tsourcePath: detail.trigger.sourcePath,\n\t\t\tpayload: detail.trigger.payload,\n\t\t\ttriggeredAt: detail.trigger.triggeredAt\n\t\t} : null,\n\t\tsteps: detail.steps,\n\t\ttrace: detail.trace ? mapTrace(detail.trace) : null,\n\t\tusage: buildHistoryUsage(usageRecords.map((record) => ({\n\t\t\tkind: record.kind,\n\t\t\tlabel: record.label,\n\t\t\tamountUsd: record.amount\n\t\t})), durationMs)\n\t};\n}\nasync function buildHistoryAgentSessionDetail(agentSlug, sessionId) {\n\tconst [detail, messageEvents] = await Promise.all([buildAgentSessionDetail({\n\t\tagentSlug,\n\t\tsessionId,\n\t\tinclude: [\"gateway\", \"trace\"]\n\t}), listMessageEventsForSession(sessionId, MESSAGE_EVENT_TYPE)]);\n\tif (!detail) return null;\n\tconst usageRecords = await listUsageRecordsForRun(sessionId, \"agent\");\n\treturn {\n\t\tkind: \"agent\",\n\t\trunId: detail.session.id,\n\t\tsession: {\n\t\t\tid: detail.session.id,\n\t\t\tagentKey: detail.session.agentSlug,\n\t\t\tstatus: detail.session.status,\n\t\t\tsource: detail.session.source,\n\t\t\tsourceId: detail.session.sourceId,\n\t\t\tcreatedAt: detail.session.createdAt,\n\t\t\tupdatedAt: detail.session.updatedAt,\n\t\t\tmessageCount: detail.session.messageCount,\n\t\t\terror: detail.session.error\n\t\t},\n\t\tgateway: detail.gateway ? {\n\t\t\tthreadId: detail.gateway.threadId,\n\t\t\tattachmentKey: detail.gateway.attachmentSlug\n\t\t} : null,\n\t\tmessages: messageEvents.map((event) => event.payload),\n\t\ttrace: detail.trace ? mapTrace(detail.trace, messageEvents) : null,\n\t\tusage: buildHistoryUsage(usageRecords.map((record) => ({\n\t\t\tkind: record.kind,\n\t\t\tlabel: record.label,\n\t\t\tamountUsd: record.amount\n\t\t})), detail.session.totalDurationMs ?? null)\n\t};\n}\n//#endregion\n//#region src/queries/history/internal.ts\nasync function countStepCompletedEventsByRunIds(runIds) {\n\tif (runIds.length === 0) return /* @__PURE__ */ new Map();\n\tconst rows = await getDb().select({\n\t\trunId: workflowEvents.runId,\n\t\tcount: sql$1`count(*)`\n\t}).from(workflowEvents).where(and$1(inArray$1(workflowEvents.runId, runIds), eq$1(workflowEvents.type, \"step_completed\"))).groupBy(workflowEvents.runId);\n\treturn new Map(rows.map((row) => [row.runId, Number(row.count ?? 0)]));\n}\nasync function countStepCompletedEvents(runId) {\n\treturn (await countStepCompletedEventsByRunIds([runId])).get(runId) ?? 0;\n}\nasync function countMessageEventsBySessionIds(sessionIds, messageEventType) {\n\tif (sessionIds.length === 0) return /* @__PURE__ */ new Map();\n\tconst rows = await getDb().select({\n\t\tsessionId: agentEvents.sessionId,\n\t\tcount: sql$1`count(*)`\n\t}).from(agentEvents).innerJoin(agentSessions, eq$1(agentSessions.id, agentEvents.sessionId)).where(and$1(inArray$1(agentEvents.sessionId, sessionIds), eq$1(agentEvents.eventType, messageEventType), isNull(agentEvents.deletedAt))).groupBy(agentEvents.sessionId);\n\treturn new Map(rows.map((row) => [row.sessionId, Number(row.count ?? 0)]));\n}\nasync function selectTriggerTypesByIds(ids) {\n\tif (ids.length === 0) return /* @__PURE__ */ new Map();\n\tconst rows = await getDb().select({\n\t\tid: triggerRuns.id,\n\t\ttriggerType: triggerRuns.triggerType\n\t}).from(triggerRuns).where(inArray$1(triggerRuns.id, ids));\n\treturn new Map(rows.map((row) => [row.id, row.triggerType]));\n}\nfunction resolveWorkflowTriggerRaw(run, triggerTypes) {\n\tif (run.sourceKind === \"gateway\") return \"gateway\";\n\tif (run.sourceKind === \"trigger\" && run.triggerRunId) {\n\t\tconst triggerType = triggerTypes.get(run.triggerRunId);\n\t\tif (triggerType) return triggerType;\n\t}\n\treturn run.trigger;\n}\nfunction resolveAgentTriggerRaw(session, triggerTypes) {\n\tif (session.sourceKind === \"trigger\" && session.sourceId) {\n\t\tconst triggerType = triggerTypes.get(session.sourceId);\n\t\tif (triggerType) return triggerType;\n\t}\n\tif (session.sourceKind === \"gateway\") return \"gateway\";\n\treturn session.sourceKind;\n}\nfunction otherServicesUsedByRunId(records) {\n\tconst byRunId = /* @__PURE__ */ new Map();\n\tfor (const record of records) {\n\t\tif (record.kind === \"llm\") continue;\n\t\tconst kinds = byRunId.get(record.runId) ?? /* @__PURE__ */ new Set();\n\t\tkinds.add(record.kind);\n\t\tbyRunId.set(record.runId, kinds);\n\t}\n\treturn new Map([...byRunId.entries()].map(([runId, kinds]) => [runId, [...kinds]]));\n}\nfunction workflowUsageRollupsByRunId(records) {\n\tconst byRunId = /* @__PURE__ */ new Map();\n\tfor (const record of records) {\n\t\tconst entry = byRunId.get(record.runId) ?? {\n\t\t\ttotalCostUsd: 0,\n\t\t\tmodelsUsed: /* @__PURE__ */ new Set()\n\t\t};\n\t\tentry.totalCostUsd += record.amount;\n\t\tif (record.kind === \"llm\") entry.modelsUsed.add(record.label);\n\t\tbyRunId.set(record.runId, entry);\n\t}\n\treturn new Map([...byRunId.entries()].map(([runId, entry]) => [runId, {\n\t\ttotalCostUsd: entry.totalCostUsd,\n\t\tmodelsUsed: [...entry.modelsUsed]\n\t}]));\n}\nasync function selectLatestAgentSessionSpansByRefIds(sessionIds) {\n\tif (sessionIds.length === 0) return /* @__PURE__ */ new Map();\n\tconst rows = await getDb().select({\n\t\tspan: traceSpans,\n\t\trefId: traceSpans.refId\n\t}).from(traceSpans).innerJoin(agentSessions, eq$1(agentSessions.id, traceSpans.refId)).where(and$1(inArray$1(traceSpans.refId, sessionIds), eq$1(traceSpans.kind, \"agent_session\"), isNull(agentSessions.deletedAt))).orderBy(desc(traceSpans.startedAt));\n\tconst latestByRefId = /* @__PURE__ */ new Map();\n\tfor (const row of rows) if (!latestByRefId.has(row.refId)) latestByRefId.set(row.refId, row.span);\n\treturn latestByRefId;\n}\nfunction historyProjectConditions(column, filter) {\n\tif (filter?.projectIds !== void 0) {\n\t\tif (filter.projectIds.length === 0) return [];\n\t\treturn [inArray$1(column, filter.projectIds)];\n\t}\n\treturn [];\n}\nfunction resolveFetchLimit(limit, status) {\n\tif (!status) return limit;\n\treturn Math.min(limit * 5, 500);\n}\nfunction matchesStatusFilter(actual, filter) {\n\tif (filter === \"running\") return actual === \"running\" || actual === \"pending\";\n\treturn actual === filter;\n}\n//#endregion\n//#region src/queries/history/list-runs.ts\nasync function listWorkflowHistoryRuns(filter, fetchLimit) {\n\tconst conditions = historyProjectConditions(workflowRuns.projectId, filter);\n\tif (filter?.projectIds !== void 0 && filter.projectIds.length === 0) return [];\n\tconst db = getDb();\n\tconst rows = await (conditions.length > 0 ? db.select({\n\t\trun: workflowRuns,\n\t\tworkflow: workflows\n\t}).from(workflowRuns).leftJoin(workflows, and$1(eq$1(workflows.projectId, workflowRuns.projectId), eq$1(workflows.slug, workflowRuns.workflowSlug), isNull(workflows.deletedAt))).where(and$1(...conditions)) : db.select({\n\t\trun: workflowRuns,\n\t\tworkflow: workflows\n\t}).from(workflowRuns).leftJoin(workflows, and$1(eq$1(workflows.projectId, workflowRuns.projectId), eq$1(workflows.slug, workflowRuns.workflowSlug), isNull(workflows.deletedAt)))).orderBy(desc(workflowRuns.triggeredAt), desc(workflowRuns.id)).limit(fetchLimit);\n\tconst runIds = rows.map((row) => row.run.id);\n\tconst triggerRunIds = rows.map((row) => row.run.sourceKind === \"trigger\" ? row.run.triggerRunId : null).filter((id) => Boolean(id));\n\tconst [stepCounts, triggerTypes, usageRecords] = await Promise.all([\n\t\tcountStepCompletedEventsByRunIds(runIds),\n\t\tselectTriggerTypesByIds(triggerRunIds),\n\t\tlistUsageRecordsForRuns(runIds, \"workflow\")\n\t]);\n\tconst usageRollups = workflowUsageRollupsByRunId(usageRecords);\n\tconst otherServicesUsed = otherServicesUsedByRunId(usageRecords);\n\treturn rows.map((row) => {\n\t\tconst rollups = usageRollups.get(row.run.id);\n\t\treturn historyRunFromWorkflow({\n\t\t\trun: row.run,\n\t\t\tworkflow: row.workflow,\n\t\t\tstepCount: stepCounts.get(row.run.id) ?? 0,\n\t\t\ttriggerRaw: resolveWorkflowTriggerRaw(row.run, triggerTypes),\n\t\t\ttotalCostUsd: rollups?.totalCostUsd ?? 0,\n\t\t\tmodelsUsed: rollups?.modelsUsed ?? [],\n\t\t\totherServicesUsed: otherServicesUsed.get(row.run.id) ?? []\n\t\t});\n\t});\n}\nasync function listAgentHistoryRuns(filter, fetchLimit) {\n\tif (filter?.projectIds !== void 0 && filter.projectIds.length === 0) return [];\n\tconst db = getDb();\n\tconst conditions = [isNull(agentSessions.deletedAt), isNull(agents.deletedAt)];\n\tif (filter?.projectIds !== void 0) conditions.push(inArray$1(agentSessions.projectId, filter.projectIds));\n\tconst rows = await db.select({\n\t\tsession: agentSessions,\n\t\tagent: agents\n\t}).from(agentSessions).innerJoin(agents, eq$1(agents.id, agentSessions.agentId)).where(and$1(...conditions)).orderBy(desc(agentSessions.updatedAt), desc(agentSessions.id)).limit(fetchLimit);\n\tconst sessionIds = rows.map((row) => row.session.id);\n\tconst triggerRunIds = rows.map((row) => row.session.sourceKind === \"trigger\" ? row.session.sourceId : null).filter((id) => Boolean(id));\n\tconst [messageCounts, triggerTypes, spansBySessionId, usageRecords] = await Promise.all([\n\t\tcountMessageEventsBySessionIds(sessionIds, MESSAGE_EVENT_TYPE),\n\t\tselectTriggerTypesByIds(triggerRunIds),\n\t\tselectLatestAgentSessionSpansByRefIds(sessionIds),\n\t\tlistUsageRecordsForRuns(sessionIds, \"agent\")\n\t]);\n\tconst usageRollups = workflowUsageRollupsByRunId(usageRecords);\n\tconst otherServicesUsed = otherServicesUsedByRunId(usageRecords);\n\treturn rows.map((row) => {\n\t\tconst messageCount = messageCounts.get(row.session.id) ?? 0;\n\t\tconst span = spansBySessionId.get(row.session.id);\n\t\tconst rollups = usageRollups.get(row.session.id);\n\t\treturn historyRunFromAgent({\n\t\t\tsession: row.session,\n\t\t\tagent: row.agent,\n\t\t\tstatus: agentSessionStatusFromSpan(span, messageCount, row.session.canceledAt),\n\t\t\tmessageCount,\n\t\t\ttriggerRaw: resolveAgentTriggerRaw(row.session, triggerTypes),\n\t\t\ttotalDurationMs: row.session.totalDurationMs,\n\t\t\ttotalCostUsd: rollups?.totalCostUsd ?? 0,\n\t\t\tmodelsUsed: rollups?.modelsUsed ?? [],\n\t\t\totherServicesUsed: otherServicesUsed.get(row.session.id) ?? []\n\t\t});\n\t});\n}\nfunction sortHistoryRuns(items) {\n\treturn [...items].sort((a, b) => new Date(b.startedAt).getTime() - new Date(a.startedAt).getTime());\n}\nasync function listHistoryRuns(options = {}) {\n\tconst limit = options.limit ?? 100;\n\tconst fetchLimit = resolveFetchLimit(limit, options.status);\n\tconst includeWorkflows = options.kind !== \"agent\";\n\tconst includeAgents = options.kind !== \"workflow\";\n\tconst projectFilter = options.projectIds !== void 0 ? { projectIds: options.projectIds } : void 0;\n\tconst [workflowItems, agentItems] = await Promise.all([includeWorkflows ? listWorkflowHistoryRuns(projectFilter, fetchLimit) : Promise.resolve([]), includeAgents ? listAgentHistoryRuns(projectFilter, fetchLimit) : Promise.resolve([])]);\n\tlet items = sortHistoryRuns([...workflowItems, ...agentItems]);\n\tif (options.status) items = items.filter((item) => matchesStatusFilter(item.status, options.status));\n\treturn items.slice(0, limit);\n}\n//#endregion\n//#region src/queries/history/find-run-core.ts\nasync function findHistoryRunCore(runId) {\n\tconst db = getDb();\n\tconst workflowRow = (await db.select({\n\t\trun: workflowRuns,\n\t\tworkflow: workflows\n\t}).from(workflowRuns).leftJoin(workflows, and$1(eq$1(workflows.projectId, workflowRuns.projectId), eq$1(workflows.slug, workflowRuns.workflowSlug), isNull(workflows.deletedAt))).where(eq$1(workflowRuns.id, runId)).limit(1))[0];\n\tif (workflowRow) {\n\t\tconst [stepCount, triggerTypes, usageRecords] = await Promise.all([\n\t\t\tcountStepCompletedEvents(workflowRow.run.id),\n\t\t\tselectTriggerTypesByIds(workflowRow.run.sourceKind === \"trigger\" && workflowRow.run.triggerRunId ? [workflowRow.run.triggerRunId] : []),\n\t\t\tlistUsageRecordsForRuns([workflowRow.run.id], \"workflow\")\n\t\t]);\n\t\tconst rollups = workflowUsageRollupsByRunId(usageRecords).get(workflowRow.run.id);\n\t\tconst otherServicesUsed = otherServicesUsedByRunId(usageRecords).get(workflowRow.run.id) ?? [];\n\t\treturn historyRunFromWorkflow({\n\t\t\trun: workflowRow.run,\n\t\t\tworkflow: workflowRow.workflow,\n\t\t\tstepCount,\n\t\t\ttriggerRaw: resolveWorkflowTriggerRaw(workflowRow.run, triggerTypes),\n\t\t\ttotalCostUsd: rollups?.totalCostUsd ?? 0,\n\t\t\tmodelsUsed: rollups?.modelsUsed ?? [],\n\t\t\totherServicesUsed\n\t\t});\n\t}\n\tconst agentRow = (await db.select({\n\t\tsession: agentSessions,\n\t\tagent: agents\n\t}).from(agentSessions).innerJoin(agents, eq$1(agents.id, agentSessions.agentId)).where(and$1(eq$1(agentSessions.id, runId), isNull(agentSessions.deletedAt), isNull(agents.deletedAt))).limit(1))[0];\n\tif (!agentRow) return null;\n\tconst sessionId = agentRow.session.id;\n\tconst [messageCounts, triggerTypes, spansBySessionId, usageRecords] = await Promise.all([\n\t\tcountMessageEventsBySessionIds([sessionId], MESSAGE_EVENT_TYPE),\n\t\tselectTriggerTypesByIds(agentRow.session.sourceKind === \"trigger\" && agentRow.session.sourceId ? [agentRow.session.sourceId] : []),\n\t\tselectLatestAgentSessionSpansByRefIds([sessionId]),\n\t\tlistUsageRecordsForRuns([sessionId], \"agent\")\n\t]);\n\tconst messageCount = messageCounts.get(sessionId) ?? 0;\n\tconst span = spansBySessionId.get(sessionId);\n\tconst rollups = workflowUsageRollupsByRunId(usageRecords).get(sessionId);\n\tconst otherServicesUsed = otherServicesUsedByRunId(usageRecords).get(sessionId) ?? [];\n\treturn historyRunFromAgent({\n\t\tsession: agentRow.session,\n\t\tagent: agentRow.agent,\n\t\tstatus: agentSessionStatusFromSpan(span, messageCount, agentRow.session.canceledAt),\n\t\tmessageCount,\n\t\ttriggerRaw: resolveAgentTriggerRaw(agentRow.session, triggerTypes),\n\t\ttotalDurationMs: agentRow.session.totalDurationMs,\n\t\ttotalCostUsd: rollups?.totalCostUsd ?? 0,\n\t\tmodelsUsed: rollups?.modelsUsed ?? [],\n\t\totherServicesUsed\n\t});\n}\n//#endregion\n//#region src/queries/credential-instances/index.ts\n/** Org/user credentials live once in the shared org database; project scope stays per-project. */\nfunction credentialScopeAnd(scopeType, ...conditions) {\n\tif (scopeType === \"project\") return scopedAnd(credentialInstances, ...conditions);\n\treturn and$1(...conditions.filter(Boolean));\n}\nfunction resolveCredentialProjectId(scopeType) {\n\tif (scopeType === \"project\") return projectScopeId();\n\treturn getServerTenantScopeId();\n}\n/** Every credential instance row in the org database (org/user rows plus all projects' rows). */\nasync function listAllCredentialInstances() {\n\treturn getDb().select().from(credentialInstances);\n}\nasync function listCredentialInstancesByConnectionId(connectionId) {\n\treturn getDb().select().from(credentialInstances).where(eq$1(credentialInstances.connectionId, connectionId));\n}\nasync function selectCredentialInstanceById(id) {\n\treturn (await getDb().select().from(credentialInstances).where(eq$1(credentialInstances.id, id)).limit(1))[0];\n}\nasync function listCredentialInstancesByScope(options) {\n\tconst db = getDb();\n\tconst conditions = [options.scopeId === null ? and$1(eq$1(credentialInstances.scopeType, options.scopeType), isNull(credentialInstances.scopeId)) : and$1(eq$1(credentialInstances.scopeType, options.scopeType), eq$1(credentialInstances.scopeId, options.scopeId))];\n\tif (options.appSlug) conditions.push(eq$1(credentialInstances.appSlug, options.appSlug));\n\treturn db.select().from(credentialInstances).where(credentialScopeAnd(options.scopeType, ...conditions));\n}\nasync function selectCredentialInstancesForScope(appSlug, scopeType, scopeId) {\n\tconst db = getDb();\n\tconst scopeCondition = scopeId === null ? and$1(eq$1(credentialInstances.scopeType, scopeType), isNull(credentialInstances.scopeId)) : and$1(eq$1(credentialInstances.scopeType, scopeType), eq$1(credentialInstances.scopeId, scopeId));\n\treturn db.select().from(credentialInstances).where(credentialScopeAnd(scopeType, eq$1(credentialInstances.appSlug, appSlug), scopeCondition));\n}\nasync function insertCredentialInstance(values) {\n\tawait getDb().insert(credentialInstances).values({\n\t\t...values,\n\t\tprojectId: resolveCredentialProjectId(values.scopeType),\n\t\tisDefault: values.isDefault ? 1 : 0\n\t});\n}\nasync function upsertCredentialInstance(values) {\n\tif (await selectCredentialInstanceById(values.id)) {\n\t\tawait getDb().update(credentialInstances).set({\n\t\t\tappSlug: values.appSlug,\n\t\t\tslug: values.slug,\n\t\t\tname: values.name ?? null,\n\t\t\tscopeType: values.scopeType,\n\t\t\tscopeId: values.scopeId,\n\t\t\tlabel: values.label,\n\t\t\tisDefault: values.isDefault ? 1 : 0,\n\t\t\tauthKind: values.authKind,\n\t\t\tciphertext: values.ciphertext,\n\t\t\tconnectionId: values.connectionId,\n\t\t\tsharedConnectionId: values.sharedConnectionId,\n\t\t\tupdatedAt: values.updatedAt\n\t\t}).where(eq$1(credentialInstances.id, values.id));\n\t\treturn;\n\t}\n\tawait insertCredentialInstance(values);\n}\nasync function deleteCredentialInstanceById(id) {\n\tif (!await selectCredentialInstanceById(id)) return false;\n\tawait getDb().delete(credentialInstances).where(eq$1(credentialInstances.id, id));\n\treturn true;\n}\nasync function clearCredentialInstanceDefaults(options) {\n\tconst db = getDb();\n\tconst scopeCondition = options.scopeId === null ? and$1(eq$1(credentialInstances.scopeType, options.scopeType), isNull(credentialInstances.scopeId)) : and$1(eq$1(credentialInstances.scopeType, options.scopeType), eq$1(credentialInstances.scopeId, options.scopeId));\n\tconst conditions = [\n\t\teq$1(credentialInstances.appSlug, options.appSlug),\n\t\tscopeCondition,\n\t\teq$1(credentialInstances.isDefault, 1)\n\t];\n\tif (options.exceptId) conditions.push(ne(credentialInstances.id, options.exceptId));\n\tawait db.update(credentialInstances).set({\n\t\tisDefault: 0,\n\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t}).where(credentialScopeAnd(options.scopeType, ...conditions));\n}\n//#endregion\n//#region src/queries/credential-assignments/index.ts\nasync function listCredentialAssignmentsByTarget(options) {\n\treturn getDb().select().from(credentialAssignments).where(scopedAnd(credentialAssignments, eq$1(credentialAssignments.targetType, options.targetType), eq$1(credentialAssignments.targetKey, options.targetKey)));\n}\nasync function selectCredentialAssignmentById(id) {\n\treturn (await getDb().select().from(credentialAssignments).where(scopedAnd(credentialAssignments, eq$1(credentialAssignments.id, id))).limit(1))[0];\n}\nasync function upsertCredentialAssignment(values) {\n\tconst db = getDb();\n\tconst id = values.id ?? crypto.randomUUID();\n\tconst now = values.updatedAt;\n\tconst projectId = projectScopeId();\n\treturn (await db.insert(credentialAssignments).values({\n\t\tid,\n\t\tprojectId,\n\t\ttargetType: values.targetType,\n\t\ttargetKey: values.targetKey,\n\t\tconsumerId: values.consumerId,\n\t\tcredentialSlug: values.credentialSlug,\n\t\tinstanceId: values.instanceId,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t}).onConflictDoUpdate({\n\t\ttarget: [\n\t\t\tcredentialAssignments.projectId,\n\t\t\tcredentialAssignments.targetType,\n\t\t\tcredentialAssignments.targetKey,\n\t\t\tcredentialAssignments.consumerId,\n\t\t\tcredentialAssignments.credentialSlug\n\t\t],\n\t\tset: {\n\t\t\tinstanceId: values.instanceId,\n\t\t\tupdatedAt: now\n\t\t}\n\t}).returning())[0];\n}\nasync function deleteCredentialAssignmentById(id) {\n\tif (!await selectCredentialAssignmentById(id)) return false;\n\tawait getDb().delete(credentialAssignments).where(eq$1(credentialAssignments.id, id));\n\treturn true;\n}\n/** Distinct step correlation ids from recent completed workflow runs. */\nasync function listRecentWorkflowStepConsumers(workflowSlug, runLimit = 5) {\n\tconst db = getDb();\n\tconst runIds = (await db.select({ id: workflowRuns.id }).from(workflowRuns).where(scopedAnd(workflowRuns, eq$1(workflowRuns.workflowSlug, workflowSlug))).orderBy(desc(workflowRuns.triggeredAt)).limit(runLimit)).map((row) => row.id);\n\tif (runIds.length === 0) return [];\n\tconst events = await db.select({ correlationId: workflowEvents.correlationId }).from(workflowEvents).where(scopedAnd(workflowEvents, inArray$1(workflowEvents.runId, runIds), eq$1(workflowEvents.type, \"step_completed\")));\n\tconst seen = /* @__PURE__ */ new Set();\n\tconst consumers = [];\n\tfor (const event of events) {\n\t\tconst id = event.correlationId;\n\t\tif (!id || seen.has(id)) continue;\n\t\tseen.add(id);\n\t\tconsumers.push(id);\n\t}\n\treturn consumers;\n}\nasync function listDistinctAssignmentConsumerIds(options) {\n\tconst rows = await listCredentialAssignmentsByTarget(options);\n\treturn [...new Set(rows.map((row) => row.consumerId))];\n}\n//#endregion\n//#region src/queries/trace-spans/index.ts\nfunction traceRootJoins$1(rootId) {\n\treturn {\n\t\tworkflowRuns: eq$1(workflowRuns.id, rootId),\n\t\ttriggerRuns: eq$1(triggerRuns.id, rootId),\n\t\tagentSessions: eq$1(agentSessions.id, rootId)\n\t};\n}\nasync function insertTraceSpan(values) {\n\tawait getDb().insert(traceSpans).values({\n\t\t...values,\n\t\tparentSpanId: values.parentSpanId ?? null,\n\t\tfinishedAt: values.finishedAt ?? null,\n\t\tmetadata: values.metadata ?? null,\n\t\terror: values.error ?? null\n\t});\n}\nasync function updateTraceSpanStatus(id, status, finishedAt, error) {\n\tif (!await selectTraceSpanById(id)) return;\n\tawait getDb().update(traceSpans).set({\n\t\tstatus,\n\t\tfinishedAt,\n\t\terror: error ?? null\n\t}).where(eq$1(traceSpans.id, id));\n}\nasync function selectTraceSpanById(id) {\n\tconst db = getDb();\n\tconst rows = await db.select({ span: traceSpans }).from(traceSpans).leftJoin(workflowRuns, eq$1(workflowRuns.id, traceSpans.traceId)).leftJoin(triggerRuns, eq$1(triggerRuns.id, traceSpans.traceId)).leftJoin(agentSessions, eq$1(agentSessions.id, traceSpans.traceId)).where(and$1(eq$1(traceSpans.id, id), traceRootProjectScopeFilter())).limit(1);\n\tif (rows[0]) return rows[0].span;\n\treturn (await db.select({ span: traceSpans }).from(traceSpans).leftJoin(workflowRuns, eq$1(workflowRuns.id, traceSpans.refId)).leftJoin(triggerRuns, eq$1(triggerRuns.id, traceSpans.refId)).leftJoin(agentSessions, eq$1(agentSessions.id, traceSpans.refId)).where(and$1(eq$1(traceSpans.id, id), traceRootProjectScopeFilter())).limit(1))[0]?.span;\n}\nasync function selectTraceSpanByRefId(refId) {\n\tconst db = getDb();\n\tconst joins = traceRootJoins$1(refId);\n\treturn (await db.select({ span: traceSpans }).from(traceSpans).leftJoin(workflowRuns, joins.workflowRuns).leftJoin(triggerRuns, joins.triggerRuns).leftJoin(agentSessions, joins.agentSessions).where(and$1(eq$1(traceSpans.refId, refId), traceRootProjectScopeFilter())).limit(1))[0]?.span;\n}\nasync function selectLatestAgentSessionSpanByRefId(refId) {\n\tconst db = getDb();\n\tconst joins = traceRootJoins$1(refId);\n\treturn (await db.select({ span: traceSpans }).from(traceSpans).leftJoin(workflowRuns, joins.workflowRuns).leftJoin(triggerRuns, joins.triggerRuns).leftJoin(agentSessions, joins.agentSessions).where(and$1(eq$1(traceSpans.refId, refId), eq$1(traceSpans.kind, \"agent_session\"), traceRootProjectScopeFilter())).orderBy(desc(traceSpans.startedAt)).limit(1))[0]?.span;\n}\nasync function listTraceSpansByTraceId(traceId) {\n\tconst db = getDb();\n\tconst joins = traceRootJoins$1(traceId);\n\treturn (await db.select({ span: traceSpans }).from(traceSpans).leftJoin(workflowRuns, joins.workflowRuns).leftJoin(triggerRuns, joins.triggerRuns).leftJoin(agentSessions, joins.agentSessions).where(and$1(eq$1(traceSpans.traceId, traceId), traceRootProjectScopeFilter())).orderBy(asc(traceSpans.startedAt))).map((row) => row.span);\n}\nasync function maxTraceLogSeq(traceId) {\n\tconst db = getDb();\n\tconst joins = traceRootJoins$1(traceId);\n\treturn (await db.select({ value: max$1(traceLogs.seq) }).from(traceLogs).leftJoin(workflowRuns, joins.workflowRuns).leftJoin(triggerRuns, joins.triggerRuns).leftJoin(agentSessions, joins.agentSessions).where(and$1(eq$1(traceLogs.traceId, traceId), traceRootProjectScopeFilter())))[0]?.value ?? 0;\n}\n//#endregion\n//#region src/queries/trace-logs/index.ts\nfunction traceRootJoins(rootId) {\n\treturn {\n\t\tworkflowRuns: eq$1(workflowRuns.id, rootId),\n\t\ttriggerRuns: eq$1(triggerRuns.id, rootId),\n\t\tagentSessions: eq$1(agentSessions.id, rootId)\n\t};\n}\nasync function insertTraceLogs(values) {\n\tif (values.length === 0) return;\n\tawait getDb().insert(traceLogs).values(values.map((entry) => ({\n\t\t...entry,\n\t\tdata: entry.data ?? null\n\t})));\n}\nasync function listTraceLogsByTraceId(traceId, options) {\n\tconst db = getDb();\n\tconst joins = traceRootJoins(traceId);\n\tconst conditions = [eq$1(traceLogs.traceId, traceId), traceRootProjectScopeFilter()];\n\tif (options?.spanId) conditions.push(eq$1(traceLogs.spanId, options.spanId));\n\tif (options?.afterSeq !== void 0) conditions.push(gt(traceLogs.seq, options.afterSeq));\n\tlet rows = await db.select({ log: traceLogs }).from(traceLogs).leftJoin(workflowRuns, joins.workflowRuns).leftJoin(triggerRuns, joins.triggerRuns).leftJoin(agentSessions, joins.agentSessions).where(and$1(...conditions)).orderBy(asc(traceLogs.seq));\n\trows = rows.map((row) => ({ log: row.log }));\n\tif (options?.limit !== void 0) rows = rows.slice(0, options.limit);\n\treturn rows.map((row) => row.log);\n}\n//#endregion\n//#region src/runs/source.ts\nfunction runSource(kind, id) {\n\treturn {\n\t\tkind,\n\t\tid: id ?? null\n\t};\n}\nfunction sourceFromSpan(span) {\n\tswitch (span.kind) {\n\t\tcase \"workflow_run\": return runSource(\"workflow\", span.refId);\n\t\tcase \"agent_session\": return runSource(\"agent\", span.refId);\n\t\tcase \"trigger_run\": return runSource(\"trigger\", span.refId);\n\t\tcase \"gateway_event\": {\n\t\t\tconst metadata = span.metadata;\n\t\t\tif (metadata && typeof metadata === \"object\" && \"gatewayAttachmentId\" in metadata) {\n\t\t\t\tconst attachmentId = metadata.gatewayAttachmentId;\n\t\t\t\tif (typeof attachmentId === \"string\") return runSource(\"gateway\", attachmentId);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tcase \"action\": {\n\t\t\tconst metadata = span.metadata;\n\t\t\tif (metadata && typeof metadata === \"object\" && \"runId\" in metadata) {\n\t\t\t\tconst runId = metadata.runId;\n\t\t\t\tif (typeof runId === \"string\") return runSource(\"workflow\", runId);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tdefault: return;\n\t}\n}\nasync function resolveRunSourceFromTraceContext() {\n\tconst parent = getTraceContext();\n\tif (!parent?.spanId) return runSource(\"api\");\n\tconst span = await selectTraceSpanById(parent.spanId);\n\tif (!span) return runSource(\"api\");\n\treturn sourceFromSpan(span) ?? runSource(\"api\");\n}\n//#endregion\n//#region src/workflows/runs.ts\nfunction serializeError(error) {\n\tif (error instanceof Error) return {\n\t\tname: error.name,\n\t\tmessage: error.message\n\t};\n\treturn { message: String(error) };\n}\nfunction triggerRunType$1(trigger) {\n\treturn trigger;\n}\nfunction resolveWorkflowRunSource(input) {\n\tif (input.sourceKind) return runSource(input.sourceKind, input.sourceId);\n\tif (input.triggerRunId) return runSource(\"trigger\", input.triggerRunId);\n\tif (input.parentWorkflowRunId) return runSource(\"workflow\", input.parentWorkflowRunId);\n\treturn runSource(\"api\");\n}\nfunction workflowRunInsertValues(input, status) {\n\tconst source = resolveWorkflowRunSource(input);\n\tconst now = status === \"running\" ? /* @__PURE__ */ new Date() : null;\n\treturn {\n\t\tid: input.id,\n\t\tworkflowSlug: input.workflowSlug,\n\t\tattachmentId: input.attachmentId ?? null,\n\t\tsubscriptionId: input.subscriptionId ?? null,\n\t\ttriggerRunId: input.triggerRunId ?? null,\n\t\tparentWorkflowRunId: input.parentWorkflowRunId ?? null,\n\t\tparentSpanId: input.parentSpanId ?? null,\n\t\tsourceKind: source.kind,\n\t\tsourceId: source.id,\n\t\tranByUserId: input.ranByUserId ?? null,\n\t\tstatus,\n\t\ttrigger: input.trigger,\n\t\ttriggeredAt: input.triggeredAt,\n\t\tstartedAt: now,\n\t\tinput: input.input ?? null,\n\t\toutput: null,\n\t\terror: null,\n\t\tfinishedAt: null\n\t};\n}\nasync function createWorkflowRun(input) {\n\tawait insertWorkflowRun(workflowRunInsertValues(input, \"running\"));\n}\nasync function createPendingWorkflowRun(input) {\n\tawait insertWorkflowRun(workflowRunInsertValues(input, \"pending\"));\n}\nasync function markWorkflowRunRunning(id) {\n\tawait markWorkflowRunRunningRow(id, /* @__PURE__ */ new Date());\n}\nasync function markWorkflowRunSleeping(id) {\n\tawait setWorkflowRunStatusRow(id, \"sleeping\");\n}\nasync function markWorkflowRunWaitingHook(id) {\n\tawait setWorkflowRunStatusRow(id, \"waiting_hook\");\n}\nasync function completeWorkflowRun(id, output) {\n\tawait completeWorkflowRunRow(id, output, /* @__PURE__ */ new Date());\n}\nasync function failWorkflowRun(id, error) {\n\tawait failWorkflowRunRow(id, serializeError(error), /* @__PURE__ */ new Date());\n}\nasync function recordWorkflowLlmUsage(options) {\n\tconst { usage } = options;\n\tawait insertUsageRecord({\n\t\tid: crypto.randomUUID(),\n\t\trunId: options.workflowRunId,\n\t\trunKind: \"workflow\",\n\t\tkind: \"llm\",\n\t\tlabel: usage.label,\n\t\tquantity: usage.quantity,\n\t\tunit: \"tokens\",\n\t\tamount: usage.amount,\n\t\tmetadata: usage.metadata,\n\t\tcreatedAt: /* @__PURE__ */ new Date()\n\t});\n}\nasync function finalizeCanceledWorkflowRun(id) {\n\tif (await cancelWorkflowRunRow(id, /* @__PURE__ */ new Date())) await appendWorkflowEvent({\n\t\tid: `run_canceled:${id}`,\n\t\trunId: id,\n\t\ttype: \"run_canceled\"\n\t});\n}\nasync function createAttachmentExecution(input) {\n\tconst triggerRunId = crypto.randomUUID();\n\tconst workflowRunId = crypto.randomUUID();\n\tawait insertTriggerRun({\n\t\tid: triggerRunId,\n\t\tattachmentId: input.attachmentId,\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 = crypto.randomUUID();\n\tconst workflowRunId = crypto.randomUUID();\n\tawait insertTriggerRun({\n\t\tid: triggerRunId,\n\t\tattachmentId: input.attachmentId,\n\t\tsourcePath: input.sourcePath ?? null,\n\t\ttriggerType: triggerRunType$1(input.trigger),\n\t\tpayload: input.payload ?? null,\n\t\ttriggeredAt: input.triggeredAt\n\t});\n\tawait insertWorkflowRun({\n\t\tid: workflowRunId,\n\t\tworkflowSlug: input.workflowSlug,\n\t\tattachmentId: input.attachmentId,\n\t\tsubscriptionId: input.subscriptionId ?? null,\n\t\ttriggerRunId,\n\t\tsourceKind: \"trigger\",\n\t\tsourceId: triggerRunId,\n\t\tstatus: \"pending\",\n\t\ttrigger: input.trigger,\n\t\ttriggeredAt: input.triggeredAt,\n\t\tstartedAt: null,\n\t\tinput: input.input ?? null,\n\t\toutput: null,\n\t\terror: null,\n\t\tfinishedAt: null\n\t});\n\treturn {\n\t\tworkflowRunId,\n\t\ttriggerRunId\n\t};\n}\nasync function markAttachmentExecutionRunning(workflowRunId) {\n\tawait markWorkflowRunRunning(workflowRunId);\n}\n//#endregion\n//#region src/history/cancel.ts\nconst CANCELABLE_STATUSES = new Set([\n\t\"pending\",\n\t\"running\",\n\t\"sleeping\",\n\t\"waiting_hook\"\n]);\nasync function cancelWorkflowRun(runId) {\n\tconst existing = await findHistoryRunCore(runId);\n\tif (!existing) return null;\n\tif (existing.kind !== \"workflow\") return existing;\n\tif (!CANCELABLE_STATUSES.has(existing.status)) return existing;\n\tawait finalizeCanceledWorkflowRun(runId);\n\treturn findHistoryRunCore(runId);\n}\nasync function cancelAgentSession(sessionId) {\n\tconst existing = await findHistoryRunCore(sessionId);\n\tif (!existing) return null;\n\tif (existing.kind !== \"agent\") return existing;\n\tif (existing.status === \"canceled\" || existing.status === \"completed\" || existing.status === \"failed\") return existing;\n\tawait cancelAgentSessionRow(sessionId, /* @__PURE__ */ new Date());\n\treturn findHistoryRunCore(sessionId);\n}\n//#endregion\n//#region src/agents/sync.ts\nfunction agentMetadata(record) {\n\treturn {\n\t\tname: record.name ?? null,\n\t\tdescription: record.description ?? null,\n\t\ttoolCount: record.toolCount ?? null,\n\t\tcredentialCount: record.credentialCount ?? null,\n\t\tappSlugs: record.appSlugs ?? null\n\t};\n}\nasync function syncAgentRegistry(records) {\n\tconst now = /* @__PURE__ */ new Date();\n\tconst slugs = records.map((record) => record.slug);\n\tconst byRoute = /* @__PURE__ */ new Map();\n\tfor (const record of records) {\n\t\tconst existing = await selectAgentBySlug(record.slug);\n\t\tif (existing) {\n\t\t\tawait updateAgentById(existing.id, {\n\t\t\t\troute: record.route,\n\t\t\t\tmoduleFile: record.moduleFile,\n\t\t\t\tmodel: record.model,\n\t\t\t\tsystemPrompt: record.systemPrompt,\n\t\t\t\t...agentMetadata(record),\n\t\t\t\tupdatedAt: now,\n\t\t\t\tdeletedAt: null\n\t\t\t});\n\t\t\tbyRoute.set(record.route, {\n\t\t\t\tid: existing.id,\n\t\t\t\tslug: record.slug\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst id = crypto.randomUUID();\n\t\tawait insertAgent({\n\t\t\tid,\n\t\t\tslug: record.slug,\n\t\t\troute: record.route,\n\t\t\tmoduleFile: record.moduleFile,\n\t\t\tmodel: record.model,\n\t\t\tsystemPrompt: record.systemPrompt,\n\t\t\t...agentMetadata(record),\n\t\t\tregisteredAt: now,\n\t\t\tupdatedAt: now,\n\t\t\tdeletedAt: null\n\t\t});\n\t\tbyRoute.set(record.route, {\n\t\t\tid,\n\t\t\tslug: record.slug\n\t\t});\n\t}\n\tif (slugs.length === 0) await softDeleteAllAgents(now);\n\telse await softDeleteAgentsNotInSlugs(slugs, now);\n\treturn byRoute;\n}\nasync function getAgentByRoute(route) {\n\treturn selectActiveAgentByRoute(route);\n}\n//#endregion\n//#region src/agents/sessions.ts\nasync function createSession(agentId, id, source = runSource(\"api\"), options) {\n\tconst now = /* @__PURE__ */ new Date();\n\tconst sessionId = id ?? crypto.randomUUID();\n\tawait insertAgentSession({\n\t\tid: sessionId,\n\t\tagentId,\n\t\tsourceKind: source.kind,\n\t\tsourceId: source.id,\n\t\tranByUserId: options?.ranByUserId ?? null,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now,\n\t\tdeletedAt: null\n\t});\n\treturn {\n\t\tid: sessionId,\n\t\tagentId,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t};\n}\nasync function getSession(sessionId) {\n\tconst row = await selectActiveAgentSession(sessionId);\n\tif (!row) return;\n\treturn {\n\t\tid: row.id,\n\t\tagentId: row.agentId,\n\t\tcreatedAt: row.createdAt,\n\t\tupdatedAt: row.updatedAt\n\t};\n}\nasync function touchSession(sessionId) {\n\tawait touchAgentSession(sessionId, /* @__PURE__ */ new Date());\n}\nasync function setSessionTitle(sessionId, title) {\n\tawait updateAgentSessionTitle(sessionId, title);\n}\nasync function nextSeq(sessionId) {\n\treturn await maxSeqForSession(sessionId) + 1;\n}\nasync function appendEvent(sessionId, eventType, payload) {\n\tconst seq = await nextSeq(sessionId);\n\tawait insertAgentEvent({\n\t\tid: crypto.randomUUID(),\n\t\tsessionId,\n\t\tseq,\n\t\teventType,\n\t\tpayload,\n\t\tcreatedAt: /* @__PURE__ */ new Date(),\n\t\tdeletedAt: null\n\t});\n\treturn seq;\n}\nasync function listMessageEvents(sessionId) {\n\treturn listMessagePayloads(sessionId, MESSAGE_EVENT_TYPE);\n}\nasync function countMessageEvents(sessionId) {\n\treturn countMessageEventsForSession(sessionId, MESSAGE_EVENT_TYPE);\n}\nasync function listSessionEvents(sessionId) {\n\treturn (await listAgentEventsForSession(sessionId)).map((row) => ({\n\t\tid: row.id,\n\t\tsessionId: row.sessionId,\n\t\tseq: row.seq,\n\t\teventType: row.eventType,\n\t\tpayload: row.payload,\n\t\tcreatedAt: row.createdAt\n\t}));\n}\nasync function setSessionLiveMessage(sessionId, message) {\n\tawait updateSessionLiveMessage(sessionId, message);\n}\nasync function clearLiveMessage(sessionId) {\n\tawait clearSessionLiveMessage(sessionId);\n}\nasync function getSessionLiveMessage(sessionId) {\n\treturn selectSessionLiveMessage(sessionId);\n}\n//#endregion\n//#region src/agents/runs.ts\nasync function recordLlmUsageFromAssistantMessage(options) {\n\tconst { usage } = options;\n\tawait insertUsageRecord({\n\t\tid: crypto.randomUUID(),\n\t\trunId: options.sessionId,\n\t\trunKind: \"agent\",\n\t\tkind: \"llm\",\n\t\tlabel: usage.label,\n\t\tquantity: usage.quantity,\n\t\tunit: \"tokens\",\n\t\tamount: usage.amount,\n\t\tmetadata: usage.metadata,\n\t\tcreatedAt: /* @__PURE__ */ new Date()\n\t});\n}\n//#endregion\n//#region src/agents/fail-session.ts\nfunction serializeSpanError(error) {\n\tif (error instanceof Error) return {\n\t\tname: error.name,\n\t\tmessage: error.message\n\t};\n\treturn { message: String(error) };\n}\n/**\n* Mark an agent session as failed by closing or inserting its terminal `agent_session`\n* trace span. History derives session status from that span.\n*/\nasync function failAgentSession(sessionId, error) {\n\tconst serializedError = serializeSpanError(error);\n\tconst finishedAt = /* @__PURE__ */ new Date();\n\tconst span = await selectLatestAgentSessionSpanByRefId(sessionId);\n\tif (span) {\n\t\tif (span.status !== \"running\") return;\n\t\tawait updateTraceSpanStatus(span.id, \"error\", finishedAt, serializedError);\n\t\treturn;\n\t}\n\tconst session = await selectAgentSessionById(sessionId);\n\tif (!session) return;\n\tawait insertTraceSpan({\n\t\tid: crypto.randomUUID(),\n\t\ttraceId: sessionId,\n\t\tkind: \"agent_session\",\n\t\trefId: sessionId,\n\t\tname: session.agentId,\n\t\tstatus: \"error\",\n\t\tstartedAt: finishedAt,\n\t\tfinishedAt,\n\t\tmetadata: {\n\t\t\tagentId: session.agentId,\n\t\t\ttrigger: \"api\"\n\t\t},\n\t\terror: serializedError\n\t});\n}\n//#endregion\n//#region src/skills/sync.ts\nfunction skillMetadata(record) {\n\treturn {\n\t\tname: record.name ?? null,\n\t\tdescription: record.description ?? null\n\t};\n}\nasync function syncSkillRegistry(records) {\n\tconst now = /* @__PURE__ */ new Date();\n\tconst slugs = records.map((record) => record.slug);\n\tconst bySlug = /* @__PURE__ */ new Map();\n\tfor (const record of records) {\n\t\tconst existing = await selectSkillBySlug(record.slug);\n\t\tif (existing) {\n\t\t\tawait updateSkillById(existing.id, {\n\t\t\t\tmoduleFile: record.moduleFile,\n\t\t\t\t...skillMetadata(record),\n\t\t\t\tupdatedAt: now,\n\t\t\t\tdeletedAt: null\n\t\t\t});\n\t\t\tbySlug.set(record.slug, {\n\t\t\t\tid: existing.id,\n\t\t\t\tslug: record.slug\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst id = crypto.randomUUID();\n\t\tawait insertSkill({\n\t\t\tid,\n\t\t\tslug: record.slug,\n\t\t\tmoduleFile: record.moduleFile,\n\t\t\t...skillMetadata(record),\n\t\t\tregisteredAt: now,\n\t\t\tupdatedAt: now,\n\t\t\tdeletedAt: null\n\t\t});\n\t\tbySlug.set(record.slug, {\n\t\t\tid,\n\t\t\tslug: record.slug\n\t\t});\n\t}\n\tif (slugs.length === 0) await softDeleteAllSkills(now);\n\telse await softDeleteSkillsNotInSlugs(slugs, now);\n\treturn bySlug;\n}\n//#endregion\n//#region src/triggers/sync.ts\nasync function syncTriggerAttachmentRegistry(records) {\n\tconst now = /* @__PURE__ */ new Date();\n\tconst slugs = records.map((record) => record.slug);\n\tconst byKey = /* @__PURE__ */ new Map();\n\tfor (const record of records) {\n\t\tconst existing = await selectTriggerAttachmentBySlug(record.slug);\n\t\tif (existing) {\n\t\t\tawait updateTriggerAttachmentById(existing.id, {\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\tmoduleFile: record.moduleFile,\n\t\t\t\tsource: record.source,\n\t\t\t\tupdatedAt: now,\n\t\t\t\tdeletedAt: null\n\t\t\t});\n\t\t\tbyKey.set(record.slug, {\n\t\t\t\tid: existing.id,\n\t\t\t\tslug: record.slug\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst id = crypto.randomUUID();\n\t\tawait insertTriggerAttachment({\n\t\t\tid,\n\t\t\tslug: record.slug,\n\t\t\ttargetKind: record.targetKind,\n\t\t\tworkflowSlug: record.workflowSlug ?? null,\n\t\t\tagentSlug: record.agentSlug ?? null,\n\t\t\tmoduleFile: record.moduleFile,\n\t\t\tsource: record.source,\n\t\t\tregisteredAt: now,\n\t\t\tupdatedAt: now,\n\t\t\tdeletedAt: null\n\t\t});\n\t\tbyKey.set(record.slug, {\n\t\t\tid,\n\t\t\tslug: record.slug\n\t\t});\n\t}\n\tif (slugs.length === 0) await softDeleteAllTriggerAttachments(now);\n\telse await softDeleteTriggerAttachmentsNotInSlugs(slugs, now);\n\treturn byKey;\n}\n//#endregion\n//#region src/triggers/agent-runs.ts\nfunction triggerRunType(trigger) {\n\tif (trigger === \"cron\" || trigger === \"poll\" || trigger === \"webhook\") return trigger;\n\tthrow new Error(`Unexpected trigger type for trigger run: ${trigger}`);\n}\nasync function createAgentAttachmentExecution(input) {\n\tconst triggerRunId = crypto.randomUUID();\n\tconst sessionId = crypto.randomUUID();\n\tconst now = /* @__PURE__ */ new Date();\n\tawait insertTriggerRun({\n\t\tid: triggerRunId,\n\t\tattachmentId: input.attachmentId,\n\t\tsourcePath: input.sourcePath ?? null,\n\t\ttriggerType: triggerRunType(input.trigger),\n\t\tpayload: input.payload ?? null,\n\t\ttriggeredAt: input.triggeredAt\n\t});\n\tawait insertAgentSession({\n\t\tid: sessionId,\n\t\tagentId: input.agentId,\n\t\tsourceKind: \"trigger\",\n\t\tsourceId: triggerRunId,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now,\n\t\tdeletedAt: null\n\t});\n\treturn {\n\t\ttriggerRunId,\n\t\tsessionId\n\t};\n}\nasync function getTriggerRunForAgentSession(sessionId) {\n\tconst session = await selectAgentSessionById(sessionId);\n\tif (session?.sourceKind !== \"trigger\" || !session.sourceId) return;\n\treturn selectTriggerRunById(session.sourceId);\n}\n//#endregion\n//#region src/triggers/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; upserts the schedule when cron/poll. */\nasync function upsertEphemeralTrigger(input) {\n\tconst now = /* @__PURE__ */ new Date();\n\tconst existing = await selectTriggerAttachmentBySlug(input.slug);\n\tif (existing && existing.origin !== \"ephemeral\") throw new Error(`Trigger \"${input.slug}\" is defined in the project and cannot be modified`);\n\tif (existing && existing.agentSlug !== input.agentSlug) throw new Error(`Trigger \"${input.slug}\" belongs to another agent`);\n\tconst lifecycle = initialLifecycle(input, existing?.lifecycle);\n\tconst enabled = lifecycle.status === \"active\";\n\tif (existing) await updateTriggerAttachmentById(existing.id, {\n\t\ttargetKind: \"agent\",\n\t\tworkflowSlug: null,\n\t\tagentSlug: input.agentSlug,\n\t\tmoduleFile: EPHEMERAL_TRIGGER_MODULE_FILE,\n\t\tsource: input.source,\n\t\tprompt: input.prompt,\n\t\tlifecycle,\n\t\tupdatedAt: now,\n\t\tdeletedAt: null\n\t});\n\telse await insertTriggerAttachment({\n\t\tid: crypto.randomUUID(),\n\t\tslug: input.slug,\n\t\ttargetKind: \"agent\",\n\t\tworkflowSlug: null,\n\t\tagentSlug: input.agentSlug,\n\t\tmoduleFile: EPHEMERAL_TRIGGER_MODULE_FILE,\n\t\tsource: input.source,\n\t\torigin: \"ephemeral\",\n\t\tprompt: input.prompt,\n\t\tlifecycle,\n\t\tcreatedBySessionId: input.createdBySessionId ?? null,\n\t\tregisteredAt: now,\n\t\tupdatedAt: now,\n\t\tdeletedAt: null\n\t});\n\tif (input.source.kind === \"cron\" || input.source.kind === \"poll\") {\n\t\tif (!input.nextRunAt) throw new Error(`Ephemeral ${input.source.kind} triggers require nextRunAt`);\n\t\tawait upsertTriggerSchedule({\n\t\t\tattachmentSlug: input.slug,\n\t\t\tkind: input.source.kind,\n\t\t\tschedule: input.source.schedule,\n\t\t\tnextRunAt: input.nextRunAt,\n\t\t\tenabled,\n\t\t\tupdatedAt: now\n\t\t});\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 || row.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 setTriggerScheduleEnabled(options.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(attachmentSlug, now = /* @__PURE__ */ new Date()) {\n\tconst row = await selectTriggerAttachmentBySlug(attachmentSlug);\n\tif (!row || row.origin !== \"ephemeral\") return;\n\tconst lifecycle = row.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(attachmentSlug, false, now);\n\t}\n\tawait updateTriggerAttachmentById(row.id, {\n\t\tlifecycle,\n\t\tupdatedAt: now\n\t});\n\treturn lifecycle;\n}\n/** Attachment keys for active ephemeral scheduled triggers — excluded from project schedule sweeps. */\nasync function selectActiveEphemeralScheduledAttachmentSlugs() {\n\treturn (await selectEphemeralTriggerAttachments()).filter((row) => (row.source.kind === \"cron\" || row.source.kind === \"poll\") && isEphemeralTriggerActive(row)).map((row) => row.slug);\n}\n/** @deprecated Use {@link selectActiveEphemeralScheduledAttachmentSlugs}. */\nasync function selectActiveEphemeralCronAttachmentSlugs() {\n\treturn selectActiveEphemeralScheduledAttachmentSlugs();\n}\n//#endregion\n//#region src/triggers/agent-list.ts\nfunction titleCaseSlug(slug) {\n\treturn slug.split(/[:/_-]+/).filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(\" \");\n}\nfunction triggerLabel(row) {\n\treturn titleCaseSlug(row.slug);\n}\nfunction triggerSchedule(source) {\n\tif (source.kind === \"cron\" || source.kind === \"poll\") return source.schedule;\n\treturn null;\n}\nfunction triggerEndpoint(source) {\n\tif (source.kind === \"webhook\") return source.endpoint;\n\treturn null;\n}\nfunction agentTriggerSummaryFromRow(row) {\n\treturn {\n\t\tid: row.slug,\n\t\tlabel: triggerLabel(row),\n\t\ttype: row.source.kind,\n\t\tschedule: triggerSchedule(row.source),\n\t\tendpoint: triggerEndpoint(row.source),\n\t\torigin: row.origin,\n\t\tprompt: row.prompt ?? null,\n\t\tstatus: row.lifecycle?.status ?? \"active\",\n\t\texecutionCount: row.lifecycle?.executionCount ?? 0,\n\t\tuntil: row.lifecycle?.until ?? null\n\t};\n}\nasync function listAgentTriggers(agentSlug) {\n\treturn (await selectTriggerAttachmentsByAgentSlug(agentSlug)).map(agentTriggerSummaryFromRow);\n}\n//#endregion\n//#region src/gateways/thread-sessions.ts\nasync function getOrCreateGatewayThreadSession(options) {\n\tconst existing = await selectGatewayThreadSessionByThreadId(options.threadId);\n\tif (existing) return existing.sessionId;\n\tconst session = await createSession(options.agentId, options.existingSessionId, runSource(\"gateway\", options.attachmentId));\n\tconst now = /* @__PURE__ */ new Date();\n\tawait upsertGatewayThreadSession({\n\t\tthreadId: options.threadId,\n\t\tagentId: options.agentId,\n\t\tsessionId: session.id,\n\t\tattachmentId: options.attachmentId,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t});\n\treturn session.id;\n}\n//#endregion\n//#region src/workflows/sync.ts\nfunction workflowMetadata(record) {\n\treturn {\n\t\tname: record.name ?? null,\n\t\tdescription: record.description ?? null\n\t};\n}\nasync function syncWorkflowRegistry(records) {\n\tconst now = /* @__PURE__ */ new Date();\n\tconst slugs = records.map((record) => record.slug);\n\tconst bySlug = /* @__PURE__ */ new Map();\n\tfor (const record of records) {\n\t\tconst existing = await selectWorkflowBySlug(record.slug);\n\t\tif (existing) {\n\t\t\tawait updateWorkflowById(existing.id, {\n\t\t\t\tmoduleFile: record.moduleFile,\n\t\t\t\tsubscribable: record.subscribable,\n\t\t\t\t...workflowMetadata(record),\n\t\t\t\tupdatedAt: now,\n\t\t\t\tdeletedAt: null\n\t\t\t});\n\t\t\tbySlug.set(record.slug, {\n\t\t\t\tid: existing.id,\n\t\t\t\tslug: record.slug,\n\t\t\t\tsubscribable: record.subscribable\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst id = crypto.randomUUID();\n\t\tawait insertWorkflow({\n\t\t\tid,\n\t\t\tslug: record.slug,\n\t\t\tmoduleFile: record.moduleFile,\n\t\t\tsubscribable: record.subscribable,\n\t\t\t...workflowMetadata(record),\n\t\t\tregisteredAt: now,\n\t\t\tupdatedAt: now,\n\t\t\tdeletedAt: null\n\t\t});\n\t\tbySlug.set(record.slug, {\n\t\t\tid,\n\t\t\tslug: record.slug,\n\t\t\tsubscribable: record.subscribable\n\t\t});\n\t}\n\tif (slugs.length === 0) await softDeleteAllWorkflows(now);\n\telse await softDeleteWorkflowsNotInSlugs(slugs, now);\n\treturn bySlug;\n}\n//#endregion\n//#region src/workflows/credentials.ts\nasync function getWorkflowSubscription(subscriptionId) {\n\tconst row = await selectWorkflowSubscriptionById(subscriptionId);\n\tif (!row) return;\n\treturn {\n\t\tid: row.id,\n\t\tworkflowSlug: row.workflowSlug,\n\t\tuserId: row.userId,\n\t\tenabled: Boolean(row.enabled)\n\t};\n}\nasync function listCredentialInstancesForAssignment(options) {\n\tconst tenantScopeId = getServerTenantScopeId();\n\tconst projectId = getProjectScopeId();\n\tconst rows = [];\n\tconst appendScope = async (scopeType, scopeId) => {\n\t\trows.push(...await listCredentialInstancesByScope({\n\t\t\t...options.appSlug ? { appSlug: options.appSlug } : {},\n\t\t\tscopeType,\n\t\t\tscopeId\n\t\t}));\n\t};\n\tawait appendScope(\"organization\", tenantScopeId);\n\tawait appendScope(\"project\", projectId);\n\tif (options.userId) await appendScope(\"user\", options.userId);\n\treturn rows;\n}\n//#endregion\n//#region src/workflows/event-log.ts\nfunction createDatabaseEventLog() {\n\treturn {\n\t\tappend(event) {\n\t\t\treturn appendWorkflowEvent(event);\n\t\t},\n\t\tasync listReplay(runId) {\n\t\t\treturn (await listReplayEvents(runId)).map((row) => ({\n\t\t\t\tid: row.id,\n\t\t\t\trunId: row.runId,\n\t\t\t\tseq: row.seq,\n\t\t\t\ttype: row.type,\n\t\t\t\tcorrelationId: row.correlationId,\n\t\t\t\tdata: row.data\n\t\t\t}));\n\t\t}\n\t};\n}\n//#endregion\n//#region src/workflows/hook-store.ts\nfunction createDatabaseHookStore() {\n\treturn {\n\t\tcreate(values) {\n\t\t\treturn insertWorkflowHook(values);\n\t\t},\n\t\tasync getByToken(token) {\n\t\t\tconst row = await selectWorkflowHookByToken(token);\n\t\t\tif (!row) return;\n\t\t\treturn {\n\t\t\t\thookId: row.hookId,\n\t\t\t\trunId: row.runId,\n\t\t\t\ttoken: row.token,\n\t\t\t\tcorrelationId: row.correlationId,\n\t\t\t\tstatus: row.status,\n\t\t\t\tpayload: row.payload\n\t\t\t};\n\t\t},\n\t\tmarkResumed(hookId, payload) {\n\t\t\treturn markWorkflowHookResumed(hookId, payload);\n\t\t}\n\t};\n}\n//#endregion\n//#region src/triggers/run-api.ts\nasync function listTriggerRunsPaginated(options) {\n\tconst attachment = await selectTriggerAttachmentBySlug(options.attachmentSlug);\n\tif (!attachment) return null;\n\tconst result = await listTriggerRunRowsPaginated({\n\t\tattachmentId: attachment.id,\n\t\tlimit: options.limit,\n\t\tcursor: options.cursor,\n\t\ttriggerType: options.triggerType\n\t});\n\tif (attachment.targetKind !== \"agent\" || !attachment.agentSlug) return result;\n\tconst sessionsByTriggerRunId = await listAgentSessionsBySourceIds({\n\t\tsourceKind: \"trigger\",\n\t\tsourceIds: result.items.map((item) => item.id)\n\t});\n\treturn {\n\t\t...result,\n\t\titems: result.items.map((item) => {\n\t\t\tconst session = sessionsByTriggerRunId.get(item.id);\n\t\t\tif (!session) return item;\n\t\t\treturn {\n\t\t\t\t...item,\n\t\t\t\tagentSession: {\n\t\t\t\t\tid: session.id,\n\t\t\t\t\tagentSlug: attachment.agentSlug\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 selectTriggerRunForAttachment(attachment.id, 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 && attachment.agentSlug) {\n\t\tconst session = (await listAgentSessionsBySourceIds({\n\t\t\tsourceKind: \"trigger\",\n\t\t\tsourceIds: [row.id]\n\t\t})).get(row.id);\n\t\tif (session) agentSessions = [{\n\t\t\tid: session.id,\n\t\t\tagentSlug: attachment.agentSlug\n\t\t}];\n\t}\n\tlet trace = null;\n\tif (includeTrace) {\n\t\tconst traceData = await getTraceForTriggerRun(row.id);\n\t\ttrace = traceData ? traceResponseToJson(traceData) : null;\n\t}\n\treturn {\n\t\trun: triggerRunRecordFromRow(row, attachment.slug),\n\t\tworkflowRuns,\n\t\tagentSessions,\n\t\ttrace\n\t};\n}\n//#endregion\n//#region src/credentials/crypto.ts\nconst ALGORITHM = \"aes-256-gcm\";\nconst IV_LENGTH = 12;\nfunction resolveEncryptionKey() {\n\tconst secret = process.env.CREDENTIALS_ENCRYPTION_KEY?.trim();\n\tif (!secret) throw new Error(\"CREDENTIALS_ENCRYPTION_KEY is required\");\n\treturn createHash(\"sha256\").update(secret).digest();\n}\nfunction encryptCredentialPayload(plaintext) {\n\tconst iv = randomBytes(IV_LENGTH);\n\tconst cipher = createCipheriv(ALGORITHM, resolveEncryptionKey(), iv);\n\tconst encrypted = Buffer.concat([cipher.update(plaintext, \"utf8\"), cipher.final()]);\n\tconst tag = cipher.getAuthTag();\n\treturn Buffer.concat([\n\t\tiv,\n\t\ttag,\n\t\tencrypted\n\t]).toString(\"base64\");\n}\nfunction decryptCredentialPayload(ciphertext) {\n\tconst buffer = Buffer.from(ciphertext, \"base64\");\n\tconst iv = buffer.subarray(0, IV_LENGTH);\n\tconst tag = buffer.subarray(IV_LENGTH, 28);\n\tconst encrypted = buffer.subarray(28);\n\tconst decipher = createDecipheriv(ALGORITHM, resolveEncryptionKey(), iv);\n\tdecipher.setAuthTag(tag);\n\treturn Buffer.concat([decipher.update(encrypted), decipher.final()]).toString(\"utf8\");\n}\n//#endregion\n//#region src/credentials/set-instance-value.ts\nasync function setCredentialInstanceValue(options) {\n\tconst now = /* @__PURE__ */ new Date();\n\tconst siblings = await selectCredentialInstancesForScope(options.appSlug, options.scopeType, options.scopeId);\n\tconst isDefault = options.isDefault ?? siblings.length === 0;\n\tconst name = options.name ?? options.label ?? null;\n\tconst slug = options.slug ?? deriveCredentialInstanceSlug({\n\t\tappSlug: options.appSlug,\n\t\tname,\n\t\ttakenSlugs: siblings.map((row) => row.slug)\n\t});\n\tif (isDefault) await clearCredentialInstanceDefaults({\n\t\tappSlug: options.appSlug,\n\t\tscopeType: options.scopeType,\n\t\tscopeId: options.scopeId,\n\t\texceptId: options.id\n\t});\n\tawait upsertCredentialInstance({\n\t\tid: options.id,\n\t\tappSlug: options.appSlug,\n\t\tslug,\n\t\tname,\n\t\tscopeType: options.scopeType,\n\t\tscopeId: options.scopeId,\n\t\tlabel: name,\n\t\tisDefault,\n\t\tauthKind: \"api_key\",\n\t\tciphertext: encryptCredentialPayload(JSON.stringify(options.value)),\n\t\tconnectionId: null,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t});\n}\n//#endregion\n//#region src/oauth/credential-instance.ts\nfunction resolveOAuthInstanceLabel(options) {\n\tconst appName = displayCredentialAppName(options.credentialKey);\n\treturn resolveUniqueCredentialInstanceLabel({\n\t\tbaseLabel: options.userLabel?.trim() || buildCredentialInstanceLabel({\n\t\t\tscopeType: options.scopeType,\n\t\t\tappName,\n\t\t\tprojectName: options.projectName\n\t\t}),\n\t\ttakenLabels: options.rows.filter((row) => !(row.authKind === \"oauth_managed\" && row.connectionId === options.connectionId)).map((row) => row.label),\n\t\tdisambiguator: options.accountLabel?.trim() || options.externalId\n\t});\n}\nasync function 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 } = options;\n\tconst hasTargets = Boolean(targets && ((targets.projectIds?.length ?? 0) > 0 || targets.organization || targets.userId));\n\tconst scopeOptions = {\n\t\tcredentialKey,\n\t\tconnectionId,\n\t\taccountLabel,\n\t\texternalId,\n\t\tuserLabel\n\t};\n\tif (!hasTargets || targets?.organization) await ensureOAuthInstanceForScope({\n\t\t...scopeOptions,\n\t\tscopeType: \"organization\",\n\t\tscopeId: getServerTenantScopeId()\n\t});\n\tfor (const projectId of targets?.projectIds ?? []) await runWithProjectScope(projectId, () => ensureOAuthInstanceForScope({\n\t\t...scopeOptions,\n\t\tscopeType: \"project\",\n\t\tscopeId: projectId,\n\t\tprojectName: targets?.projectNamesById?.[projectId]\n\t}));\n\tif (targets?.userId) await ensureOAuthInstanceForScope({\n\t\t...scopeOptions,\n\t\tscopeType: \"user\",\n\t\tscopeId: targets.userId\n\t});\n}\n//#endregion\n//#region src/oauth/keystroke-credential-instance.ts\nfunction resolveKeystrokeInstanceLabel(options) {\n\tconst appName = displayCredentialAppName(options.credentialKey);\n\treturn resolveUniqueCredentialInstanceLabel({\n\t\tbaseLabel: 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\tdisambiguator: options.accountLabel?.trim()\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 ?? rows.find((row) => row.authKind === \"keystroke\" && row.label === name);\n\tconst slug = existing?.slug ?? deriveCredentialInstanceSlug({\n\t\tappSlug: options.credentialKey,\n\t\tname,\n\t\ttakenSlugs: rows.map((row) => row.slug)\n\t});\n\tawait upsertCredentialInstance({\n\t\tid: existing?.id ?? crypto.randomUUID(),\n\t\tappSlug: options.credentialKey,\n\t\tslug,\n\t\tname,\n\t\tscopeType: options.scopeType,\n\t\tscopeId: options.scopeId,\n\t\tlabel: name,\n\t\tisDefault: existing ? Boolean(existing.isDefault) : rows.length === 0,\n\t\tauthKind: \"keystroke\",\n\t\tciphertext: null,\n\t\tconnectionId: options.connectionId,\n\t\tsharedConnectionId: options.sharedConnectionId,\n\t\tcreatedAt: existing?.createdAt ?? now,\n\t\tupdatedAt: now\n\t});\n}\nasync function ensureKeystrokeCredentialInstance(options) {\n\tconst { scopeType, scopeId, ...scopeOptions } = options;\n\tif (scopeType === \"project\") {\n\t\tawait runWithProjectScope(scopeId, () => ensureKeystrokeInstanceForScope({\n\t\t\t...scopeOptions,\n\t\t\tscopeType,\n\t\t\tscopeId\n\t\t}));\n\t\treturn;\n\t}\n\tawait ensureKeystrokeInstanceForScope({\n\t\t...scopeOptions,\n\t\tscopeType,\n\t\tscopeId\n\t});\n}\n//#endregion\n//#region src/scheduler/jobs.ts\nconst DEFAULT_MAX_ATTEMPTS = 3;\nasync function enqueueJob(input) {\n\tconst id = crypto.randomUUID();\n\tawait insertJob({\n\t\tid,\n\t\tkind: input.kind,\n\t\ttargetId: input.targetId,\n\t\trunId: input.runId,\n\t\ttrigger: input.trigger,\n\t\tpayload: input.payload ?? null,\n\t\tstatus: \"pending\",\n\t\tscheduledAt: input.scheduledAt ?? /* @__PURE__ */ new Date(),\n\t\tattempt: input.attempt ?? 1,\n\t\tmaxAttempts: input.maxAttempts ?? DEFAULT_MAX_ATTEMPTS,\n\t\tleasedBy: null,\n\t\tleaseExpiresAt: null,\n\t\tcompletedAt: null,\n\t\terror: null\n\t});\n\treturn id;\n}\nasync function claimNextJob(workerId) {\n\tconst row = await claimNextJobRow(workerId);\n\tif (!row) return;\n\tawait markJobRunning(row.id);\n\treturn {\n\t\tid: row.id,\n\t\tkind: row.kind,\n\t\ttargetId: row.targetId,\n\t\trunId: row.runId,\n\t\ttrigger: row.trigger,\n\t\tpayload: row.payload ?? {},\n\t\tattempt: row.attempt,\n\t\tmaxAttempts: row.maxAttempts,\n\t\tscheduledAt: row.scheduledAt\n\t};\n}\nasync function markJobComplete(jobId) {\n\tawait completeJobRow(jobId, /* @__PURE__ */ new Date());\n}\nasync function markJobFailed(jobId, error) {\n\tawait failJobRow(jobId, error instanceof Error ? {\n\t\tname: error.name,\n\t\tmessage: error.message\n\t} : { message: String(error) }, /* @__PURE__ */ new Date());\n}\nasync function scheduleJobRetry(jobId, attempt, delayMs) {\n\tawait resetJobForRetry(jobId, new Date(Date.now() + delayMs), attempt);\n}\nasync function getJobByRunId(runId) {\n\tconst row = await selectJobByRunId(runId);\n\tif (!row) return;\n\treturn {\n\t\tid: row.id,\n\t\tkind: row.kind,\n\t\ttargetId: row.targetId,\n\t\trunId: row.runId,\n\t\tstatus: row.status,\n\t\ttrigger: row.trigger,\n\t\tpayload: row.payload ?? {},\n\t\tattempt: row.attempt,\n\t\tmaxAttempts: row.maxAttempts,\n\t\tscheduledAt: row.scheduledAt,\n\t\terror: row.error ?? null\n\t};\n}\n//#endregion\nexport { DEFAULT_DATABASE_URL, DEFAULT_PROJECT_ID, EPHEMERAL_TRIGGER_MODULE_FILE, GatewayChannelConflictError, MESSAGE_EVENT_TYPE, adaptPgMigrationsForSearchPath, addAgentSessionDuration, appendEvent, appendSearchPathToUrl, buildAgentSessionChatState, buildAgentSessionDetail, buildHistoryAgentSessionDetail, buildHistoryWorkflowRunDetail, buildPostgresUrl, buildTriggerRunDetail, buildWorkflowRunDetail, cancelAgentSession, cancelWorkflowRun, claimDueTriggerSchedules, claimDueTriggerSchedulesForOrg, claimNextJob, clearAgentSessionCancellation, clearCredentialInstanceDefaults, clearLiveMessage, closeAllProjectDatabasePools, closeDatabase, completeWorkflowRun, countMessageEvents, createAgentAttachmentExecution, createAttachmentExecution, createConnection, createDatabaseEventLog, createDatabaseHookStore, createDatabaseTracingSink, createPendingAttachmentExecution, createPendingWorkflowRun, createPgConnection, createPostgresCancelChannel, createSession, createSqliteConnection, createWorkflowRun, decryptCredentialPayload, deleteCredentialAssignmentById, deleteCredentialInstanceById, deleteEphemeralTrigger, deleteWorkflowSubscriptionById, disableAllTriggerSchedules, disableTriggerSchedulesNotInSlugs, encryptCredentialPayload, enqueueJob, ensureKeystrokeCredentialInstance, ensureOAuthCredentialInstance, failAgentSession, failWorkflowRun, finalizeCanceledWorkflowRun, findHistoryRunCore, gatewayAttachmentKeyForChannel, getActiveGatewayAttachmentByChannel, getActiveOrgGatewayAttachmentByChannel, getActiveOrgGatewayAttachmentByTeamAndChannel, getAgentByRoute, getBoundProjectScopeId, getDatabaseHandle, getGatewayAttachmentBySlug, getJobByRunId, getOrCreateGatewayThreadSession, getProjectScopeId, getServerTenantScopeId, getSession, getSessionLiveMessage, getTraceForAgentSession, getTraceForTriggerRun, getTraceForWorkflowRun, getTriggerAttachmentBySlug, getTriggerRunForAgentSession, getWorkflowSubscription, inferDialect, initDatabase, insertWorkflowSubscription, isDatabaseInitialized, isEphemeralTriggerActive, listActiveAgents, listActiveGatewayAttachments, listActiveGatewayAttachmentsByAgentSlug, listActiveGatewayAttachmentsByPlatform, listActiveOrgGatewayBindingsByPlatform, listActiveSkills, listActiveTriggerAttachments, listActiveWorkflows, listAgentSessionsPaginated, listAgentTriggers, listAllCredentialInstances, listCredentialAssignmentsByTarget, listCredentialInstancesByConnectionId, listCredentialInstancesByScope, listCredentialInstancesForAssignment, listDistinctAssignmentConsumerIds, listEnabledTriggerSchedules, listEnabledWorkflowSubscriptionsByWorkflowSlug, listHistoryRuns, listMessageEvents, listRecentResourceActivity, listRecentWorkflowStepConsumers, listSessionEvents, listStepCompletedEvents, listTriggerRunsPaginated, listTriggerSchedulesBySlugs, listWorkflowRunsByWorkflowSlug, listWorkflowRunsPaginated, listWorkflowSubscriptionsByWorkflowSlug, loadMigrations, markAttachmentExecutionRunning, markJobComplete, markJobFailed, markWorkflowRunRunning, markWorkflowRunSleeping, markWorkflowRunWaitingHook, migratePgDatabase, nextSeq, parsePostgresUrl, primarySearchPathSchema, qualifyConnectionUser, recordEphemeralTriggerExecution, recordLlmUsageFromAssistantMessage, recordWorkflowLlmUsage, requeueExpiredLeases, resolveAgentProjectId, resolveDatabaseUrlFromEnv, resolveMigrationsFolder, resolveMigrationsSchema, resolvePostgresConfigFromEnv, resolvePostgresUrlFromEnv, resolveProjectDatabaseUrlFromEnv, resolveRunSourceFromTraceContext, resolveSearchPath, resolveSqlitePath, resolveWorkflowRunProjectId, runMigrations, runSource, runWithProjectDatabase, runWithProjectScope, runWithTenantScope, scheduleJobRetry, selectActiveAgentById, selectActiveAgentsByIds, selectActiveEphemeralCronAttachmentSlugs, selectActiveEphemeralScheduledAttachmentSlugs, selectActiveSkillById, selectActiveSkillsByIds, selectActiveWorkflowById, selectActiveWorkflowBySlug, selectActiveWorkflowsByIds, selectAgentBySlug, selectAgentLastRunAtByIds, selectAgentSessionById, selectCredentialAssignmentById, selectCredentialInstanceById, selectCredentialInstancesForScope, selectEphemeralTriggerAttachments, selectEphemeralTriggerAttachmentsByAgentSlug, selectGatewayThreadSessionByThreadId, selectProjectResourceCounts, selectTriggerAttachmentsByAgentSlug, selectTriggerScheduleBySlug, selectWebhookTriggerAttachments, selectWorkflowLastRunAtByIds, selectWorkflowRunById, selectWorkflowRunForWorkflow, selectWorkflowSubscriptionById, selectWorkflowSubscriptionByWorkflowAndUser, setCredentialInstanceValue, setSessionLiveMessage, setSessionTitle, softDeleteGatewayAttachmentByChannel, softDeleteGatewayAttachmentsForAgentPlatformTeam, sourceFromSpan, syncAgentRegistry, syncSkillRegistry, syncTriggerAttachmentRegistry, syncWorkflowRegistry, touchResourceActivity, touchSession, updateWorkflowSubscriptionById, upsertCredentialAssignment, upsertCredentialInstance, upsertEphemeralTrigger, upsertGatewayAttachmentByChannel, upsertTriggerSchedule };\n\n//# sourceMappingURL=index.mjs.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","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","/**\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","export const ignoreOverride = Symbol(\"Let zodToJsonSchema decide on which parser to use\");\nexport const jsonDescription = (jsonSchema, def) => {\n if (def.description) {\n try {\n return {\n ...jsonSchema,\n ...JSON.parse(def.description),\n };\n }\n catch { }\n }\n return jsonSchema;\n};\nexport const defaultOptions = {\n name: undefined,\n $refStrategy: \"root\",\n basePath: [\"#\"],\n effectStrategy: \"input\",\n pipeStrategy: \"all\",\n dateStrategy: \"format:date-time\",\n mapStrategy: \"entries\",\n removeAdditionalStrategy: \"passthrough\",\n allowedAdditionalProperties: true,\n rejectedAdditionalProperties: false,\n definitionPath: \"definitions\",\n target: \"jsonSchema7\",\n strictUnions: false,\n definitions: {},\n errorMessages: false,\n markdownDescription: false,\n patternStrategy: \"escape\",\n applyRegexFlags: false,\n emailStrategy: \"format:email\",\n base64Strategy: \"contentEncoding:base64\",\n nameStrategy: \"ref\",\n openAiAnyTypeName: \"OpenAiAnyType\"\n};\nexport const getDefaultOptions = (options) => (typeof options === \"string\"\n ? {\n ...defaultOptions,\n name: options,\n }\n : {\n ...defaultOptions,\n ...options,\n });\n","import { getDefaultOptions } from \"./Options.js\";\nexport const getRefs = (options) => {\n const _options = getDefaultOptions(options);\n const currentPath = _options.name !== undefined\n ? [..._options.basePath, _options.definitionPath, _options.name]\n : _options.basePath;\n return {\n ..._options,\n flags: { hasReferencedOpenAiAnyType: false },\n currentPath: currentPath,\n propertyPath: undefined,\n seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [\n def._def,\n {\n def: def._def,\n path: [..._options.basePath, _options.definitionPath, name],\n // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.\n jsonSchema: undefined,\n },\n ])),\n };\n};\n","export function addErrorMessage(res, key, errorMessage, refs) {\n if (!refs?.errorMessages)\n return;\n if (errorMessage) {\n res.errorMessage = {\n ...res.errorMessage,\n [key]: errorMessage,\n };\n }\n}\nexport function setResponseValueAndErrors(res, key, value, errorMessage, refs) {\n res[key] = value;\n addErrorMessage(res, key, errorMessage, refs);\n}\n","export const getRelativePath = (pathA, pathB) => {\n let i = 0;\n for (; i < pathA.length && i < pathB.length; i++) {\n if (pathA[i] !== pathB[i])\n break;\n }\n return [(pathA.length - i).toString(), ...pathB.slice(i)].join(\"/\");\n};\n","import { getRelativePath } from \"../getRelativePath.js\";\nexport function parseAnyDef(refs) {\n if (refs.target !== \"openAi\") {\n return {};\n }\n const anyDefinitionPath = [\n ...refs.basePath,\n refs.definitionPath,\n refs.openAiAnyTypeName,\n ];\n refs.flags.hasReferencedOpenAiAnyType = true;\n return {\n $ref: refs.$refStrategy === \"relative\"\n ? getRelativePath(anyDefinitionPath, refs.currentPath)\n : anyDefinitionPath.join(\"/\"),\n };\n}\n","import { ZodFirstPartyTypeKind } from \"zod/v3\";\nimport { setResponseValueAndErrors } from \"../errorMessages.js\";\nimport { parseDef } from \"../parseDef.js\";\nexport function parseArrayDef(def, refs) {\n const res = {\n type: \"array\",\n };\n if (def.type?._def &&\n def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) {\n res.items = parseDef(def.type._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\"],\n });\n }\n if (def.minLength) {\n setResponseValueAndErrors(res, \"minItems\", def.minLength.value, def.minLength.message, refs);\n }\n if (def.maxLength) {\n setResponseValueAndErrors(res, \"maxItems\", def.maxLength.value, def.maxLength.message, refs);\n }\n if (def.exactLength) {\n setResponseValueAndErrors(res, \"minItems\", def.exactLength.value, def.exactLength.message, refs);\n setResponseValueAndErrors(res, \"maxItems\", def.exactLength.value, def.exactLength.message, refs);\n }\n return res;\n}\n","import { setResponseValueAndErrors } from \"../errorMessages.js\";\nexport function parseBigintDef(def, refs) {\n const res = {\n type: \"integer\",\n format: \"int64\",\n };\n if (!def.checks)\n return res;\n for (const check of def.checks) {\n switch (check.kind) {\n case \"min\":\n if (refs.target === \"jsonSchema7\") {\n if (check.inclusive) {\n setResponseValueAndErrors(res, \"minimum\", check.value, check.message, refs);\n }\n else {\n setResponseValueAndErrors(res, \"exclusiveMinimum\", check.value, check.message, refs);\n }\n }\n else {\n if (!check.inclusive) {\n res.exclusiveMinimum = true;\n }\n setResponseValueAndErrors(res, \"minimum\", check.value, check.message, refs);\n }\n break;\n case \"max\":\n if (refs.target === \"jsonSchema7\") {\n if (check.inclusive) {\n setResponseValueAndErrors(res, \"maximum\", check.value, check.message, refs);\n }\n else {\n setResponseValueAndErrors(res, \"exclusiveMaximum\", check.value, check.message, refs);\n }\n }\n else {\n if (!check.inclusive) {\n res.exclusiveMaximum = true;\n }\n setResponseValueAndErrors(res, \"maximum\", check.value, check.message, refs);\n }\n break;\n case \"multipleOf\":\n setResponseValueAndErrors(res, \"multipleOf\", check.value, check.message, refs);\n break;\n }\n }\n return res;\n}\n","export function parseBooleanDef() {\n return {\n type: \"boolean\",\n };\n}\n","import { parseDef } from \"../parseDef.js\";\nexport function parseBrandedDef(_def, refs) {\n return parseDef(_def.type._def, refs);\n}\n","import { parseDef } from \"../parseDef.js\";\nexport const parseCatchDef = (def, refs) => {\n return parseDef(def.innerType._def, refs);\n};\n","import { setResponseValueAndErrors } from \"../errorMessages.js\";\nexport function parseDateDef(def, refs, overrideDateStrategy) {\n const strategy = overrideDateStrategy ?? refs.dateStrategy;\n if (Array.isArray(strategy)) {\n return {\n anyOf: strategy.map((item, i) => parseDateDef(def, refs, item)),\n };\n }\n switch (strategy) {\n case \"string\":\n case \"format:date-time\":\n return {\n type: \"string\",\n format: \"date-time\",\n };\n case \"format:date\":\n return {\n type: \"string\",\n format: \"date\",\n };\n case \"integer\":\n return integerDateParser(def, refs);\n }\n}\nconst integerDateParser = (def, refs) => {\n const res = {\n type: \"integer\",\n format: \"unix-time\",\n };\n if (refs.target === \"openApi3\") {\n return res;\n }\n for (const check of def.checks) {\n switch (check.kind) {\n case \"min\":\n setResponseValueAndErrors(res, \"minimum\", check.value, // This is in milliseconds\n check.message, refs);\n break;\n case \"max\":\n setResponseValueAndErrors(res, \"maximum\", check.value, // This is in milliseconds\n check.message, refs);\n break;\n }\n }\n return res;\n};\n","import { parseDef } from \"../parseDef.js\";\nexport function parseDefaultDef(_def, refs) {\n return {\n ...parseDef(_def.innerType._def, refs),\n default: _def.defaultValue(),\n };\n}\n","import { parseDef } from \"../parseDef.js\";\nimport { parseAnyDef } from \"./any.js\";\nexport function parseEffectsDef(_def, refs) {\n return refs.effectStrategy === \"input\"\n ? parseDef(_def.schema._def, refs)\n : parseAnyDef(refs);\n}\n","export function parseEnumDef(def) {\n return {\n type: \"string\",\n enum: Array.from(def.values),\n };\n}\n","import { parseDef } from \"../parseDef.js\";\nconst isJsonSchema7AllOfType = (type) => {\n if (\"type\" in type && type.type === \"string\")\n return false;\n return \"allOf\" in type;\n};\nexport function parseIntersectionDef(def, refs) {\n const allOf = [\n parseDef(def.left._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"allOf\", \"0\"],\n }),\n parseDef(def.right._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"allOf\", \"1\"],\n }),\n ].filter((x) => !!x);\n let unevaluatedProperties = refs.target === \"jsonSchema2019-09\"\n ? { unevaluatedProperties: false }\n : undefined;\n const mergedAllOf = [];\n // If either of the schemas is an allOf, merge them into a single allOf\n allOf.forEach((schema) => {\n if (isJsonSchema7AllOfType(schema)) {\n mergedAllOf.push(...schema.allOf);\n if (schema.unevaluatedProperties === undefined) {\n // If one of the schemas has no unevaluatedProperties set,\n // the merged schema should also have no unevaluatedProperties set\n unevaluatedProperties = undefined;\n }\n }\n else {\n let nestedSchema = schema;\n if (\"additionalProperties\" in schema &&\n schema.additionalProperties === false) {\n const { additionalProperties, ...rest } = schema;\n nestedSchema = rest;\n }\n else {\n // As soon as one of the schemas has additionalProperties set not to false, we allow unevaluatedProperties\n unevaluatedProperties = undefined;\n }\n mergedAllOf.push(nestedSchema);\n }\n });\n return mergedAllOf.length\n ? {\n allOf: mergedAllOf,\n ...unevaluatedProperties,\n }\n : undefined;\n}\n","export function parseLiteralDef(def, refs) {\n const parsedType = typeof def.value;\n if (parsedType !== \"bigint\" &&\n parsedType !== \"number\" &&\n parsedType !== \"boolean\" &&\n parsedType !== \"string\") {\n return {\n type: Array.isArray(def.value) ? \"array\" : \"object\",\n };\n }\n if (refs.target === \"openApi3\") {\n return {\n type: parsedType === \"bigint\" ? \"integer\" : parsedType,\n enum: [def.value],\n };\n }\n return {\n type: parsedType === \"bigint\" ? \"integer\" : parsedType,\n const: def.value,\n };\n}\n","import { setResponseValueAndErrors } from \"../errorMessages.js\";\nlet emojiRegex = undefined;\n/**\n * Generated from the regular expressions found here as of 2024-05-22:\n * https://github.com/colinhacks/zod/blob/master/src/types.ts.\n *\n * Expressions with /i flag have been changed accordingly.\n */\nexport const zodPatterns = {\n /**\n * `c` was changed to `[cC]` to replicate /i flag\n */\n cuid: /^[cC][^\\s-]{8,}$/,\n cuid2: /^[0-9a-z]+$/,\n ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,\n /**\n * `a-z` was added to replicate /i flag\n */\n email: /^(?!\\.)(?!.*\\.\\.)([a-zA-Z0-9_'+\\-\\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\\-]*\\.)+[a-zA-Z]{2,}$/,\n /**\n * Constructed a valid Unicode RegExp\n *\n * Lazily instantiate since this type of regex isn't supported\n * in all envs (e.g. React Native).\n *\n * See:\n * https://github.com/colinhacks/zod/issues/2433\n * Fix in Zod:\n * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b\n */\n emoji: () => {\n if (emojiRegex === undefined) {\n emojiRegex = RegExp(\"^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$\", \"u\");\n }\n return emojiRegex;\n },\n /**\n * Unused\n */\n uuid: /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/,\n /**\n * Unused\n */\n ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,\n ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/,\n /**\n * Unused\n */\n ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,\n ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,\n base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,\n base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,\n nanoid: /^[a-zA-Z0-9_-]{21}$/,\n jwt: /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/,\n};\nexport function parseStringDef(def, refs) {\n const res = {\n type: \"string\",\n };\n if (def.checks) {\n for (const check of def.checks) {\n switch (check.kind) {\n case \"min\":\n setResponseValueAndErrors(res, \"minLength\", typeof res.minLength === \"number\"\n ? Math.max(res.minLength, check.value)\n : check.value, check.message, refs);\n break;\n case \"max\":\n setResponseValueAndErrors(res, \"maxLength\", typeof res.maxLength === \"number\"\n ? Math.min(res.maxLength, check.value)\n : check.value, check.message, refs);\n break;\n case \"email\":\n switch (refs.emailStrategy) {\n case \"format:email\":\n addFormat(res, \"email\", check.message, refs);\n break;\n case \"format:idn-email\":\n addFormat(res, \"idn-email\", check.message, refs);\n break;\n case \"pattern:zod\":\n addPattern(res, zodPatterns.email, check.message, refs);\n break;\n }\n break;\n case \"url\":\n addFormat(res, \"uri\", check.message, refs);\n break;\n case \"uuid\":\n addFormat(res, \"uuid\", check.message, refs);\n break;\n case \"regex\":\n addPattern(res, check.regex, check.message, refs);\n break;\n case \"cuid\":\n addPattern(res, zodPatterns.cuid, check.message, refs);\n break;\n case \"cuid2\":\n addPattern(res, zodPatterns.cuid2, check.message, refs);\n break;\n case \"startsWith\":\n addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs);\n break;\n case \"endsWith\":\n addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs);\n break;\n case \"datetime\":\n addFormat(res, \"date-time\", check.message, refs);\n break;\n case \"date\":\n addFormat(res, \"date\", check.message, refs);\n break;\n case \"time\":\n addFormat(res, \"time\", check.message, refs);\n break;\n case \"duration\":\n addFormat(res, \"duration\", check.message, refs);\n break;\n case \"length\":\n setResponseValueAndErrors(res, \"minLength\", typeof res.minLength === \"number\"\n ? Math.max(res.minLength, check.value)\n : check.value, check.message, refs);\n setResponseValueAndErrors(res, \"maxLength\", typeof res.maxLength === \"number\"\n ? Math.min(res.maxLength, check.value)\n : check.value, check.message, refs);\n break;\n case \"includes\": {\n addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs);\n break;\n }\n case \"ip\": {\n if (check.version !== \"v6\") {\n addFormat(res, \"ipv4\", check.message, refs);\n }\n if (check.version !== \"v4\") {\n addFormat(res, \"ipv6\", check.message, refs);\n }\n break;\n }\n case \"base64url\":\n addPattern(res, zodPatterns.base64url, check.message, refs);\n break;\n case \"jwt\":\n addPattern(res, zodPatterns.jwt, check.message, refs);\n break;\n case \"cidr\": {\n if (check.version !== \"v6\") {\n addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);\n }\n if (check.version !== \"v4\") {\n addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);\n }\n break;\n }\n case \"emoji\":\n addPattern(res, zodPatterns.emoji(), check.message, refs);\n break;\n case \"ulid\": {\n addPattern(res, zodPatterns.ulid, check.message, refs);\n break;\n }\n case \"base64\": {\n switch (refs.base64Strategy) {\n case \"format:binary\": {\n addFormat(res, \"binary\", check.message, refs);\n break;\n }\n case \"contentEncoding:base64\": {\n setResponseValueAndErrors(res, \"contentEncoding\", \"base64\", check.message, refs);\n break;\n }\n case \"pattern:zod\": {\n addPattern(res, zodPatterns.base64, check.message, refs);\n break;\n }\n }\n break;\n }\n case \"nanoid\": {\n addPattern(res, zodPatterns.nanoid, check.message, refs);\n }\n case \"toLowerCase\":\n case \"toUpperCase\":\n case \"trim\":\n break;\n default:\n ((_) => { })(check);\n }\n }\n }\n return res;\n}\nfunction escapeLiteralCheckValue(literal, refs) {\n return refs.patternStrategy === \"escape\"\n ? escapeNonAlphaNumeric(literal)\n : literal;\n}\nconst ALPHA_NUMERIC = new Set(\"ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789\");\nfunction escapeNonAlphaNumeric(source) {\n let result = \"\";\n for (let i = 0; i < source.length; i++) {\n if (!ALPHA_NUMERIC.has(source[i])) {\n result += \"\\\\\";\n }\n result += source[i];\n }\n return result;\n}\n// Adds a \"format\" keyword to the schema. If a format exists, both formats will be joined in an allOf-node, along with subsequent ones.\nfunction addFormat(schema, value, message, refs) {\n if (schema.format || schema.anyOf?.some((x) => x.format)) {\n if (!schema.anyOf) {\n schema.anyOf = [];\n }\n if (schema.format) {\n schema.anyOf.push({\n format: schema.format,\n ...(schema.errorMessage &&\n refs.errorMessages && {\n errorMessage: { format: schema.errorMessage.format },\n }),\n });\n delete schema.format;\n if (schema.errorMessage) {\n delete schema.errorMessage.format;\n if (Object.keys(schema.errorMessage).length === 0) {\n delete schema.errorMessage;\n }\n }\n }\n schema.anyOf.push({\n format: value,\n ...(message &&\n refs.errorMessages && { errorMessage: { format: message } }),\n });\n }\n else {\n setResponseValueAndErrors(schema, \"format\", value, message, refs);\n }\n}\n// Adds a \"pattern\" keyword to the schema. If a pattern exists, both patterns will be joined in an allOf-node, along with subsequent ones.\nfunction addPattern(schema, regex, message, refs) {\n if (schema.pattern || schema.allOf?.some((x) => x.pattern)) {\n if (!schema.allOf) {\n schema.allOf = [];\n }\n if (schema.pattern) {\n schema.allOf.push({\n pattern: schema.pattern,\n ...(schema.errorMessage &&\n refs.errorMessages && {\n errorMessage: { pattern: schema.errorMessage.pattern },\n }),\n });\n delete schema.pattern;\n if (schema.errorMessage) {\n delete schema.errorMessage.pattern;\n if (Object.keys(schema.errorMessage).length === 0) {\n delete schema.errorMessage;\n }\n }\n }\n schema.allOf.push({\n pattern: stringifyRegExpWithFlags(regex, refs),\n ...(message &&\n refs.errorMessages && { errorMessage: { pattern: message } }),\n });\n }\n else {\n setResponseValueAndErrors(schema, \"pattern\", stringifyRegExpWithFlags(regex, refs), message, refs);\n }\n}\n// Mutate z.string.regex() in a best attempt to accommodate for regex flags when applyRegexFlags is true\nfunction stringifyRegExpWithFlags(regex, refs) {\n if (!refs.applyRegexFlags || !regex.flags) {\n return regex.source;\n }\n // Currently handled flags\n const flags = {\n i: regex.flags.includes(\"i\"),\n m: regex.flags.includes(\"m\"),\n s: regex.flags.includes(\"s\"), // `.` matches newlines\n };\n // The general principle here is to step through each character, one at a time, applying mutations as flags require. We keep track when the current character is escaped, and when it's inside a group /like [this]/ or (also) a range like /[a-z]/. The following is fairly brittle imperative code; edit at your peril!\n const source = flags.i ? regex.source.toLowerCase() : regex.source;\n let pattern = \"\";\n let isEscaped = false;\n let inCharGroup = false;\n let inCharRange = false;\n for (let i = 0; i < source.length; i++) {\n if (isEscaped) {\n pattern += source[i];\n isEscaped = false;\n continue;\n }\n if (flags.i) {\n if (inCharGroup) {\n if (source[i].match(/[a-z]/)) {\n if (inCharRange) {\n pattern += source[i];\n pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();\n inCharRange = false;\n }\n else if (source[i + 1] === \"-\" && source[i + 2]?.match(/[a-z]/)) {\n pattern += source[i];\n inCharRange = true;\n }\n else {\n pattern += `${source[i]}${source[i].toUpperCase()}`;\n }\n continue;\n }\n }\n else if (source[i].match(/[a-z]/)) {\n pattern += `[${source[i]}${source[i].toUpperCase()}]`;\n continue;\n }\n }\n if (flags.m) {\n if (source[i] === \"^\") {\n pattern += `(^|(?<=[\\r\\n]))`;\n continue;\n }\n else if (source[i] === \"$\") {\n pattern += `($|(?=[\\r\\n]))`;\n continue;\n }\n }\n if (flags.s && source[i] === \".\") {\n pattern += inCharGroup ? `${source[i]}\\r\\n` : `[${source[i]}\\r\\n]`;\n continue;\n }\n pattern += source[i];\n if (source[i] === \"\\\\\") {\n isEscaped = true;\n }\n else if (inCharGroup && source[i] === \"]\") {\n inCharGroup = false;\n }\n else if (!inCharGroup && source[i] === \"[\") {\n inCharGroup = true;\n }\n }\n try {\n new RegExp(pattern);\n }\n catch {\n console.warn(`Could not convert regex pattern at ${refs.currentPath.join(\"/\")} to a flag-independent form! Falling back to the flag-ignorant source`);\n return regex.source;\n }\n return pattern;\n}\n","import { ZodFirstPartyTypeKind, } from \"zod/v3\";\nimport { parseDef } from \"../parseDef.js\";\nimport { parseStringDef } from \"./string.js\";\nimport { parseBrandedDef } from \"./branded.js\";\nimport { parseAnyDef } from \"./any.js\";\nexport function parseRecordDef(def, refs) {\n if (refs.target === \"openAi\") {\n console.warn(\"Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.\");\n }\n if (refs.target === \"openApi3\" &&\n def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {\n return {\n type: \"object\",\n required: def.keyType._def.values,\n properties: def.keyType._def.values.reduce((acc, key) => ({\n ...acc,\n [key]: parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"properties\", key],\n }) ?? parseAnyDef(refs),\n }), {}),\n additionalProperties: refs.rejectedAdditionalProperties,\n };\n }\n const schema = {\n type: \"object\",\n additionalProperties: parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"additionalProperties\"],\n }) ?? refs.allowedAdditionalProperties,\n };\n if (refs.target === \"openApi3\") {\n return schema;\n }\n if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString &&\n def.keyType._def.checks?.length) {\n const { type, ...keyType } = parseStringDef(def.keyType._def, refs);\n return {\n ...schema,\n propertyNames: keyType,\n };\n }\n else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {\n return {\n ...schema,\n propertyNames: {\n enum: def.keyType._def.values,\n },\n };\n }\n else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodBranded &&\n def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString &&\n def.keyType._def.type._def.checks?.length) {\n const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs);\n return {\n ...schema,\n propertyNames: keyType,\n };\n }\n return schema;\n}\n","import { parseDef } from \"../parseDef.js\";\nimport { parseRecordDef } from \"./record.js\";\nimport { parseAnyDef } from \"./any.js\";\nexport function parseMapDef(def, refs) {\n if (refs.mapStrategy === \"record\") {\n return parseRecordDef(def, refs);\n }\n const keys = parseDef(def.keyType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\", \"items\", \"0\"],\n }) || parseAnyDef(refs);\n const values = parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\", \"items\", \"1\"],\n }) || parseAnyDef(refs);\n return {\n type: \"array\",\n maxItems: 125,\n items: {\n type: \"array\",\n items: [keys, values],\n minItems: 2,\n maxItems: 2,\n },\n };\n}\n","export function parseNativeEnumDef(def) {\n const object = def.values;\n const actualKeys = Object.keys(def.values).filter((key) => {\n return typeof object[object[key]] !== \"number\";\n });\n const actualValues = actualKeys.map((key) => object[key]);\n const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));\n return {\n type: parsedTypes.length === 1\n ? parsedTypes[0] === \"string\"\n ? \"string\"\n : \"number\"\n : [\"string\", \"number\"],\n enum: actualValues,\n };\n}\n","import { parseAnyDef } from \"./any.js\";\nexport function parseNeverDef(refs) {\n return refs.target === \"openAi\"\n ? undefined\n : {\n not: parseAnyDef({\n ...refs,\n currentPath: [...refs.currentPath, \"not\"],\n }),\n };\n}\n","export function parseNullDef(refs) {\n return refs.target === \"openApi3\"\n ? {\n enum: [\"null\"],\n nullable: true,\n }\n : {\n type: \"null\",\n };\n}\n","import { parseDef } from \"../parseDef.js\";\nexport const primitiveMappings = {\n ZodString: \"string\",\n ZodNumber: \"number\",\n ZodBigInt: \"integer\",\n ZodBoolean: \"boolean\",\n ZodNull: \"null\",\n};\nexport function parseUnionDef(def, refs) {\n if (refs.target === \"openApi3\")\n return asAnyOf(def, refs);\n const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;\n // This blocks tries to look ahead a bit to produce nicer looking schemas with type array instead of anyOf.\n if (options.every((x) => x._def.typeName in primitiveMappings &&\n (!x._def.checks || !x._def.checks.length))) {\n // all types in union are primitive and lack checks, so might as well squash into {type: [...]}\n const types = options.reduce((types, x) => {\n const type = primitiveMappings[x._def.typeName]; //Can be safely casted due to row 43\n return type && !types.includes(type) ? [...types, type] : types;\n }, []);\n return {\n type: types.length > 1 ? types : types[0],\n };\n }\n else if (options.every((x) => x._def.typeName === \"ZodLiteral\" && !x.description)) {\n // all options literals\n const types = options.reduce((acc, x) => {\n const type = typeof x._def.value;\n switch (type) {\n case \"string\":\n case \"number\":\n case \"boolean\":\n return [...acc, type];\n case \"bigint\":\n return [...acc, \"integer\"];\n case \"object\":\n if (x._def.value === null)\n return [...acc, \"null\"];\n case \"symbol\":\n case \"undefined\":\n case \"function\":\n default:\n return acc;\n }\n }, []);\n if (types.length === options.length) {\n // all the literals are primitive, as far as null can be considered primitive\n const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);\n return {\n type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],\n enum: options.reduce((acc, x) => {\n return acc.includes(x._def.value) ? acc : [...acc, x._def.value];\n }, []),\n };\n }\n }\n else if (options.every((x) => x._def.typeName === \"ZodEnum\")) {\n return {\n type: \"string\",\n enum: options.reduce((acc, x) => [\n ...acc,\n ...x._def.values.filter((x) => !acc.includes(x)),\n ], []),\n };\n }\n return asAnyOf(def, refs);\n}\nconst asAnyOf = (def, refs) => {\n const anyOf = (def.options instanceof Map\n ? Array.from(def.options.values())\n : def.options)\n .map((x, i) => parseDef(x._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"anyOf\", `${i}`],\n }))\n .filter((x) => !!x &&\n (!refs.strictUnions ||\n (typeof x === \"object\" && Object.keys(x).length > 0)));\n return anyOf.length ? { anyOf } : undefined;\n};\n","import { parseDef } from \"../parseDef.js\";\nimport { primitiveMappings } from \"./union.js\";\nexport function parseNullableDef(def, refs) {\n if ([\"ZodString\", \"ZodNumber\", \"ZodBigInt\", \"ZodBoolean\", \"ZodNull\"].includes(def.innerType._def.typeName) &&\n (!def.innerType._def.checks || !def.innerType._def.checks.length)) {\n if (refs.target === \"openApi3\") {\n return {\n type: primitiveMappings[def.innerType._def.typeName],\n nullable: true,\n };\n }\n return {\n type: [\n primitiveMappings[def.innerType._def.typeName],\n \"null\",\n ],\n };\n }\n if (refs.target === \"openApi3\") {\n const base = parseDef(def.innerType._def, {\n ...refs,\n currentPath: [...refs.currentPath],\n });\n if (base && \"$ref\" in base)\n return { allOf: [base], nullable: true };\n return base && { ...base, nullable: true };\n }\n const base = parseDef(def.innerType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"anyOf\", \"0\"],\n });\n return base && { anyOf: [base, { type: \"null\" }] };\n}\n","import { addErrorMessage, setResponseValueAndErrors, } from \"../errorMessages.js\";\nexport function parseNumberDef(def, refs) {\n const res = {\n type: \"number\",\n };\n if (!def.checks)\n return res;\n for (const check of def.checks) {\n switch (check.kind) {\n case \"int\":\n res.type = \"integer\";\n addErrorMessage(res, \"type\", check.message, refs);\n break;\n case \"min\":\n if (refs.target === \"jsonSchema7\") {\n if (check.inclusive) {\n setResponseValueAndErrors(res, \"minimum\", check.value, check.message, refs);\n }\n else {\n setResponseValueAndErrors(res, \"exclusiveMinimum\", check.value, check.message, refs);\n }\n }\n else {\n if (!check.inclusive) {\n res.exclusiveMinimum = true;\n }\n setResponseValueAndErrors(res, \"minimum\", check.value, check.message, refs);\n }\n break;\n case \"max\":\n if (refs.target === \"jsonSchema7\") {\n if (check.inclusive) {\n setResponseValueAndErrors(res, \"maximum\", check.value, check.message, refs);\n }\n else {\n setResponseValueAndErrors(res, \"exclusiveMaximum\", check.value, check.message, refs);\n }\n }\n else {\n if (!check.inclusive) {\n res.exclusiveMaximum = true;\n }\n setResponseValueAndErrors(res, \"maximum\", check.value, check.message, refs);\n }\n break;\n case \"multipleOf\":\n setResponseValueAndErrors(res, \"multipleOf\", check.value, check.message, refs);\n break;\n }\n }\n return res;\n}\n","import { parseDef } from \"../parseDef.js\";\nexport function parseObjectDef(def, refs) {\n const forceOptionalIntoNullable = refs.target === \"openAi\";\n const result = {\n type: \"object\",\n properties: {},\n };\n const required = [];\n const shape = def.shape();\n for (const propName in shape) {\n let propDef = shape[propName];\n if (propDef === undefined || propDef._def === undefined) {\n continue;\n }\n let propOptional = safeIsOptional(propDef);\n if (propOptional && forceOptionalIntoNullable) {\n if (propDef._def.typeName === \"ZodOptional\") {\n propDef = propDef._def.innerType;\n }\n if (!propDef.isNullable()) {\n propDef = propDef.nullable();\n }\n propOptional = false;\n }\n const parsedDef = parseDef(propDef._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"properties\", propName],\n propertyPath: [...refs.currentPath, \"properties\", propName],\n });\n if (parsedDef === undefined) {\n continue;\n }\n result.properties[propName] = parsedDef;\n if (!propOptional) {\n required.push(propName);\n }\n }\n if (required.length) {\n result.required = required;\n }\n const additionalProperties = decideAdditionalProperties(def, refs);\n if (additionalProperties !== undefined) {\n result.additionalProperties = additionalProperties;\n }\n return result;\n}\nfunction decideAdditionalProperties(def, refs) {\n if (def.catchall._def.typeName !== \"ZodNever\") {\n return parseDef(def.catchall._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"additionalProperties\"],\n });\n }\n switch (def.unknownKeys) {\n case \"passthrough\":\n return refs.allowedAdditionalProperties;\n case \"strict\":\n return refs.rejectedAdditionalProperties;\n case \"strip\":\n return refs.removeAdditionalStrategy === \"strict\"\n ? refs.allowedAdditionalProperties\n : refs.rejectedAdditionalProperties;\n }\n}\nfunction safeIsOptional(schema) {\n try {\n return schema.isOptional();\n }\n catch {\n return true;\n }\n}\n","import { parseDef } from \"../parseDef.js\";\nimport { parseAnyDef } from \"./any.js\";\nexport const parseOptionalDef = (def, refs) => {\n if (refs.currentPath.toString() === refs.propertyPath?.toString()) {\n return parseDef(def.innerType._def, refs);\n }\n const innerSchema = parseDef(def.innerType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"anyOf\", \"1\"],\n });\n return innerSchema\n ? {\n anyOf: [\n {\n not: parseAnyDef(refs),\n },\n innerSchema,\n ],\n }\n : parseAnyDef(refs);\n};\n","import { parseDef } from \"../parseDef.js\";\nexport const parsePipelineDef = (def, refs) => {\n if (refs.pipeStrategy === \"input\") {\n return parseDef(def.in._def, refs);\n }\n else if (refs.pipeStrategy === \"output\") {\n return parseDef(def.out._def, refs);\n }\n const a = parseDef(def.in._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"allOf\", \"0\"],\n });\n const b = parseDef(def.out._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"allOf\", a ? \"1\" : \"0\"],\n });\n return {\n allOf: [a, b].filter((x) => x !== undefined),\n };\n};\n","import { parseDef } from \"../parseDef.js\";\nexport function parsePromiseDef(def, refs) {\n return parseDef(def.type._def, refs);\n}\n","import { setResponseValueAndErrors } from \"../errorMessages.js\";\nimport { parseDef } from \"../parseDef.js\";\nexport function parseSetDef(def, refs) {\n const items = parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\"],\n });\n const schema = {\n type: \"array\",\n uniqueItems: true,\n items,\n };\n if (def.minSize) {\n setResponseValueAndErrors(schema, \"minItems\", def.minSize.value, def.minSize.message, refs);\n }\n if (def.maxSize) {\n setResponseValueAndErrors(schema, \"maxItems\", def.maxSize.value, def.maxSize.message, refs);\n }\n return schema;\n}\n","import { parseDef } from \"../parseDef.js\";\nexport function parseTupleDef(def, refs) {\n if (def.rest) {\n return {\n type: \"array\",\n minItems: def.items.length,\n items: def.items\n .map((x, i) => parseDef(x._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\", `${i}`],\n }))\n .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []),\n additionalItems: parseDef(def.rest._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"additionalItems\"],\n }),\n };\n }\n else {\n return {\n type: \"array\",\n minItems: def.items.length,\n maxItems: def.items.length,\n items: def.items\n .map((x, i) => parseDef(x._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\", `${i}`],\n }))\n .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []),\n };\n }\n}\n","import { parseAnyDef } from \"./any.js\";\nexport function parseUndefinedDef(refs) {\n return {\n not: parseAnyDef(refs),\n };\n}\n","import { parseAnyDef } from \"./any.js\";\nexport function parseUnknownDef(refs) {\n return parseAnyDef(refs);\n}\n","import { parseDef } from \"../parseDef.js\";\nexport const parseReadonlyDef = (def, refs) => {\n return parseDef(def.innerType._def, refs);\n};\n","import { ZodFirstPartyTypeKind } from \"zod/v3\";\nimport { parseAnyDef } from \"./parsers/any.js\";\nimport { parseArrayDef } from \"./parsers/array.js\";\nimport { parseBigintDef } from \"./parsers/bigint.js\";\nimport { parseBooleanDef } from \"./parsers/boolean.js\";\nimport { parseBrandedDef } from \"./parsers/branded.js\";\nimport { parseCatchDef } from \"./parsers/catch.js\";\nimport { parseDateDef } from \"./parsers/date.js\";\nimport { parseDefaultDef } from \"./parsers/default.js\";\nimport { parseEffectsDef } from \"./parsers/effects.js\";\nimport { parseEnumDef } from \"./parsers/enum.js\";\nimport { parseIntersectionDef } from \"./parsers/intersection.js\";\nimport { parseLiteralDef } from \"./parsers/literal.js\";\nimport { parseMapDef } from \"./parsers/map.js\";\nimport { parseNativeEnumDef } from \"./parsers/nativeEnum.js\";\nimport { parseNeverDef } from \"./parsers/never.js\";\nimport { parseNullDef } from \"./parsers/null.js\";\nimport { parseNullableDef } from \"./parsers/nullable.js\";\nimport { parseNumberDef } from \"./parsers/number.js\";\nimport { parseObjectDef } from \"./parsers/object.js\";\nimport { parseOptionalDef } from \"./parsers/optional.js\";\nimport { parsePipelineDef } from \"./parsers/pipeline.js\";\nimport { parsePromiseDef } from \"./parsers/promise.js\";\nimport { parseRecordDef } from \"./parsers/record.js\";\nimport { parseSetDef } from \"./parsers/set.js\";\nimport { parseStringDef } from \"./parsers/string.js\";\nimport { parseTupleDef } from \"./parsers/tuple.js\";\nimport { parseUndefinedDef } from \"./parsers/undefined.js\";\nimport { parseUnionDef } from \"./parsers/union.js\";\nimport { parseUnknownDef } from \"./parsers/unknown.js\";\nimport { parseReadonlyDef } from \"./parsers/readonly.js\";\nexport const selectParser = (def, typeName, refs) => {\n switch (typeName) {\n case ZodFirstPartyTypeKind.ZodString:\n return parseStringDef(def, refs);\n case ZodFirstPartyTypeKind.ZodNumber:\n return parseNumberDef(def, refs);\n case ZodFirstPartyTypeKind.ZodObject:\n return parseObjectDef(def, refs);\n case ZodFirstPartyTypeKind.ZodBigInt:\n return parseBigintDef(def, refs);\n case ZodFirstPartyTypeKind.ZodBoolean:\n return parseBooleanDef();\n case ZodFirstPartyTypeKind.ZodDate:\n return parseDateDef(def, refs);\n case ZodFirstPartyTypeKind.ZodUndefined:\n return parseUndefinedDef(refs);\n case ZodFirstPartyTypeKind.ZodNull:\n return parseNullDef(refs);\n case ZodFirstPartyTypeKind.ZodArray:\n return parseArrayDef(def, refs);\n case ZodFirstPartyTypeKind.ZodUnion:\n case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:\n return parseUnionDef(def, refs);\n case ZodFirstPartyTypeKind.ZodIntersection:\n return parseIntersectionDef(def, refs);\n case ZodFirstPartyTypeKind.ZodTuple:\n return parseTupleDef(def, refs);\n case ZodFirstPartyTypeKind.ZodRecord:\n return parseRecordDef(def, refs);\n case ZodFirstPartyTypeKind.ZodLiteral:\n return parseLiteralDef(def, refs);\n case ZodFirstPartyTypeKind.ZodEnum:\n return parseEnumDef(def);\n case ZodFirstPartyTypeKind.ZodNativeEnum:\n return parseNativeEnumDef(def);\n case ZodFirstPartyTypeKind.ZodNullable:\n return parseNullableDef(def, refs);\n case ZodFirstPartyTypeKind.ZodOptional:\n return parseOptionalDef(def, refs);\n case ZodFirstPartyTypeKind.ZodMap:\n return parseMapDef(def, refs);\n case ZodFirstPartyTypeKind.ZodSet:\n return parseSetDef(def, refs);\n case ZodFirstPartyTypeKind.ZodLazy:\n return () => def.getter()._def;\n case ZodFirstPartyTypeKind.ZodPromise:\n return parsePromiseDef(def, refs);\n case ZodFirstPartyTypeKind.ZodNaN:\n case ZodFirstPartyTypeKind.ZodNever:\n return parseNeverDef(refs);\n case ZodFirstPartyTypeKind.ZodEffects:\n return parseEffectsDef(def, refs);\n case ZodFirstPartyTypeKind.ZodAny:\n return parseAnyDef(refs);\n case ZodFirstPartyTypeKind.ZodUnknown:\n return parseUnknownDef(refs);\n case ZodFirstPartyTypeKind.ZodDefault:\n return parseDefaultDef(def, refs);\n case ZodFirstPartyTypeKind.ZodBranded:\n return parseBrandedDef(def, refs);\n case ZodFirstPartyTypeKind.ZodReadonly:\n return parseReadonlyDef(def, refs);\n case ZodFirstPartyTypeKind.ZodCatch:\n return parseCatchDef(def, refs);\n case ZodFirstPartyTypeKind.ZodPipeline:\n return parsePipelineDef(def, refs);\n case ZodFirstPartyTypeKind.ZodFunction:\n case ZodFirstPartyTypeKind.ZodVoid:\n case ZodFirstPartyTypeKind.ZodSymbol:\n return undefined;\n default:\n return ((_) => undefined)(typeName);\n }\n};\n","import { ignoreOverride } from \"./Options.js\";\nimport { selectParser } from \"./selectParser.js\";\nimport { getRelativePath } from \"./getRelativePath.js\";\nimport { parseAnyDef } from \"./parsers/any.js\";\nexport function parseDef(def, refs, forceResolution = false) {\n const seenItem = refs.seen.get(def);\n if (refs.override) {\n const overrideResult = refs.override?.(def, refs, seenItem, forceResolution);\n if (overrideResult !== ignoreOverride) {\n return overrideResult;\n }\n }\n if (seenItem && !forceResolution) {\n const seenSchema = get$ref(seenItem, refs);\n if (seenSchema !== undefined) {\n return seenSchema;\n }\n }\n const newItem = { def, path: refs.currentPath, jsonSchema: undefined };\n refs.seen.set(def, newItem);\n const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);\n // If the return was a function, then the inner definition needs to be extracted before a call to parseDef (recursive)\n const jsonSchema = typeof jsonSchemaOrGetter === \"function\"\n ? parseDef(jsonSchemaOrGetter(), refs)\n : jsonSchemaOrGetter;\n if (jsonSchema) {\n addMeta(def, refs, jsonSchema);\n }\n if (refs.postProcess) {\n const postProcessResult = refs.postProcess(jsonSchema, def, refs);\n newItem.jsonSchema = jsonSchema;\n return postProcessResult;\n }\n newItem.jsonSchema = jsonSchema;\n return jsonSchema;\n}\nconst get$ref = (item, refs) => {\n switch (refs.$refStrategy) {\n case \"root\":\n return { $ref: item.path.join(\"/\") };\n case \"relative\":\n return { $ref: getRelativePath(refs.currentPath, item.path) };\n case \"none\":\n case \"seen\": {\n if (item.path.length < refs.currentPath.length &&\n item.path.every((value, index) => refs.currentPath[index] === value)) {\n console.warn(`Recursive reference detected at ${refs.currentPath.join(\"/\")}! Defaulting to any`);\n return parseAnyDef(refs);\n }\n return refs.$refStrategy === \"seen\" ? parseAnyDef(refs) : undefined;\n }\n }\n};\nconst addMeta = (def, refs, jsonSchema) => {\n if (def.description) {\n jsonSchema.description = def.description;\n if (refs.markdownDescription) {\n jsonSchema.markdownDescription = def.description;\n }\n }\n return jsonSchema;\n};\n","import { parseDef } from \"./parseDef.js\";\nimport { getRefs } from \"./Refs.js\";\nimport { parseAnyDef } from \"./parsers/any.js\";\nconst zodToJsonSchema = (schema, options) => {\n const refs = getRefs(options);\n let definitions = typeof options === \"object\" && options.definitions\n ? Object.entries(options.definitions).reduce((acc, [name, schema]) => ({\n ...acc,\n [name]: parseDef(schema._def, {\n ...refs,\n currentPath: [...refs.basePath, refs.definitionPath, name],\n }, true) ?? parseAnyDef(refs),\n }), {})\n : undefined;\n const name = typeof options === \"string\"\n ? options\n : options?.nameStrategy === \"title\"\n ? undefined\n : options?.name;\n const main = parseDef(schema._def, name === undefined\n ? refs\n : {\n ...refs,\n currentPath: [...refs.basePath, refs.definitionPath, name],\n }, false) ?? parseAnyDef(refs);\n const title = typeof options === \"object\" &&\n options.name !== undefined &&\n options.nameStrategy === \"title\"\n ? options.name\n : undefined;\n if (title !== undefined) {\n main.title = title;\n }\n if (refs.flags.hasReferencedOpenAiAnyType) {\n if (!definitions) {\n definitions = {};\n }\n if (!definitions[refs.openAiAnyTypeName]) {\n definitions[refs.openAiAnyTypeName] = {\n // Skipping \"object\" as no properties can be defined and additionalProperties must be \"false\"\n type: [\"string\", \"number\", \"integer\", \"boolean\", \"array\", \"null\"],\n items: {\n $ref: refs.$refStrategy === \"relative\"\n ? \"1\"\n : [\n ...refs.basePath,\n refs.definitionPath,\n refs.openAiAnyTypeName,\n ].join(\"/\"),\n },\n };\n }\n }\n const combined = name === undefined\n ? definitions\n ? {\n ...main,\n [refs.definitionPath]: definitions,\n }\n : main\n : {\n $ref: [\n ...(refs.$refStrategy === \"relative\" ? [] : refs.basePath),\n refs.definitionPath,\n name,\n ].join(\"/\"),\n [refs.definitionPath]: {\n ...definitions,\n [name]: main,\n },\n };\n if (refs.target === \"jsonSchema7\") {\n combined.$schema = \"http://json-schema.org/draft-07/schema#\";\n }\n else if (refs.target === \"jsonSchema2019-09\" || refs.target === \"openAi\") {\n combined.$schema = \"https://json-schema.org/draft/2019-09/schema#\";\n }\n if (refs.target === \"openAi\" &&\n (\"anyOf\" in combined ||\n \"oneOf\" in combined ||\n \"allOf\" in combined ||\n (\"type\" in combined && Array.isArray(combined.type)))) {\n console.warn(\"Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.\");\n }\n return combined;\n};\nexport { zodToJsonSchema };\n","// 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","let crypto;\ncrypto =\n globalThis.crypto?.webcrypto ?? // Node.js [18-16] REPL\n globalThis.crypto ?? // Node.js >18\n import(\"node:crypto\").then(m => m.webcrypto); // Node.js <18 Non-REPL\n/**\n * Creates an array of length `size` of random bytes\n * @param size\n * @returns Array of random ints (0 to 255)\n */\nasync function getRandomValues(size) {\n return (await crypto).getRandomValues(new Uint8Array(size));\n}\n/** Generate cryptographically strong random string\n * @param size The desired length of the string\n * @returns The random string\n */\nasync function random(size) {\n const mask = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~\";\n const evenDistCutoff = Math.pow(2, 8) - Math.pow(2, 8) % mask.length;\n let result = \"\";\n while (result.length < size) {\n const randomBytes = await getRandomValues(size - result.length);\n for (const randomByte of randomBytes) {\n if (randomByte < evenDistCutoff) {\n result += mask[randomByte % mask.length];\n }\n }\n }\n return result;\n}\n/** Generate a PKCE challenge verifier\n * @param length Length of the verifier\n * @returns A random verifier `length` characters long\n */\nasync function generateVerifier(length) {\n return await random(length);\n}\n/** Generate a PKCE code challenge from a code verifier\n * @param code_verifier\n * @returns The base64 url encoded code challenge\n */\nexport async function generateChallenge(code_verifier) {\n const buffer = await (await crypto).subtle.digest(\"SHA-256\", new TextEncoder().encode(code_verifier));\n // Generate base64url string\n // btoa is deprecated in Node.js but is used here for web browser compatibility\n // (which has no good replacement yet, see also https://github.com/whatwg/html/issues/6811)\n return btoa(String.fromCharCode(...new Uint8Array(buffer)))\n .replace(/\\//g, '_')\n .replace(/\\+/g, '-')\n .replace(/=/g, '');\n}\n/** Generate a PKCE challenge pair\n * @param length Length of the verifer (between 43-128). Defaults to 43.\n * @returns PKCE challenge pair\n */\nexport default async function pkceChallenge(length) {\n if (!length)\n length = 43;\n if (length < 43 || length > 128) {\n throw `Expected a length between 43 and 128. Received ${length}.`;\n }\n const verifier = await generateVerifier(length);\n const challenge = await generateChallenge(verifier);\n return {\n code_verifier: verifier,\n code_challenge: challenge,\n };\n}\n/** Verify that a code_verifier produces the expected code challenge\n * @param code_verifier\n * @param expectedChallenge The code challenge to verify\n * @returns True if challenges are equal. False otherwise.\n */\nexport async function verifyChallenge(code_verifier, expectedChallenge) {\n const actualChallenge = await generateChallenge(code_verifier);\n return actualChallenge === expectedChallenge;\n}\n","import * as z from 'zod/v4';\n/**\n * Reusable URL validation that disallows javascript: scheme\n */\nexport const SafeUrlSchema = z\n .url()\n .superRefine((val, ctx) => {\n if (!URL.canParse(val)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'URL must be parseable',\n fatal: true\n });\n return z.NEVER;\n }\n})\n .refine(url => {\n const u = new URL(url);\n return u.protocol !== 'javascript:' && u.protocol !== 'data:' && u.protocol !== 'vbscript:';\n}, { message: 'URL cannot use javascript:, data:, or vbscript: scheme' });\n/**\n * RFC 9728 OAuth Protected Resource Metadata\n */\nexport const OAuthProtectedResourceMetadataSchema = z.looseObject({\n resource: z.string().url(),\n authorization_servers: z.array(SafeUrlSchema).optional(),\n jwks_uri: z.string().url().optional(),\n scopes_supported: z.array(z.string()).optional(),\n bearer_methods_supported: z.array(z.string()).optional(),\n resource_signing_alg_values_supported: z.array(z.string()).optional(),\n resource_name: z.string().optional(),\n resource_documentation: z.string().optional(),\n resource_policy_uri: z.string().url().optional(),\n resource_tos_uri: z.string().url().optional(),\n tls_client_certificate_bound_access_tokens: z.boolean().optional(),\n authorization_details_types_supported: z.array(z.string()).optional(),\n dpop_signing_alg_values_supported: z.array(z.string()).optional(),\n dpop_bound_access_tokens_required: z.boolean().optional()\n});\n/**\n * RFC 8414 OAuth 2.0 Authorization Server Metadata\n */\nexport const OAuthMetadataSchema = z.looseObject({\n issuer: z.string(),\n authorization_endpoint: SafeUrlSchema,\n token_endpoint: SafeUrlSchema,\n registration_endpoint: SafeUrlSchema.optional(),\n scopes_supported: z.array(z.string()).optional(),\n response_types_supported: z.array(z.string()),\n response_modes_supported: z.array(z.string()).optional(),\n grant_types_supported: z.array(z.string()).optional(),\n token_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),\n service_documentation: SafeUrlSchema.optional(),\n revocation_endpoint: SafeUrlSchema.optional(),\n revocation_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n revocation_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),\n introspection_endpoint: z.string().optional(),\n introspection_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n introspection_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),\n code_challenge_methods_supported: z.array(z.string()).optional(),\n client_id_metadata_document_supported: z.boolean().optional()\n});\n/**\n * OpenID Connect Discovery 1.0 Provider Metadata\n * see: https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata\n */\nexport const OpenIdProviderMetadataSchema = z.looseObject({\n issuer: z.string(),\n authorization_endpoint: SafeUrlSchema,\n token_endpoint: SafeUrlSchema,\n userinfo_endpoint: SafeUrlSchema.optional(),\n jwks_uri: SafeUrlSchema,\n registration_endpoint: SafeUrlSchema.optional(),\n scopes_supported: z.array(z.string()).optional(),\n response_types_supported: z.array(z.string()),\n response_modes_supported: z.array(z.string()).optional(),\n grant_types_supported: z.array(z.string()).optional(),\n acr_values_supported: z.array(z.string()).optional(),\n subject_types_supported: z.array(z.string()),\n id_token_signing_alg_values_supported: z.array(z.string()),\n id_token_encryption_alg_values_supported: z.array(z.string()).optional(),\n id_token_encryption_enc_values_supported: z.array(z.string()).optional(),\n userinfo_signing_alg_values_supported: z.array(z.string()).optional(),\n userinfo_encryption_alg_values_supported: z.array(z.string()).optional(),\n userinfo_encryption_enc_values_supported: z.array(z.string()).optional(),\n request_object_signing_alg_values_supported: z.array(z.string()).optional(),\n request_object_encryption_alg_values_supported: z.array(z.string()).optional(),\n request_object_encryption_enc_values_supported: z.array(z.string()).optional(),\n token_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),\n display_values_supported: z.array(z.string()).optional(),\n claim_types_supported: z.array(z.string()).optional(),\n claims_supported: z.array(z.string()).optional(),\n service_documentation: z.string().optional(),\n claims_locales_supported: z.array(z.string()).optional(),\n ui_locales_supported: z.array(z.string()).optional(),\n claims_parameter_supported: z.boolean().optional(),\n request_parameter_supported: z.boolean().optional(),\n request_uri_parameter_supported: z.boolean().optional(),\n require_request_uri_registration: z.boolean().optional(),\n op_policy_uri: SafeUrlSchema.optional(),\n op_tos_uri: SafeUrlSchema.optional(),\n client_id_metadata_document_supported: z.boolean().optional()\n});\n/**\n * OpenID Connect Discovery metadata that may include OAuth 2.0 fields\n * This schema represents the real-world scenario where OIDC providers\n * return a mix of OpenID Connect and OAuth 2.0 metadata fields\n */\nexport const OpenIdProviderDiscoveryMetadataSchema = z.object({\n ...OpenIdProviderMetadataSchema.shape,\n ...OAuthMetadataSchema.pick({\n code_challenge_methods_supported: true\n }).shape\n});\n/**\n * OAuth 2.1 token response\n */\nexport const OAuthTokensSchema = z\n .object({\n access_token: z.string(),\n id_token: z.string().optional(), // Optional for OAuth 2.1, but necessary in OpenID Connect\n token_type: z.string(),\n expires_in: z.coerce.number().optional(),\n scope: z.string().optional(),\n refresh_token: z.string().optional()\n})\n .strip();\n/**\n * OAuth 2.1 error response\n */\nexport const OAuthErrorResponseSchema = z.object({\n error: z.string(),\n error_description: z.string().optional(),\n error_uri: z.string().optional()\n});\n/**\n * Optional version of SafeUrlSchema that allows empty string for retrocompatibility on tos_uri and logo_uri\n */\nexport const OptionalSafeUrlSchema = SafeUrlSchema.optional().or(z.literal('').transform(() => undefined));\n/**\n * RFC 7591 OAuth 2.0 Dynamic Client Registration metadata\n */\nexport const OAuthClientMetadataSchema = z\n .object({\n redirect_uris: z.array(SafeUrlSchema),\n token_endpoint_auth_method: z.string().optional(),\n grant_types: z.array(z.string()).optional(),\n response_types: z.array(z.string()).optional(),\n client_name: z.string().optional(),\n client_uri: SafeUrlSchema.optional(),\n logo_uri: OptionalSafeUrlSchema,\n scope: z.string().optional(),\n contacts: z.array(z.string()).optional(),\n tos_uri: OptionalSafeUrlSchema,\n policy_uri: z.string().optional(),\n jwks_uri: SafeUrlSchema.optional(),\n jwks: z.any().optional(),\n software_id: z.string().optional(),\n software_version: z.string().optional(),\n software_statement: z.string().optional()\n})\n .strip();\n/**\n * RFC 7591 OAuth 2.0 Dynamic Client Registration client information\n */\nexport const OAuthClientInformationSchema = z\n .object({\n client_id: z.string(),\n client_secret: z.string().optional(),\n client_id_issued_at: z.number().optional(),\n client_secret_expires_at: z.number().optional()\n})\n .strip();\n/**\n * RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata)\n */\nexport const OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema);\n/**\n * RFC 7591 OAuth 2.0 Dynamic Client Registration error response\n */\nexport const OAuthClientRegistrationErrorSchema = z\n .object({\n error: z.string(),\n error_description: z.string().optional()\n})\n .strip();\n/**\n * RFC 7009 OAuth 2.0 Token Revocation request\n */\nexport const OAuthTokenRevocationRequestSchema = z\n .object({\n token: z.string(),\n token_type_hint: z.string().optional()\n})\n .strip();\n//# sourceMappingURL=auth.js.map","/**\n * 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","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","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","module.exports = isexe\nisexe.sync = sync\n\nvar fs = require('fs')\n\nfunction checkPathExt (path, options) {\n var pathext = options.pathExt !== undefined ?\n options.pathExt : process.env.PATHEXT\n\n if (!pathext) {\n return true\n }\n\n pathext = pathext.split(';')\n if (pathext.indexOf('') !== -1) {\n return true\n }\n for (var i = 0; i < pathext.length; i++) {\n var p = pathext[i].toLowerCase()\n if (p && path.substr(-p.length).toLowerCase() === p) {\n return true\n }\n }\n return false\n}\n\nfunction checkStat (stat, path, options) {\n if (!stat.isSymbolicLink() && !stat.isFile()) {\n return false\n }\n return checkPathExt(path, options)\n}\n\nfunction isexe (path, options, cb) {\n fs.stat(path, function (er, stat) {\n cb(er, er ? false : checkStat(stat, path, options))\n })\n}\n\nfunction sync (path, options) {\n return checkStat(fs.statSync(path), path, options)\n}\n","module.exports = isexe\nisexe.sync = sync\n\nvar fs = require('fs')\n\nfunction isexe (path, options, cb) {\n fs.stat(path, function (er, stat) {\n cb(er, er ? false : checkStat(stat, options))\n })\n}\n\nfunction sync (path, options) {\n return checkStat(fs.statSync(path), options)\n}\n\nfunction checkStat (stat, options) {\n return stat.isFile() && checkMode(stat, options)\n}\n\nfunction checkMode (stat, options) {\n var mod = stat.mode\n var uid = stat.uid\n var gid = stat.gid\n\n var myUid = options.uid !== undefined ?\n options.uid : process.getuid && process.getuid()\n var myGid = options.gid !== undefined ?\n options.gid : process.getgid && process.getgid()\n\n var u = parseInt('100', 8)\n var g = parseInt('010', 8)\n var o = parseInt('001', 8)\n var ug = u | g\n\n var ret = (mod & o) ||\n (mod & g) && gid === myGid ||\n (mod & u) && uid === myUid ||\n (mod & ug) && myUid === 0\n\n return ret\n}\n","var fs = require('fs')\nvar core\nif (process.platform === 'win32' || global.TESTING_WINDOWS) {\n core = require('./windows.js')\n} else {\n core = require('./mode.js')\n}\n\nmodule.exports = isexe\nisexe.sync = sync\n\nfunction isexe (path, options, cb) {\n if (typeof options === 'function') {\n cb = options\n options = {}\n }\n\n if (!cb) {\n if (typeof Promise !== 'function') {\n throw new TypeError('callback not provided')\n }\n\n return new Promise(function (resolve, reject) {\n isexe(path, options || {}, function (er, is) {\n if (er) {\n reject(er)\n } else {\n resolve(is)\n }\n })\n })\n }\n\n core(path, options || {}, function (er, is) {\n // ignore EACCES because that just means we aren't allowed to run it\n if (er) {\n if (er.code === 'EACCES' || options && options.ignoreErrors) {\n er = null\n is = false\n }\n }\n cb(er, is)\n })\n}\n\nfunction sync (path, options) {\n // my kingdom for a filtered catch\n try {\n return core.sync(path, options || {})\n } catch (er) {\n if (options && options.ignoreErrors || er.code === 'EACCES') {\n return false\n } else {\n throw er\n }\n }\n}\n","const isWindows = process.platform === 'win32' ||\n process.env.OSTYPE === 'cygwin' ||\n process.env.OSTYPE === 'msys'\n\nconst path = require('path')\nconst COLON = isWindows ? ';' : ':'\nconst isexe = require('isexe')\n\nconst getNotFoundError = (cmd) =>\n Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' })\n\nconst getPathInfo = (cmd, opt) => {\n const colon = opt.colon || COLON\n\n // If it has a slash, then we don't bother searching the pathenv.\n // just check the file itself, and that's it.\n const pathEnv = cmd.match(/\\//) || isWindows && cmd.match(/\\\\/) ? ['']\n : (\n [\n // windows always checks the cwd first\n ...(isWindows ? [process.cwd()] : []),\n ...(opt.path || process.env.PATH ||\n /* istanbul ignore next: very unusual */ '').split(colon),\n ]\n )\n const pathExtExe = isWindows\n ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM'\n : ''\n const pathExt = isWindows ? pathExtExe.split(colon) : ['']\n\n if (isWindows) {\n if (cmd.indexOf('.') !== -1 && pathExt[0] !== '')\n pathExt.unshift('')\n }\n\n return {\n pathEnv,\n pathExt,\n pathExtExe,\n }\n}\n\nconst which = (cmd, opt, cb) => {\n if (typeof opt === 'function') {\n cb = opt\n opt = {}\n }\n if (!opt)\n opt = {}\n\n const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)\n const found = []\n\n const step = i => new Promise((resolve, reject) => {\n if (i === pathEnv.length)\n return opt.all && found.length ? resolve(found)\n : reject(getNotFoundError(cmd))\n\n const ppRaw = pathEnv[i]\n const pathPart = /^\".*\"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw\n\n const pCmd = path.join(pathPart, cmd)\n const p = !pathPart && /^\\.[\\\\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd\n : pCmd\n\n resolve(subStep(p, i, 0))\n })\n\n const subStep = (p, i, ii) => new Promise((resolve, reject) => {\n if (ii === pathExt.length)\n return resolve(step(i + 1))\n const ext = pathExt[ii]\n isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {\n if (!er && is) {\n if (opt.all)\n found.push(p + ext)\n else\n return resolve(p + ext)\n }\n return resolve(subStep(p, i, ii + 1))\n })\n })\n\n return cb ? step(0).then(res => cb(null, res), cb) : step(0)\n}\n\nconst whichSync = (cmd, opt) => {\n opt = opt || {}\n\n const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)\n const found = []\n\n for (let i = 0; i < pathEnv.length; i ++) {\n const ppRaw = pathEnv[i]\n const pathPart = /^\".*\"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw\n\n const pCmd = path.join(pathPart, cmd)\n const p = !pathPart && /^\\.[\\\\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd\n : pCmd\n\n for (let j = 0; j < pathExt.length; j ++) {\n const cur = p + pathExt[j]\n try {\n const is = isexe.sync(cur, { pathExt: pathExtExe })\n if (is) {\n if (opt.all)\n found.push(cur)\n else\n return cur\n }\n } catch (ex) {}\n }\n }\n\n if (opt.all && found.length)\n return found\n\n if (opt.nothrow)\n return null\n\n throw getNotFoundError(cmd)\n}\n\nmodule.exports = which\nwhich.sync = whichSync\n","'use strict';\n\nconst pathKey = (options = {}) => {\n\tconst environment = options.env || process.env;\n\tconst platform = options.platform || process.platform;\n\n\tif (platform !== 'win32') {\n\t\treturn 'PATH';\n\t}\n\n\treturn Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path';\n};\n\nmodule.exports = pathKey;\n// TODO: Remove this for the next major release\nmodule.exports.default = pathKey;\n","'use strict';\n\nconst path = require('path');\nconst which = require('which');\nconst getPathKey = require('path-key');\n\nfunction resolveCommandAttempt(parsed, withoutPathExt) {\n const env = parsed.options.env || process.env;\n const cwd = process.cwd();\n const hasCustomCwd = parsed.options.cwd != null;\n // Worker threads do not have process.chdir()\n const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled;\n\n // If a custom `cwd` was specified, we need to change the process cwd\n // because `which` will do stat calls but does not support a custom cwd\n if (shouldSwitchCwd) {\n try {\n process.chdir(parsed.options.cwd);\n } catch (err) {\n /* Empty */\n }\n }\n\n let resolved;\n\n try {\n resolved = which.sync(parsed.command, {\n path: env[getPathKey({ env })],\n pathExt: withoutPathExt ? path.delimiter : undefined,\n });\n } catch (e) {\n /* Empty */\n } finally {\n if (shouldSwitchCwd) {\n process.chdir(cwd);\n }\n }\n\n // If we successfully resolved, ensure that an absolute path is returned\n // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it\n if (resolved) {\n resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved);\n }\n\n return resolved;\n}\n\nfunction resolveCommand(parsed) {\n return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);\n}\n\nmodule.exports = resolveCommand;\n","'use strict';\n\n// See http://www.robvanderwoude.com/escapechars.php\nconst metaCharsRegExp = /([()\\][%!^\"`<>&|;, *?])/g;\n\nfunction escapeCommand(arg) {\n // Escape meta chars\n arg = arg.replace(metaCharsRegExp, '^$1');\n\n return arg;\n}\n\nfunction escapeArgument(arg, doubleEscapeMetaChars) {\n // Convert to string\n arg = `${arg}`;\n\n // Algorithm below is based on https://qntm.org/cmd\n // It's slightly altered to disable JS backtracking to avoid hanging on specially crafted input\n // Please see https://github.com/moxystudio/node-cross-spawn/pull/160 for more information\n\n // Sequence of backslashes followed by a double quote:\n // double up all the backslashes and escape the double quote\n arg = arg.replace(/(?=(\\\\+?)?)\\1\"/g, '$1$1\\\\\"');\n\n // Sequence of backslashes followed by the end of the string\n // (which will become a double quote later):\n // double up all the backslashes\n arg = arg.replace(/(?=(\\\\+?)?)\\1$/, '$1$1');\n\n // All other backslashes occur literally\n\n // Quote the whole thing:\n arg = `\"${arg}\"`;\n\n // Escape meta chars\n arg = arg.replace(metaCharsRegExp, '^$1');\n\n // Double escape meta chars if necessary\n if (doubleEscapeMetaChars) {\n arg = arg.replace(metaCharsRegExp, '^$1');\n }\n\n return arg;\n}\n\nmodule.exports.command = escapeCommand;\nmodule.exports.argument = escapeArgument;\n","'use strict';\nmodule.exports = /^#!(.*)/;\n","'use strict';\nconst shebangRegex = require('shebang-regex');\n\nmodule.exports = (string = '') => {\n\tconst match = string.match(shebangRegex);\n\n\tif (!match) {\n\t\treturn null;\n\t}\n\n\tconst [path, argument] = match[0].replace(/#! ?/, '').split(' ');\n\tconst binary = path.split('/').pop();\n\n\tif (binary === 'env') {\n\t\treturn argument;\n\t}\n\n\treturn argument ? `${binary} ${argument}` : binary;\n};\n","'use strict';\n\nconst fs = require('fs');\nconst shebangCommand = require('shebang-command');\n\nfunction readShebang(command) {\n // Read the first 150 bytes from the file\n const size = 150;\n const buffer = Buffer.alloc(size);\n\n let fd;\n\n try {\n fd = fs.openSync(command, 'r');\n fs.readSync(fd, buffer, 0, size, 0);\n fs.closeSync(fd);\n } catch (e) { /* Empty */ }\n\n // Attempt to extract shebang (null is returned if not a shebang)\n return shebangCommand(buffer.toString());\n}\n\nmodule.exports = readShebang;\n","'use strict';\n\nconst path = require('path');\nconst resolveCommand = require('./util/resolveCommand');\nconst escape = require('./util/escape');\nconst readShebang = require('./util/readShebang');\n\nconst isWin = process.platform === 'win32';\nconst isExecutableRegExp = /\\.(?:com|exe)$/i;\nconst isCmdShimRegExp = /node_modules[\\\\/].bin[\\\\/][^\\\\/]+\\.cmd$/i;\n\nfunction detectShebang(parsed) {\n parsed.file = resolveCommand(parsed);\n\n const shebang = parsed.file && readShebang(parsed.file);\n\n if (shebang) {\n parsed.args.unshift(parsed.file);\n parsed.command = shebang;\n\n return resolveCommand(parsed);\n }\n\n return parsed.file;\n}\n\nfunction parseNonShell(parsed) {\n if (!isWin) {\n return parsed;\n }\n\n // Detect & add support for shebangs\n const commandFile = detectShebang(parsed);\n\n // We don't need a shell if the command filename is an executable\n const needsShell = !isExecutableRegExp.test(commandFile);\n\n // If a shell is required, use cmd.exe and take care of escaping everything correctly\n // Note that `forceShell` is an hidden option used only in tests\n if (parsed.options.forceShell || needsShell) {\n // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/`\n // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument\n // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called,\n // we need to double escape them\n const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);\n\n // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\\bar)\n // This is necessary otherwise it will always fail with ENOENT in those cases\n parsed.command = path.normalize(parsed.command);\n\n // Escape command & arguments\n parsed.command = escape.command(parsed.command);\n parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));\n\n const shellCommand = [parsed.command].concat(parsed.args).join(' ');\n\n parsed.args = ['/d', '/s', '/c', `\"${shellCommand}\"`];\n parsed.command = process.env.comspec || 'cmd.exe';\n parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped\n }\n\n return parsed;\n}\n\nfunction parse(command, args, options) {\n // Normalize arguments, similar to nodejs\n if (args && !Array.isArray(args)) {\n options = args;\n args = null;\n }\n\n args = args ? args.slice(0) : []; // Clone array to avoid changing the original\n options = Object.assign({}, options); // Clone object to avoid changing the original\n\n // Build our parsed object\n const parsed = {\n command,\n args,\n options,\n file: undefined,\n original: {\n command,\n args,\n },\n };\n\n // Delegate further parsing to shell or non-shell\n return options.shell ? parsed : parseNonShell(parsed);\n}\n\nmodule.exports = parse;\n","'use strict';\n\nconst isWin = process.platform === 'win32';\n\nfunction notFoundError(original, syscall) {\n return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {\n code: 'ENOENT',\n errno: 'ENOENT',\n syscall: `${syscall} ${original.command}`,\n path: original.command,\n spawnargs: original.args,\n });\n}\n\nfunction hookChildProcess(cp, parsed) {\n if (!isWin) {\n return;\n }\n\n const originalEmit = cp.emit;\n\n cp.emit = function (name, arg1) {\n // If emitting \"exit\" event and exit code is 1, we need to check if\n // the command exists and emit an \"error\" instead\n // See https://github.com/IndigoUnited/node-cross-spawn/issues/16\n if (name === 'exit') {\n const err = verifyENOENT(arg1, parsed);\n\n if (err) {\n return originalEmit.call(cp, 'error', err);\n }\n }\n\n return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params\n };\n}\n\nfunction verifyENOENT(status, parsed) {\n if (isWin && status === 1 && !parsed.file) {\n return notFoundError(parsed.original, 'spawn');\n }\n\n return null;\n}\n\nfunction verifyENOENTSync(status, parsed) {\n if (isWin && status === 1 && !parsed.file) {\n return notFoundError(parsed.original, 'spawnSync');\n }\n\n return null;\n}\n\nmodule.exports = {\n hookChildProcess,\n verifyENOENT,\n verifyENOENTSync,\n notFoundError,\n};\n","'use strict';\n\nconst cp = require('child_process');\nconst parse = require('./lib/parse');\nconst enoent = require('./lib/enoent');\n\nfunction spawn(command, args, options) {\n // Parse the arguments\n const parsed = parse(command, args, options);\n\n // Spawn the child process\n const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);\n\n // Hook into child process \"exit\" event to emit an error if the command\n // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16\n enoent.hookChildProcess(spawned, parsed);\n\n return spawned;\n}\n\nfunction spawnSync(command, args, options) {\n // Parse the arguments\n const parsed = parse(command, args, options);\n\n // Spawn the child process\n const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);\n\n // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16\n result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);\n\n return result;\n}\n\nmodule.exports = spawn;\nmodule.exports.spawn = spawn;\nmodule.exports.sync = spawnSync;\n\nmodule.exports._parse = parse;\nmodule.exports._enoent = enoent;\n","import { JSONRPCMessageSchema } from '../types.js';\n/**\n * Buffers a continuous stdio stream into discrete JSON-RPC messages.\n */\nexport class ReadBuffer {\n append(chunk) {\n this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk;\n }\n readMessage() {\n if (!this._buffer) {\n return null;\n }\n const index = this._buffer.indexOf('\\n');\n if (index === -1) {\n return null;\n }\n const line = this._buffer.toString('utf8', 0, index).replace(/\\r$/, '');\n this._buffer = this._buffer.subarray(index + 1);\n return deserializeMessage(line);\n }\n clear() {\n this._buffer = undefined;\n }\n}\nexport function deserializeMessage(line) {\n return JSONRPCMessageSchema.parse(JSON.parse(line));\n}\nexport function serializeMessage(message) {\n return JSON.stringify(message) + '\\n';\n}\n//# sourceMappingURL=stdio.js.map","import spawn from 'cross-spawn';\nimport process from 'node:process';\nimport { PassThrough } from 'node:stream';\nimport { ReadBuffer, serializeMessage } from '../shared/stdio.js';\n/**\n * Environment variables to inherit by default, if an environment is not explicitly given.\n */\nexport const DEFAULT_INHERITED_ENV_VARS = process.platform === 'win32'\n ? [\n 'APPDATA',\n 'HOMEDRIVE',\n 'HOMEPATH',\n 'LOCALAPPDATA',\n 'PATH',\n 'PROCESSOR_ARCHITECTURE',\n 'SYSTEMDRIVE',\n 'SYSTEMROOT',\n 'TEMP',\n 'USERNAME',\n 'USERPROFILE',\n 'PROGRAMFILES'\n ]\n : /* list inspired by the default env inheritance of sudo */\n ['HOME', 'LOGNAME', 'PATH', 'SHELL', 'TERM', 'USER'];\n/**\n * Returns a default environment object including only environment variables deemed safe to inherit.\n */\nexport function getDefaultEnvironment() {\n const env = {};\n for (const key of DEFAULT_INHERITED_ENV_VARS) {\n const value = process.env[key];\n if (value === undefined) {\n continue;\n }\n if (value.startsWith('()')) {\n // Skip functions, which are a security risk.\n continue;\n }\n env[key] = value;\n }\n return env;\n}\n/**\n * Client transport for stdio: this will connect to a server by spawning a process and communicating with it over stdin/stdout.\n *\n * This transport is only available in Node.js environments.\n */\nexport class StdioClientTransport {\n constructor(server) {\n this._readBuffer = new ReadBuffer();\n this._stderrStream = null;\n this._serverParams = server;\n if (server.stderr === 'pipe' || server.stderr === 'overlapped') {\n this._stderrStream = new PassThrough();\n }\n }\n /**\n * Starts the server process and prepares to communicate with it.\n */\n async start() {\n if (this._process) {\n throw new Error('StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.');\n }\n return new Promise((resolve, reject) => {\n this._process = spawn(this._serverParams.command, this._serverParams.args ?? [], {\n // merge default env with server env because mcp server needs some env vars\n env: {\n ...getDefaultEnvironment(),\n ...this._serverParams.env\n },\n stdio: ['pipe', 'pipe', this._serverParams.stderr ?? 'inherit'],\n shell: false,\n windowsHide: process.platform === 'win32',\n cwd: this._serverParams.cwd\n });\n this._process.on('error', error => {\n reject(error);\n this.onerror?.(error);\n });\n this._process.on('spawn', () => {\n resolve();\n });\n this._process.on('close', _code => {\n this._process = undefined;\n this.onclose?.();\n });\n this._process.stdin?.on('error', error => {\n this.onerror?.(error);\n });\n this._process.stdout?.on('data', chunk => {\n this._readBuffer.append(chunk);\n this.processReadBuffer();\n });\n this._process.stdout?.on('error', error => {\n this.onerror?.(error);\n });\n if (this._stderrStream && this._process.stderr) {\n this._process.stderr.pipe(this._stderrStream);\n }\n });\n }\n /**\n * The stderr stream of the child process, if `StdioServerParameters.stderr` was set to \"pipe\" or \"overlapped\".\n *\n * If stderr piping was requested, a PassThrough stream is returned _immediately_, allowing callers to\n * attach listeners before the start method is invoked. This prevents loss of any early\n * error output emitted by the child process.\n */\n get stderr() {\n if (this._stderrStream) {\n return this._stderrStream;\n }\n return this._process?.stderr ?? null;\n }\n /**\n * The child process pid spawned by this transport.\n *\n * This is only available after the transport has been started.\n */\n get pid() {\n return this._process?.pid ?? null;\n }\n processReadBuffer() {\n while (true) {\n try {\n const message = this._readBuffer.readMessage();\n if (message === null) {\n break;\n }\n this.onmessage?.(message);\n }\n catch (error) {\n this.onerror?.(error);\n }\n }\n }\n async close() {\n if (this._process) {\n const processToClose = this._process;\n this._process = undefined;\n const closePromise = new Promise(resolve => {\n processToClose.once('close', () => {\n resolve();\n });\n });\n try {\n processToClose.stdin?.end();\n }\n catch {\n // ignore\n }\n await Promise.race([closePromise, new Promise(resolve => setTimeout(resolve, 2000).unref())]);\n if (processToClose.exitCode === null) {\n try {\n processToClose.kill('SIGTERM');\n }\n catch {\n // ignore\n }\n await Promise.race([closePromise, new Promise(resolve => setTimeout(resolve, 2000).unref())]);\n }\n if (processToClose.exitCode === null) {\n try {\n processToClose.kill('SIGKILL');\n }\n catch {\n // ignore\n }\n }\n }\n this._readBuffer.clear();\n }\n send(message) {\n return new Promise(resolve => {\n if (!this._process?.stdin) {\n throw new Error('Not connected');\n }\n const json = serializeMessage(message);\n if (this._process.stdin.write(json)) {\n resolve();\n }\n else {\n this._process.stdin.once('drain', resolve);\n }\n });\n }\n}\n//# sourceMappingURL=stdio.js.map","import { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { randomUUID } from \"node:crypto\";\nimport { StdioClientTransport } from \"@modelcontextprotocol/sdk/client/stdio.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/format.ts\nfunction formatMcpResult(result) {\n\tconst parts = [];\n\tif (result.structuredContent !== void 0) parts.push(`Structured content:\\n${JSON.stringify(result.structuredContent, null, 2)}`);\n\tfor (const item of result.content ?? []) {\n\t\tif (item.type === \"text\") {\n\t\t\tparts.push(item.text);\n\t\t\tcontinue;\n\t\t}\n\t\tif (item.type === \"image\") {\n\t\t\tparts.push(`[Image: ${item.mimeType}, ${item.data.length} base64 chars]`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (item.type === \"audio\") {\n\t\t\tparts.push(`[Audio: ${item.mimeType}, ${item.data.length} base64 chars]`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (item.type === \"resource\") {\n\t\t\tconst resource = item.resource;\n\t\t\tif (\"text\" in resource) parts.push(`[Resource: ${resource.uri}]\\n${resource.text}`);\n\t\t\telse parts.push(`[Resource: ${resource.uri}, ${resource.blob.length} base64 chars]`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (item.type === \"resource_link\") {\n\t\t\tconst description = item.description ? ` - ${item.description}` : \"\";\n\t\t\tparts.push(`[Resource link: ${item.name} (${item.uri})${description}]`);\n\t\t\tcontinue;\n\t\t}\n\t\tparts.push(JSON.stringify(item));\n\t}\n\tif (parts.length === 0 && \"toolResult\" in result) parts.push(JSON.stringify(result.toolResult, null, 2));\n\treturn parts.filter(Boolean).join(\"\\n\\n\") || \"(MCP tool returned no content)\";\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}\nfunction createToolDescription(serverName, tool) {\n\tconst originalName = tool.name;\n\tconst title = tool.title ?? tool.annotations?.title;\n\tconst parts = [`MCP tool \"${originalName}\" from server \"${serverName}\".`];\n\tif (title && title !== originalName) parts.push(`Title: ${title}.`);\n\tif (tool.description) parts.push(tool.description);\n\treturn parts.join(\" \");\n}\nfunction mcpToolsToAgentTools(serverName, client, tools) {\n\tconst names = /* @__PURE__ */ new Set();\n\treturn tools.map((tool) => {\n\t\tconst toolName = createToolName(serverName, tool.name);\n\t\tif (names.has(toolName)) throw new Error(`MCP tools from server \"${serverName}\" produced duplicate tool name \"${toolName}\".`);\n\t\tnames.add(toolName);\n\t\treturn {\n\t\t\tname: toolName,\n\t\t\tlabel: tool.title ?? tool.name,\n\t\t\tdescription: createToolDescription(serverName, tool),\n\t\t\tparameters: normalizeInputSchema(tool.inputSchema),\n\t\t\tasync execute(_toolCallId, args, signal) {\n\t\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\t\tconst result = await client.callTool({\n\t\t\t\t\tname: tool.name,\n\t\t\t\t\targuments: args\n\t\t\t\t}, void 0, { signal });\n\t\t\t\tconst formatted = formatMcpResult(result);\n\t\t\t\tif (result.isError) throw new Error(formatted);\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: formatted\n\t\t\t\t\t}],\n\t\t\t\t\tdetails: {}\n\t\t\t\t};\n\t\t\t}\n\t\t};\n\t});\n}\n//#endregion\n//#region src/create-mcp-connection.ts\nfunction createMcpConnection(name, tools, close) {\n\tconst toolByName = new Map(tools.map((tool) => [tool.name, tool]));\n\treturn {\n\t\tname,\n\t\ttools,\n\t\tasync callTool(toolName, args, options) {\n\t\t\tconst agentName = toolName.startsWith(\"mcp__\") ? toolName : createToolName(name, toolName);\n\t\t\tconst tool = toolByName.get(agentName);\n\t\t\tif (!tool) throw new Error(`MCP tool \"${toolName}\" not found on server \"${name}\"`);\n\t\t\treturn tool.execute(randomUUID(), args, options?.signal);\n\t\t},\n\t\tclose\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 requestInit = mergeRequestInit(options.requestInit, options.headers);\n\tconst transport = await createTransport(url, options.transport ?? \"streamable-http\", requestInit, options.fetch);\n\tconst client = new Client({\n\t\tname: options.clientName ?? \"keystroke\",\n\t\tversion: options.clientVersion ?? \"0.0.0\"\n\t});\n\ttry {\n\t\tawait client.connect(transport);\n\t\tconst { tools } = await client.listTools();\n\t\treturn createMcpConnection(name, mcpToolsToAgentTools(name, client, tools), () => client.close());\n\t} catch (error) {\n\t\tawait client.close().catch(() => void 0);\n\t\tthrow error;\n\t}\n}\nasync function createTransport(url, transport, requestInit, fetchImpl) {\n\tif (transport === \"sse\") {\n\t\tconst { SSEClientTransport } = await import(\"@modelcontextprotocol/sdk/client/sse.js\");\n\t\treturn new SSEClientTransport(url, {\n\t\t\trequestInit,\n\t\t\tfetch: fetchImpl\n\t\t});\n\t}\n\treturn new StreamableHTTPClientTransport(url, {\n\t\trequestInit,\n\t\tfetch: fetchImpl\n\t});\n}\nfunction mergeRequestInit(requestInit, headers) {\n\tif (!headers) return requestInit ?? {};\n\tconst mergedHeaders = new Headers(requestInit?.headers);\n\tfor (const [key, value] of Object.entries(headers)) mergedHeaders.set(key, value);\n\treturn {\n\t\t...requestInit,\n\t\theaders: mergedHeaders\n\t};\n}\n//#endregion\n//#region src/connect-stdio.ts\nasync function connectMcpStdio(name, options) {\n\tconst transport = new StdioClientTransport({\n\t\tcommand: options.command,\n\t\targs: options.args,\n\t\tenv: options.env,\n\t\tcwd: options.cwd,\n\t\tstderr: options.stderr\n\t});\n\tconst client = new Client({\n\t\tname: options.clientName ?? \"keystroke\",\n\t\tversion: options.clientVersion ?? \"0.0.0\"\n\t});\n\ttry {\n\t\tawait client.connect(transport);\n\t\tconst { tools } = await client.listTools();\n\t\treturn createMcpConnection(name, mcpToolsToAgentTools(name, client, tools), async () => {\n\t\t\tawait transport.close();\n\t\t\tawait client.close();\n\t\t});\n\t} catch (error) {\n\t\tawait transport.close().catch(() => void 0);\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\nexport { MCP, connectMcpDefinition, connectMcpServer, connectMcpStdio, createToolName, defineMcp, isMcp, mcpToolsToAgentTools, normalizeInputSchema };\n\n//# sourceMappingURL=index.mjs.map","import { boolean, index, integer, jsonb, pgTable, text, timestamp } from \"drizzle-orm/pg-core\";\nimport { index as index$1, integer as integer$1, sqliteTable, text as text$1 } from \"drizzle-orm/sqlite-core\";\n//#region src/client/context.ts\nlet handle;\nfunction isDatabaseInitialized() {\n\treturn handle !== void 0;\n}\nfunction getDatabaseHandle() {\n\tif (!handle) throw new Error(\"Database not initialized. Call initDatabase() before getDb().\");\n\treturn handle;\n}\nfunction setDatabaseHandle(next) {\n\thandle = next;\n}\nfunction getDbFromContext() {\n\treturn getDatabaseHandle().db;\n}\n//#endregion\n//#region src/schema/tables/users.ts\nconst users = pgTable(\"users\", {\n\tid: text(\"id\").primaryKey(),\n\tname: text(\"name\").notNull(),\n\temail: text(\"email\").notNull().unique(),\n\temailVerified: boolean(\"email_verified\").notNull(),\n\timage: text(\"image\"),\n\tpreferences: jsonb(\"preferences\"),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n});\nconst usersSqlite = sqliteTable(\"users\", {\n\tid: text$1(\"id\").primaryKey(),\n\tname: text$1(\"name\").notNull(),\n\temail: text$1(\"email\").notNull().unique(),\n\temailVerified: integer$1(\"email_verified\", { mode: \"boolean\" }).notNull(),\n\timage: text$1(\"image\"),\n\tpreferences: text$1(\"preferences\", { mode: \"json\" }),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n});\n//#endregion\n//#region src/schema/tables/auth-accounts.ts\nconst authAccounts = pgTable(\"accounts\", {\n\tid: text(\"id\").primaryKey(),\n\taccountId: text(\"account_id\").notNull(),\n\tproviderId: text(\"provider_id\").notNull(),\n\tuserId: text(\"user_id\").notNull().references(() => users.id, { onDelete: \"cascade\" }),\n\taccessToken: text(\"access_token\"),\n\trefreshToken: text(\"refresh_token\"),\n\tidToken: text(\"id_token\"),\n\taccessTokenExpiresAt: timestamp(\"access_token_expires_at\", { withTimezone: true }),\n\trefreshTokenExpiresAt: timestamp(\"refresh_token_expires_at\", { withTimezone: true }),\n\tscope: text(\"scope\"),\n\tpassword: text(\"password\"),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [index(\"account_user_id_idx\").on(table.userId)]);\nconst authAccountsSqlite = sqliteTable(\"accounts\", {\n\tid: text$1(\"id\").primaryKey(),\n\taccountId: text$1(\"account_id\").notNull(),\n\tproviderId: text$1(\"provider_id\").notNull(),\n\tuserId: text$1(\"user_id\").notNull().references(() => usersSqlite.id, { onDelete: \"cascade\" }),\n\taccessToken: text$1(\"access_token\"),\n\trefreshToken: text$1(\"refresh_token\"),\n\tidToken: text$1(\"id_token\"),\n\taccessTokenExpiresAt: integer$1(\"access_token_expires_at\", { mode: \"timestamp_ms\" }),\n\trefreshTokenExpiresAt: integer$1(\"refresh_token_expires_at\", { mode: \"timestamp_ms\" }),\n\tscope: text$1(\"scope\"),\n\tpassword: text$1(\"password\"),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [index$1(\"account_user_id_idx\").on(table.userId)]);\n//#endregion\n//#region src/schema/tables/auth-device-codes.ts\nconst authDeviceCodes = pgTable(\"device_auth_codes\", {\n\tid: text(\"id\").primaryKey(),\n\tdeviceCode: text(\"device_code\").notNull(),\n\tuserCode: text(\"user_code\").notNull(),\n\tuserId: text(\"user_id\"),\n\texpiresAt: timestamp(\"expires_at\", { withTimezone: true }).notNull(),\n\tstatus: text(\"status\").notNull(),\n\tlastPolledAt: timestamp(\"last_polled_at\", { withTimezone: true }),\n\tpollingInterval: integer(\"polling_interval\"),\n\tclientId: text(\"client_id\"),\n\tscope: text(\"scope\")\n});\nconst authDeviceCodesSqlite = sqliteTable(\"device_auth_codes\", {\n\tid: text$1(\"id\").primaryKey(),\n\tdeviceCode: text$1(\"device_code\").notNull(),\n\tuserCode: text$1(\"user_code\").notNull(),\n\tuserId: text$1(\"user_id\"),\n\texpiresAt: integer$1(\"expires_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tstatus: text$1(\"status\").notNull(),\n\tlastPolledAt: integer$1(\"last_polled_at\", { mode: \"timestamp_ms\" }),\n\tpollingInterval: integer$1(\"polling_interval\"),\n\tclientId: text$1(\"client_id\"),\n\tscope: text$1(\"scope\")\n});\n//#endregion\n//#region src/schema/tables/auth-jwks.ts\nconst authJwks = pgTable(\"jwks\", {\n\tid: text(\"id\").primaryKey(),\n\tpublicKey: text(\"public_key\").notNull(),\n\tprivateKey: text(\"private_key\").notNull(),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\texpiresAt: timestamp(\"expires_at\", { withTimezone: true })\n});\nconst authJwksSqlite = sqliteTable(\"jwks\", {\n\tid: text$1(\"id\").primaryKey(),\n\tpublicKey: text$1(\"public_key\").notNull(),\n\tprivateKey: text$1(\"private_key\").notNull(),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\texpiresAt: integer$1(\"expires_at\", { mode: \"timestamp_ms\" })\n});\n//#endregion\n//#region src/schema/tables/auth-sessions.ts\nconst authSessions = pgTable(\"sessions\", {\n\tid: text(\"id\").primaryKey(),\n\texpiresAt: timestamp(\"expires_at\", { withTimezone: true }).notNull(),\n\ttoken: text(\"token\").notNull().unique(),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tipAddress: text(\"ip_address\"),\n\tuserAgent: text(\"user_agent\"),\n\tuserId: text(\"user_id\").notNull().references(() => users.id, { onDelete: \"cascade\" })\n}, (table) => [index(\"session_user_id_idx\").on(table.userId)]);\nconst authSessionsSqlite = sqliteTable(\"sessions\", {\n\tid: text$1(\"id\").primaryKey(),\n\texpiresAt: integer$1(\"expires_at\", { mode: \"timestamp_ms\" }).notNull(),\n\ttoken: text$1(\"token\").notNull().unique(),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tipAddress: text$1(\"ip_address\"),\n\tuserAgent: text$1(\"user_agent\"),\n\tuserId: text$1(\"user_id\").notNull().references(() => usersSqlite.id, { onDelete: \"cascade\" })\n}, (table) => [index$1(\"session_user_id_idx\").on(table.userId)]);\n//#endregion\n//#region src/schema/tables/auth-verifications.ts\nconst authVerifications = pgTable(\"verification\", {\n\tid: text(\"id\").primaryKey(),\n\tidentifier: text(\"identifier\").notNull(),\n\tvalue: text(\"value\").notNull(),\n\texpiresAt: timestamp(\"expires_at\", { withTimezone: true }).notNull(),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [index(\"verification_identifier_idx\").on(table.identifier)]);\nconst authVerificationsSqlite = sqliteTable(\"verification\", {\n\tid: text$1(\"id\").primaryKey(),\n\tidentifier: text$1(\"identifier\").notNull(),\n\tvalue: text$1(\"value\").notNull(),\n\texpiresAt: integer$1(\"expires_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [index$1(\"verification_identifier_idx\").on(table.identifier)]);\n//#endregion\nexport { authJwks as a, authDeviceCodesSqlite as c, users as d, usersSqlite as f, setDatabaseHandle as g, isDatabaseInitialized as h, authSessionsSqlite as i, authAccounts as l, getDbFromContext as m, authVerificationsSqlite as n, authJwksSqlite as o, getDatabaseHandle as p, authSessions as r, authDeviceCodes as s, authVerifications as t, authAccountsSqlite as u };\n\n//# sourceMappingURL=auth-verifications-D-no86bc.mjs.map","import { a as authJwks, c as authDeviceCodesSqlite, d as users, f as usersSqlite, g as setDatabaseHandle, h as isDatabaseInitialized, i as authSessionsSqlite, l as authAccounts, m as getDbFromContext, n as authVerificationsSqlite, o as authJwksSqlite, p as getDatabaseHandle, r as authSessions, s as authDeviceCodes, t as authVerifications, u as authAccountsSqlite } from \"./auth-verifications-D-no86bc.mjs\";\nimport { n as resolvePlatformPostgresConfig, r as DEFAULT_PLATFORM_DATABASE_URL, t as resolvePlatformDatabaseUrl } from \"./database-url-w9bkrlHx.mjs\";\nimport { DEFAULT_PROJECT_ID, adaptPgMigrationsForSearchPath, buildPostgresUrl, decryptCredentialPayload, decryptCredentialPayload as decryptCredentialPayload$1, encryptCredentialPayload, encryptCredentialPayload as encryptCredentialPayload$1, inferDialect, loadMigrations, migratePgDatabase, qualifyConnectionUser, resolveMigrationsSchema, resolveSearchPath, resolveSqlitePath, runWithProjectScope, runWithTenantScope } from \"@keystrokehq/database\";\nimport { Pool } from \"pg\";\nimport { drizzle } from \"drizzle-orm/node-postgres\";\nimport { boolean, index, integer, jsonb, pgEnum, pgTable, primaryKey, text, timestamp, uniqueIndex } from \"drizzle-orm/pg-core\";\nimport { index as index$1, integer as integer$1, primaryKey as primaryKey$1, sqliteTable, text as text$1, uniqueIndex as uniqueIndex$1 } from \"drizzle-orm/sqlite-core\";\nimport { and, and as and$1, asc, desc, eq, eq as eq$1, gt, inArray, inArray as inArray$1, isNull, isNull as isNull$1, max, ne, or, sql, sql as sql$1 } from \"drizzle-orm\";\nimport { existsSync, mkdirSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport BetterSqlite3 from \"better-sqlite3\";\nimport { drizzle as drizzle$1 } from \"drizzle-orm/better-sqlite3\";\nimport { fileURLToPath } from \"node:url\";\nimport { migrate } from \"drizzle-orm/better-sqlite3/migrator\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { AppSlugSchema, ClaimableOrganizationSlugSchema, ORGANIZATION_SLUG_TAKEN_MESSAGE, OrganizationSlugSchema, PROJECT_SLUG_TAKEN_MESSAGE, ProjectSlugSchema, RESERVED_ORGANIZATION_SLUGS, normalizeOrganizationSidebarBranding, qualifyOrgSlug, slugifyAppName, slugifyOrganizationName, slugifyProjectName } from \"@keystrokehq/shared\";\nimport { createHash, randomBytes, timingSafeEqual } from \"node:crypto\";\nimport { containerPresignEndpointFromEnv, createContainerPresignStorage, createStorage } from \"@keystrokehq/storage\";\n//#region \\0rolldown/runtime.js\nvar __defProp = Object.defineProperty;\nvar __exportAll = (all, no_symbols) => {\n\tlet target = {};\n\tfor (var name in all) __defProp(target, name, {\n\t\tget: all[name],\n\t\tenumerable: true\n\t});\n\tif (!no_symbols) __defProp(target, Symbol.toStringTag, { value: \"Module\" });\n\treturn target;\n};\n//#endregion\n//#region src/client/close.ts\nasync function closeDatabase() {\n\tif (!isDatabaseInitialized()) return;\n\tawait getDatabaseHandle().close();\n\tsetDatabaseHandle(void 0);\n}\n//#endregion\n//#region src/schema/bundle.ts\nfunction buildPgSchema(registry) {\n\treturn Object.fromEntries(Object.entries(registry).map(([name, { pg }]) => [name, pg]));\n}\nfunction buildSqliteSchema(registry) {\n\treturn Object.fromEntries(Object.entries(registry).map(([name, { sqlite }]) => [name, sqlite]));\n}\n//#endregion\n//#region src/schema/tables/api-keys.ts\n/** Better Auth API Key shape (`apikey` model → physical `api_keys`). */\nconst authApiKeys = pgTable(\"api_keys\", {\n\tid: text(\"id\").primaryKey(),\n\tconfigId: text(\"config_id\").notNull().default(\"default\"),\n\tname: text(\"name\"),\n\tstart: text(\"start\"),\n\tprefix: text(\"prefix\"),\n\t/** Hashed secret for verification (Better Auth `key`). */\n\tkey: text(\"key\").notNull(),\n\t/** Encrypted plaintext secret — keystroke extension for re-display. */\n\tkeyCiphertext: text(\"key_ciphertext\"),\n\treferenceId: text(\"reference_id\").notNull(),\n\trefillInterval: integer(\"refill_interval\"),\n\trefillAmount: integer(\"refill_amount\"),\n\tlastRefillAt: timestamp(\"last_refill_at\", { withTimezone: true }),\n\tenabled: boolean(\"enabled\").default(true),\n\trateLimitEnabled: boolean(\"rate_limit_enabled\").default(true),\n\trateLimitTimeWindow: integer(\"rate_limit_time_window\"),\n\trateLimitMax: integer(\"rate_limit_max\"),\n\trequestCount: integer(\"request_count\").default(0),\n\tremaining: integer(\"remaining\"),\n\tlastRequest: timestamp(\"last_request\", { withTimezone: true }),\n\texpiresAt: timestamp(\"expires_at\", { withTimezone: true }),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tpermissions: text(\"permissions\"),\n\tmetadata: text(\"metadata\")\n}, (table) => [\n\tindex(\"api_keys_reference_id_idx\").on(table.referenceId),\n\tindex(\"api_keys_config_id_idx\").on(table.configId),\n\tindex(\"api_keys_key_idx\").on(table.key)\n]);\nconst authApiKeysSqlite = sqliteTable(\"api_keys\", {\n\tid: text$1(\"id\").primaryKey(),\n\tconfigId: text$1(\"config_id\").notNull().default(\"default\"),\n\tname: text$1(\"name\"),\n\tstart: text$1(\"start\"),\n\tprefix: text$1(\"prefix\"),\n\tkey: text$1(\"key\").notNull(),\n\tkeyCiphertext: text$1(\"key_ciphertext\"),\n\treferenceId: text$1(\"reference_id\").notNull(),\n\trefillInterval: integer$1(\"refill_interval\"),\n\trefillAmount: integer$1(\"refill_amount\"),\n\tlastRefillAt: integer$1(\"last_refill_at\", { mode: \"timestamp_ms\" }),\n\tenabled: integer$1(\"enabled\", { mode: \"boolean\" }).default(true),\n\trateLimitEnabled: integer$1(\"rate_limit_enabled\", { mode: \"boolean\" }).default(true),\n\trateLimitTimeWindow: integer$1(\"rate_limit_time_window\"),\n\trateLimitMax: integer$1(\"rate_limit_max\"),\n\trequestCount: integer$1(\"request_count\").default(0),\n\tremaining: integer$1(\"remaining\"),\n\tlastRequest: integer$1(\"last_request\", { mode: \"timestamp_ms\" }),\n\texpiresAt: integer$1(\"expires_at\", { mode: \"timestamp_ms\" }),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tpermissions: text$1(\"permissions\"),\n\tmetadata: text$1(\"metadata\")\n}, (table) => [\n\tindex$1(\"api_keys_reference_id_idx\").on(table.referenceId),\n\tindex$1(\"api_keys_config_id_idx\").on(table.configId),\n\tindex$1(\"api_keys_key_idx\").on(table.key)\n]);\n//#endregion\n//#region src/schema/tables/organizations.ts\nconst organizations = pgTable(\"organizations\", {\n\tid: text(\"id\").primaryKey(),\n\tname: text(\"name\").notNull(),\n\tslug: text(\"slug\").notNull(),\n\tdbSchema: text(\"db_schema\").notNull(),\n\tdbUser: text(\"db_user\").notNull(),\n\tdbPasswordCiphertext: text(\"db_password_ciphertext\").notNull(),\n\thostingAppName: text(\"hosting_app_name\"),\n\truntimeId: text(\"runtime_id\"),\n\tbaseUrl: text(\"base_url\"),\n\tstorageBucket: text(\"storage_bucket\"),\n\tstorageEndpoint: text(\"storage_endpoint\"),\n\tstorageAccessKeyIdCiphertext: text(\"storage_access_key_id_ciphertext\"),\n\tstorageSecretAccessKeyCiphertext: text(\"storage_secret_access_key_ciphertext\"),\n\tstorageRegion: text(\"storage_region\"),\n\tstorageForcePathStyle: boolean(\"storage_force_path_style\"),\n\tcustomLogoEnabled: boolean(\"custom_logo_enabled\").notNull().default(false),\n\tcustomLogoExplicitlyDisabled: boolean(\"custom_logo_explicitly_disabled\").notNull().default(false),\n\tlogoLightUrl: text(\"logo_light_url\"),\n\tlogoDarkUrl: text(\"logo_dark_url\"),\n\tlogoHeightPx: integer(\"logo_height_px\").notNull().default(20),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tverifiedAt: timestamp(\"verified_at\", { withTimezone: true }),\n\tdeletedAt: timestamp(\"deleted_at\", { withTimezone: true })\n}, (table) => [uniqueIndex(\"organizations_slug_unique\").on(table.slug)]);\nconst organizationsSqlite = sqliteTable(\"organizations\", {\n\tid: text$1(\"id\").primaryKey(),\n\tname: text$1(\"name\").notNull(),\n\tslug: text$1(\"slug\").notNull(),\n\tdbSchema: text$1(\"db_schema\").notNull(),\n\tdbUser: text$1(\"db_user\").notNull(),\n\tdbPasswordCiphertext: text$1(\"db_password_ciphertext\").notNull(),\n\thostingAppName: text$1(\"hosting_app_name\"),\n\truntimeId: text$1(\"runtime_id\"),\n\tbaseUrl: text$1(\"base_url\"),\n\tstorageBucket: text$1(\"storage_bucket\"),\n\tstorageEndpoint: text$1(\"storage_endpoint\"),\n\tstorageAccessKeyIdCiphertext: text$1(\"storage_access_key_id_ciphertext\"),\n\tstorageSecretAccessKeyCiphertext: text$1(\"storage_secret_access_key_ciphertext\"),\n\tstorageRegion: text$1(\"storage_region\"),\n\tstorageForcePathStyle: integer$1(\"storage_force_path_style\", { mode: \"boolean\" }),\n\tcustomLogoEnabled: integer$1(\"custom_logo_enabled\", { mode: \"boolean\" }).notNull().default(false),\n\tcustomLogoExplicitlyDisabled: integer$1(\"custom_logo_explicitly_disabled\", { mode: \"boolean\" }).notNull().default(false),\n\tlogoLightUrl: text$1(\"logo_light_url\"),\n\tlogoDarkUrl: text$1(\"logo_dark_url\"),\n\tlogoHeightPx: integer$1(\"logo_height_px\").notNull().default(20),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tverifiedAt: integer$1(\"verified_at\", { mode: \"timestamp_ms\" }),\n\tdeletedAt: integer$1(\"deleted_at\", { mode: \"timestamp_ms\" })\n}, (table) => [uniqueIndex$1(\"organizations_slug_unique\").on(table.slug)]);\n//#endregion\n//#region src/schema/tables/apps.ts\nconst apps = pgTable(\"apps\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").references(() => organizations.id, { onDelete: \"cascade\" }),\n\tslug: text(\"slug\").notNull(),\n\tname: text(\"name\").notNull(),\n\tdescription: text(\"description\").notNull(),\n\tcategory: text(\"category\").notNull(),\n\tlogo: text(\"logo\"),\n\tauthKind: text(\"auth_kind\").$type().notNull(),\n\toauthScopes: jsonb(\"oauth_scopes\").$type().notNull(),\n\tcredentialFields: jsonb(\"credential_fields\").$type().notNull().default({}),\n\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\tsource: text$1(\"source\").$type().notNull(),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [uniqueIndex$1(\"apps_slug_idx\").on(table.slug), index$1(\"apps_organization_id_idx\").on(table.organizationId)]);\n//#endregion\n//#region src/schema/tables/oauth-apps.ts\nconst oauthApps = pgTable(\"oauth_apps\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id, { onDelete: \"cascade\" }),\n\tprovider: text(\"provider\").notNull(),\n\tslug: text(\"slug\").notNull(),\n\ttokenStrategy: text(\"token_strategy\").$type().notNull(),\n\tclientIdCiphertext: text(\"client_id_ciphertext\").notNull(),\n\tclientSecretCiphertext: text(\"client_secret_ciphertext\").notNull(),\n\tsigningSecretCiphertext: text(\"signing_secret_ciphertext\"),\n\tredirectUri: text(\"redirect_uri\"),\n\tmetadata: jsonb(\"metadata\").$type(),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [uniqueIndex(\"oauth_apps_organization_id_slug_idx\").on(table.organizationId, table.slug), index(\"oauth_apps_slug_idx\").on(table.slug)]);\nconst oauthAppsSqlite = sqliteTable(\"oauth_apps\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id, { onDelete: \"cascade\" }),\n\tprovider: text$1(\"provider\").notNull(),\n\tslug: text$1(\"slug\").notNull(),\n\ttokenStrategy: text$1(\"token_strategy\").$type().notNull(),\n\tclientIdCiphertext: text$1(\"client_id_ciphertext\").notNull(),\n\tclientSecretCiphertext: text$1(\"client_secret_ciphertext\").notNull(),\n\tsigningSecretCiphertext: text$1(\"signing_secret_ciphertext\"),\n\tredirectUri: text$1(\"redirect_uri\"),\n\tmetadata: text$1(\"metadata\", { mode: \"json\" }).$type(),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [uniqueIndex$1(\"oauth_apps_organization_id_slug_idx\").on(table.organizationId, table.slug), index$1(\"oauth_apps_slug_idx\").on(table.slug)]);\n//#endregion\n//#region src/schema/tables/oauth-connections.ts\nconst oauthConnections = pgTable(\"oauth_connections\", {\n\tid: text(\"id\").primaryKey(),\n\tappId: text(\"app_id\").notNull().references(() => oauthApps.id, { onDelete: \"cascade\" }),\n\texternalId: text(\"external_id\").notNull(),\n\taccessTokenCiphertext: text(\"access_token_ciphertext\").notNull(),\n\trefreshTokenCiphertext: text(\"refresh_token_ciphertext\"),\n\taccessTokenExpiresAt: timestamp(\"access_token_expires_at\", { withTimezone: true }),\n\tgrantedScopes: jsonb(\"granted_scopes\").$type(),\n\tmetadata: jsonb(\"metadata\").$type(),\n\tconnectedAt: timestamp(\"connected_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [uniqueIndex(\"oauth_connections_app_external_unique\").on(table.appId, table.externalId), index(\"oauth_connections_external_id_idx\").on(table.externalId)]);\nconst oauthConnectionsSqlite = sqliteTable(\"oauth_connections\", {\n\tid: text$1(\"id\").primaryKey(),\n\tappId: text$1(\"app_id\").notNull().references(() => oauthAppsSqlite.id, { onDelete: \"cascade\" }),\n\texternalId: text$1(\"external_id\").notNull(),\n\taccessTokenCiphertext: text$1(\"access_token_ciphertext\").notNull(),\n\trefreshTokenCiphertext: text$1(\"refresh_token_ciphertext\"),\n\taccessTokenExpiresAt: integer$1(\"access_token_expires_at\", { mode: \"timestamp_ms\" }),\n\tgrantedScopes: text$1(\"granted_scopes\", { mode: \"json\" }).$type(),\n\tmetadata: text$1(\"metadata\", { mode: \"json\" }).$type(),\n\tconnectedAt: integer$1(\"connected_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [uniqueIndex$1(\"oauth_connections_app_external_unique\").on(table.appId, table.externalId), index$1(\"oauth_connections_external_id_idx\").on(table.externalId)]);\n//#endregion\n//#region src/schema/tables/organization-users.ts\nconst organizationUserRoles = [\n\t\"owner\",\n\t\"admin\",\n\t\"builder\"\n];\nconst organizationUsers = pgTable(\"organization_users\", {\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id, { onDelete: \"cascade\" }),\n\tuserId: text(\"user_id\").notNull().references(() => users.id, { onDelete: \"cascade\" }),\n\trole: text(\"role\").notNull().$type(),\n\tstatus: text(\"status\").notNull().$type().default(\"active\"),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tdeletedAt: timestamp(\"deleted_at\", { withTimezone: true })\n}, (table) => [primaryKey({ columns: [table.organizationId, table.userId] }), index(\"organization_users_user_id_idx\").on(table.userId)]);\nconst organizationUsersSqlite = sqliteTable(\"organization_users\", {\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id, { onDelete: \"cascade\" }),\n\tuserId: text$1(\"user_id\").notNull().references(() => usersSqlite.id, { onDelete: \"cascade\" }),\n\trole: text$1(\"role\").notNull().$type(),\n\tstatus: text$1(\"status\").notNull().$type().default(\"active\"),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tdeletedAt: integer$1(\"deleted_at\", { mode: \"timestamp_ms\" })\n}, (table) => [primaryKey$1({ columns: [table.organizationId, table.userId] }), index$1(\"organization_users_user_id_idx\").on(table.userId)]);\n//#endregion\n//#region src/schema/tables/organization-invitations.ts\nconst organizationInvitationStatuses = [\n\t\"pending\",\n\t\"accepted\",\n\t\"declined\",\n\t\"revoked\"\n];\nconst organizationInvitations = pgTable(\"organization_invitations\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id, { onDelete: \"cascade\" }),\n\tuserId: text(\"user_id\").notNull().references(() => users.id, { onDelete: \"cascade\" }),\n\temail: text(\"email\").notNull(),\n\trole: text(\"role\").notNull().$type(),\n\tstatus: text(\"status\").notNull().$type(),\n\tinvitedByUserId: text(\"invited_by_user_id\").notNull().references(() => users.id, { onDelete: \"cascade\" }),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\texpiresAt: timestamp(\"expires_at\", { withTimezone: true })\n}, (table) => [\n\tindex(\"organization_invitations_user_id_idx\").on(table.userId),\n\tindex(\"organization_invitations_organization_id_idx\").on(table.organizationId),\n\tuniqueIndex(\"organization_invitations_org_user_pending_unique\").on(table.organizationId, table.userId).where(sql`${table.status} = 'pending'`)\n]);\nconst organizationInvitationsSqlite = sqliteTable(\"organization_invitations\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id, { onDelete: \"cascade\" }),\n\tuserId: text$1(\"user_id\").notNull().references(() => usersSqlite.id, { onDelete: \"cascade\" }),\n\temail: text$1(\"email\").notNull(),\n\trole: text$1(\"role\").notNull().$type(),\n\tstatus: text$1(\"status\").notNull().$type(),\n\tinvitedByUserId: text$1(\"invited_by_user_id\").notNull().references(() => usersSqlite.id, { onDelete: \"cascade\" }),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\texpiresAt: integer$1(\"expires_at\", { mode: \"timestamp_ms\" })\n}, (table) => [\n\tindex$1(\"organization_invitations_user_id_idx\").on(table.userId),\n\tindex$1(\"organization_invitations_organization_id_idx\").on(table.organizationId),\n\tuniqueIndex$1(\"organization_invitations_org_user_pending_unique\").on(table.organizationId, table.userId).where(sql`${table.status} = 'pending'`)\n]);\n//#endregion\n//#region src/schema/tables/projects.ts\nconst projectStatuses = [\n\t\"inactive\",\n\t\"starting\",\n\t\"active\",\n\t\"failed\"\n];\nconst projectStatusEnum = pgEnum(\"project_status\", projectStatuses);\nconst projects = pgTable(\"projects\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id, { onDelete: \"cascade\" }),\n\tname: text(\"name\").notNull(),\n\tslug: text(\"slug\").notNull(),\n\tdescription: text(\"description\"),\n\tdefaultMemberRole: text(\"default_member_role\").notNull().$type().default(\"builder\"),\n\tinvitePermission: text(\"invite_permission\").notNull().$type().default(\"admin\"),\n\tcreatedByUserId: text(\"created_by_user_id\").references(() => users.id, { onDelete: \"set null\" }),\n\tstatus: projectStatusEnum(\"status\").notNull(),\n\tbaseUrl: text(\"base_url\"),\n\truntimeId: text(\"runtime_id\"),\n\tactiveArtifactId: text(\"active_artifact_id\"),\n\tpendingArtifactId: text(\"pending_artifact_id\"),\n\tlastError: text(\"last_error\"),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tdeletedAt: timestamp(\"deleted_at\", { withTimezone: true })\n}, (table) => [index(\"projects_organization_id_idx\").on(table.organizationId), uniqueIndex(\"projects_organization_slug_unique\").on(table.organizationId, table.slug).where(sql`${table.deletedAt} IS NULL`)]);\nconst projectsSqlite = sqliteTable(\"projects\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id, { onDelete: \"cascade\" }),\n\tname: text$1(\"name\").notNull(),\n\tslug: text$1(\"slug\").notNull(),\n\tdescription: text$1(\"description\"),\n\tdefaultMemberRole: text$1(\"default_member_role\").notNull().$type().default(\"builder\"),\n\tinvitePermission: text$1(\"invite_permission\").notNull().$type().default(\"admin\"),\n\tcreatedByUserId: text$1(\"created_by_user_id\").references(() => usersSqlite.id, { onDelete: \"set null\" }),\n\tstatus: text$1(\"status\").$type().notNull(),\n\tbaseUrl: text$1(\"base_url\"),\n\truntimeId: text$1(\"runtime_id\"),\n\tactiveArtifactId: text$1(\"active_artifact_id\"),\n\tpendingArtifactId: text$1(\"pending_artifact_id\"),\n\tlastError: text$1(\"last_error\"),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tdeletedAt: integer$1(\"deleted_at\", { mode: \"timestamp_ms\" })\n}, (table) => [index$1(\"projects_organization_id_idx\").on(table.organizationId), uniqueIndex$1(\"projects_organization_slug_unique\").on(table.organizationId, table.slug).where(sql`${table.deletedAt} IS NULL`)]);\n//#endregion\n//#region src/schema/tables/project-artifacts.ts\nconst projectArtifactStatuses = [\"pending\", \"ready\"];\nconst projectArtifactStatusEnum = pgEnum(\"project_artifact_status\", projectArtifactStatuses);\nconst projectArtifacts = pgTable(\"project_artifacts\", {\n\tid: text(\"id\").primaryKey(),\n\tprojectId: text(\"project_id\").notNull().references(() => projects.id, { onDelete: \"cascade\" }),\n\tstorageKey: text(\"storage_key\").notNull(),\n\tmanifestJson: jsonb(\"manifest_json\"),\n\tsourceManifestJson: jsonb(\"source_manifest_json\"),\n\tversion: integer(\"version\").notNull(),\n\tcreatedByUserId: text(\"created_by_user_id\").references(() => users.id, { onDelete: \"set null\" }),\n\tstatus: projectArtifactStatusEnum(\"status\").notNull(),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [index(\"project_artifacts_project_id_idx\").on(table.projectId)]);\nconst projectArtifactsSqlite = sqliteTable(\"project_artifacts\", {\n\tid: text$1(\"id\").primaryKey(),\n\tprojectId: text$1(\"project_id\").notNull().references(() => projectsSqlite.id, { onDelete: \"cascade\" }),\n\tstorageKey: text$1(\"storage_key\").notNull(),\n\tmanifestJson: text$1(\"manifest_json\", { mode: \"json\" }),\n\tsourceManifestJson: text$1(\"source_manifest_json\", { mode: \"json\" }),\n\tversion: integer$1(\"version\").notNull(),\n\tcreatedByUserId: text$1(\"created_by_user_id\").references(() => usersSqlite.id, { onDelete: \"set null\" }),\n\tstatus: text$1(\"status\").$type().notNull(),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [index$1(\"project_artifacts_project_id_idx\").on(table.projectId)]);\n//#endregion\n//#region src/schema/tables/project-users.ts\nconst projectUsers = pgTable(\"project_users\", {\n\tprojectId: text(\"project_id\").notNull().references(() => projects.id, { onDelete: \"cascade\" }),\n\tuserId: text(\"user_id\").notNull().references(() => users.id, { onDelete: \"cascade\" }),\n\trole: text(\"role\").notNull().$type(),\n\tstatus: text(\"status\").notNull().$type().default(\"active\"),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull(),\n\tdeletedAt: timestamp(\"deleted_at\", { withTimezone: true })\n}, (table) => [primaryKey({ columns: [table.projectId, table.userId] }), index(\"project_users_user_id_idx\").on(table.userId)]);\nconst projectUsersSqlite = sqliteTable(\"project_users\", {\n\tprojectId: text$1(\"project_id\").notNull().references(() => projectsSqlite.id, { onDelete: \"cascade\" }),\n\tuserId: text$1(\"user_id\").notNull().references(() => usersSqlite.id, { onDelete: \"cascade\" }),\n\trole: text$1(\"role\").notNull().$type(),\n\tstatus: text$1(\"status\").notNull().$type().default(\"active\"),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tdeletedAt: integer$1(\"deleted_at\", { mode: \"timestamp_ms\" })\n}, (table) => [primaryKey$1({ columns: [table.projectId, table.userId] }), index$1(\"project_users_user_id_idx\").on(table.userId)]);\n//#endregion\n//#region src/schema/tables/secret-values.ts\nconst secretValues = pgTable(\"secret_values\", {\n\tid: text(\"id\").primaryKey(),\n\torganizationId: text(\"organization_id\").notNull().references(() => organizations.id, { onDelete: \"cascade\" }),\n\trefKind: text(\"ref_kind\").$type().notNull(),\n\trefId: text(\"ref_id\").notNull(),\n\tfield: text(\"field\").$type().notNull(),\n\tciphertext: text(\"ciphertext\").notNull(),\n\tcreatedAt: timestamp(\"created_at\", { withTimezone: true }).notNull(),\n\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true }).notNull()\n}, (table) => [uniqueIndex(\"secret_values_ref_unique\").on(table.organizationId, table.refKind, table.refId, table.field), index(\"secret_values_ref_idx\").on(table.organizationId, table.refKind, table.refId)]);\nconst secretValuesSqlite = sqliteTable(\"secret_values\", {\n\tid: text$1(\"id\").primaryKey(),\n\torganizationId: text$1(\"organization_id\").notNull().references(() => organizationsSqlite.id, { onDelete: \"cascade\" }),\n\trefKind: text$1(\"ref_kind\").$type().notNull(),\n\trefId: text$1(\"ref_id\").notNull(),\n\tfield: text$1(\"field\").$type().notNull(),\n\tciphertext: text$1(\"ciphertext\").notNull(),\n\tcreatedAt: integer$1(\"created_at\", { mode: \"timestamp_ms\" }).notNull(),\n\tupdatedAt: integer$1(\"updated_at\", { mode: \"timestamp_ms\" }).notNull()\n}, (table) => [uniqueIndex$1(\"secret_values_ref_unique\").on(table.organizationId, table.refKind, table.refId, table.field), index$1(\"secret_values_ref_idx\").on(table.organizationId, table.refKind, table.refId)]);\n//#endregion\n//#region src/schema/registrations.ts\n/**\n* Platform control-plane tables — Postgres (hosted) or SQLite (local dev).\n*/\nconst tableRegistry = {\n\torganizations: {\n\t\tpg: organizations,\n\t\tsqlite: organizationsSqlite\n\t},\n\torganizationUsers: {\n\t\tpg: organizationUsers,\n\t\tsqlite: organizationUsersSqlite\n\t},\n\torganizationInvitations: {\n\t\tpg: organizationInvitations,\n\t\tsqlite: organizationInvitationsSqlite\n\t},\n\tprojects: {\n\t\tpg: projects,\n\t\tsqlite: projectsSqlite\n\t},\n\tprojectUsers: {\n\t\tpg: projectUsers,\n\t\tsqlite: projectUsersSqlite\n\t},\n\tprojectArtifacts: {\n\t\tpg: projectArtifacts,\n\t\tsqlite: projectArtifactsSqlite\n\t},\n\tusers: {\n\t\tpg: users,\n\t\tsqlite: usersSqlite\n\t},\n\tauthSessions: {\n\t\tpg: authSessions,\n\t\tsqlite: authSessionsSqlite\n\t},\n\tauthAccounts: {\n\t\tpg: authAccounts,\n\t\tsqlite: authAccountsSqlite\n\t},\n\tauthVerifications: {\n\t\tpg: authVerifications,\n\t\tsqlite: authVerificationsSqlite\n\t},\n\tauthDeviceCodes: {\n\t\tpg: authDeviceCodes,\n\t\tsqlite: authDeviceCodesSqlite\n\t},\n\tauthJwks: {\n\t\tpg: authJwks,\n\t\tsqlite: authJwksSqlite\n\t},\n\tauthApiKeys: {\n\t\tpg: authApiKeys,\n\t\tsqlite: authApiKeysSqlite\n\t},\n\tapps: {\n\t\tpg: apps,\n\t\tsqlite: appsSqlite\n\t},\n\toauthApps: {\n\t\tpg: oauthApps,\n\t\tsqlite: oauthAppsSqlite\n\t},\n\toauthConnections: {\n\t\tpg: oauthConnections,\n\t\tsqlite: oauthConnectionsSqlite\n\t},\n\tsecretValues: {\n\t\tpg: secretValues,\n\t\tsqlite: secretValuesSqlite\n\t}\n};\nconst schema = buildPgSchema(tableRegistry);\nbuildSqliteSchema(tableRegistry);\n//#endregion\n//#region src/connection/pg/db.ts\n/** Inferred from `schema` — `getDb()` and query files use this type. */\nfunction createPgDb(pool) {\n\treturn drizzle(pool, { schema });\n}\n//#endregion\n//#region src/connection/pg/index.ts\nfunction createPgConnection(options) {\n\tconst searchPath = resolveSearchPath(options.url, options.searchPath);\n\tconst pool = new Pool({\n\t\tconnectionString: options.url,\n\t\tmax: options.max ?? 10,\n\t\tconnectionTimeoutMillis: 5e3,\n\t\tidleTimeoutMillis: 3e4,\n\t\tkeepAlive: true\n\t});\n\treturn {\n\t\tdialect: \"postgres\",\n\t\tdb: createPgDb(pool),\n\t\tpool,\n\t\tsearchPath,\n\t\tclose: () => pool.end()\n\t};\n}\n//#endregion\n//#region src/connection/sqlite/index.ts\nfunction configureSqlite(client) {\n\tclient.pragma(\"journal_mode = WAL\");\n\tclient.pragma(\"foreign_keys = ON\");\n}\nfunction createSqliteConnection(options) {\n\tconst path = resolveSqlitePath(options.url);\n\tif (path !== \":memory:\") mkdirSync(dirname(path), { recursive: true });\n\tconst client = new BetterSqlite3(path);\n\tconfigureSqlite(client);\n\treturn {\n\t\tdialect: \"sqlite\",\n\t\tdb: drizzle$1(client, { schema }),\n\t\tclose: () => client.close()\n\t};\n}\n//#endregion\n//#region src/connection/create-connection.ts\nfunction createConnection(options) {\n\tif ((options.dialect ?? inferDialect(options.url)) === \"postgres\") return createPgConnection({\n\t\turl: options.url,\n\t\tmax: options.max,\n\t\tsearchPath: options.searchPath\n\t});\n\treturn createSqliteConnection({ url: options.url });\n}\n//#endregion\n//#region src/migrate/resolve-folder.ts\nfunction resolvePackageRoot() {\n\tlet dir = dirname(fileURLToPath(import.meta.url));\n\tfor (;;) {\n\t\tif (existsSync(join(dir, \"drizzle\", \"pg\", \"meta\", \"_journal.json\"))) return dir;\n\t\tconst parent = dirname(dir);\n\t\tif (parent === dir) break;\n\t\tdir = parent;\n\t}\n\tthrow new Error(\"Could not resolve @keystrokehq/platform-database package root for migrations\");\n}\nfunction resolveMigrationsFolder(dialect, override) {\n\tif (override) return override;\n\ttry {\n\t\treturn join(resolvePackageRoot(), \"drizzle\", dialect);\n\t} catch {\n\t\treturn join(dirname(fileURLToPath(import.meta.url)), \"..\", \"..\", \"drizzle\", dialect);\n\t}\n}\n//#endregion\n//#region src/migrate/migrations.pg.generated.ts\nconst platformPgMigrations = [\n\t{\n\t\t\"sql\": [\n\t\t\t\"CREATE TYPE \\\"public\\\".\\\"project_artifact_status\\\" AS ENUM('pending', 'ready');\",\n\t\t\t\"\\nCREATE TYPE \\\"public\\\".\\\"project_status\\\" AS ENUM('inactive', 'starting', 'active', 'failed');\",\n\t\t\t\"\\nCREATE TABLE \\\"accounts\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"account_id\\\" text NOT NULL,\\n\t\\\"provider_id\\\" text NOT NULL,\\n\t\\\"user_id\\\" text NOT NULL,\\n\t\\\"access_token\\\" text,\\n\t\\\"refresh_token\\\" text,\\n\t\\\"id_token\\\" text,\\n\t\\\"access_token_expires_at\\\" timestamp with time zone,\\n\t\\\"refresh_token_expires_at\\\" timestamp with time zone,\\n\t\\\"scope\\\" text,\\n\t\\\"password\\\" text,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"api_keys\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"config_id\\\" text DEFAULT 'default' NOT NULL,\\n\t\\\"name\\\" text,\\n\t\\\"start\\\" text,\\n\t\\\"prefix\\\" text,\\n\t\\\"key\\\" text NOT NULL,\\n\t\\\"key_ciphertext\\\" text,\\n\t\\\"reference_id\\\" text NOT NULL,\\n\t\\\"refill_interval\\\" integer,\\n\t\\\"refill_amount\\\" integer,\\n\t\\\"last_refill_at\\\" timestamp with time zone,\\n\t\\\"enabled\\\" boolean DEFAULT true,\\n\t\\\"rate_limit_enabled\\\" boolean DEFAULT true,\\n\t\\\"rate_limit_time_window\\\" integer,\\n\t\\\"rate_limit_max\\\" integer,\\n\t\\\"request_count\\\" integer DEFAULT 0,\\n\t\\\"remaining\\\" integer,\\n\t\\\"last_request\\\" timestamp with time zone,\\n\t\\\"expires_at\\\" timestamp with time zone,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"permissions\\\" text,\\n\t\\\"metadata\\\" text\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"device_auth_codes\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"device_code\\\" text NOT NULL,\\n\t\\\"user_code\\\" text NOT NULL,\\n\t\\\"user_id\\\" text,\\n\t\\\"expires_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"status\\\" text NOT NULL,\\n\t\\\"last_polled_at\\\" timestamp with time zone,\\n\t\\\"polling_interval\\\" integer,\\n\t\\\"client_id\\\" text,\\n\t\\\"scope\\\" text\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"jwks\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"public_key\\\" text NOT NULL,\\n\t\\\"private_key\\\" text NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"expires_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"sessions\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"expires_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"token\\\" text NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"ip_address\\\" text,\\n\t\\\"user_agent\\\" text,\\n\t\\\"user_id\\\" text NOT NULL,\\n\tCONSTRAINT \\\"sessions_token_unique\\\" UNIQUE(\\\"token\\\")\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"verification\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"identifier\\\" text NOT NULL,\\n\t\\\"value\\\" text NOT NULL,\\n\t\\\"expires_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"oauth_apps\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text NOT NULL,\\n\t\\\"provider\\\" text NOT NULL,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"token_strategy\\\" text NOT NULL,\\n\t\\\"client_id_ciphertext\\\" text NOT NULL,\\n\t\\\"client_secret_ciphertext\\\" text NOT NULL,\\n\t\\\"signing_secret_ciphertext\\\" text,\\n\t\\\"redirect_uri\\\" text,\\n\t\\\"metadata\\\" jsonb,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"oauth_connections\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"app_id\\\" text NOT NULL,\\n\t\\\"external_id\\\" text NOT NULL,\\n\t\\\"access_token_ciphertext\\\" text NOT NULL,\\n\t\\\"refresh_token_ciphertext\\\" text,\\n\t\\\"access_token_expires_at\\\" timestamp with time zone,\\n\t\\\"granted_scopes\\\" jsonb,\\n\t\\\"metadata\\\" jsonb,\\n\t\\\"connected_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"organization_invitations\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text NOT NULL,\\n\t\\\"user_id\\\" text NOT NULL,\\n\t\\\"email\\\" text NOT NULL,\\n\t\\\"role\\\" text NOT NULL,\\n\t\\\"status\\\" text NOT NULL,\\n\t\\\"invited_by_user_id\\\" text NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"expires_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"organization_users\\\" (\\n\t\\\"organization_id\\\" text NOT NULL,\\n\t\\\"user_id\\\" text NOT NULL,\\n\t\\\"role\\\" text NOT NULL,\\n\t\\\"status\\\" text DEFAULT 'active' NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"deleted_at\\\" timestamp with time zone,\\n\tCONSTRAINT \\\"organization_users_organization_id_user_id_pk\\\" PRIMARY KEY(\\\"organization_id\\\",\\\"user_id\\\")\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"organizations\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"name\\\" text NOT NULL,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"db_schema\\\" text NOT NULL,\\n\t\\\"db_user\\\" text NOT NULL,\\n\t\\\"db_password_ciphertext\\\" text NOT NULL,\\n\t\\\"hosting_app_name\\\" text,\\n\t\\\"storage_bucket\\\" text,\\n\t\\\"storage_endpoint\\\" text,\\n\t\\\"storage_access_key_id_ciphertext\\\" text,\\n\t\\\"storage_secret_access_key_ciphertext\\\" text,\\n\t\\\"storage_region\\\" text,\\n\t\\\"storage_force_path_style\\\" boolean,\\n\t\\\"custom_logo_enabled\\\" boolean DEFAULT false NOT NULL,\\n\t\\\"custom_logo_explicitly_disabled\\\" boolean DEFAULT false NOT NULL,\\n\t\\\"logo_light_url\\\" text,\\n\t\\\"logo_dark_url\\\" text,\\n\t\\\"logo_height_px\\\" integer DEFAULT 20 NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"deleted_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"project_artifacts\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"storage_key\\\" text NOT NULL,\\n\t\\\"manifest_json\\\" jsonb,\\n\t\\\"source_manifest_json\\\" jsonb,\\n\t\\\"version\\\" integer NOT NULL,\\n\t\\\"created_by_user_id\\\" text,\\n\t\\\"status\\\" \\\"project_artifact_status\\\" NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"projects\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text NOT NULL,\\n\t\\\"name\\\" text NOT NULL,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"description\\\" text,\\n\t\\\"created_by_user_id\\\" text,\\n\t\\\"status\\\" \\\"project_status\\\" NOT NULL,\\n\t\\\"base_url\\\" text,\\n\t\\\"runtime_id\\\" text,\\n\t\\\"active_artifact_id\\\" text,\\n\t\\\"pending_artifact_id\\\" text,\\n\t\\\"last_error\\\" text,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"deleted_at\\\" timestamp with time zone\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"secret_values\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text NOT NULL,\\n\t\\\"ref_kind\\\" text NOT NULL,\\n\t\\\"ref_id\\\" text NOT NULL,\\n\t\\\"field\\\" text NOT NULL,\\n\t\\\"ciphertext\\\" text NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nCREATE TABLE \\\"users\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"name\\\" text NOT NULL,\\n\t\\\"email\\\" text NOT NULL,\\n\t\\\"email_verified\\\" boolean NOT NULL,\\n\t\\\"image\\\" text,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\tCONSTRAINT \\\"users_email_unique\\\" UNIQUE(\\\"email\\\")\\n);\\n\",\n\t\t\t\"\\nALTER TABLE \\\"accounts\\\" ADD CONSTRAINT \\\"accounts_user_id_users_id_fk\\\" FOREIGN KEY (\\\"user_id\\\") REFERENCES \\\"public\\\".\\\"users\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"sessions\\\" ADD CONSTRAINT \\\"sessions_user_id_users_id_fk\\\" FOREIGN KEY (\\\"user_id\\\") REFERENCES \\\"public\\\".\\\"users\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"oauth_apps\\\" ADD CONSTRAINT \\\"oauth_apps_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"oauth_connections\\\" ADD CONSTRAINT \\\"oauth_connections_app_id_oauth_apps_id_fk\\\" FOREIGN KEY (\\\"app_id\\\") REFERENCES \\\"public\\\".\\\"oauth_apps\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"organization_invitations\\\" ADD CONSTRAINT \\\"organization_invitations_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"organization_invitations\\\" ADD CONSTRAINT \\\"organization_invitations_user_id_users_id_fk\\\" FOREIGN KEY (\\\"user_id\\\") REFERENCES \\\"public\\\".\\\"users\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"organization_invitations\\\" ADD CONSTRAINT \\\"organization_invitations_invited_by_user_id_users_id_fk\\\" FOREIGN KEY (\\\"invited_by_user_id\\\") REFERENCES \\\"public\\\".\\\"users\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"organization_users\\\" ADD CONSTRAINT \\\"organization_users_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"organization_users\\\" ADD CONSTRAINT \\\"organization_users_user_id_users_id_fk\\\" FOREIGN KEY (\\\"user_id\\\") REFERENCES \\\"public\\\".\\\"users\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"project_artifacts\\\" ADD CONSTRAINT \\\"project_artifacts_project_id_projects_id_fk\\\" FOREIGN KEY (\\\"project_id\\\") REFERENCES \\\"public\\\".\\\"projects\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"project_artifacts\\\" ADD CONSTRAINT \\\"project_artifacts_created_by_user_id_users_id_fk\\\" FOREIGN KEY (\\\"created_by_user_id\\\") REFERENCES \\\"public\\\".\\\"users\\\"(\\\"id\\\") ON DELETE set null ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"projects\\\" ADD CONSTRAINT \\\"projects_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"projects\\\" ADD CONSTRAINT \\\"projects_created_by_user_id_users_id_fk\\\" FOREIGN KEY (\\\"created_by_user_id\\\") REFERENCES \\\"public\\\".\\\"users\\\"(\\\"id\\\") ON DELETE set null ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"secret_values\\\" ADD CONSTRAINT \\\"secret_values_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nCREATE INDEX \\\"account_user_id_idx\\\" ON \\\"accounts\\\" USING btree (\\\"user_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"api_keys_reference_id_idx\\\" ON \\\"api_keys\\\" USING btree (\\\"reference_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"api_keys_config_id_idx\\\" ON \\\"api_keys\\\" USING btree (\\\"config_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"api_keys_key_idx\\\" ON \\\"api_keys\\\" USING btree (\\\"key\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"session_user_id_idx\\\" ON \\\"sessions\\\" USING btree (\\\"user_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"verification_identifier_idx\\\" ON \\\"verification\\\" USING btree (\\\"identifier\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"oauth_apps_organization_id_slug_idx\\\" ON \\\"oauth_apps\\\" USING btree (\\\"organization_id\\\",\\\"slug\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"oauth_apps_slug_idx\\\" ON \\\"oauth_apps\\\" USING btree (\\\"slug\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"oauth_connections_app_external_unique\\\" ON \\\"oauth_connections\\\" USING btree (\\\"app_id\\\",\\\"external_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"oauth_connections_external_id_idx\\\" ON \\\"oauth_connections\\\" USING btree (\\\"external_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"organization_invitations_user_id_idx\\\" ON \\\"organization_invitations\\\" USING btree (\\\"user_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"organization_invitations_organization_id_idx\\\" ON \\\"organization_invitations\\\" USING btree (\\\"organization_id\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"organization_invitations_org_user_pending_unique\\\" ON \\\"organization_invitations\\\" USING btree (\\\"organization_id\\\",\\\"user_id\\\") WHERE \\\"organization_invitations\\\".\\\"status\\\" = 'pending';\",\n\t\t\t\"\\nCREATE INDEX \\\"organization_users_user_id_idx\\\" ON \\\"organization_users\\\" USING btree (\\\"user_id\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"organizations_slug_unique\\\" ON \\\"organizations\\\" USING btree (\\\"slug\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"project_artifacts_project_id_idx\\\" ON \\\"project_artifacts\\\" USING btree (\\\"project_id\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"projects_organization_id_idx\\\" ON \\\"projects\\\" USING btree (\\\"organization_id\\\");\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"projects_org_auto_created_by_user_unique\\\" ON \\\"projects\\\" USING btree (\\\"organization_id\\\",\\\"created_by_user_id\\\") WHERE \\\"projects\\\".\\\"created_by_user_id\\\" IS NOT NULL AND \\\"projects\\\".\\\"deleted_at\\\" IS NULL;\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"projects_organization_slug_unique\\\" ON \\\"projects\\\" USING btree (\\\"organization_id\\\",\\\"slug\\\") WHERE \\\"projects\\\".\\\"deleted_at\\\" IS NULL;\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"secret_values_ref_unique\\\" ON \\\"secret_values\\\" USING btree (\\\"organization_id\\\",\\\"ref_kind\\\",\\\"ref_id\\\",\\\"field\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"secret_values_ref_idx\\\" ON \\\"secret_values\\\" USING btree (\\\"organization_id\\\",\\\"ref_kind\\\",\\\"ref_id\\\");\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1781213647047,\n\t\t\"hash\": \"48e4b0a3b93c74edcdf88867eb21556327144131da0870bc764edee3e08560c1\"\n\t},\n\t{\n\t\t\"sql\": [\"ALTER TABLE \\\"users\\\" ADD COLUMN \\\"preferences\\\" jsonb;\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1781276711832,\n\t\t\"hash\": \"aa68be6edc75bf379abd0d5ce031ff60008fe881d7d785a996b002b63d424bc7\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"CREATE TABLE \\\"project_users\\\" (\\n\t\\\"project_id\\\" text NOT NULL,\\n\t\\\"user_id\\\" text NOT NULL,\\n\t\\\"role\\\" text NOT NULL,\\n\t\\\"status\\\" text DEFAULT 'active' NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"deleted_at\\\" timestamp with time zone,\\n\tCONSTRAINT \\\"project_users_project_id_user_id_pk\\\" PRIMARY KEY(\\\"project_id\\\",\\\"user_id\\\")\\n);\\n\",\n\t\t\t\"\\nALTER TABLE \\\"projects\\\" ADD COLUMN \\\"default_member_role\\\" text DEFAULT 'builder' NOT NULL;\",\n\t\t\t\"\\nALTER TABLE \\\"projects\\\" ADD COLUMN \\\"invite_permission\\\" text DEFAULT 'admin' NOT NULL;\",\n\t\t\t\"\\nALTER TABLE \\\"project_users\\\" ADD CONSTRAINT \\\"project_users_project_id_projects_id_fk\\\" FOREIGN KEY (\\\"project_id\\\") REFERENCES \\\"public\\\".\\\"projects\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nALTER TABLE \\\"project_users\\\" ADD CONSTRAINT \\\"project_users_user_id_users_id_fk\\\" FOREIGN KEY (\\\"user_id\\\") REFERENCES \\\"public\\\".\\\"users\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nCREATE INDEX \\\"project_users_user_id_idx\\\" ON \\\"project_users\\\" USING btree (\\\"user_id\\\");\",\n\t\t\t\"\\nINSERT INTO \\\"project_users\\\" (\\\"project_id\\\", \\\"user_id\\\", \\\"role\\\", \\\"status\\\", \\\"created_at\\\", \\\"updated_at\\\")\\nSELECT p.id, p.created_by_user_id, 'admin', 'active', NOW(), NOW()\\nFROM \\\"projects\\\" p\\nWHERE p.created_by_user_id IS NOT NULL AND p.deleted_at IS NULL\\nON CONFLICT (\\\"project_id\\\", \\\"user_id\\\") DO NOTHING;\\n\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 178128e7,\n\t\t\"hash\": \"d8809c81a5d2340d8651c36dfddad9427f039ac1481d3d0b3dcd63a73a79d11a\"\n\t},\n\t{\n\t\t\"sql\": [\"DELETE FROM \\\"project_users\\\" AS pu\\nUSING \\\"projects\\\" AS p, \\\"organization_users\\\" AS ou\\nWHERE pu.project_id = p.id\\n AND pu.user_id = ou.user_id\\n AND ou.organization_id = p.organization_id\\n AND ou.role = 'builder'\\n AND pu.role = 'builder'\\n AND pu.user_id IS DISTINCT FROM p.created_by_user_id;\\n\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 17812836e5,\n\t\t\"hash\": \"a025effc73d9ea3e21e734834a60a74f9e2b84c558eeef2c1bd18fd0311f8c5c\"\n\t},\n\t{\n\t\t\"sql\": [\"DROP INDEX IF EXISTS \\\"projects_org_auto_created_by_user_unique\\\";\\n\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 17812872e5,\n\t\t\"hash\": \"51ceed699b982b1ea96119e6ca7261a5e2ca854c456b7b89c65736a91114e1a6\"\n\t},\n\t{\n\t\t\"sql\": [\n\t\t\t\"CREATE TABLE \\\"apps\\\" (\\n\t\\\"id\\\" text PRIMARY KEY NOT NULL,\\n\t\\\"organization_id\\\" text,\\n\t\\\"slug\\\" text NOT NULL,\\n\t\\\"name\\\" text NOT NULL,\\n\t\\\"description\\\" text NOT NULL,\\n\t\\\"category\\\" text NOT NULL,\\n\t\\\"logo\\\" text,\\n\t\\\"auth_kind\\\" text NOT NULL,\\n\t\\\"oauth_scopes\\\" jsonb NOT NULL,\\n\t\\\"source\\\" text NOT NULL,\\n\t\\\"created_at\\\" timestamp with time zone NOT NULL,\\n\t\\\"updated_at\\\" timestamp with time zone NOT NULL\\n);\\n\",\n\t\t\t\"\\nALTER TABLE \\\"apps\\\" ADD CONSTRAINT \\\"apps_organization_id_organizations_id_fk\\\" FOREIGN KEY (\\\"organization_id\\\") REFERENCES \\\"public\\\".\\\"organizations\\\"(\\\"id\\\") ON DELETE cascade ON UPDATE no action;\",\n\t\t\t\"\\nCREATE UNIQUE INDEX \\\"apps_slug_idx\\\" ON \\\"apps\\\" USING btree (\\\"slug\\\");\",\n\t\t\t\"\\nCREATE INDEX \\\"apps_organization_id_idx\\\" ON \\\"apps\\\" USING btree (\\\"organization_id\\\");\"\n\t\t],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1781819893736,\n\t\t\"hash\": \"22be601d95e9d4dd557036fd150112e7f05e98f33d0a99315aabd4739d1730b0\"\n\t},\n\t{\n\t\t\"sql\": [\"ALTER TABLE \\\"organizations\\\" ADD COLUMN \\\"runtime_id\\\" text;\", \"\\nALTER TABLE \\\"organizations\\\" ADD COLUMN \\\"base_url\\\" text;\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1781990311400,\n\t\t\"hash\": \"41b6a62e955cf3accd8292902c3762f01712dc3a6068388edcc42b66b4c1d6a0\"\n\t},\n\t{\n\t\t\"sql\": [\"ALTER TABLE \\\"apps\\\" ADD COLUMN \\\"credential_fields\\\" jsonb DEFAULT '{}'::jsonb NOT NULL;\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1782105700654,\n\t\t\"hash\": \"063e3b85fb5a17325381bfd0425edc0b8ee8cbf0677c390fa67a7e52b7e758c2\"\n\t},\n\t{\n\t\t\"sql\": [\"ALTER TABLE \\\"organizations\\\" ADD COLUMN \\\"verified_at\\\" timestamp with time zone;\", \"\\nUPDATE \\\"organizations\\\" SET \\\"verified_at\\\" = \\\"created_at\\\" WHERE \\\"verified_at\\\" IS NULL;\"],\n\t\t\"bps\": true,\n\t\t\"folderMillis\": 1782144854087,\n\t\t\"hash\": \"316191ff040fe6d2b4de9b49d6d0de8a607ab87660bbdfbd9b697aaf387f5e1b\"\n\t}\n];\n//#endregion\n//#region src/migrate/run.ts\nasync function runMigrations(handle, migrationsFolder) {\n\tif (handle.dialect === \"sqlite\") {\n\t\tmigrate(handle.db, { migrationsFolder });\n\t\treturn;\n\t}\n\tconst config = {\n\t\tmigrationsFolder,\n\t\tmigrationsSchema: resolveMigrationsSchema(handle.searchPath)\n\t};\n\tconst loaded = loadMigrations(migrationsFolder, platformPgMigrations);\n\tconst migrations = handle.searchPath ? adaptPgMigrationsForSearchPath(loaded) : loaded;\n\tawait migratePgDatabase(handle.db, config, migrations);\n}\n//#endregion\n//#region src/client/init.ts\nfunction resolveUrl(url) {\n\treturn url ?? resolvePlatformDatabaseUrl();\n}\nasync function initDatabase(options = {}) {\n\tif (isDatabaseInitialized()) return;\n\tconst url = resolveUrl(options.url);\n\tconst dialect = options.dialect ?? inferDialect(url);\n\tconst searchPath = dialect === \"postgres\" ? resolveSearchPath(url, options.searchPath) : void 0;\n\tconst next = createConnection({\n\t\turl,\n\t\tdialect,\n\t\tmax: options.max,\n\t\tsearchPath\n\t});\n\tsetDatabaseHandle(next);\n\tif (options.migrate ?? true) await runMigrations(next, resolveMigrationsFolder(dialect, options.migrationsFolder));\n}\n//#endregion\n//#region src/config/organization-scope.ts\nconst organizationScopeStorage = new AsyncLocalStorage();\nfunction runWithOrganizationScope(organizationId, fn) {\n\treturn organizationScopeStorage.run(organizationId, fn);\n}\nfunction getOrganizationScopeId() {\n\treturn organizationScopeStorage.getStore();\n}\nfunction requireOrganizationScopeId() {\n\tconst organizationId = getOrganizationScopeId();\n\tif (!organizationId) throw new Error(\"Organization scope is not set\");\n\treturn organizationId;\n}\n//#endregion\n//#region src/project-database/names.ts\nconst PG_IDENT = /^[a-zA-Z_][a-zA-Z0-9_]*$/;\nfunction sanitizeIdForPgIdent(id) {\n\treturn id.replace(/-/g, \"_\");\n}\n/**\n* Per-org sqlite db lives beside the platform (public) sqlite db so that each\n* standalone instance / test working directory is isolated. Falls back to\n* `<cwd>/data` when the platform db is in-memory or not a file URL.\n*/\nfunction orgDbFilePath(organizationId) {\n\tconst standaloneDataDir = process.env.KEYSTROKE_STANDALONE_DATA_DIR?.trim();\n\tif (standaloneDataDir) return join(standaloneDataDir, `org_${sanitizeIdForPgIdent(organizationId)}.db`);\n\tconst platformPath = resolveSqlitePath(resolvePlatformDatabaseUrl());\n\treturn join(platformPath !== \"\" && !platformPath.startsWith(\":memory:\") ? dirname(platformPath) : join(process.cwd(), \"data\"), `org_${sanitizeIdForPgIdent(organizationId)}.db`);\n}\n/** @deprecated Use {@link orgDbSchemaName} — per-project schemas replaced by org schema + project_id. */\nfunction projectDbSchemaName(projectId) {\n\tconst name = `project_${sanitizeIdForPgIdent(projectId)}`;\n\tassertPgIdent(name);\n\treturn name;\n}\n/** @deprecated Use {@link orgDbRoleName}. */\nfunction projectDbRoleName(projectId) {\n\tconst name = `project_${sanitizeIdForPgIdent(projectId)}_user`;\n\tassertPgIdent(name);\n\treturn name;\n}\nfunction orgDbSchemaName(organizationId) {\n\tconst name = `org_${sanitizeIdForPgIdent(organizationId)}`;\n\tassertPgIdent(name);\n\treturn name;\n}\nfunction orgDbRoleName(organizationId) {\n\tconst name = `org_${sanitizeIdForPgIdent(organizationId)}_user`;\n\tassertPgIdent(name);\n\treturn name;\n}\nfunction assertPgIdent(name) {\n\tif (!PG_IDENT.test(name)) throw new Error(`Invalid Postgres identifier: ${name}`);\n}\nfunction quotePgIdent(name) {\n\tassertPgIdent(name);\n\treturn `\"${name.replace(/\"/g, \"\\\"\\\"\")}\"`;\n}\n//#endregion\n//#region src/project-database/provision.ts\nasync function provisionOrgDatabaseSqlite(organizationId) {\n\tconst { createConnection, resolveMigrationsFolder, runMigrations } = await import(\"@keystrokehq/database\");\n\tconst dbSchema = orgDbFilePath(organizationId);\n\tmkdirSync(dirname(dbSchema), { recursive: true });\n\tconst handle = createConnection({\n\t\turl: `file:${dbSchema}`,\n\t\tdialect: \"sqlite\"\n\t});\n\ttry {\n\t\tawait runMigrations(handle, resolveMigrationsFolder(\"sqlite\"));\n\t} finally {\n\t\thandle.close();\n\t}\n\treturn {\n\t\tdbSchema,\n\t\tdbUser: \"\",\n\t\tdbPasswordCiphertext: \"\"\n\t};\n}\nasync function quoteLiteral(pool, value) {\n\tconst { rows } = await pool.query(\"SELECT quote_literal($1) AS quoted\", [value]);\n\tconst quoted = rows[0]?.quoted;\n\tif (!quoted) throw new Error(\"Failed to quote Postgres literal\");\n\treturn quoted;\n}\nasync function grantOrgSchemaObjects(pool, dbSchema, dbUser) {\n\tconst schemaIdent = quotePgIdent(dbSchema);\n\tconst roleIdent = quotePgIdent(dbUser);\n\tawait pool.query(`GRANT ALL ON ALL TABLES IN SCHEMA ${schemaIdent} TO ${roleIdent}`);\n\tawait pool.query(`GRANT ALL ON ALL SEQUENCES IN SCHEMA ${schemaIdent} TO ${roleIdent}`);\n\tawait pool.query(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${schemaIdent} GRANT ALL ON TABLES TO ${roleIdent}`);\n\tawait pool.query(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${schemaIdent} GRANT ALL ON SEQUENCES TO ${roleIdent}`);\n\tconst { rows } = await pool.query(`SELECT n.nspname, t.typname\n FROM pg_type t\n JOIN pg_namespace n ON n.oid = t.typnamespace\n WHERE n.nspname = $1 AND t.typtype = 'e'`, [dbSchema]);\n\tfor (const row of rows) {\n\t\tconst typeIdent = `${quotePgIdent(row.nspname)}.${quotePgIdent(row.typname)}`;\n\t\tawait pool.query(`GRANT USAGE ON TYPE ${typeIdent} TO ${roleIdent}`);\n\t}\n}\nasync function provisionOrgDatabasePostgres(organizationId) {\n\tconst { randomBytes } = await import(\"node:crypto\");\n\tconst { Pool: PgPool } = await import(\"pg\");\n\tconst { createConnection, encryptCredentialPayload, resolveMigrationsFolder, runMigrations } = await import(\"@keystrokehq/database\");\n\tconst { buildOrgDatabaseUrl } = await Promise.resolve().then(() => build_url_exports);\n\tconst { grantPgBossAccess } = await Promise.resolve().then(() => pgboss_grants_exports);\n\tconst dbSchema = orgDbSchemaName(organizationId);\n\tconst dbUser = orgDbRoleName(organizationId);\n\tconst password = randomBytes(32).toString(\"base64url\");\n\tconst pool = new PgPool({ connectionString: resolvePlatformDatabaseUrl() });\n\ttry {\n\t\tconst quotedPassword = await quoteLiteral(pool, password);\n\t\tconst schemaIdent = quotePgIdent(dbSchema);\n\t\tconst roleIdent = quotePgIdent(dbUser);\n\t\tawait pool.query(`CREATE ROLE ${roleIdent} WITH LOGIN PASSWORD ${quotedPassword}`);\n\t\tawait pool.query(`REVOKE ALL ON SCHEMA public FROM ${roleIdent}`);\n\t\tawait pool.query(`CREATE SCHEMA ${schemaIdent}`);\n\t\tawait pool.query(`GRANT ALL ON SCHEMA ${schemaIdent} TO ${roleIdent}`);\n\t\tconst { rows: dbRows } = await pool.query(\"SELECT current_database() AS name\");\n\t\tconst databaseName = dbRows[0]?.name;\n\t\tif (!databaseName) throw new Error(\"Failed to resolve current database name\");\n\t\tawait pool.query(`GRANT CREATE ON DATABASE ${quotePgIdent(databaseName)} TO ${roleIdent}`);\n\t\tawait pool.query(`ALTER ROLE ${roleIdent} SET search_path TO ${schemaIdent}`);\n\t\tawait grantPgBossAccess(pool, dbUser);\n\t\tconst handle = createConnection({\n\t\t\turl: buildOrgDatabaseUrl(dbUser, password),\n\t\t\tdialect: \"postgres\",\n\t\t\tsearchPath: dbSchema\n\t\t});\n\t\ttry {\n\t\t\tawait runMigrations(handle, resolveMigrationsFolder(\"postgres\"));\n\t\t} finally {\n\t\t\tawait handle.close();\n\t\t}\n\t\tawait grantOrgSchemaObjects(pool, dbSchema, dbUser);\n\t\treturn {\n\t\t\tdbSchema,\n\t\t\tdbUser,\n\t\t\tdbPasswordCiphertext: encryptCredentialPayload(password)\n\t\t};\n\t} catch (error) {\n\t\tawait deprovisionOrgDatabase({\n\t\t\tdbSchema,\n\t\t\tdbUser\n\t\t}).catch(() => void 0);\n\t\tthrow error;\n\t} finally {\n\t\tawait pool.end();\n\t}\n}\nasync function provisionOrgDatabase(organizationId) {\n\tif (inferDialect(resolvePlatformDatabaseUrl()) === \"sqlite\") return provisionOrgDatabaseSqlite(organizationId);\n\treturn provisionOrgDatabasePostgres(organizationId);\n}\nasync function deprovisionOrgDatabase(input) {\n\tif (inferDialect(resolvePlatformDatabaseUrl()) === \"sqlite\") {\n\t\tconst { unlinkSync } = await import(\"node:fs\");\n\t\ttry {\n\t\t\tunlinkSync(input.dbSchema);\n\t\t} catch {}\n\t\treturn;\n\t}\n\tconst { Pool: PgPool } = await import(\"pg\");\n\tconst pool = new PgPool({ connectionString: resolvePlatformDatabaseUrl() });\n\ttry {\n\t\tconst roleIdent = quotePgIdent(input.dbUser);\n\t\tawait pool.query(`DROP SCHEMA IF EXISTS ${quotePgIdent(input.dbSchema)} CASCADE`);\n\t\tif (input.dbUser) {\n\t\t\tawait pool.query(`DROP OWNED BY ${roleIdent}`);\n\t\t\tawait pool.query(`DROP ROLE IF EXISTS ${roleIdent}`);\n\t\t}\n\t} finally {\n\t\tawait pool.end();\n\t}\n}\n//#endregion\n//#region src/queries/_internal.ts\n/** Internal: only `queries/**` may call this. */\nfunction getDb() {\n\treturn getDbFromContext();\n}\nfunction isSqliteDialect() {\n\treturn getDatabaseHandle().dialect === \"sqlite\";\n}\n/** Drizzle sqlite handle when the control-plane runs on sqlite. */\nfunction getSqliteDb() {\n\treturn getDbFromContext();\n}\n//#endregion\n//#region src/queries/users/email.ts\nfunction normalizeUserEmail(email) {\n\treturn email.trim().toLowerCase();\n}\nfunction placeholderNameFromEmail(email) {\n\tconst localPart = email.split(\"@\")[0]?.trim();\n\treturn localPart && localPart.length > 0 ? localPart : \"User\";\n}\n//#endregion\n//#region src/queries/users/index.ts\nasync function selectUserByNormalizedEmail(email) {\n\tconst normalized = normalizeUserEmail(email);\n\treturn (await getDb().select().from(users).where(sql$1`lower(${users.email}) = ${normalized}`).limit(1))[0];\n}\nasync function selectUserByEmail(email) {\n\treturn selectUserByNormalizedEmail(email);\n}\nasync function findOrCreateUserByEmail(email) {\n\tconst normalized = normalizeUserEmail(email);\n\tconst existing = await selectUserByNormalizedEmail(normalized);\n\tif (existing) return existing;\n\tconst now = /* @__PURE__ */ new Date();\n\tconst db = getDb();\n\ttry {\n\t\tconst [created] = await db.insert(users).values({\n\t\t\tid: crypto.randomUUID(),\n\t\t\tname: placeholderNameFromEmail(normalized),\n\t\t\temail: normalized,\n\t\t\temailVerified: false,\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now\n\t\t}).returning();\n\t\tif (!created) throw new Error(\"Failed to create user\");\n\t\treturn created;\n\t} catch (error) {\n\t\tconst raced = await selectUserByNormalizedEmail(normalized);\n\t\tif (raced) return raced;\n\t\tthrow error;\n\t}\n}\nasync function selectUserById(id) {\n\treturn (await getDb().select().from(users).where(eq$1(users.id, id)).limit(1))[0];\n}\nasync function selectUsersByIds(ids) {\n\tif (ids.length === 0) return [];\n\treturn getDb().select().from(users).where(inArray$1(users.id, ids));\n}\nasync function updateUserById(id, values) {\n\tawait getDb().update(users).set(values).where(eq$1(users.id, id));\n}\n//#endregion\n//#region src/queries/projects/slug.ts\nvar ProjectSlugTakenError = class extends Error {\n\tconstructor() {\n\t\tsuper(PROJECT_SLUG_TAKEN_MESSAGE);\n\t\tthis.name = \"ProjectSlugTakenError\";\n\t}\n};\nfunction isProjectSlugUniqueViolation(error) {\n\tif (typeof error !== \"object\" || error === null) return false;\n\treturn (\"code\" in error ? String(error.code) : \"\") === \"23505\";\n}\nasync function isProjectSlugTaken(executor, organizationId, slug, excludeProjectId) {\n\treturn (await executor.select({ id: projects.id }).from(projects).where(and(eq(projects.organizationId, organizationId), eq(projects.slug, slug), isNull(projects.deletedAt), excludeProjectId ? ne(projects.id, excludeProjectId) : void 0)).limit(1)).length > 0;\n}\nasync function resolveAvailableProjectSlug(executor, organizationId, name) {\n\tconst base = slugifyProjectName(name);\n\tif (!await isProjectSlugTaken(executor, organizationId, base)) return base;\n\tfor (let suffix = 2; suffix < 1e4; suffix += 1) {\n\t\tconst candidate = ProjectSlugSchema.parse(`${base}-${suffix}`);\n\t\tif (!await isProjectSlugTaken(executor, organizationId, candidate)) return candidate;\n\t}\n\tthrow new Error(\"Unable to allocate a unique project slug\");\n}\nasync function checkProjectSlugAvailability(organizationId, slug, excludeProjectId) {\n\tconst normalized = slug.trim().toLowerCase();\n\tconst format = ProjectSlugSchema.safeParse(normalized);\n\tif (!format.success) return {\n\t\tslug: normalized,\n\t\tavailable: false,\n\t\treason: \"invalid\"\n\t};\n\tconst parsed = format.data;\n\tif (await isProjectSlugTaken(getDb(), organizationId, parsed, excludeProjectId)) return {\n\t\tslug: parsed,\n\t\tavailable: false,\n\t\treason: \"taken\",\n\t\tsuggestion: await resolveAvailableProjectSlug(getDb(), organizationId, parsed)\n\t};\n\treturn {\n\t\tslug: parsed,\n\t\tavailable: true\n\t};\n}\n//#endregion\n//#region src/queries/projects/default-project.ts\n/** e.g. Alex → Alex's, Wells → Wells' */\nfunction formatPossessive(name) {\n\treturn name.endsWith(\"s\") || name.endsWith(\"S\") ? `${name}'` : `${name}'s`;\n}\n/** Auto-created projects only — not used for manual `POST /api/projects`. */\nfunction buildDefaultProjectDescription(displayName) {\n\treturn `${formatPossessive(displayName)} personal project for agents, workflows, and other stuff.`;\n}\nfunction firstNameFromUser(user) {\n\tconst fromName = user.name.trim().split(/\\s+/)[0];\n\tif (fromName) return fromName;\n\tconst local = user.email.split(\"@\")[0]?.replace(/[._+-]/g, \" \").trim();\n\treturn local && local.length > 0 ? local : \"My\";\n}\nfunction buildDefaultProjectForUser(user) {\n\tconst firstName = firstNameFromUser(user);\n\treturn {\n\t\tname: `${formatPossessive(firstName)} Project`,\n\t\tdescription: buildDefaultProjectDescription(firstName)\n\t};\n}\nasync function selectAutoCreatedProjectForUser(executor, organizationId, userId) {\n\treturn (await executor.select().from(projects).where(and$1(eq$1(projects.organizationId, organizationId), eq$1(projects.createdByUserId, userId), isNull$1(projects.deletedAt))).limit(1))[0];\n}\nasync function insertAutoCreatedProject(executor, organizationId, userId, name, description) {\n\tconst existing = await selectAutoCreatedProjectForUser(executor, organizationId, userId);\n\tif (existing) return existing;\n\tconst now = /* @__PURE__ */ new Date();\n\tconst projectId = crypto.randomUUID();\n\tconst slug = await resolveAvailableProjectSlug(executor, organizationId, name);\n\tconst [inserted] = await executor.insert(projects).values({\n\t\tid: projectId,\n\t\torganizationId,\n\t\tname,\n\t\tslug,\n\t\tdescription,\n\t\tdefaultMemberRole: \"builder\",\n\t\tinvitePermission: \"admin\",\n\t\tcreatedByUserId: userId,\n\t\tstatus: \"inactive\",\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t}).returning();\n\tif (inserted) {\n\t\tawait executor.insert(projectUsers).values({\n\t\t\tprojectId: inserted.id,\n\t\t\tuserId,\n\t\t\trole: \"admin\",\n\t\t\tstatus: \"active\",\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now\n\t\t}).onConflictDoNothing();\n\t\treturn inserted;\n\t}\n\treturn selectAutoCreatedProjectForUser(executor, organizationId, userId);\n}\n/**\n* Creates the user's personal default project in `organizationId` when they do\n* not already have an auto-created project there.\n*/\nasync function ensureDefaultProjectForUserInTransaction(tx, userId, organizationId) {\n\tconst user = await selectUserById(userId);\n\tif (!user) throw new Error(\"User not found\");\n\tconst { name, description } = buildDefaultProjectForUser(user);\n\treturn insertAutoCreatedProject(tx, organizationId, userId, name, description);\n}\nasync function ensureDefaultProjectForUser(userId, organizationId) {\n\tconst user = await selectUserById(userId);\n\tif (!user) throw new Error(\"User not found\");\n\tconst { name, description } = buildDefaultProjectForUser(user);\n\treturn insertAutoCreatedProject(getDb(), organizationId, userId, name, description);\n}\n//#endregion\n//#region src/queries/organizations/slug.ts\nasync function checkOrganizationSlugAvailability(slug, excludeOrganizationId) {\n\tconst normalized = slug.trim().toLowerCase();\n\tconst format = OrganizationSlugSchema.safeParse(normalized);\n\tif (!format.success) return {\n\t\tslug: normalized,\n\t\tavailable: false,\n\t\treason: \"invalid\"\n\t};\n\tconst parsed = format.data;\n\tif (RESERVED_ORGANIZATION_SLUGS.has(parsed)) return {\n\t\tslug: parsed,\n\t\tavailable: false,\n\t\treason: \"reserved\"\n\t};\n\tif (await isOrganizationSlugTaken(parsed, excludeOrganizationId)) return {\n\t\tslug: parsed,\n\t\tavailable: false,\n\t\treason: \"taken\",\n\t\tsuggestion: await resolveAvailableOrganizationSlug(parsed, parsed)\n\t};\n\treturn {\n\t\tslug: parsed,\n\t\tavailable: true\n\t};\n}\nasync function isOrganizationSlugTaken(slug, excludeOrganizationId) {\n\treturn (await getDb().select({ id: organizations.id }).from(organizations).where(excludeOrganizationId ? and(eq(organizations.slug, slug), ne(organizations.id, excludeOrganizationId)) : eq(organizations.slug, slug)).limit(1)).length > 0;\n}\nfunction normalizeOrganizationSlugInput(name, slug) {\n\tif (slug?.trim()) {\n\t\tconst normalized = slug.trim().toLowerCase();\n\t\tif (normalized === slugifyOrganizationName(name)) return OrganizationSlugSchema.parse(normalized);\n\t\treturn ClaimableOrganizationSlugSchema.parse(normalized);\n\t}\n\treturn OrganizationSlugSchema.parse(slugifyOrganizationName(name));\n}\nasync function resolveAvailableOrganizationSlug(name, preferredSlug) {\n\tconst base = normalizeOrganizationSlugInput(name, preferredSlug);\n\tif (!RESERVED_ORGANIZATION_SLUGS.has(base) && !await isOrganizationSlugTaken(base)) return base;\n\tfor (let suffix = 2; suffix < 1e4; suffix += 1) {\n\t\tconst candidate = OrganizationSlugSchema.parse(`${base}-${suffix}`);\n\t\tif (!await isOrganizationSlugTaken(candidate)) return candidate;\n\t}\n\tthrow new Error(\"Unable to allocate a unique organization slug\");\n}\n//#endregion\n//#region src/queries/organizations/branding.ts\nfunction organizationRowToSidebarBranding(organization) {\n\treturn normalizeOrganizationSidebarBranding({\n\t\tcustomLogoEnabled: organization.customLogoEnabled,\n\t\tcustomLogoExplicitlyDisabled: organization.customLogoExplicitlyDisabled,\n\t\tlogoLightUrl: organization.logoLightUrl,\n\t\tlogoDarkUrl: organization.logoDarkUrl,\n\t\tlogoHeightPx: organization.logoHeightPx\n\t});\n}\nasync function updateOrganizationSidebarBranding(organizationId, input) {\n\tconst db = getDb();\n\tconst updates = { updatedAt: /* @__PURE__ */ new Date() };\n\tif (input.customLogoEnabled !== void 0) updates.customLogoEnabled = input.customLogoEnabled;\n\tif (input.customLogoExplicitlyDisabled !== void 0) updates.customLogoExplicitlyDisabled = input.customLogoExplicitlyDisabled;\n\tif (input.logoLightUrl !== void 0) updates.logoLightUrl = input.logoLightUrl;\n\tif (input.logoDarkUrl !== void 0) updates.logoDarkUrl = input.logoDarkUrl;\n\tif (input.logoHeightPx !== void 0) updates.logoHeightPx = input.logoHeightPx;\n\tconst [organization] = await db.update(organizations).set(updates).where(eq(organizations.id, organizationId)).returning();\n\tif (!organization) throw new Error(`Organization not found: ${organizationId}`);\n\treturn organization;\n}\n//#endregion\n//#region src/queries/organizations/index.ts\nfunction userOrganizationSelect() {\n\treturn {\n\t\torganization: organizations,\n\t\trole: organizationUsers.role\n\t};\n}\nasync function selectOrganizationById(id) {\n\treturn (await getDb().select().from(organizations).where(eq(organizations.id, id)).limit(1))[0];\n}\nasync function selectOrganizationBySlug(slug) {\n\treturn (await getDb().select().from(organizations).where(eq(organizations.slug, slug)).limit(1))[0];\n}\nasync function isOrganizationStorageBucketInUse(bucket) {\n\treturn (await getDb().select({ id: organizations.id }).from(organizations).where(and(eq(organizations.storageBucket, bucket), isNull(organizations.deletedAt))).limit(1)).length > 0;\n}\nasync function selectActiveOrganizationIds() {\n\treturn (await getDb().select({ id: organizations.id }).from(organizations).where(isNull(organizations.deletedAt))).map((row) => row.id);\n}\nfunction activeOrganizationUserFilter(userId, organizationId) {\n\tconst clauses = [\n\t\teq(organizationUsers.userId, userId),\n\t\teq(organizationUsers.status, \"active\"),\n\t\tisNull(organizationUsers.deletedAt)\n\t];\n\tif (organizationId) clauses.push(eq(organizationUsers.organizationId, organizationId));\n\treturn and(...clauses);\n}\nasync function selectUserOrganizations(userId) {\n\treturn getDb().select(userOrganizationSelect()).from(organizationUsers).innerJoin(organizations, eq(organizationUsers.organizationId, organizations.id)).where(activeOrganizationUserFilter(userId));\n}\nasync function selectUserOrganization(userId) {\n\treturn (await selectUserOrganizations(userId))[0];\n}\nasync function selectUserOrganizationMembership(userId, organizationId) {\n\treturn (await getDb().select(userOrganizationSelect()).from(organizationUsers).innerJoin(organizations, eq(organizationUsers.organizationId, organizations.id)).where(activeOrganizationUserFilter(userId, organizationId)).limit(1))[0];\n}\nasync function updateOrganizationActive(organizationId, input) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\treturn (await db.update(organizations).set({\n\t\tbaseUrl: input.baseUrl,\n\t\truntimeId: input.runtimeId,\n\t\tupdatedAt: now\n\t}).where(eq(organizations.id, organizationId)).returning())[0];\n}\nasync function updateOrganizationFailed(organizationId, _lastError) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\treturn (await db.update(organizations).set({ updatedAt: now }).where(eq(organizations.id, organizationId)).returning())[0];\n}\nasync function updateOrganizationName(organizationId, name) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\tconst [organization] = await db.update(organizations).set({\n\t\tname,\n\t\tupdatedAt: now\n\t}).where(eq(organizations.id, organizationId)).returning();\n\tif (!organization) throw new Error(`Organization not found: ${organizationId}`);\n\treturn organization;\n}\nasync function updateOrganizationSlug(organizationId, slug) {\n\tconst db = getDb();\n\tconst parsedSlug = ClaimableOrganizationSlugSchema.parse(slug);\n\tif (await isOrganizationSlugTaken(parsedSlug, organizationId)) throw new OrganizationSlugTakenError();\n\tconst now = /* @__PURE__ */ new Date();\n\ttry {\n\t\tconst [organization] = await db.update(organizations).set({\n\t\t\tslug: parsedSlug,\n\t\t\tupdatedAt: now\n\t\t}).where(eq(organizations.id, organizationId)).returning();\n\t\tif (!organization) throw new Error(`Organization not found: ${organizationId}`);\n\t\treturn organization;\n\t} catch (error) {\n\t\tif (isOrganizationSlugUniqueViolation(error)) throw new OrganizationSlugTakenError();\n\t\tthrow error;\n\t}\n}\nvar OrganizationSlugTakenError = class extends Error {\n\tconstructor() {\n\t\tsuper(ORGANIZATION_SLUG_TAKEN_MESSAGE);\n\t\tthis.name = \"OrganizationSlugTakenError\";\n\t}\n};\nfunction isOrganizationSlugUniqueViolation(error) {\n\tif (typeof error !== \"object\" || error === null) return false;\n\tif ((\"code\" in error ? String(error.code) : \"\") === \"23505\") return true;\n\treturn (\"message\" in error ? String(error.message) : \"\").includes(\"organizations_slug_unique\");\n}\nasync function resolveNewOrganizationIdentity(name, preferredSlug) {\n\tconst trimmedName = name.trim();\n\tif (!trimmedName) throw new Error(\"Organization name is required\");\n\tconst organizationId = crypto.randomUUID();\n\tconst autoSlug = slugifyOrganizationName(trimmedName);\n\tconst requestedSlug = preferredSlug?.trim() ? normalizeOrganizationSlugInput(trimmedName, preferredSlug) : autoSlug;\n\treturn {\n\t\torganizationId,\n\t\tslug: Boolean(preferredSlug?.trim()) ? await (async () => {\n\t\t\tif (await isOrganizationSlugTaken(requestedSlug)) throw new OrganizationSlugTakenError();\n\t\t\treturn requestedSlug;\n\t\t})() : await resolveAvailableOrganizationSlug(trimmedName, requestedSlug)\n\t};\n}\nasync function createOrganizationForUser(userId, name, preferredSlug, options = {}) {\n\tconst db = getDb();\n\tconst trimmedName = name.trim();\n\tif (!trimmedName) throw new Error(\"Organization name is required\");\n\tconst { organizationId, slug } = options.organizationId && options.slug ? {\n\t\torganizationId: options.organizationId,\n\t\tslug: options.slug\n\t} : await resolveNewOrganizationIdentity(trimmedName, preferredSlug);\n\tconst now = /* @__PURE__ */ new Date();\n\tconst database = await provisionOrgDatabase(organizationId);\n\ttry {\n\t\treturn await db.transaction(async (tx) => {\n\t\t\tconst [organization] = await tx.insert(organizations).values({\n\t\t\t\tid: organizationId,\n\t\t\t\tname: trimmedName,\n\t\t\t\tslug,\n\t\t\t\tdbSchema: database.dbSchema,\n\t\t\t\tdbUser: database.dbUser,\n\t\t\t\tdbPasswordCiphertext: database.dbPasswordCiphertext,\n\t\t\t\thostingAppName: options.hostingAppName ?? null,\n\t\t\t\tstorageBucket: options.storage?.bucket ?? null,\n\t\t\t\tstorageEndpoint: options.storage?.endpoint ?? null,\n\t\t\t\tstorageAccessKeyIdCiphertext: options.storage?.accessKeyIdCiphertext ?? null,\n\t\t\t\tstorageSecretAccessKeyCiphertext: options.storage?.secretAccessKeyCiphertext ?? null,\n\t\t\t\tstorageRegion: options.storage?.region ?? null,\n\t\t\t\tstorageForcePathStyle: options.storage?.forcePathStyle ?? null,\n\t\t\t\tcreatedAt: now,\n\t\t\t\tupdatedAt: now\n\t\t\t}).returning();\n\t\t\tawait tx.insert(organizationUsers).values({\n\t\t\t\torganizationId,\n\t\t\t\tuserId,\n\t\t\t\trole: \"owner\",\n\t\t\t\tstatus: \"active\",\n\t\t\t\tcreatedAt: now,\n\t\t\t\tupdatedAt: now\n\t\t\t});\n\t\t\tif (!organization) throw new Error(\"Failed to create organization\");\n\t\t\tawait ensureDefaultProjectForUserInTransaction(tx, userId, organizationId);\n\t\t\treturn {\n\t\t\t\torganization,\n\t\t\t\trole: \"owner\"\n\t\t\t};\n\t\t});\n\t} catch (error) {\n\t\tawait deprovisionOrgDatabase(database).catch(() => void 0);\n\t\tif (isOrganizationSlugUniqueViolation(error)) throw new OrganizationSlugTakenError();\n\t\tthrow error;\n\t}\n}\n//#endregion\n//#region src/queries/project-users/index.ts\nasync function selectUserProjectMembership(userId, projectId) {\n\treturn (await getDb().select().from(projectUsers).where(and$1(eq$1(projectUsers.projectId, projectId), eq$1(projectUsers.userId, userId), isNull$1(projectUsers.deletedAt))).limit(1))[0];\n}\nasync function selectProjectMembers(projectId) {\n\treturn (await getDb().select({\n\t\tid: users.id,\n\t\tprojectId: projectUsers.projectId,\n\t\tname: users.name,\n\t\temail: users.email,\n\t\trole: projectUsers.role,\n\t\torgStatus: organizationUsers.status,\n\t\timage: users.image,\n\t\tcreatedAt: projectUsers.createdAt\n\t}).from(projectUsers).innerJoin(users, eq$1(projectUsers.userId, users.id)).innerJoin(projects, eq$1(projectUsers.projectId, projects.id)).leftJoin(organizationUsers, and$1(eq$1(organizationUsers.organizationId, projects.organizationId), eq$1(organizationUsers.userId, projectUsers.userId), isNull$1(organizationUsers.deletedAt))).where(and$1(eq$1(projectUsers.projectId, projectId), isNull$1(projectUsers.deletedAt)))).map(({ orgStatus, ...row }) => ({\n\t\t...row,\n\t\tstatus: orgStatus === \"invited\" ? \"invited\" : \"active\"\n\t}));\n}\nasync function selectProjectIdsForUser(organizationId, userId) {\n\treturn (await getDb().select({ projectId: projectUsers.projectId }).from(projectUsers).innerJoin(projects, eq$1(projectUsers.projectId, projects.id)).where(and$1(eq$1(projects.organizationId, organizationId), eq$1(projectUsers.userId, userId), isNull$1(projectUsers.deletedAt), isNull$1(projects.deletedAt)))).map((row) => row.projectId);\n}\nasync function upsertProjectMember(input) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\tconst [existing] = await db.select().from(projectUsers).where(and$1(eq$1(projectUsers.projectId, input.projectId), eq$1(projectUsers.userId, input.userId))).limit(1);\n\tif (!existing) {\n\t\tawait db.insert(projectUsers).values({\n\t\t\tprojectId: input.projectId,\n\t\t\tuserId: input.userId,\n\t\t\trole: input.role,\n\t\t\tstatus: \"active\",\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now\n\t\t});\n\t\treturn;\n\t}\n\tawait db.update(projectUsers).set({\n\t\trole: input.role,\n\t\tstatus: \"active\",\n\t\tupdatedAt: now,\n\t\tdeletedAt: null\n\t}).where(and$1(eq$1(projectUsers.projectId, input.projectId), eq$1(projectUsers.userId, input.userId)));\n}\nasync function updateProjectMemberRole(projectId, userId, role) {\n\tif (!await selectUserProjectMembership(userId, projectId)) throw new ProjectMemberNotFoundError();\n\tconst now = /* @__PURE__ */ new Date();\n\tawait getDb().update(projectUsers).set({\n\t\trole,\n\t\tupdatedAt: now\n\t}).where(and$1(eq$1(projectUsers.projectId, projectId), eq$1(projectUsers.userId, userId), isNull$1(projectUsers.deletedAt)));\n\tconst [member] = (await selectProjectMembers(projectId)).filter((row) => row.id === userId);\n\tif (!member) throw new ProjectMemberNotFoundError();\n\treturn member;\n}\nasync function removeProjectMember(projectId, userId) {\n\tif (!await selectUserProjectMembership(userId, projectId)) throw new ProjectMemberNotFoundError();\n\tconst now = /* @__PURE__ */ new Date();\n\tawait getDb().update(projectUsers).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(and$1(eq$1(projectUsers.projectId, projectId), eq$1(projectUsers.userId, userId), isNull$1(projectUsers.deletedAt)));\n}\nasync function backfillProjectUsers() {\n\tconst activeProjects = await getDb().select({\n\t\tid: projects.id,\n\t\tcreatedByUserId: projects.createdByUserId\n\t}).from(projects).where(isNull$1(projects.deletedAt));\n\tfor (const project of activeProjects) if (project.createdByUserId) await upsertProjectMember({\n\t\tprojectId: project.id,\n\t\tuserId: project.createdByUserId,\n\t\trole: \"admin\"\n\t});\n}\nasync function inviteProjectMembers(input) {\n\tconst seen = /* @__PURE__ */ new Set();\n\tconst results = [];\n\tconst db = getDb();\n\tfor (const rawEmail of input.emails) {\n\t\tconst normalized = normalizeUserEmail(rawEmail);\n\t\tif (seen.has(normalized)) continue;\n\t\tseen.add(normalized);\n\t\tif (!/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(normalized)) {\n\t\t\tresults.push({\n\t\t\t\temail: rawEmail.trim(),\n\t\t\t\tstatus: \"invalid\"\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst [orgUser] = await db.select({ userId: organizationUsers.userId }).from(organizationUsers).innerJoin(users, eq$1(organizationUsers.userId, users.id)).where(and$1(eq$1(organizationUsers.organizationId, input.organizationId), eq$1(users.email, normalized), inArray$1(organizationUsers.status, [\"active\", \"invited\"]), isNull$1(organizationUsers.deletedAt))).limit(1);\n\t\tif (!orgUser) {\n\t\t\tresults.push({\n\t\t\t\temail: normalized,\n\t\t\t\tstatus: \"not_org_member\"\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (await selectUserProjectMembership(orgUser.userId, input.projectId)) {\n\t\t\tresults.push({\n\t\t\t\temail: normalized,\n\t\t\t\tstatus: \"already_member\"\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tawait upsertProjectMember({\n\t\t\tprojectId: input.projectId,\n\t\t\tuserId: orgUser.userId,\n\t\t\trole: input.role\n\t\t});\n\t\tresults.push({\n\t\t\temail: normalized,\n\t\t\tstatus: \"added\"\n\t\t});\n\t}\n\treturn results;\n}\nvar ProjectMemberNotFoundError = class extends Error {\n\tconstructor(message = \"Project member not found\") {\n\t\tsuper(message);\n\t\tthis.name = \"ProjectMemberNotFoundError\";\n\t}\n};\n//#endregion\n//#region src/queries/projects/index.ts\nasync function selectProjectById(projectId) {\n\treturn (await getDb().select().from(projects).where(eq(projects.id, projectId)).limit(1))[0];\n}\nasync function selectProjectsByOrganizationId(organizationId, options) {\n\tconst db = getDb();\n\tconst grantedIds = options?.grantedProjectIds;\n\tconst conditions = [eq(projects.organizationId, organizationId), isNull(projects.deletedAt)];\n\tif (grantedIds !== void 0) {\n\t\tif (grantedIds.length === 0) return [];\n\t\tconditions.push(inArray(projects.id, grantedIds));\n\t}\n\treturn db.select().from(projects).where(and(...conditions)).orderBy(asc(projects.createdAt));\n}\nasync function selectProjectForOrganization(organizationId, projectId) {\n\treturn (await getDb().select().from(projects).where(and(eq(projects.id, projectId), eq(projects.organizationId, organizationId), isNull(projects.deletedAt))).limit(1))[0];\n}\nasync function selectProjectForOrganizationBySlug(organizationId, slug) {\n\tconst db = getDb();\n\tconst normalizedSlug = slug.trim().toLowerCase();\n\treturn (await db.select().from(projects).where(and(eq(projects.organizationId, organizationId), eq(projects.slug, normalizedSlug), isNull(projects.deletedAt))).limit(1))[0];\n}\nasync function createProjectForOrganization(organizationId, name, description, createdByUserId) {\n\tconst db = getDb();\n\tconst trimmedName = name.trim();\n\tif (!trimmedName) throw new Error(\"Project name is required\");\n\tconst trimmedDescription = description === void 0 || description === null ? null : description.trim() || null;\n\tconst now = /* @__PURE__ */ new Date();\n\tconst projectId = crypto.randomUUID();\n\tconst slug = await resolveAvailableProjectSlug(db, organizationId, trimmedName);\n\tconst [project] = await db.insert(projects).values({\n\t\tid: projectId,\n\t\torganizationId,\n\t\tname: trimmedName,\n\t\tslug,\n\t\tdescription: trimmedDescription,\n\t\tdefaultMemberRole: \"builder\",\n\t\tinvitePermission: \"admin\",\n\t\tcreatedByUserId: createdByUserId ?? null,\n\t\tstatus: \"inactive\",\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t}).returning();\n\tif (!project) throw new Error(\"Failed to create project\");\n\tif (createdByUserId) await upsertProjectMember({\n\t\tprojectId: project.id,\n\t\tuserId: createdByUserId,\n\t\trole: \"admin\"\n\t});\n\treturn project;\n}\nasync function updateProjectForOrganization(organizationId, projectId, patch) {\n\tconst existing = await selectProjectForOrganization(organizationId, projectId);\n\tif (!existing) return;\n\tconst updates = { updatedAt: /* @__PURE__ */ new Date() };\n\tif (patch.name !== void 0) {\n\t\tconst trimmedName = patch.name.trim();\n\t\tif (!trimmedName) throw new Error(\"Project name is required\");\n\t\tupdates.name = trimmedName;\n\t}\n\tif (patch.description !== void 0) updates.description = patch.description.trim() || null;\n\tconst db = getDb();\n\tif (patch.slug !== void 0) {\n\t\tconst parsedSlug = ProjectSlugSchema.parse(patch.slug.trim().toLowerCase());\n\t\tif (parsedSlug !== existing.slug) {\n\t\t\tif (await isProjectSlugTaken(db, organizationId, parsedSlug, projectId)) throw new ProjectSlugTakenError();\n\t\t\tupdates.slug = parsedSlug;\n\t\t}\n\t}\n\ttry {\n\t\treturn (await db.update(projects).set(updates).where(eq(projects.id, projectId)).returning())[0];\n\t} catch (error) {\n\t\tif (isProjectSlugUniqueViolation(error)) throw new ProjectSlugTakenError();\n\t\tthrow error;\n\t}\n}\nasync function updateProjectSettings(organizationId, projectId, patch) {\n\tif (!await selectProjectForOrganization(organizationId, projectId)) return;\n\tconst updates = { updatedAt: /* @__PURE__ */ new Date() };\n\tif (patch.description !== void 0) updates.description = patch.description.trim() || null;\n\tif (patch.defaultMemberRole !== void 0) updates.defaultMemberRole = patch.defaultMemberRole;\n\tif (patch.invitePermission !== void 0) updates.invitePermission = patch.invitePermission;\n\treturn (await getDb().update(projects).set(updates).where(eq(projects.id, projectId)).returning())[0];\n}\nasync function deleteProjectForOrganization(organizationId, projectId) {\n\tif (!await selectProjectForOrganization(organizationId, projectId)) return;\n\tconst now = /* @__PURE__ */ new Date();\n\treturn (await getDb().update(projects).set({\n\t\tdeletedAt: now,\n\t\tupdatedAt: now\n\t}).where(eq(projects.id, projectId)).returning())[0];\n}\nasync function updateProjectActive(projectId, input) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\treturn (await db.update(projects).set({\n\t\tstatus: \"active\",\n\t\tbaseUrl: input.baseUrl,\n\t\truntimeId: input.runtimeId,\n\t\tlastError: null,\n\t\tupdatedAt: now\n\t}).where(eq(projects.id, projectId)).returning())[0];\n}\nasync function updateProjectFailed(projectId, lastError) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\treturn (await db.update(projects).set({\n\t\tstatus: \"failed\",\n\t\tlastError,\n\t\tupdatedAt: now\n\t}).where(eq(projects.id, projectId)).returning())[0];\n}\n//#endregion\n//#region src/standalone/default-org.ts\nconst DEFAULT_STANDALONE_ORGANIZATION_ID = \"default\";\nconst DEFAULT_STANDALONE_ORGANIZATION_SLUG = \"default\";\nconst DEFAULT_STANDALONE_ORGANIZATION_NAME = \"Default Organization\";\nconst DEFAULT_STANDALONE_PROJECT_NAME = \"Default Project\";\nconst DEFAULT_STANDALONE_PROJECT_SLUG = \"default\";\nfunction isStandaloneMode(env = process.env) {\n\treturn env.KEYSTROKE_APP_MODE === \"standalone\" || env.KEYSTROKE_STANDALONE === \"1\";\n}\nasync function ensureDefaultOrganization() {\n\tconst organizationId = DEFAULT_STANDALONE_ORGANIZATION_ID;\n\tif (await selectOrganizationById(organizationId)) return { organizationId };\n\tconst now = /* @__PURE__ */ new Date();\n\tconst provisioned = await provisionOrgDatabase(organizationId);\n\tif (isSqliteDialect()) await getSqliteDb().insert(organizationsSqlite).values({\n\t\tid: organizationId,\n\t\tname: DEFAULT_STANDALONE_ORGANIZATION_NAME,\n\t\tslug: DEFAULT_STANDALONE_ORGANIZATION_SLUG,\n\t\tdbSchema: provisioned.dbSchema,\n\t\tdbUser: provisioned.dbUser,\n\t\tdbPasswordCiphertext: provisioned.dbPasswordCiphertext,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now,\n\t\tverifiedAt: now\n\t});\n\telse await getDb().insert(organizations).values({\n\t\tid: organizationId,\n\t\tname: DEFAULT_STANDALONE_ORGANIZATION_NAME,\n\t\tslug: DEFAULT_STANDALONE_ORGANIZATION_SLUG,\n\t\tdbSchema: provisioned.dbSchema,\n\t\tdbUser: provisioned.dbUser,\n\t\tdbPasswordCiphertext: provisioned.dbPasswordCiphertext,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now,\n\t\tverifiedAt: now\n\t});\n\treturn { organizationId };\n}\nasync function ensureDefaultProject(organizationId) {\n\tconst projectId = DEFAULT_PROJECT_ID;\n\tif (await selectProjectForOrganization(organizationId, projectId)) return { projectId };\n\tconst now = /* @__PURE__ */ new Date();\n\tif (isSqliteDialect()) await getSqliteDb().insert(projectsSqlite).values({\n\t\tid: projectId,\n\t\torganizationId,\n\t\tname: DEFAULT_STANDALONE_PROJECT_NAME,\n\t\tslug: DEFAULT_STANDALONE_PROJECT_SLUG,\n\t\tdescription: \"Default standalone project\",\n\t\tdefaultMemberRole: \"builder\",\n\t\tinvitePermission: \"admin\",\n\t\tstatus: \"inactive\",\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t});\n\telse await getDb().insert(projects).values({\n\t\tid: projectId,\n\t\torganizationId,\n\t\tname: DEFAULT_STANDALONE_PROJECT_NAME,\n\t\tslug: DEFAULT_STANDALONE_PROJECT_SLUG,\n\t\tdescription: \"Default standalone project\",\n\t\tdefaultMemberRole: \"builder\",\n\t\tinvitePermission: \"admin\",\n\t\tstatus: \"inactive\",\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t});\n\treturn { projectId };\n}\nasync function ensureDefaultOrganizationAndProject() {\n\tconst { organizationId } = await ensureDefaultOrganization();\n\tconst { projectId } = await ensureDefaultProject(organizationId);\n\treturn {\n\t\torganizationId,\n\t\tprojectId\n\t};\n}\nasync function runWithStandaloneScope(fn) {\n\tconst { organizationId, projectId } = await ensureDefaultOrganizationAndProject();\n\treturn runWithOrganizationScope(organizationId, () => runWithTenantScope(organizationId, () => runWithProjectScope(projectId, fn)));\n}\n//#endregion\n//#region src/queries/api-keys/index.ts\nasync function selectApiKeyByConfigName(configId, name) {\n\treturn (await getDb().select().from(authApiKeys).where(and$1(eq$1(authApiKeys.configId, configId), eq$1(authApiKeys.name, name))).limit(1))[0];\n}\nasync function selectApiKeyById(id) {\n\treturn (await getDb().select().from(authApiKeys).where(eq$1(authApiKeys.id, id)).limit(1))[0];\n}\nasync function selectApiKeyByConfigAndHash(configId, keyHash) {\n\treturn (await getDb().select().from(authApiKeys).where(and$1(eq$1(authApiKeys.configId, configId), eq$1(authApiKeys.key, keyHash))).limit(1))[0];\n}\nasync function listApiKeysByConfigId(configId) {\n\treturn getDb().select().from(authApiKeys).where(eq$1(authApiKeys.configId, configId));\n}\nasync function listApiKeysByConfigReferenceId(configId, referenceId) {\n\treturn getDb().select().from(authApiKeys).where(and$1(eq$1(authApiKeys.configId, configId), eq$1(authApiKeys.referenceId, referenceId)));\n}\nasync function insertApiKey(values) {\n\tif (isSqliteDialect()) {\n\t\tawait getSqliteDb().insert(authApiKeysSqlite).values(values);\n\t\treturn;\n\t}\n\tawait getDb().insert(authApiKeys).values(values);\n}\nasync function deleteApiKeyById(id) {\n\tawait getDb().delete(authApiKeys).where(eq$1(authApiKeys.id, id));\n}\n//#endregion\n//#region src/queries/members/errors.ts\nvar OrganizationMemberMutationError = class extends Error {\n\tcode;\n\tconstructor(code, message) {\n\t\tsuper(message);\n\t\tthis.name = \"OrganizationMemberMutationError\";\n\t\tthis.code = code;\n\t}\n};\nvar CannotModifyOwnerError = class extends OrganizationMemberMutationError {\n\tconstructor(message = \"Organization owners cannot be modified this way\") {\n\t\tsuper(\"cannot_modify_owner\", message);\n\t}\n};\nvar LastOwnerError = class extends OrganizationMemberMutationError {\n\tconstructor(message = \"The organization must have at least one owner\") {\n\t\tsuper(\"last_owner\", message);\n\t}\n};\nvar OrganizationMemberNotFoundError = class extends OrganizationMemberMutationError {\n\tconstructor(message = \"Member not found\") {\n\t\tsuper(\"member_not_found\", message);\n\t}\n};\n//#endregion\n//#region src/queries/members/index.ts\nconst INVITATION_TTL_MS = 336 * 60 * 60 * 1e3;\nasync function selectOrganizationMembers(organizationId) {\n\treturn getDb().select({\n\t\tid: users.id,\n\t\tname: users.name,\n\t\temail: users.email,\n\t\trole: organizationUsers.role,\n\t\tstatus: organizationUsers.status,\n\t\timage: users.image,\n\t\tcreatedAt: organizationUsers.createdAt\n\t}).from(organizationUsers).innerJoin(users, eq$1(organizationUsers.userId, users.id)).where(and$1(eq$1(organizationUsers.organizationId, organizationId), isNull$1(organizationUsers.deletedAt)));\n}\nasync function selectOrganizationMembership(organizationId, userId) {\n\treturn (await getDb().select().from(organizationUsers).where(and$1(eq$1(organizationUsers.organizationId, organizationId), eq$1(organizationUsers.userId, userId), isNull$1(organizationUsers.deletedAt))).limit(1))[0];\n}\nasync function selectPendingInvitation(organizationId, userId) {\n\treturn (await getDb().select().from(organizationInvitations).where(and$1(eq$1(organizationInvitations.organizationId, organizationId), eq$1(organizationInvitations.userId, userId), eq$1(organizationInvitations.status, \"pending\"))).limit(1))[0];\n}\nfunction isValidInviteEmail(email) {\n\treturn /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email);\n}\nasync function inviteOrganizationMembers(input) {\n\tconst seen = /* @__PURE__ */ new Set();\n\tconst results = [];\n\tfor (const rawEmail of input.emails) {\n\t\tconst normalized = normalizeUserEmail(rawEmail);\n\t\tif (seen.has(normalized)) continue;\n\t\tseen.add(normalized);\n\t\tif (!isValidInviteEmail(normalized)) {\n\t\t\tresults.push({\n\t\t\t\temail: rawEmail.trim(),\n\t\t\t\tstatus: \"invalid\"\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst user = await findOrCreateUserByEmail(normalized);\n\t\tif ((await selectOrganizationMembership(input.organizationId, user.id))?.status === \"active\") {\n\t\t\tresults.push({\n\t\t\t\temail: normalized,\n\t\t\t\tstatus: \"already_member\"\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst pending = await selectPendingInvitation(input.organizationId, user.id);\n\t\tif (pending) {\n\t\t\tresults.push({\n\t\t\t\temail: normalized,\n\t\t\t\tstatus: \"pending\",\n\t\t\t\tinvitationId: pending.id\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst now = /* @__PURE__ */ new Date();\n\t\tconst db = getDb();\n\t\tconst invitationId = crypto.randomUUID();\n\t\ttry {\n\t\t\tawait db.transaction(async (tx) => {\n\t\t\t\tawait tx.insert(organizationInvitations).values({\n\t\t\t\t\tid: invitationId,\n\t\t\t\t\torganizationId: input.organizationId,\n\t\t\t\t\tuserId: user.id,\n\t\t\t\t\temail: normalized,\n\t\t\t\t\trole: input.role,\n\t\t\t\t\tstatus: \"pending\",\n\t\t\t\t\tinvitedByUserId: input.invitedByUserId,\n\t\t\t\t\tcreatedAt: now,\n\t\t\t\t\tupdatedAt: now,\n\t\t\t\t\texpiresAt: new Date(now.getTime() + INVITATION_TTL_MS)\n\t\t\t\t});\n\t\t\t\tconst [existing] = await tx.select().from(organizationUsers).where(and$1(eq$1(organizationUsers.organizationId, input.organizationId), eq$1(organizationUsers.userId, user.id))).limit(1);\n\t\t\t\tif (!existing) await tx.insert(organizationUsers).values({\n\t\t\t\t\torganizationId: input.organizationId,\n\t\t\t\t\tuserId: user.id,\n\t\t\t\t\trole: input.role,\n\t\t\t\t\tstatus: \"invited\",\n\t\t\t\t\tcreatedAt: now,\n\t\t\t\t\tupdatedAt: now\n\t\t\t\t});\n\t\t\t\telse await tx.update(organizationUsers).set({\n\t\t\t\t\trole: input.role,\n\t\t\t\t\tstatus: \"invited\",\n\t\t\t\t\tupdatedAt: now,\n\t\t\t\t\tdeletedAt: null\n\t\t\t\t}).where(and$1(eq$1(organizationUsers.organizationId, input.organizationId), eq$1(organizationUsers.userId, user.id)));\n\t\t\t});\n\t\t\tresults.push({\n\t\t\t\temail: normalized,\n\t\t\t\tstatus: \"sent\",\n\t\t\t\tinvitationId\n\t\t\t});\n\t\t} catch {\n\t\t\tconst raced = await selectPendingInvitation(input.organizationId, user.id);\n\t\t\tresults.push({\n\t\t\t\temail: normalized,\n\t\t\t\tstatus: raced ? \"pending\" : \"sent\",\n\t\t\t\tinvitationId: raced?.id ?? invitationId\n\t\t\t});\n\t\t}\n\t}\n\treturn results;\n}\nfunction isEditableOrganizationMemberStatus(status) {\n\treturn status === \"active\" || status === \"invited\";\n}\nasync function updateOrganizationMemberRole(organizationId, userId, role) {\n\tconst membership = await selectOrganizationMembership(organizationId, userId);\n\tif (!membership || !isEditableOrganizationMemberStatus(membership.status)) throw new OrganizationMemberNotFoundError();\n\tif (membership.role === \"owner\") throw new CannotModifyOwnerError();\n\tconst now = /* @__PURE__ */ new Date();\n\tawait getDb().transaction(async (tx) => {\n\t\tawait tx.update(organizationUsers).set({\n\t\t\trole,\n\t\t\tupdatedAt: now\n\t\t}).where(and$1(eq$1(organizationUsers.organizationId, organizationId), eq$1(organizationUsers.userId, userId), isNull$1(organizationUsers.deletedAt)));\n\t\tif (membership.status === \"invited\") await tx.update(organizationInvitations).set({\n\t\t\trole,\n\t\t\tupdatedAt: now\n\t\t}).where(and$1(eq$1(organizationInvitations.organizationId, organizationId), eq$1(organizationInvitations.userId, userId), eq$1(organizationInvitations.status, \"pending\")));\n\t});\n\tconst [member] = await selectOrganizationMembers(organizationId).then((rows) => rows.filter((row) => row.id === userId));\n\tif (!member) throw new OrganizationMemberNotFoundError();\n\treturn member;\n}\nasync function removeOrganizationMember(organizationId, userId) {\n\tconst membership = await selectOrganizationMembership(organizationId, userId);\n\tif (!membership) throw new OrganizationMemberNotFoundError();\n\tif (membership.role === \"owner\" && membership.status === \"active\") throw new CannotModifyOwnerError(\"Organization owners cannot be removed\");\n\tif (membership.status === \"suspended\") return;\n\tconst now = /* @__PURE__ */ new Date();\n\tawait getDb().transaction(async (tx) => {\n\t\tif (membership.status === \"invited\") await tx.update(organizationInvitations).set({\n\t\t\tstatus: \"declined\",\n\t\t\tupdatedAt: now\n\t\t}).where(and$1(eq$1(organizationInvitations.organizationId, organizationId), eq$1(organizationInvitations.userId, userId), eq$1(organizationInvitations.status, \"pending\")));\n\t\tawait tx.update(organizationUsers).set({\n\t\t\tstatus: \"suspended\",\n\t\t\tupdatedAt: now,\n\t\t\tdeletedAt: null\n\t\t}).where(and$1(eq$1(organizationUsers.organizationId, organizationId), eq$1(organizationUsers.userId, userId), isNull$1(organizationUsers.deletedAt)));\n\t});\n}\n//#endregion\n//#region src/queries/invitations/index.ts\nvar OrganizationInvitationNotFoundError = class extends Error {\n\tconstructor(message = \"Invitation not found\") {\n\t\tsuper(message);\n\t\tthis.name = \"OrganizationInvitationNotFoundError\";\n\t}\n};\nvar OrganizationInvitationForbiddenError = class extends Error {\n\tconstructor(message = \"Forbidden\") {\n\t\tsuper(message);\n\t\tthis.name = \"OrganizationInvitationForbiddenError\";\n\t}\n};\nvar OrganizationInvitationExpiredError = class extends Error {\n\tconstructor(message = \"Invitation has expired\") {\n\t\tsuper(message);\n\t\tthis.name = \"OrganizationInvitationExpiredError\";\n\t}\n};\nasync function selectInvitationById(invitationId) {\n\treturn (await getDb().select().from(organizationInvitations).where(eq$1(organizationInvitations.id, invitationId)).limit(1))[0];\n}\nfunction isInvitationExpired(invitation, now = /* @__PURE__ */ new Date()) {\n\treturn invitation.expiresAt !== null && invitation.expiresAt.getTime() <= now.getTime();\n}\nasync function selectPendingInvitationsForUser(userId) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\treturn db.select({\n\t\tid: organizationInvitations.id,\n\t\torganizationName: organizations.name,\n\t\torganizationSlug: organizations.slug,\n\t\trole: organizationInvitations.role,\n\t\tinvitedByName: users.name,\n\t\tinvitedByEmail: users.email\n\t}).from(organizationInvitations).innerJoin(organizations, eq$1(organizationInvitations.organizationId, organizations.id)).innerJoin(users, eq$1(organizationInvitations.invitedByUserId, users.id)).where(and$1(eq$1(organizationInvitations.userId, userId), eq$1(organizationInvitations.status, \"pending\"), or(isNull$1(organizationInvitations.expiresAt), gt(organizationInvitations.expiresAt, now))));\n}\nasync function acceptInvitation(invitationId, userId) {\n\tconst invitation = await selectInvitationById(invitationId);\n\tif (!invitation || invitation.status !== \"pending\") throw new OrganizationInvitationNotFoundError();\n\tif (invitation.userId !== userId) throw new OrganizationInvitationForbiddenError();\n\tif (isInvitationExpired(invitation)) throw new OrganizationInvitationExpiredError();\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\tawait db.transaction(async (tx) => {\n\t\tconst [existing] = await tx.select().from(organizationUsers).where(and$1(eq$1(organizationUsers.organizationId, invitation.organizationId), eq$1(organizationUsers.userId, userId))).limit(1);\n\t\tif (!existing) await tx.insert(organizationUsers).values({\n\t\t\torganizationId: invitation.organizationId,\n\t\t\tuserId,\n\t\t\trole: invitation.role,\n\t\t\tstatus: \"active\",\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now\n\t\t});\n\t\telse await tx.update(organizationUsers).set({\n\t\t\trole: existing.role === \"owner\" ? \"owner\" : invitation.role,\n\t\t\tstatus: \"active\",\n\t\t\tupdatedAt: now,\n\t\t\tdeletedAt: null\n\t\t}).where(and$1(eq$1(organizationUsers.organizationId, invitation.organizationId), eq$1(organizationUsers.userId, userId)));\n\t\tawait ensureDefaultProjectForUserInTransaction(tx, userId, invitation.organizationId);\n\t\tawait tx.update(organizationInvitations).set({\n\t\t\tstatus: \"accepted\",\n\t\t\tupdatedAt: now\n\t\t}).where(eq$1(organizationInvitations.id, invitationId));\n\t});\n\tconst membership = await selectUserOrganizationMembership(userId, invitation.organizationId);\n\tif (!membership) throw new OrganizationMemberNotFoundError(\"Failed to load membership after accept\");\n\treturn membership;\n}\nasync function declineInvitation(invitationId, userId) {\n\tconst invitation = await selectInvitationById(invitationId);\n\tif (!invitation || invitation.status !== \"pending\") throw new OrganizationInvitationNotFoundError();\n\tif (invitation.userId !== userId) throw new OrganizationInvitationForbiddenError();\n\tconst now = /* @__PURE__ */ new Date();\n\tawait getDb().transaction(async (tx) => {\n\t\tawait tx.update(organizationUsers).set({\n\t\t\tstatus: \"rejected\",\n\t\t\tupdatedAt: now\n\t\t}).where(and$1(eq$1(organizationUsers.organizationId, invitation.organizationId), eq$1(organizationUsers.userId, userId), isNull$1(organizationUsers.deletedAt)));\n\t\tawait tx.update(organizationInvitations).set({\n\t\t\tstatus: \"declined\",\n\t\t\tupdatedAt: now\n\t\t}).where(eq$1(organizationInvitations.id, invitationId));\n\t});\n}\n//#endregion\n//#region src/queries/organization-users/index.ts\nasync function selectOrganizationUsersByUserId(userId) {\n\treturn getDb().select().from(organizationUsers).where(eq(organizationUsers.userId, userId));\n}\n//#endregion\n//#region src/queries/project-artifacts/complete-promote.ts\n/** Mark artifact ready and stage it as pending — does not flip activeArtifactId or sync registry. */\nasync function completeProjectArtifact(input) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\tif (isSqliteDialect()) {\n\t\tconst [artifact] = await db.update(projectArtifacts).set({\n\t\t\tstatus: \"ready\",\n\t\t\tmanifestJson: input.manifestJson ?? null,\n\t\t\tupdatedAt: now\n\t\t}).where(and(eq(projectArtifacts.id, input.artifactId), eq(projectArtifacts.projectId, input.projectId), eq(projectArtifacts.status, \"pending\"))).returning();\n\t\tif (!artifact) throw new Error(\"Artifact not found or already completed\");\n\t\tconst [project] = await db.update(projects).set({\n\t\t\tpendingArtifactId: artifact.id,\n\t\t\tstatus: \"starting\",\n\t\t\tlastError: null,\n\t\t\tupdatedAt: now\n\t\t}).where(eq(projects.id, input.projectId)).returning();\n\t\tif (!project) throw new Error(\"Project not found\");\n\t\treturn {\n\t\t\tartifact,\n\t\t\tproject\n\t\t};\n\t}\n\treturn db.transaction(async (tx) => {\n\t\tconst [artifact] = await tx.update(projectArtifacts).set({\n\t\t\tstatus: \"ready\",\n\t\t\tmanifestJson: input.manifestJson ?? null,\n\t\t\tupdatedAt: now\n\t\t}).where(and(eq(projectArtifacts.id, input.artifactId), eq(projectArtifacts.projectId, input.projectId), eq(projectArtifacts.status, \"pending\"))).returning();\n\t\tif (!artifact) throw new Error(\"Artifact not found or already completed\");\n\t\tconst [project] = await tx.update(projects).set({\n\t\t\tpendingArtifactId: artifact.id,\n\t\t\tstatus: \"starting\",\n\t\t\tlastError: null,\n\t\t\tupdatedAt: now\n\t\t}).where(eq(projects.id, input.projectId)).returning();\n\t\tif (!project) throw new Error(\"Project not found\");\n\t\treturn {\n\t\t\tartifact,\n\t\t\tproject\n\t\t};\n\t});\n}\n/** Cut over live deploy to a staged artifact after the new runtime is healthy. */\nasync function promoteProjectArtifact(input) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\tif (isSqliteDialect()) {\n\t\tconst [project] = await db.select().from(projects).where(eq(projects.id, input.projectId)).limit(1);\n\t\tif (!project) throw new Error(\"Project not found\");\n\t\tif (project.pendingArtifactId !== input.artifactId) throw new Error(\"Artifact is not the pending deploy for this project\");\n\t\tconst [artifact] = await db.select().from(projectArtifacts).where(and(eq(projectArtifacts.id, input.artifactId), eq(projectArtifacts.projectId, input.projectId), eq(projectArtifacts.status, \"ready\"))).limit(1);\n\t\tif (!artifact) throw new Error(\"Pending artifact not found or not ready\");\n\t\tconst [updatedProject] = await db.update(projects).set({\n\t\t\tactiveArtifactId: artifact.id,\n\t\t\tpendingArtifactId: null,\n\t\t\tupdatedAt: now\n\t\t}).where(eq(projects.id, input.projectId)).returning();\n\t\tif (!updatedProject) throw new Error(\"Project not found\");\n\t\treturn {\n\t\t\tartifact,\n\t\t\tproject: updatedProject\n\t\t};\n\t}\n\treturn db.transaction(async (tx) => {\n\t\tconst [project] = await tx.select().from(projects).where(eq(projects.id, input.projectId)).limit(1);\n\t\tif (!project) throw new Error(\"Project not found\");\n\t\tif (project.pendingArtifactId !== input.artifactId) throw new Error(\"Artifact is not the pending deploy for this project\");\n\t\tconst [artifact] = await tx.select().from(projectArtifacts).where(and(eq(projectArtifacts.id, input.artifactId), eq(projectArtifacts.projectId, input.projectId), eq(projectArtifacts.status, \"ready\"))).limit(1);\n\t\tif (!artifact) throw new Error(\"Pending artifact not found or not ready\");\n\t\tconst [updatedProject] = await tx.update(projects).set({\n\t\t\tactiveArtifactId: artifact.id,\n\t\t\tpendingArtifactId: null,\n\t\t\tupdatedAt: now\n\t\t}).where(eq(projects.id, input.projectId)).returning();\n\t\tif (!updatedProject) throw new Error(\"Project not found\");\n\t\treturn {\n\t\t\tartifact,\n\t\t\tproject: updatedProject\n\t\t};\n\t});\n}\nasync function updateProjectArtifactManifest(input) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\tconst [artifact] = await db.update(projectArtifacts).set({\n\t\tmanifestJson: input.manifestJson,\n\t\tupdatedAt: now\n\t}).where(eq(projectArtifacts.id, input.artifactId)).returning();\n\tif (!artifact) throw new Error(\"Artifact not found\");\n\treturn artifact;\n}\n/** Attach a deploy's source manifest (file tree) to its artifact. */\nasync function updateProjectArtifactSourceManifest(input) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\tconst [artifact] = await db.update(projectArtifacts).set({\n\t\tsourceManifestJson: input.sourceManifestJson,\n\t\tupdatedAt: now\n\t}).where(and(eq(projectArtifacts.id, input.artifactId), eq(projectArtifacts.projectId, input.projectId))).returning();\n\tif (!artifact) throw new Error(\"Artifact not found\");\n\treturn artifact;\n}\n//#endregion\n//#region src/queries/project-artifacts/last-deployment.ts\n/** Latest ready artifact timestamp per project for an organization. */\nasync function selectLastDeploymentAtByProject(organizationId) {\n\tconst rows = await getDb().select({\n\t\tprojectId: projectArtifacts.projectId,\n\t\tlastDeploymentAt: max(projectArtifacts.updatedAt)\n\t}).from(projectArtifacts).innerJoin(projects, eq(projects.id, projectArtifacts.projectId)).where(and(eq(projects.organizationId, organizationId), isNull(projects.deletedAt), eq(projectArtifacts.status, \"ready\"))).groupBy(projectArtifacts.projectId);\n\tconst result = {};\n\tfor (const row of rows) if (row.lastDeploymentAt) result[row.projectId] = row.lastDeploymentAt;\n\treturn result;\n}\n//#endregion\n//#region src/queries/project-artifacts/deployments.ts\n/** Ready artifact deploy history for a project, newest first. */\nasync function selectProjectDeployments(projectId) {\n\treturn (await getDb().select({\n\t\tid: projectArtifacts.id,\n\t\tprojectId: projectArtifacts.projectId,\n\t\tversion: projectArtifacts.version,\n\t\tcreatedAt: projectArtifacts.createdAt,\n\t\tactiveArtifactId: projects.activeArtifactId,\n\t\tdeployedByName: users.name,\n\t\tdeployedByEmail: users.email,\n\t\tdeployedByAvatarUrl: users.image\n\t}).from(projectArtifacts).innerJoin(projects, eq(projects.id, projectArtifacts.projectId)).leftJoin(users, eq(users.id, projectArtifacts.createdByUserId)).where(and(eq(projectArtifacts.projectId, projectId), eq(projectArtifacts.status, \"ready\"))).orderBy(desc(projectArtifacts.createdAt))).map((row) => ({\n\t\tid: row.id,\n\t\tprojectId: row.projectId,\n\t\tversion: row.version,\n\t\tcreatedAt: row.createdAt,\n\t\tactive: row.activeArtifactId === row.id,\n\t\tdeployedByName: row.deployedByName,\n\t\tdeployedByEmail: row.deployedByEmail,\n\t\tdeployedByAvatarUrl: row.deployedByAvatarUrl\n\t}));\n}\n//#endregion\n//#region src/queries/project-artifacts/index.ts\nasync function insertProjectArtifact(input) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\tconst [versionRow] = await db.select({ maxVersion: max(projectArtifacts.version) }).from(projectArtifacts).where(eq(projectArtifacts.projectId, input.projectId));\n\tconst version = (versionRow?.maxVersion ?? 0) + 1;\n\tconst [row] = await db.insert(projectArtifacts).values({\n\t\tid: input.id,\n\t\tprojectId: input.projectId,\n\t\tstorageKey: input.storageKey,\n\t\tversion,\n\t\tcreatedByUserId: input.createdByUserId ?? null,\n\t\tstatus: \"pending\",\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t}).returning();\n\tif (!row) throw new Error(\"Failed to create project artifact\");\n\treturn row;\n}\nasync function selectProjectArtifactById(artifactId) {\n\treturn (await getDb().select().from(projectArtifacts).where(eq(projectArtifacts.id, artifactId)).limit(1))[0];\n}\nasync function selectProjectArtifactForProject(artifactId, projectId) {\n\treturn (await getDb().select().from(projectArtifacts).where(and(eq(projectArtifacts.id, artifactId), eq(projectArtifacts.projectId, projectId))).limit(1))[0];\n}\nasync function selectActiveProjectArtifactForProject(projectId) {\n\tconst activeArtifactId = (await getDb().select({ activeArtifactId: projects.activeArtifactId }).from(projects).where(eq(projects.id, projectId)).limit(1))[0]?.activeArtifactId;\n\tif (!activeArtifactId) return;\n\treturn selectProjectArtifactForProject(activeArtifactId, projectId);\n}\nasync function selectActiveArtifactManifestForProject(projectId) {\n\treturn (await getDb().select({ manifestJson: projectArtifacts.manifestJson }).from(projects).innerJoin(projectArtifacts, eq(projects.activeArtifactId, projectArtifacts.id)).where(eq(projects.id, projectId)).limit(1))[0]?.manifestJson ?? void 0;\n}\n/** Source manifest (file tree) for the project's currently active deploy. */\nasync function selectActiveArtifactSourceManifestForProject(projectId) {\n\treturn (await getDb().select({\n\t\tartifactId: projectArtifacts.id,\n\t\tsourceManifestJson: projectArtifacts.sourceManifestJson\n\t}).from(projects).innerJoin(projectArtifacts, eq(projects.activeArtifactId, projectArtifacts.id)).where(eq(projects.id, projectId)).limit(1))[0];\n}\n/** Runtime and source manifests for active deploys in an organization. */\nasync function selectActiveArtifactManifestsByOrganizationId(organizationId) {\n\treturn getDb().select({\n\t\tprojectId: projects.id,\n\t\tprojectUpdatedAt: projects.updatedAt,\n\t\tartifactId: projectArtifacts.id,\n\t\tartifactUpdatedAt: projectArtifacts.updatedAt,\n\t\tmanifestJson: projectArtifacts.manifestJson,\n\t\tsourceManifestJson: projectArtifacts.sourceManifestJson\n\t}).from(projects).innerJoin(projectArtifacts, eq(projects.activeArtifactId, projectArtifacts.id)).where(and(eq(projects.organizationId, organizationId), isNull(projects.deletedAt)));\n}\n//#endregion\n//#region src/api-keys/constants.ts\nconst WEBHOOK_API_KEY_CONFIG_ID = \"webhook\";\nconst ORG_PLATFORM_API_KEY_CONFIG_ID = \"org-platform\";\nfunction generateApiKeySecret(prefix = \"wh_\") {\n\treturn `${prefix}${randomBytes(32).toString(\"base64url\")}`;\n}\nfunction apiKeyStart(secret, length = 8) {\n\treturn secret.slice(0, length);\n}\nfunction encryptApiKeySecret(secret) {\n\treturn encryptCredentialPayload$1(secret);\n}\nfunction decryptApiKeySecret(ciphertext) {\n\treturn decryptCredentialPayload$1(ciphertext);\n}\nfunction hashApiKeySecret(secret) {\n\treturn createHash(\"sha256\").update(secret).digest(\"base64\");\n}\nfunction verifyApiKeySecret(secret, storedHash) {\n\tconst actual = Buffer.from(hashApiKeySecret(secret));\n\tconst expected = Buffer.from(storedHash);\n\tif (actual.length !== expected.length) return false;\n\treturn timingSafeEqual(actual, expected);\n}\n//#endregion\n//#region src/api-keys/metadata.ts\nfunction parseWebhookApiKeyMetadata(metadata) {\n\tif (!metadata) return null;\n\ttry {\n\t\tconst value = JSON.parse(metadata);\n\t\tif (value.kind !== \"trigger-webhook\" || typeof value.route !== \"string\" || typeof value.projectId !== \"string\") return null;\n\t\tconst attachmentKeys = Array.isArray(value.attachmentKeys) ? value.attachmentKeys.filter((key) => typeof key === \"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\tattachmentKeys\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\nfunction serializeWebhookApiKeyMetadata(metadata) {\n\treturn JSON.stringify(metadata);\n}\n//#endregion\n//#region src/api-keys/list.ts\nasync function listWebhookApiKeys() {\n\tconst rows = await listApiKeysByConfigId(WEBHOOK_API_KEY_CONFIG_ID);\n\tconst views = [];\n\tfor (const row of rows) {\n\t\tconst parsed = parseWebhookApiKeyMetadata(row.metadata);\n\t\tif (!parsed || !row.keyCiphertext) continue;\n\t\tviews.push({\n\t\t\tid: row.id,\n\t\t\tprojectId: parsed.projectId,\n\t\t\troute: parsed.route,\n\t\t\tname: row.name,\n\t\t\tstart: row.start,\n\t\t\tprefix: row.prefix,\n\t\t\ttoken: decryptApiKeySecret(row.keyCiphertext),\n\t\t\tattachmentKeys: parsed.attachmentKeys,\n\t\t\tcreatedAt: row.createdAt,\n\t\t\tupdatedAt: row.updatedAt\n\t\t});\n\t}\n\treturn views;\n}\nasync function listWebhookApiKeysForProject(projectId) {\n\treturn (await listWebhookApiKeys()).filter((key) => key.projectId === projectId);\n}\n//#endregion\n//#region src/api-keys/ensure.ts\nfunction webhookEndpointSuffix(route) {\n\treturn route.startsWith(\"/triggers/\") ? route.slice(10) : route;\n}\nfunction webhookApiKeyName(projectId, route) {\n\treturn `${projectId}:${webhookEndpointSuffix(route)}`;\n}\nasync function ensureWebhookApiKeys(projectId, routes, referenceId) {\n\tconst created = [];\n\tconst existing = [];\n\tfor (const { route, attachmentKeys } 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\tattachmentKeys\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, attachmentKeys) {\n\tconst created = (await ensureWebhookApiKeys(projectId, [{\n\t\troute,\n\t\tattachmentKeys\n\t}], projectId)).created.find((entry) => entry.route === route);\n\tif (created) return created.token;\n\tconst existing = (await listWebhookApiKeysForProject(projectId)).find((entry) => entry.route === route);\n\tif (!existing?.token) throw new Error(`Webhook API key not found for route ${route}`);\n\treturn existing.token;\n}\n//#endregion\n//#region src/api-keys/verify.ts\nasync function verifyWebhookApiKeyForRoute(projectId, route, secret) {\n\tconst row = await selectApiKeyByConfigName(WEBHOOK_API_KEY_CONFIG_ID, webhookApiKeyName(projectId, route));\n\tif (!row) return false;\n\treturn verifyApiKeySecret(secret, row.key);\n}\n//#endregion\n//#region src/api-keys/org-platform-metadata.ts\nfunction parseOrgPlatformApiKeyMetadata(metadata) {\n\tif (!metadata) return null;\n\ttry {\n\t\tconst value = JSON.parse(metadata);\n\t\tif (value.kind !== \"org-platform\" || typeof value.organizationId !== \"string\" || typeof value.createdByUserId !== \"string\" || typeof value.keyPreview !== \"string\") return null;\n\t\treturn {\n\t\t\tkind: \"org-platform\",\n\t\t\torganizationId: value.organizationId,\n\t\t\tcreatedByUserId: value.createdByUserId,\n\t\t\tkeyPreview: value.keyPreview\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\nfunction serializeOrgPlatformApiKeyMetadata(metadata) {\n\treturn JSON.stringify(metadata);\n}\n//#endregion\n//#region src/api-keys/org-platform.ts\nvar OrgPlatformApiKeyNotFoundError = class extends Error {\n\tconstructor() {\n\t\tsuper(\"API key not found\");\n\t\tthis.name = \"OrgPlatformApiKeyNotFoundError\";\n\t}\n};\nfunction keyPreviewFromSecret(secret) {\n\treturn `******${secret.slice(-4)}`;\n}\nfunction parseOrgPlatformRow(row) {\n\tconst metadata = parseOrgPlatformApiKeyMetadata(row.metadata);\n\tif (!metadata || row.name == null) return null;\n\treturn {\n\t\tid: row.id,\n\t\tname: row.name,\n\t\tkeyPreview: metadata.keyPreview,\n\t\tcreatedAt: row.createdAt,\n\t\tcreatedByUserId: metadata.createdByUserId\n\t};\n}\nfunction isActiveApiKey(row) {\n\tif (row.enabled === false) return false;\n\tif (row.expiresAt && row.expiresAt.getTime() <= Date.now()) return false;\n\treturn true;\n}\nasync function listOrgPlatformApiKeysForUser(organizationId, userId) {\n\tconst rows = await listApiKeysByConfigReferenceId(ORG_PLATFORM_API_KEY_CONFIG_ID, userId);\n\tconst records = [];\n\tfor (const row of rows) {\n\t\tconst metadata = parseOrgPlatformApiKeyMetadata(row.metadata);\n\t\tif (!metadata || metadata.organizationId !== organizationId || metadata.createdByUserId !== userId) continue;\n\t\tconst record = parseOrgPlatformRow(row);\n\t\tif (record) records.push(record);\n\t}\n\treturn records;\n}\nasync function listOrgPlatformApiKeysForOrganization(organizationId) {\n\tconst rows = await listApiKeysByConfigId(ORG_PLATFORM_API_KEY_CONFIG_ID);\n\tconst records = [];\n\tfor (const row of rows) {\n\t\tconst metadata = parseOrgPlatformApiKeyMetadata(row.metadata);\n\t\tif (!metadata || metadata.organizationId !== organizationId) continue;\n\t\tconst record = parseOrgPlatformRow(row);\n\t\tif (record) records.push(record);\n\t}\n\treturn records;\n}\nasync function createOrgPlatformApiKey(input) {\n\tconst secret = generateApiKeySecret(\"sk_\");\n\tconst now = /* @__PURE__ */ new Date();\n\tconst metadata = serializeOrgPlatformApiKeyMetadata({\n\t\tkind: \"org-platform\",\n\t\torganizationId: input.organizationId,\n\t\tcreatedByUserId: input.userId,\n\t\tkeyPreview: keyPreviewFromSecret(secret)\n\t});\n\tconst record = {\n\t\tid: crypto.randomUUID(),\n\t\tname: input.name,\n\t\tkeyPreview: keyPreviewFromSecret(secret),\n\t\tcreatedAt: now,\n\t\tcreatedByUserId: input.userId,\n\t\tsecret\n\t};\n\tawait insertApiKey({\n\t\tid: record.id,\n\t\tconfigId: ORG_PLATFORM_API_KEY_CONFIG_ID,\n\t\tname: input.name,\n\t\tstart: apiKeyStart(secret),\n\t\tprefix: \"sk_\",\n\t\tkey: hashApiKeySecret(secret),\n\t\tkeyCiphertext: encryptApiKeySecret(secret),\n\t\treferenceId: input.userId,\n\t\tmetadata,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t});\n\treturn record;\n}\nasync function selectOrgPlatformApiKeyForOrganization(apiKeyId, organizationId) {\n\tconst row = await selectApiKeyById(apiKeyId);\n\tif (!row || row.configId !== \"org-platform\") return null;\n\tconst record = parseOrgPlatformRow(row);\n\tif (!record) return null;\n\tif (parseOrgPlatformApiKeyMetadata(row.metadata)?.organizationId !== organizationId) return null;\n\treturn record;\n}\nasync function revokeOrgPlatformApiKey(apiKeyId, organizationId) {\n\tif (!await selectOrgPlatformApiKeyForOrganization(apiKeyId, organizationId)) throw new OrgPlatformApiKeyNotFoundError();\n\tawait deleteApiKeyById(apiKeyId);\n}\nasync function verifyOrgPlatformApiKeySecret(secret) {\n\tif (!secret.startsWith(\"sk_\")) return null;\n\tconst row = await selectApiKeyByConfigAndHash(ORG_PLATFORM_API_KEY_CONFIG_ID, hashApiKeySecret(secret));\n\tif (!row || !isActiveApiKey(row)) return null;\n\tconst metadata = parseOrgPlatformApiKeyMetadata(row.metadata);\n\tif (!metadata) return null;\n\treturn {\n\t\tapiKeyId: row.id,\n\t\torganizationId: metadata.organizationId,\n\t\tuserId: metadata.createdByUserId\n\t};\n}\nasync function loadOrgPlatformApiKeyUser(userId) {\n\treturn await selectUserById(userId) ?? null;\n}\nfunction mapOrgPlatformApiKeyCreator(user) {\n\treturn {\n\t\tid: user.id,\n\t\tname: user.name,\n\t\temail: user.email,\n\t\tavatarUrl: user.image ?? void 0\n\t};\n}\nfunction mapOrgPlatformApiKeyCreatorOrDeleted(userId, user) {\n\tif (user) return mapOrgPlatformApiKeyCreator(user);\n\treturn {\n\t\tid: userId,\n\t\tname: \"Deleted user\",\n\t\tdeleted: true\n\t};\n}\n//#endregion\n//#region src/client/workspace-context.ts\nconst storage = new AsyncLocalStorage();\nfunction runWithWorkspaceContext(context, fn) {\n\treturn storage.run(context, fn);\n}\nfunction getWorkspaceContext() {\n\treturn storage.getStore();\n}\nfunction requireWorkspaceContext() {\n\tconst context = getWorkspaceContext();\n\tif (!context) throw new Error(\"Workspace context is not set\");\n\treturn context;\n}\n//#endregion\n//#region src/project-database/build-url.ts\nvar build_url_exports = /* @__PURE__ */ __exportAll({\n\tbuildOrgDatabaseUrl: () => buildOrgDatabaseUrl,\n\tbuildProjectDatabaseUrl: () => buildProjectDatabaseUrl,\n\tresolveOrgDatabaseUrl: () => resolveOrgDatabaseUrl,\n\tresolveProjectDatabaseUrl: () => resolveProjectDatabaseUrl\n});\nfunction buildOrgDatabaseUrl(user, password, env = process.env) {\n\treturn buildPostgresUrl({\n\t\t...resolvePlatformPostgresConfig(env),\n\t\tuser: qualifyConnectionUser(user, env),\n\t\tpassword\n\t});\n}\nfunction resolveOrgDatabaseUrl(organization) {\n\tif (inferDialect(resolvePlatformDatabaseUrl()) === \"sqlite\") return organization.dbSchema.startsWith(\"file:\") ? organization.dbSchema : `file:${organization.dbSchema}`;\n\tconst password = decryptCredentialPayload$1(organization.dbPasswordCiphertext);\n\treturn buildOrgDatabaseUrl(organization.dbUser, password);\n}\n/** @deprecated Use {@link resolveOrgDatabaseUrl}. */\nfunction resolveProjectDatabaseUrl(organization) {\n\treturn resolveOrgDatabaseUrl(organization);\n}\n/** @deprecated Use {@link buildOrgDatabaseUrl}. */\nfunction buildProjectDatabaseUrl(_baseUrl, user, password) {\n\treturn buildOrgDatabaseUrl(user, password);\n}\n//#endregion\n//#region src/project-database/runtime-env.ts\nasync function resolveOrgRuntimeDatabase(organizationId) {\n\tconst organization = await selectOrganizationById(organizationId);\n\tif (!organization) throw new Error(`Organization not found: ${organizationId}`);\n\tif (inferDialect(resolvePlatformDatabaseUrl()) === \"sqlite\") {\n\t\tconst url = organization.dbSchema.startsWith(\"file:\") ? organization.dbSchema : `file:${organization.dbSchema}`;\n\t\treturn {\n\t\t\thost: \"\",\n\t\t\tport: 0,\n\t\t\tdatabase: organization.dbSchema,\n\t\t\tuser: \"\",\n\t\t\tpassword: \"\",\n\t\t\tsearchPath: \"\",\n\t\t\turl\n\t\t};\n\t}\n\tconst platform = resolvePlatformPostgresConfig();\n\treturn {\n\t\thost: platform.host,\n\t\tport: platform.port,\n\t\tdatabase: platform.database,\n\t\tuser: qualifyConnectionUser(organization.dbUser),\n\t\tpassword: decryptCredentialPayload$1(organization.dbPasswordCiphertext),\n\t\tsearchPath: organization.dbSchema\n\t};\n}\nasync function resolveProjectRuntimeDatabase(input) {\n\treturn {\n\t\t...await resolveOrgRuntimeDatabase(input.organizationId),\n\t\tprojectId: input.projectId,\n\t\torganizationId: input.organizationId\n\t};\n}\n//#endregion\n//#region src/project-database/pgboss-grants.ts\nvar pgboss_grants_exports = /* @__PURE__ */ __exportAll({ grantPgBossAccess: () => grantPgBossAccess });\nasync function grantPgBossAccess(pool, dbUser) {\n\tconst roleIdent = quotePgIdent(dbUser);\n\tconst { rows } = await pool.query(`SELECT EXISTS (\n SELECT 1 FROM information_schema.schemata WHERE schema_name = 'pgboss'\n ) AS exists`);\n\tif (!rows[0]?.exists) return;\n\tawait pool.query(`GRANT USAGE ON SCHEMA pgboss TO ${roleIdent}`);\n\tawait pool.query(`GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA pgboss TO ${roleIdent}`);\n\tawait pool.query(`GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA pgboss TO ${roleIdent}`);\n}\n//#endregion\n//#region src/project-database/ensure-pgboss-grants.ts\nasync function ensureOrgPgBossGrants() {\n\tconst pool = new Pool({ connectionString: resolvePlatformDatabaseUrl() });\n\ttry {\n\t\tconst rows = await getDb().select({ dbUser: organizations.dbUser }).from(organizations).where(isNull(organizations.deletedAt));\n\t\tconst users = [...new Set(rows.map((row) => row.dbUser))];\n\t\tfor (const dbUser of users) await grantPgBossAccess(pool, dbUser);\n\t} finally {\n\t\tawait pool.end();\n\t}\n}\n/** @deprecated Use {@link ensureOrgPgBossGrants}. */\nconst ensureProjectPgBossGrants = ensureOrgPgBossGrants;\n//#endregion\n//#region src/project-database/ensure-org-runtime-migrations.ts\nasync function ensureOrgRuntimeMigrations() {\n\tconst dialect = inferDialect(resolvePlatformDatabaseUrl());\n\tconst { createConnection, resolveMigrationsFolder, runMigrations } = await import(\"@keystrokehq/database\");\n\tconst rows = await getDb().select({\n\t\tdbSchema: organizations.dbSchema,\n\t\tdbUser: organizations.dbUser,\n\t\tdbPasswordCiphertext: organizations.dbPasswordCiphertext\n\t}).from(organizations).where(isNull(organizations.deletedAt));\n\tconst migrationsFolder = resolveMigrationsFolder(dialect);\n\tfor (const org of rows) {\n\t\tconst handle = createConnection({\n\t\t\turl: resolveOrgDatabaseUrl(org),\n\t\t\tdialect,\n\t\t\t...dialect === \"postgres\" ? { searchPath: org.dbSchema } : {}\n\t\t});\n\t\ttry {\n\t\t\tawait runMigrations(handle, migrationsFolder);\n\t\t} finally {\n\t\t\thandle.close();\n\t\t}\n\t}\n}\n/** @deprecated Use {@link ensureOrgRuntimeMigrations}. */\nconst ensureProjectRuntimeMigrations = ensureOrgRuntimeMigrations;\n//#endregion\n//#region src/org-storage/resolve-config.ts\nfunction hasOrgStorageConfig(organization) {\n\treturn !!organization.storageBucket && !!organization.storageEndpoint && !!organization.storageAccessKeyIdCiphertext && !!organization.storageSecretAccessKeyCiphertext;\n}\nfunction resolveOrgStorageConfig(organization) {\n\tif (!hasOrgStorageConfig(organization)) throw new Error(\"Organization storage is not configured\");\n\treturn {\n\t\tbucket: organization.storageBucket,\n\t\tendpoint: organization.storageEndpoint,\n\t\taccessKeyId: decryptCredentialPayload$1(organization.storageAccessKeyIdCiphertext),\n\t\tsecretAccessKey: decryptCredentialPayload$1(organization.storageSecretAccessKeyCiphertext),\n\t\tregion: organization.storageRegion ?? \"us-east-1\",\n\t\tforcePathStyle: organization.storageForcePathStyle ?? true\n\t};\n}\n//#endregion\n//#region src/org-storage/client.ts\nfunction createOrgStorageClient(organization) {\n\treturn createStorage(resolveOrgStorageConfig(organization));\n}\nfunction createOrgContainerPresign(organization) {\n\treturn createContainerPresignStorage(resolveOrgStorageConfig(organization));\n}\n//#endregion\n//#region src/org-storage/runtime-env.ts\nfunction orgStorageRuntimeEnv(config, containerEnv) {\n\treturn {\n\t\tSTORAGE_ACCESS_KEY_ID: config.accessKeyId,\n\t\tSTORAGE_SECRET_ACCESS_KEY: config.secretAccessKey,\n\t\tSTORAGE_ENDPOINT: containerEnv ? containerPresignEndpointFromEnv(config.endpoint, containerEnv) : config.endpoint,\n\t\tSTORAGE_REGION: config.region,\n\t\tSTORAGE_FORCE_PATH_STYLE: String(config.forcePathStyle),\n\t\tKEYSTROKE_WORKSPACES_BUCKET: config.bucket\n\t};\n}\nfunction orgWorkspacesRuntimeEnv(organization, options) {\n\tif (!hasOrgStorageConfig(organization)) return {};\n\treturn orgStorageRuntimeEnv(resolveOrgStorageConfig(organization), options?.containerEnv);\n}\n//#endregion\n//#region src/queries/_internal/organization-scope.ts\nfunction eqOrganizationScope(table) {\n\treturn eq$1(table.organizationId, requireOrganizationScopeId());\n}\nfunction scopedAnd(table, ...conditions) {\n\treturn and$1(eqOrganizationScope(table), ...conditions);\n}\nfunction organizationScopeId() {\n\treturn requireOrganizationScopeId();\n}\n//#endregion\n//#region src/queries/oauth-apps/index.ts\nasync function selectOAuthAppBySlug(slug) {\n\treturn (await getDb().select().from(oauthApps).where(scopedAnd(oauthApps, eq$1(oauthApps.slug, slug))).limit(1))[0];\n}\nasync function selectOAuthAppById(id) {\n\treturn (await getDb().select().from(oauthApps).where(scopedAnd(oauthApps, eq$1(oauthApps.id, id))).limit(1))[0];\n}\nasync function insertOAuthApp(values) {\n\tawait getDb().insert(oauthApps).values({\n\t\t...values,\n\t\torganizationId: organizationScopeId()\n\t});\n}\nasync function updateOAuthAppBySlug(slug, values) {\n\tawait getDb().update(oauthApps).set(values).where(scopedAnd(oauthApps, eq$1(oauthApps.slug, slug)));\n}\n//#endregion\n//#region src/queries/oauth-apps/global.ts\n/** Org-unscoped lookup — used before organization scope is known (e.g. inbound Slack webhooks). */\nasync function listOAuthAppsBySlugUnscoped(slug) {\n\treturn getDb().select().from(oauthApps).where(eq$1(oauthApps.slug, slug));\n}\n//#endregion\n//#region src/queries/oauth-connections/index.ts\nasync function selectOAuthConnectionById(id) {\n\treturn (await getDb().select({ connection: oauthConnections }).from(oauthConnections).innerJoin(oauthApps, eq$1(oauthApps.id, oauthConnections.appId)).where(scopedAnd(oauthApps, eq$1(oauthConnections.id, id))).limit(1))[0]?.connection;\n}\nasync function selectOAuthConnectionsByIds(ids) {\n\tif (ids.length === 0) return [];\n\treturn (await getDb().select({ connection: oauthConnections }).from(oauthConnections).innerJoin(oauthApps, eq$1(oauthApps.id, oauthConnections.appId)).where(scopedAnd(oauthApps, inArray$1(oauthConnections.id, ids)))).map((row) => row.connection);\n}\nasync function selectOAuthConnectionByAppAndExternalId(appId, externalId) {\n\treturn (await getDb().select({ connection: oauthConnections }).from(oauthConnections).innerJoin(oauthApps, eq$1(oauthApps.id, oauthConnections.appId)).where(scopedAnd(oauthApps, eq$1(oauthConnections.appId, appId), eq$1(oauthConnections.externalId, externalId))).limit(1))[0]?.connection;\n}\nasync function listOAuthConnectionsByAppId(appId) {\n\treturn (await getDb().select({ connection: oauthConnections }).from(oauthConnections).innerJoin(oauthApps, eq$1(oauthApps.id, oauthConnections.appId)).where(scopedAnd(oauthApps, eq$1(oauthConnections.appId, appId)))).map((row) => row.connection);\n}\nasync function deleteOAuthConnectionById(id) {\n\tif (!await selectOAuthConnectionById(id)) return false;\n\tawait getDb().delete(oauthConnections).where(eq$1(oauthConnections.id, id));\n\treturn true;\n}\nasync function insertOAuthConnection(values) {\n\tawait getDb().insert(oauthConnections).values(values);\n}\n/** Returns the id of the persisted row: the existing row's id on update, `values.id` on insert. */\nasync function upsertOAuthConnection(values) {\n\tconst existing = await selectOAuthConnectionByAppAndExternalId(values.appId, values.externalId);\n\tif (existing) {\n\t\tawait getDb().update(oauthConnections).set({\n\t\t\taccessTokenCiphertext: values.accessTokenCiphertext,\n\t\t\trefreshTokenCiphertext: values.refreshTokenCiphertext,\n\t\t\taccessTokenExpiresAt: values.accessTokenExpiresAt,\n\t\t\tgrantedScopes: values.grantedScopes && values.grantedScopes.length > 0 ? values.grantedScopes : existing.grantedScopes,\n\t\t\tmetadata: values.metadata,\n\t\t\tupdatedAt: values.updatedAt\n\t\t}).where(eq$1(oauthConnections.id, existing.id));\n\t\treturn existing.id;\n\t}\n\tawait insertOAuthConnection(values);\n\treturn values.id;\n}\n//#endregion\n//#region src/queries/oauth-connections/global.ts\n/** Org-unscoped lookup — resolves a Slack team_id (externalId) to org + connection via oauth_apps.slug. */\nasync function selectOAuthInstallationsByAppSlugAndExternalId(appSlug, externalId) {\n\treturn getDb().select({\n\t\torganizationId: oauthApps.organizationId,\n\t\tconnectionId: oauthConnections.id,\n\t\tappId: oauthApps.id,\n\t\texternalId: oauthConnections.externalId\n\t}).from(oauthConnections).innerJoin(oauthApps, eq$1(oauthApps.id, oauthConnections.appId)).where(and$1(eq$1(oauthApps.slug, appSlug), eq$1(oauthConnections.externalId, externalId)));\n}\n//#endregion\n//#region src/queries/secret-values/index.ts\nasync function selectSecretValue(refKind, refId, field) {\n\treturn (await getDb().select().from(secretValues).where(scopedAnd(secretValues, eq$1(secretValues.refKind, refKind), eq$1(secretValues.refId, refId), eq$1(secretValues.field, field))).limit(1))[0];\n}\nasync function upsertSecretValue(values) {\n\tconst db = getDb();\n\tconst existing = await selectSecretValue(values.refKind, values.refId, values.field);\n\tif (existing) {\n\t\tawait db.update(secretValues).set({\n\t\t\tciphertext: values.ciphertext,\n\t\t\tupdatedAt: values.updatedAt\n\t\t}).where(eq$1(secretValues.id, existing.id));\n\t\treturn;\n\t}\n\tawait db.insert(secretValues).values({\n\t\t...values,\n\t\torganizationId: organizationScopeId()\n\t});\n}\nasync function deleteSecretValuesForRef(refKind, refId) {\n\tawait getDb().delete(secretValues).where(scopedAnd(secretValues, eq$1(secretValues.refKind, refKind), eq$1(secretValues.refId, refId)));\n}\n//#endregion\n//#region src/oauth/app.ts\nfunction metadataMatches(existing, next) {\n\treturn JSON.stringify(existing ?? null) === JSON.stringify(next ?? null);\n}\nfunction oauthAppValuesDiffer(existing, options) {\n\tconst nextSigningSecret = options.signingSecret ?? \"\";\n\treturn existing.clientId !== options.clientId || existing.clientSecret !== options.clientSecret || existing.signingSecret !== nextSigningSecret || !metadataMatches(existing.metadata, options.metadata ?? null);\n}\nfunction encryptOAuthAppValues(options) {\n\treturn {\n\t\tclientIdCiphertext: encryptCredentialPayload$1(options.clientId),\n\t\tclientSecretCiphertext: encryptCredentialPayload$1(options.clientSecret),\n\t\tsigningSecretCiphertext: options.signingSecret ? encryptCredentialPayload$1(options.signingSecret) : null,\n\t\tmetadata: options.metadata ?? null\n\t};\n}\nfunction decryptOAuthAppRow(row) {\n\treturn {\n\t\tid: row.id,\n\t\tprovider: row.provider,\n\t\tslug: row.slug,\n\t\ttokenStrategy: row.tokenStrategy,\n\t\tclientId: decryptCredentialPayload$1(row.clientIdCiphertext),\n\t\tclientSecret: decryptCredentialPayload$1(row.clientSecretCiphertext),\n\t\tsigningSecret: row.signingSecretCiphertext ? decryptCredentialPayload$1(row.signingSecretCiphertext) : \"\",\n\t\tredirectUri: row.redirectUri,\n\t\tmetadata: row.metadata ?? null\n\t};\n}\nasync function getDecryptedOAuthAppBySlug(slug) {\n\tconst row = await selectOAuthAppBySlug(slug);\n\tif (!row) return null;\n\treturn decryptOAuthAppRow(row);\n}\nasync function getDecryptedOAuthAppById(id) {\n\tconst row = await selectOAuthAppById(id);\n\tif (!row) return null;\n\treturn decryptOAuthAppRow(row);\n}\nasync function ensureOAuthApp(options) {\n\tconst existing = await selectOAuthAppBySlug(options.slug);\n\tif (existing) {\n\t\tif (!oauthAppValuesDiffer(decryptOAuthAppRow(existing), options)) return {\n\t\t\tid: existing.id,\n\t\t\tcreated: false,\n\t\t\tupdated: false\n\t\t};\n\t\tawait updateOAuthAppBySlug(options.slug, {\n\t\t\t...encryptOAuthAppValues(options),\n\t\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t\t});\n\t\treturn {\n\t\t\tid: existing.id,\n\t\t\tcreated: false,\n\t\t\tupdated: true\n\t\t};\n\t}\n\tconst now = /* @__PURE__ */ new Date();\n\tconst id = crypto.randomUUID();\n\tawait insertOAuthApp({\n\t\tid,\n\t\tprovider: options.provider,\n\t\tslug: options.slug,\n\t\ttokenStrategy: options.tokenStrategy,\n\t\t...encryptOAuthAppValues(options),\n\t\tredirectUri: null,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t});\n\treturn {\n\t\tid,\n\t\tcreated: true,\n\t\tupdated: false\n\t};\n}\n//#endregion\n//#region src/oauth/connection.ts\nfunction decryptOAuthConnectionRow(row) {\n\treturn {\n\t\tid: row.id,\n\t\tappId: row.appId,\n\t\texternalId: row.externalId,\n\t\taccessToken: decryptCredentialPayload$1(row.accessTokenCiphertext),\n\t\trefreshToken: row.refreshTokenCiphertext ? decryptCredentialPayload$1(row.refreshTokenCiphertext) : null,\n\t\taccessTokenExpiresAt: row.accessTokenExpiresAt ?? null,\n\t\tgrantedScopes: row.grantedScopes ?? null,\n\t\tmetadata: row.metadata ?? null\n\t};\n}\nasync function getDecryptedOAuthConnectionById(id) {\n\tconst row = await selectOAuthConnectionById(id);\n\tif (!row) return null;\n\treturn decryptOAuthConnectionRow(row);\n}\nasync function getDecryptedOAuthConnectionsByAppSlug(appSlug) {\n\tconst app = await selectOAuthAppBySlug(appSlug);\n\tif (!app) return [];\n\treturn (await listOAuthConnectionsByAppId(app.id)).map(decryptOAuthConnectionRow);\n}\nasync function getDecryptedOAuthConnectionByAppSlugAndExternalId(appSlug, externalId) {\n\tconst app = await selectOAuthAppBySlug(appSlug);\n\tif (!app) return null;\n\tconst row = await selectOAuthConnectionByAppAndExternalId(app.id, externalId);\n\tif (!row) return null;\n\treturn decryptOAuthConnectionRow(row);\n}\nasync function saveOAuthConnection(options) {\n\tconst now = /* @__PURE__ */ new Date();\n\treturn upsertOAuthConnection({\n\t\tid: options.connectionId ?? crypto.randomUUID(),\n\t\tappId: options.appId,\n\t\texternalId: options.externalId,\n\t\taccessTokenCiphertext: encryptCredentialPayload$1(options.accessToken),\n\t\trefreshTokenCiphertext: options.refreshToken ? encryptCredentialPayload$1(options.refreshToken) : null,\n\t\taccessTokenExpiresAt: options.accessTokenExpiresAt ?? null,\n\t\tgrantedScopes: options.grantedScopes ?? null,\n\t\tmetadata: options.metadata ?? null,\n\t\tconnectedAt: now,\n\t\tupdatedAt: now\n\t});\n}\n//#endregion\n//#region src/oauth/refresh-token.ts\nconst TOKEN_EXPIRY_BUFFER_MS = 6e4;\nfunction accessTokenIsStale(expiresAt) {\n\tif (!expiresAt) return true;\n\treturn expiresAt.getTime() <= Date.now() + TOKEN_EXPIRY_BUFFER_MS;\n}\nasync function resolveOAuthAccessToken(connection, app, tokenRefresh) {\n\tif (app.tokenStrategy === \"installation\" || app.tokenStrategy === \"app_installation\") return connection.accessToken;\n\tif (!accessTokenIsStale(connection.accessTokenExpiresAt)) return connection.accessToken;\n\tif (!connection.refreshToken) throw new Error(`OAuth connection \"${connection.id}\" is missing a refresh token.`);\n\tconst refresh = tokenRefresh?.get(app.slug);\n\tif (!refresh) throw new Error(`OAuth refresh is not registered for app \"${app.slug}\".`);\n\tconst refreshed = await refresh({\n\t\tclientId: app.clientId,\n\t\tclientSecret: app.clientSecret,\n\t\trefreshToken: connection.refreshToken\n\t});\n\tawait saveOAuthConnection({\n\t\tappId: connection.appId,\n\t\texternalId: connection.externalId,\n\t\taccessToken: refreshed.accessToken,\n\t\trefreshToken: refreshed.refreshToken ?? connection.refreshToken,\n\t\taccessTokenExpiresAt: refreshed.accessTokenExpiresAt,\n\t\tgrantedScopes: connection.grantedScopes ?? void 0,\n\t\tmetadata: connection.metadata ?? void 0,\n\t\tconnectionId: connection.id\n\t});\n\treturn refreshed.accessToken;\n}\n//#endregion\n//#region src/oauth/global-lookup.ts\n/** Signing secret for inbound webhooks before org scope is known (shared managed Slack app). */\nasync function getOAuthAppSigningSecretBySlugGlobal(appSlug) {\n\tconst fromEnv = process.env.SLACK_SIGNING_SECRET?.trim();\n\tif (fromEnv) return fromEnv;\n\tconst apps = await listOAuthAppsBySlugUnscoped(appSlug);\n\tfor (const app of apps) if (app.signingSecretCiphertext) return decryptCredentialPayload$1(app.signingSecretCiphertext);\n\treturn null;\n}\n/** All orgs connected to a Slack workspace (team_id). */\nasync function listOAuthInstallationsByAppSlugAndExternalId(appSlug, externalId) {\n\treturn (await selectOAuthInstallationsByAppSlugAndExternalId(appSlug, externalId)).map((row) => ({\n\t\torganizationId: row.organizationId,\n\t\tconnectionId: row.connectionId\n\t}));\n}\n/** Bot token for a team from any org's connection (same Slack app + team → same token). */\nasync function getGlobalOAuthAccessTokenByAppSlugAndExternalId(appSlug, externalId) {\n\tconst first = (await selectOAuthInstallationsByAppSlugAndExternalId(appSlug, externalId))[0];\n\tif (!first) return null;\n\tconst connection = await selectOAuthConnectionById(first.connectionId);\n\tif (!connection) return null;\n\treturn decryptCredentialPayload$1(connection.accessTokenCiphertext);\n}\n//#endregion\n//#region src/queries/apps/slug.ts\nasync function isOrgAppSlugTaken(orgSlug, slugPart) {\n\tconst qualified = qualifyOrgSlug(orgSlug, slugPart);\n\treturn (await getDb().select({ id: apps.id }).from(apps).where(eq$1(apps.slug, qualified)).limit(1)).length > 0;\n}\nasync function resolveAvailableOrgAppSlug(orgSlug, nameOrSlug) {\n\tconst base = slugifyAppName(nameOrSlug);\n\tif (!await isOrgAppSlugTaken(orgSlug, base)) return base;\n\tfor (let suffix = 2; suffix < 1e4; suffix += 1) {\n\t\tconst candidate = AppSlugSchema.parse(`${base}-${suffix}`);\n\t\tif (!await isOrgAppSlugTaken(orgSlug, candidate)) return candidate;\n\t}\n\tthrow new Error(\"Unable to allocate a unique app slug\");\n}\nasync function checkOrgAppSlugAvailability(orgSlug, slugPart) {\n\tconst normalized = slugPart.trim().toLowerCase();\n\tconst format = AppSlugSchema.safeParse(normalized);\n\tif (!format.success) return {\n\t\tslug: normalized,\n\t\tavailable: false,\n\t\treason: \"invalid\"\n\t};\n\tconst parsed = format.data;\n\tif (await isOrgAppSlugTaken(orgSlug, parsed)) return {\n\t\tslug: parsed,\n\t\tavailable: false,\n\t\treason: \"taken\",\n\t\tsuggestion: await resolveAvailableOrgAppSlug(orgSlug, parsed)\n\t};\n\treturn {\n\t\tslug: parsed,\n\t\tavailable: true\n\t};\n}\n//#endregion\n//#region src/queries/apps/index.ts\nvar OrgAppSlugTakenError = class extends Error {\n\tslug;\n\tconstructor(slug) {\n\t\tsuper(`App slug already exists: ${slug}`);\n\t\tthis.name = \"OrgAppSlugTakenError\";\n\t\tthis.slug = slug;\n\t}\n};\nasync function selectAppBySlug(slug) {\n\treturn (await getDb().select().from(apps).where(eq$1(apps.slug, slug)).limit(1))[0];\n}\nasync function listOfficialApps() {\n\treturn getDb().select().from(apps).where(isNull$1(apps.organizationId));\n}\nasync function listAppsForOrganization(organizationId) {\n\treturn getDb().select().from(apps).where(or(isNull$1(apps.organizationId), eq$1(apps.organizationId, organizationId)));\n}\nasync function selectAppForOrganization(organizationId, slug) {\n\tconst row = await selectAppBySlug(slug);\n\tif (!row) return;\n\tif (row.organizationId === null || row.organizationId === organizationId) return row;\n}\nasync function createOrgApp(values) {\n\tconst db = getDb();\n\tconst slug = qualifyOrgSlug(values.orgSlug, values.slug);\n\tif (await selectAppBySlug(slug)) throw new OrgAppSlugTakenError(slug);\n\tconst now = /* @__PURE__ */ new Date();\n\treturn (await db.insert(apps).values({\n\t\tid: crypto.randomUUID(),\n\t\torganizationId: values.organizationId,\n\t\tslug,\n\t\tname: values.name,\n\t\tdescription: values.description,\n\t\tcategory: \"Custom\",\n\t\tlogo: null,\n\t\tauthKind: \"api_key\",\n\t\toauthScopes: [],\n\t\tcredentialFields: values.credentialFields,\n\t\tsource: \"custom\",\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t}).returning())[0];\n}\nasync function upsertOfficialApp(values) {\n\tconst db = getDb();\n\tconst now = /* @__PURE__ */ new Date();\n\tif (await selectAppBySlug(values.slug)) return (await db.update(apps).set({\n\t\tname: values.name,\n\t\tdescription: values.description,\n\t\tcategory: values.category,\n\t\t...values.logo !== void 0 ? { logo: values.logo } : {},\n\t\tauthKind: values.authKind,\n\t\toauthScopes: values.oauthScopes,\n\t\tsource: values.source,\n\t\tupdatedAt: now\n\t}).where(eq$1(apps.slug, values.slug)).returning())[0];\n\treturn (await db.insert(apps).values({\n\t\tid: crypto.randomUUID(),\n\t\torganizationId: null,\n\t\tcredentialFields: {},\n\t\t...values,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t}).returning())[0];\n}\nfunction hasCredentialFieldTemplate(row) {\n\treturn Object.keys(row.credentialFields).length > 0;\n}\nasync function selectOrgAppBySlug(organizationId, slug) {\n\treturn (await getDb().select().from(apps).where(and$1(eq$1(apps.slug, slug), eq$1(apps.organizationId, organizationId))).limit(1))[0];\n}\n//#endregion\n//#region src/apps/seed.ts\n/** Upsert official apps from a hosted manifest. Idempotent — safe to run on a schedule. */\nasync function seedOfficialApps(entries) {\n\tfor (const entry of entries) await upsertOfficialApp({\n\t\tslug: entry.slug,\n\t\tname: entry.name,\n\t\tdescription: entry.description,\n\t\tcategory: entry.category,\n\t\t...entry.logo !== void 0 ? { logo: entry.logo } : {},\n\t\tauthKind: entry.authKind,\n\t\toauthScopes: entry.oauthScopes,\n\t\tsource: entry.source\n\t});\n}\n//#endregion\nexport { CannotModifyOwnerError, DEFAULT_PLATFORM_DATABASE_URL, DEFAULT_STANDALONE_ORGANIZATION_ID, DEFAULT_STANDALONE_ORGANIZATION_NAME, DEFAULT_STANDALONE_ORGANIZATION_SLUG, DEFAULT_STANDALONE_PROJECT_NAME, DEFAULT_STANDALONE_PROJECT_SLUG, LastOwnerError, ORG_PLATFORM_API_KEY_CONFIG_ID, OrgAppSlugTakenError, OrgPlatformApiKeyNotFoundError, OrganizationInvitationExpiredError, OrganizationInvitationForbiddenError, OrganizationInvitationNotFoundError, OrganizationMemberNotFoundError, OrganizationSlugTakenError, ProjectMemberNotFoundError, ProjectSlugTakenError, WEBHOOK_API_KEY_CONFIG_ID, acceptInvitation, apps, backfillProjectUsers, buildDefaultProjectDescription, buildDefaultProjectForUser, buildOrgDatabaseUrl, buildProjectDatabaseUrl, checkOrgAppSlugAvailability, checkOrganizationSlugAvailability, checkProjectSlugAvailability, closeDatabase, completeProjectArtifact, createConnection, createOrgApp, createOrgContainerPresign, createOrgPlatformApiKey, createOrgStorageClient, createOrganizationForUser, createPgConnection, createProjectForOrganization, createSqliteConnection, declineInvitation, decryptCredentialPayload, deleteOAuthConnectionById, deleteProjectForOrganization, deleteSecretValuesForRef, deprovisionOrgDatabase, encryptCredentialPayload, ensureDefaultOrganization, ensureDefaultOrganizationAndProject, ensureDefaultProject, ensureDefaultProjectForUser, ensureDefaultProjectForUserInTransaction, ensureOAuthApp, ensureOrgPgBossGrants, ensureOrgRuntimeMigrations, ensureProjectPgBossGrants, ensureProjectRuntimeMigrations, ensureWebhookApiKeyForRoute, ensureWebhookApiKeys, findOrCreateUserByEmail, firstNameFromUser, getDatabaseHandle, getDecryptedOAuthAppById, getDecryptedOAuthAppBySlug, getDecryptedOAuthConnectionByAppSlugAndExternalId, getDecryptedOAuthConnectionById, getDecryptedOAuthConnectionsByAppSlug, getGlobalOAuthAccessTokenByAppSlugAndExternalId, getOAuthAppSigningSecretBySlugGlobal, getOrganizationScopeId, getWorkspaceContext, hasCredentialFieldTemplate, initDatabase, insertOAuthApp, insertProjectArtifact, inviteOrganizationMembers, inviteProjectMembers, isDatabaseInitialized, isOrganizationStorageBucketInUse, isStandaloneMode, listAppsForOrganization, listOAuthAppsBySlugUnscoped, listOAuthConnectionsByAppId, listOAuthInstallationsByAppSlugAndExternalId, listOfficialApps, listOrgPlatformApiKeysForOrganization, listOrgPlatformApiKeysForUser, listWebhookApiKeys, listWebhookApiKeysForProject, loadOrgPlatformApiKeyUser, mapOrgPlatformApiKeyCreator, mapOrgPlatformApiKeyCreatorOrDeleted, normalizeUserEmail, orgDbRoleName, orgDbSchemaName, orgWorkspacesRuntimeEnv, organizationInvitationStatuses, organizationRowToSidebarBranding, organizationUserRoles, projectArtifactStatuses, projectDbRoleName, projectDbSchemaName, projectStatuses, promoteProjectArtifact, provisionOrgDatabase, removeOrganizationMember, removeProjectMember, requireOrganizationScopeId, requireWorkspaceContext, resolveMigrationsFolder, resolveNewOrganizationIdentity, resolveOAuthAccessToken, resolveOrgDatabaseUrl, resolveOrgRuntimeDatabase, resolveOrgStorageConfig, resolveProjectDatabaseUrl, resolveProjectRuntimeDatabase, revokeOrgPlatformApiKey, runMigrations, runWithOrganizationScope, runWithStandaloneScope, runWithWorkspaceContext, saveOAuthConnection, seedOfficialApps, selectActiveArtifactManifestForProject, selectActiveArtifactManifestsByOrganizationId, selectActiveArtifactSourceManifestForProject, selectActiveOrganizationIds, selectActiveProjectArtifactForProject, selectAppBySlug, selectAppForOrganization, selectLastDeploymentAtByProject, selectOAuthAppById, selectOAuthAppBySlug, selectOAuthConnectionByAppAndExternalId, selectOAuthConnectionById, selectOAuthConnectionsByIds, selectOAuthInstallationsByAppSlugAndExternalId, selectOrgAppBySlug, selectOrgPlatformApiKeyForOrganization, selectOrganizationById, selectOrganizationBySlug, selectOrganizationMembers, selectOrganizationUsersByUserId, selectPendingInvitationsForUser, selectProjectArtifactById, selectProjectArtifactForProject, selectProjectById, selectProjectDeployments, selectProjectForOrganization, selectProjectForOrganizationBySlug, selectProjectIdsForUser, selectProjectMembers, selectProjectsByOrganizationId, selectSecretValue, selectUserByEmail, selectUserById, selectUserByNormalizedEmail, selectUserOrganization, selectUserOrganizationMembership, selectUserOrganizations, selectUserProjectMembership, selectUsersByIds, updateOAuthAppBySlug, updateOrganizationActive, updateOrganizationFailed, updateOrganizationMemberRole, updateOrganizationName, updateOrganizationSidebarBranding, updateOrganizationSlug, updateProjectActive, updateProjectArtifactManifest, updateProjectArtifactSourceManifest, updateProjectFailed, updateProjectForOrganization, updateProjectMemberRole, updateProjectSettings, updateUserById, upsertOAuthConnection, upsertOfficialApp, upsertProjectMember, upsertSecretValue, verifyOrgPlatformApiKeySecret, verifyWebhookApiKeyForRoute, webhookApiKeyName, webhookEndpointSuffix };\n\n//# sourceMappingURL=index.mjs.map","import { clearCredentialInstanceDefaults, deleteCredentialAssignmentById, deleteCredentialInstanceById, ensureKeystrokeCredentialInstance, ensureOAuthCredentialInstance, getProjectScopeId, getServerTenantScopeId, listCredentialAssignmentsByTarget, listCredentialInstancesByScope, listDistinctAssignmentConsumerIds, listRecentWorkflowStepConsumers, selectCredentialAssignmentById, selectCredentialInstanceById, selectCredentialInstancesForScope, upsertCredentialAssignment, upsertCredentialInstance } from \"@keystrokehq/database\";\nimport { ensureOAuthApp, getDecryptedOAuthAppById as getDecryptedOAuthAppById$1, getDecryptedOAuthAppBySlug, getDecryptedOAuthConnectionByAppSlugAndExternalId, getDecryptedOAuthConnectionById as getDecryptedOAuthConnectionById$1, getDecryptedOAuthConnectionsByAppSlug, resolveOAuthAccessToken, saveOAuthConnection } from \"@keystrokehq/platform-database\";\n//#region src/store/credential-assignments.ts\nfunction normalizeRow(row) {\n\tconst { projectId: _projectId, ...rest } = row;\n\treturn rest;\n}\nasync function listCredentialAssignmentsByTarget$1(options) {\n\treturn (await listCredentialAssignmentsByTarget(options)).map(normalizeRow);\n}\nasync function selectCredentialAssignmentById$1(id) {\n\tconst row = await selectCredentialAssignmentById(id);\n\treturn row ? normalizeRow(row) : void 0;\n}\nasync function upsertCredentialAssignment$1(values) {\n\treturn normalizeRow(await upsertCredentialAssignment(values));\n}\nasync function deleteCredentialAssignmentById$1(id) {\n\treturn deleteCredentialAssignmentById(id);\n}\nasync function listDistinctAssignmentConsumerIds$1(options) {\n\treturn listDistinctAssignmentConsumerIds(options);\n}\nasync function listRecentWorkflowStepConsumers$1(workflowSlug, runLimit) {\n\treturn listRecentWorkflowStepConsumers(workflowSlug, runLimit);\n}\n//#endregion\n//#region src/store/credential-instances.ts\nfunction normalizeLocalRow(row) {\n\tconst { projectId: _projectId, ...rest } = row;\n\treturn rest;\n}\nasync function selectCredentialInstanceById$1(id) {\n\tconst row = await selectCredentialInstanceById(id);\n\treturn row ? normalizeLocalRow(row) : void 0;\n}\nasync function selectCredentialInstancesForScope$1(appSlug, scopeType, scopeId) {\n\treturn (await selectCredentialInstancesForScope(appSlug, scopeType, scopeId)).map(normalizeLocalRow);\n}\nasync function listCredentialInstancesByScope$1(options) {\n\treturn (await listCredentialInstancesByScope(options)).map(normalizeLocalRow);\n}\nasync function upsertCredentialInstance$1(values) {\n\tawait upsertCredentialInstance(values);\n}\nasync function deleteCredentialInstanceById$1(id) {\n\treturn deleteCredentialInstanceById(id);\n}\nasync function clearCredentialInstanceDefaults$1(options) {\n\tawait clearCredentialInstanceDefaults(options);\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$1({\n\t\t\t...options.appSlug ? { appSlug: options.appSlug } : {},\n\t\t\tscopeType,\n\t\t\tscopeId\n\t\t}));\n\t};\n\tif (options.appSlug) {\n\t\tawait appendScope(\"organization\", tenantScopeId);\n\t\tawait appendScope(\"project\", projectId);\n\t\tif (options.userId) await appendScope(\"user\", options.userId);\n\t\treturn rows;\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/store/oauth.ts\nasync function resolveOAuthAccessTokenForStore(connection, app, tokenRefresh) {\n\treturn resolveOAuthAccessToken(connection, app, tokenRefresh);\n}\n//#endregion\nexport { upsertCredentialAssignment$1 as C, selectCredentialAssignmentById$1 as S, upsertCredentialInstance$1 as _, getDecryptedOAuthAppBySlug as a, listDistinctAssignmentConsumerIds$1 as b, getDecryptedOAuthConnectionsByAppSlug as c, clearCredentialInstanceDefaults$1 as d, deleteCredentialInstanceById$1 as f, selectCredentialInstancesForScope$1 as g, selectCredentialInstanceById$1 as h, getDecryptedOAuthAppById$1 as i, resolveOAuthAccessTokenForStore as l, listCredentialInstancesForAssignment as m, ensureOAuthApp as n, getDecryptedOAuthConnectionByAppSlugAndExternalId as o, listCredentialInstancesByScope$1 as p, ensureOAuthCredentialInstance as r, getDecryptedOAuthConnectionById$1 as s, ensureKeystrokeCredentialInstance as t, saveOAuthConnection as u, deleteCredentialAssignmentById$1 as v, listRecentWorkflowStepConsumers$1 as x, listCredentialAssignmentsByTarget$1 as y };\n\n//# sourceMappingURL=store-BokhwcCi.mjs.map","import { deriveCredentialInstanceSlug } from \"@keystrokehq/shared\";\nimport { clearCredentialInstanceDefaults, encryptCredentialPayload, selectCredentialInstancesForScope, upsertCredentialInstance } from \"@keystrokehq/database\";\nimport { deleteSecretValuesForRef, getOrganizationScopeId, selectSecretValue, upsertSecretValue } from \"@keystrokehq/platform-database\";\nimport { createCipheriv, createDecipheriv, createHash, randomBytes } from \"node:crypto\";\n//#region src/crypto.ts\nconst ALGORITHM = \"aes-256-gcm\";\nconst IV_LENGTH = 12;\nfunction resolveEncryptionKey() {\n\tconst secret = process.env.PLATFORM_SECRETS_ENCRYPTION_KEY?.trim() ?? 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 encryptSecretPayload(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 decryptSecretPayload(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/store.ts\nfunction usePlatformStore() {\n\treturn getOrganizationScopeId() !== void 0;\n}\nfunction assertOrganizationScope() {\n\tif (!usePlatformStore()) throw new Error(\"Secret store requires organization scope\");\n}\nfunction createSecretStore() {\n\treturn {\n\t\tasync get(ref) {\n\t\t\tassertOrganizationScope();\n\t\t\tconst row = await selectSecretValue(ref.kind, ref.id, ref.field);\n\t\t\tif (!row) return null;\n\t\t\treturn decryptSecretPayload(row.ciphertext);\n\t\t},\n\t\tasync set(ref, plaintext) {\n\t\t\tassertOrganizationScope();\n\t\t\tconst now = /* @__PURE__ */ new Date();\n\t\t\tconst ciphertext = encryptSecretPayload(plaintext);\n\t\t\tawait upsertSecretValue({\n\t\t\t\tid: crypto.randomUUID(),\n\t\t\t\trefKind: ref.kind,\n\t\t\t\trefId: ref.id,\n\t\t\t\tfield: ref.field,\n\t\t\t\tciphertext,\n\t\t\t\tcreatedAt: now,\n\t\t\t\tupdatedAt: now\n\t\t\t});\n\t\t},\n\t\tasync deleteRef(kind, id) {\n\t\t\tassertOrganizationScope();\n\t\t\tawait deleteSecretValuesForRef(kind, id);\n\t\t}\n\t};\n}\n//#endregion\n//#region src/credential-instance.ts\nasync function setCredentialInstanceSecret(options) {\n\tconst now = /* @__PURE__ */ new Date();\n\tconst siblings = await selectCredentialInstancesForScope(options.key, 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.key,\n\t\tname,\n\t\ttakenSlugs: siblings.map((row) => row.slug)\n\t});\n\tif (isDefault) await clearCredentialInstanceDefaults({\n\t\tappSlug: options.key,\n\t\tscopeType: options.scopeType,\n\t\tscopeId: options.scopeId,\n\t\texceptId: options.id\n\t});\n\tif (getOrganizationScopeId() !== void 0) {\n\t\tawait upsertCredentialInstance({\n\t\t\tid: options.id,\n\t\t\tappSlug: options.key,\n\t\t\tslug,\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,\n\t\t\tauthKind: \"api_key\",\n\t\t\tciphertext: null,\n\t\t\tconnectionId: null,\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now\n\t\t});\n\t\tawait createSecretStore().set({\n\t\t\tkind: \"credential_instance\",\n\t\t\tid: options.id,\n\t\t\tfield: \"payload\"\n\t\t}, JSON.stringify(options.value));\n\t\treturn;\n\t}\n\tawait upsertCredentialInstance({\n\t\tid: options.id,\n\t\tappSlug: options.key,\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}\nasync function readCredentialInstanceSecret(instanceId) {\n\tif (getOrganizationScopeId() === void 0) return null;\n\treturn createSecretStore().get({\n\t\tkind: \"credential_instance\",\n\t\tid: instanceId,\n\t\tfield: \"payload\"\n\t});\n}\nasync function deleteCredentialInstanceSecret(instanceId) {\n\tif (getOrganizationScopeId() === void 0) return;\n\tawait createSecretStore().deleteRef(\"credential_instance\", instanceId);\n}\n//#endregion\nexport { createSecretStore, decryptSecretPayload, deleteCredentialInstanceSecret, encryptSecretPayload, readCredentialInstanceSecret, setCredentialInstanceSecret };\n\n//# sourceMappingURL=index.mjs.map","import { g as selectCredentialInstancesForScope$2, h as selectCredentialInstanceById$2, m as listCredentialInstancesForAssignment, y as listCredentialAssignmentsByTarget$1 } from \"./store-BokhwcCi.mjs\";\nimport { CREDENTIAL_SCOPE_TYPES, buildConnectDeeplink, mcpEntityId, normalizeCredentialList } from \"@keystrokehq/shared\";\nimport { decryptCredentialPayload, getBoundProjectScopeId, getServerTenantScopeId, isDatabaseInitialized, selectCredentialInstanceById } from \"@keystrokehq/database\";\nimport { getDecryptedOAuthAppById, getDecryptedOAuthConnectionById, resolveOAuthAccessToken, selectOrganizationById, selectProjectById } from \"@keystrokehq/platform-database\";\nimport { readCredentialInstanceSecret } from \"@keystrokehq/secrets\";\nimport { selectCredentialInstanceById as selectCredentialInstanceById$1, selectCredentialInstancesForScope as selectCredentialInstancesForScope$1 } from \"@keystrokehq/credentials/store\";\nimport { connectMcpDefinition, createToolName, defineMcp as defineMcp$1, normalizeInputSchema } from \"@keystrokehq/mcp\";\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}\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 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};\nfunction isCredentialError(error) {\n\treturn error instanceof MissingCredentialsError || error instanceof NeedsSelectionError || error instanceof OAuthNotConfiguredError;\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/backend/local.ts\nfunction createLocalCredentialBackend(options = {}) {\n\tconst { tokenRefresh } = options;\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\tasync getOAuthAccessToken(connectionId) {\n\t\t\tconst connection = await getDecryptedOAuthConnectionById(connectionId);\n\t\t\tif (!connection) throw new Error(`OAuth connection not found: ${connectionId}`);\n\t\t\tconst app = await getDecryptedOAuthAppById(connection.appId);\n\t\t\tif (!app) throw new Error(`OAuth app not found for connection: ${connectionId}`);\n\t\t\treturn { accessToken: await resolveOAuthAccessToken(connection, app, tokenRefresh) };\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\tthrow new Error(payload?.message ?? `Platform credential materialize failed (${response.status})`);\n\t\t}\n\t\tconst payload = await response.json();\n\t\tif (payload.kind === \"api_key\") 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};\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/capture-credential-tool-errors.ts\nfunction captureCredentialToolErrors(tools) {\n\tlet captured;\n\treturn {\n\t\ttools: tools.map((tool) => {\n\t\t\tif (!tool.execute) return tool;\n\t\t\tconst execute = tool.execute.bind(tool);\n\t\t\treturn {\n\t\t\t\t...tool,\n\t\t\t\tasync execute(...args) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\treturn await execute(...args);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (isCredentialError(error)) {\n\t\t\t\t\t\t\tcaptured = error;\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\terror.message = formatCredentialErrorMessage(error, await resolveAgentConnectContext() ?? void 0);\n\t\t\t\t\t\t\t} catch {}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\t\t}),\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\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/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\treturn {\n\t\torgId: request.orgId ?? subscription?.orgId,\n\t\tprojectId: request.projectId ?? subscription?.projectId,\n\t\tuserId: request.userId ?? subscription?.userId,\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/workflow-context.ts\nfunction buildWorkflowRunContext(input) {\n\tconst request = input.request ?? {};\n\tconst userId = request.userId ?? input.subscription?.userId ?? input.actor?.userId;\n\treturn {\n\t\torgId: request.orgId,\n\t\tprojectId: request.projectId,\n\t\tuserId,\n\t\tuserIds: request.userIds,\n\t\tselection: request.selection ?? {}\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}\nasync function resolveInstanceValue(row, requirement, backend) {\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});\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});\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 requirement.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});\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 requirement.schema.parse(value);\n\t}\n\treturn backend.resolveApiKey(row.id, requirement.schema);\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) {\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());\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) {\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);\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);\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);\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);\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);\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);\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);\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\tfor (const requirement of requirements) resolved[requirement.key] = await resolvePolicy(requirement, options.context, options.consumer, backend);\n\treturn resolved;\n}\n//#endregion\n//#region src/create-credential-resolver.ts\nfunction createCredentialResolver(options) {\n\tconst credentialBackend = options.credentialBackend ?? getProjectCredentialBackend() ?? createCredentialBackend();\n\treturn { async resolve(requirements, consumer, contextOverride) {\n\t\treturn resolveCredentialRequirements({\n\t\t\trequirements,\n\t\t\tconsumer,\n\t\t\tcredentialBackend,\n\t\t\tcontext: {\n\t\t\t\t...options.context,\n\t\t\t\t...contextOverride,\n\t\t\t\tselection: {\n\t\t\t\t\t...options.context.selection,\n\t\t\t\t\t...contextOverride?.selection\n\t\t\t\t},\n\t\t\t\tuserIds: {\n\t\t\t\t\t...options.context.userIds,\n\t\t\t\t\t...contextOverride?.userIds\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t} };\n}\n//#endregion\n//#region src/mcp/resolve-mcp-tools.ts\nfunction createToolDescription(def, toolName, description) {\n\tconst parts = [`MCP tool \"${toolName}\" from server \"${def.key}\".`];\n\tif (description) parts.push(description);\n\treturn parts.join(\" \");\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 connectMcpDefinition(def, await resolveMcpAuth(def, resolver));\n\t\treturn {\n\t\t\ttools: connection.tools,\n\t\t\tconnection\n\t\t};\n\t}\n\tlet connection;\n\tconst ensureConnected = async () => {\n\t\tif (connection) return connection;\n\t\tconnection = await connectMcpDefinition(def, await resolveMcpAuth(def, resolver));\n\t\treturn connection;\n\t};\n\tconst tools = def.declaredTools.map((declared) => {\n\t\treturn {\n\t\t\tname: createToolName(def.key, declared.name),\n\t\t\tlabel: declared.title ?? declared.name,\n\t\t\tdescription: createToolDescription(def, declared.name, declared.description),\n\t\t\tparameters: 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\tasync execute(_toolCallId, params, signal) {\n\t\t\t\treturn (await ensureConnected()).callTool(declared.name, params, { signal });\n\t\t\t}\n\t\t};\n\t});\n\treturn {\n\t\ttools,\n\t\tconnection: {\n\t\t\tname: def.key,\n\t\t\ttools,\n\t\t\tasync callTool(toolName, args, options) {\n\t\t\t\treturn (await ensureConnected()).callTool(toolName, args, options);\n\t\t\t},\n\t\t\tclose: async () => {\n\t\t\t\tawait connection?.close();\n\t\t\t}\n\t\t}\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, MissingCredentialsError, NeedsSelectionError, OAuthNotConfiguredError, buildAssignmentSet, buildCredentialRunContext, buildWorkflowRunContext, canAssignCredentialInstance, canManageCredentialInstance, captureCredentialToolErrors, createCredentialBackend, createCredentialResolver, createLocalCredentialBackend, createOAuthTokenAdapterFromBackend, createOAuthTokenRefreshRegistry, createPlatformCredentialBackend, credentialScopeMatchesContext, credentialScopePrefix, defineMcp, formatCredentialErrorMessage, formatCredentialRef, formatCredentialRefSuggestion, getProjectCredentialBackend, isCredentialError, isWorkerRuntime, loadCredentialAssignments, parseCredentialRef, parseResolvedCredentials, resolveActionCredentials, resolveAgentConnectContext, resolveCredentialRef, resolveCredentialRequirements, resolveKeystrokeInstanceId, resolveMcpTools, selectAssignedInstanceId, setProjectCredentialBackend, stubOAuthTokenAdapter, withCredentialAssignments };\n\n//# sourceMappingURL=index.mjs.map"],"x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,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,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,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,161,162,163,164,165,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],"mappings":";;;;;;;;;;;;;;AAAA,MAAM,aAAa,OAAO,IAAI,oBAAoB;AAElD,SAAS,GAAG,OAAO,MAAM;CACvB,IAAI,CAAC,SAAS,OAAO,UAAU,UAC7B,OAAO;CAET,IAAI,iBAAiB,MACnB,OAAO;CAET,IAAI,CAAC,OAAO,UAAU,eAAe,KAAK,MAAM,UAAU,GACxD,MAAM,IAAI,MACR,UAAU,KAAK,QAAQ,YAAY,8HACrC;CAEF,IAAI,MAAM,OAAO,eAAe,KAAK,EAAE;CACvC,IAAI,KACF,OAAO,KAAK;EACV,IAAI,cAAc,OAAO,IAAI,gBAAgB,KAAK,aAChD,OAAO;EAET,MAAM,OAAO,eAAe,GAAG;CACjC;CAEF,OAAO;AACT;;;ACvBA,IAAM,SAAN,MAAa;CACX,YAAY,OAA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