@selvajs/selva 4.20.1-beta.4 → 4.21.0-beta.6
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/build/adapter-node.js +1 -1
- package/build/client/_app/immutable/chunks/{CzfnuBzq.js → BAhtiTKe.js} +1 -1
- package/build/client/_app/immutable/chunks/BAhtiTKe.js.br +0 -0
- package/build/client/_app/immutable/chunks/BAhtiTKe.js.gz +0 -0
- package/build/client/_app/immutable/chunks/{D-uUm_OB.js → BepzH9eI.js} +4 -4
- package/build/client/_app/immutable/chunks/BepzH9eI.js.br +0 -0
- package/build/client/_app/immutable/chunks/{D-uUm_OB.js.gz → BepzH9eI.js.gz} +0 -0
- package/build/client/_app/immutable/chunks/BmoT9ksD.js +1 -0
- package/build/client/_app/immutable/chunks/BmoT9ksD.js.br +1 -0
- package/build/client/_app/immutable/chunks/BmoT9ksD.js.gz +0 -0
- package/build/client/_app/immutable/chunks/{qi43d-TM.js → CKbHmAlc.js} +1 -1
- package/build/client/_app/immutable/chunks/CKbHmAlc.js.br +0 -0
- package/build/client/_app/immutable/chunks/CKbHmAlc.js.gz +0 -0
- package/build/client/_app/immutable/chunks/{C6Y_BUwr.js → CmlXAF26.js} +1 -1
- package/build/client/_app/immutable/chunks/CmlXAF26.js.br +0 -0
- package/build/client/_app/immutable/chunks/CmlXAF26.js.gz +0 -0
- package/build/client/_app/immutable/chunks/{BDYCH-_Q.js → D5j4-ZO1.js} +1 -1
- package/build/client/_app/immutable/chunks/D5j4-ZO1.js.br +0 -0
- package/build/client/_app/immutable/chunks/D5j4-ZO1.js.gz +0 -0
- package/build/client/_app/immutable/chunks/DW5EJMC7.js +1 -0
- package/build/client/_app/immutable/chunks/DW5EJMC7.js.br +0 -0
- package/build/client/_app/immutable/chunks/DW5EJMC7.js.gz +0 -0
- package/build/client/_app/immutable/chunks/{DzxE3j6C.js → qXnHMKD9.js} +1 -1
- package/build/client/_app/immutable/chunks/qXnHMKD9.js.br +0 -0
- package/build/client/_app/immutable/chunks/qXnHMKD9.js.gz +0 -0
- package/build/client/_app/immutable/entry/{app.BpT6WkO1.js → app.DblLep9O.js} +2 -2
- package/build/client/_app/immutable/entry/app.DblLep9O.js.br +0 -0
- package/build/client/_app/immutable/entry/app.DblLep9O.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{1.D3kiiIk_.js → 1.DWd6YbcT.js} +1 -1
- package/build/client/_app/immutable/nodes/1.DWd6YbcT.js.br +0 -0
- package/build/client/_app/immutable/nodes/1.DWd6YbcT.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{2.CUNbzjI_.js → 2.CS32Eh9m.js} +1 -1
- package/build/client/_app/immutable/nodes/2.CS32Eh9m.js.br +0 -0
- package/build/client/_app/immutable/nodes/2.CS32Eh9m.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{20.9OIre0ah.js → 20.CUK41A3B.js} +1 -1
- package/build/client/_app/immutable/nodes/20.CUK41A3B.js.br +0 -0
- package/build/client/_app/immutable/nodes/20.CUK41A3B.js.gz +0 -0
- package/build/client/_app/immutable/nodes/21.DvC40Ypm.js +1 -0
- package/build/client/_app/immutable/nodes/21.DvC40Ypm.js.br +0 -0
- package/build/client/_app/immutable/nodes/21.DvC40Ypm.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{25.DW1_vMxq.js → 25.D6EkgNRa.js} +1 -1
- package/build/client/_app/immutable/nodes/25.D6EkgNRa.js.br +0 -0
- package/build/client/_app/immutable/nodes/25.D6EkgNRa.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{3.3Z4QUsQQ.js → 3.Ctd9OGCk.js} +1 -1
- package/build/client/_app/immutable/nodes/3.Ctd9OGCk.js.br +0 -0
- package/build/client/_app/immutable/nodes/3.Ctd9OGCk.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{5.DmA9lTA-.js → 5.Wh_w3RkZ.js} +1 -1
- package/build/client/_app/immutable/nodes/5.Wh_w3RkZ.js.br +2 -0
- package/build/client/_app/immutable/nodes/5.Wh_w3RkZ.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{6.D6WLqCgl.js → 6.C-DiUI5R.js} +1 -1
- package/build/client/_app/immutable/nodes/6.C-DiUI5R.js.br +0 -0
- package/build/client/_app/immutable/nodes/6.C-DiUI5R.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{7.CNuRjkv2.js → 7.B8yubYrv.js} +1 -1
- package/build/client/_app/immutable/nodes/7.B8yubYrv.js.br +0 -0
- package/build/client/_app/immutable/nodes/7.B8yubYrv.js.gz +0 -0
- package/build/client/_app/version.json +1 -1
- package/build/client/_app/version.json.br +0 -0
- package/build/client/_app/version.json.gz +0 -0
- package/build/server/.vite/manifest.json +7 -5
- package/build/server/chunks/api.js +9 -2
- package/build/server/chunks/api.js.map +1 -1
- package/build/server/chunks/computeRateLimit.server.js +1 -1
- package/build/server/chunks/engine.server.js +2 -2
- package/build/server/chunks/engine.server.js.map +1 -1
- package/build/server/chunks/grasshopper.js +217 -162
- package/build/server/chunks/grasshopper.js.map +1 -1
- package/build/server/chunks/handlers.js +1 -1
- package/build/server/chunks/instance.js +3 -3
- package/build/server/chunks/internal.js +1 -1
- package/build/server/chunks/liveSolve.server.js +1 -1
- package/build/server/chunks/localeContext.svelte.js +14 -0
- package/build/server/chunks/localeContext.svelte.js.map +1 -1
- package/build/server/chunks/{outcome-DNrffAXp.js → outcome-D28FgvFK.js} +9 -6
- package/build/server/chunks/outcome-D28FgvFK.js.map +1 -0
- package/build/server/chunks/package.js +1 -1
- package/build/server/chunks/package.js.map +1 -1
- package/build/server/chunks/providers.server.js +59 -40
- package/build/server/chunks/providers.server.js.map +1 -1
- package/build/server/chunks/registry.js +1 -1
- package/build/server/chunks/schema.js +1 -1
- package/build/server/chunks/schema.js.map +1 -1
- package/build/server/chunks/serverStats.server.js +1 -1
- package/build/server/chunks/solve.server.js +31 -4
- package/build/server/chunks/solve.server.js.map +1 -1
- package/build/server/chunks/sveltekit.js +1 -1
- package/build/server/entries/endpoints/api/admin/compute/status/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/admin/orgs/_id_/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/admin/orgs/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/admin/projects/_id_/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/admin/projects/_id_/grants/_grantId_/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/admin/projects/_id_/grants/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/admin/projects/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/admin/users/_id_/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/admin/users/_id_/disable/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/admin/users/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/compute/_server.ts.js +5 -1
- package/build/server/entries/endpoints/api/v1/compute/_server.ts.js.map +1 -1
- package/build/server/entries/endpoints/api/v1/compute/schema/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/definitions/_guid_/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/definitions/_guid_/image/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/definitions/_guid_/publish/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/definitions/_guid_/schema/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/definitions/_guid_/share-links/_linkId_/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/definitions/_guid_/share-links/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/definitions/_guid_/solve/_server.ts.js +2 -1
- package/build/server/entries/endpoints/api/v1/definitions/_guid_/solve/_server.ts.js.map +1 -1
- package/build/server/entries/endpoints/api/v1/definitions/_guid_/versions/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/definitions/_guid_/versions/_versionId_/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/definitions/_guid_/versions/_versionId_/schema/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/projects/_id_/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/projects/_id_/members/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/projects/_id_/members/_userId_/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/projects/_id_/reclaim/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/solve/_solveId_/cancel/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/solve-events/_server.ts.js +1 -1
- package/build/server/entries/endpoints/docs/api/openapi.yaml/_server.ts.js +1 -1
- package/build/server/entries/pages/library/_guid_/_page.server.ts.js +4 -4
- package/build/server/entries/pages/library/_guid_/_page.server.ts.js.map +1 -1
- package/build/server/entries/pages/library/_guid_/_page.svelte.js +232 -11
- package/build/server/entries/pages/library/_guid_/_page.svelte.js.map +1 -1
- package/build/server/manifest-full.js +1 -1
- package/build/server/manifest.js +1 -1
- package/build/server/nodes/1.js +1 -1
- package/build/server/nodes/2.js +1 -1
- package/build/server/nodes/20.js +1 -1
- package/build/server/nodes/21.js +1 -1
- package/build/server/nodes/25.js +1 -1
- package/build/server/nodes/3.js +1 -1
- package/build/server/nodes/5.js +1 -1
- package/build/server/nodes/6.js +1 -1
- package/build/server/nodes/7.js +1 -1
- package/build/server/server.js +1 -1
- package/package.json +10 -10
- package/build/client/_app/immutable/chunks/BDYCH-_Q.js.br +0 -0
- package/build/client/_app/immutable/chunks/BDYCH-_Q.js.gz +0 -0
- package/build/client/_app/immutable/chunks/C6Y_BUwr.js.br +0 -0
- package/build/client/_app/immutable/chunks/C6Y_BUwr.js.gz +0 -0
- package/build/client/_app/immutable/chunks/CzfnuBzq.js.br +0 -0
- package/build/client/_app/immutable/chunks/CzfnuBzq.js.gz +0 -0
- package/build/client/_app/immutable/chunks/D-uUm_OB.js.br +0 -0
- package/build/client/_app/immutable/chunks/D84F7w9g.js +0 -1
- package/build/client/_app/immutable/chunks/D84F7w9g.js.br +0 -1
- package/build/client/_app/immutable/chunks/D84F7w9g.js.gz +0 -0
- package/build/client/_app/immutable/chunks/DQsP4nZb.js +0 -1
- package/build/client/_app/immutable/chunks/DQsP4nZb.js.br +0 -0
- package/build/client/_app/immutable/chunks/DQsP4nZb.js.gz +0 -0
- package/build/client/_app/immutable/chunks/DzxE3j6C.js.br +0 -0
- package/build/client/_app/immutable/chunks/DzxE3j6C.js.gz +0 -0
- package/build/client/_app/immutable/chunks/qi43d-TM.js.br +0 -0
- package/build/client/_app/immutable/chunks/qi43d-TM.js.gz +0 -0
- package/build/client/_app/immutable/entry/app.BpT6WkO1.js.br +0 -0
- package/build/client/_app/immutable/entry/app.BpT6WkO1.js.gz +0 -0
- package/build/client/_app/immutable/nodes/1.D3kiiIk_.js.br +0 -0
- package/build/client/_app/immutable/nodes/1.D3kiiIk_.js.gz +0 -0
- package/build/client/_app/immutable/nodes/2.CUNbzjI_.js.br +0 -0
- package/build/client/_app/immutable/nodes/2.CUNbzjI_.js.gz +0 -0
- package/build/client/_app/immutable/nodes/20.9OIre0ah.js.br +0 -0
- package/build/client/_app/immutable/nodes/20.9OIre0ah.js.gz +0 -0
- package/build/client/_app/immutable/nodes/21.BkNlRItr.js +0 -1
- package/build/client/_app/immutable/nodes/21.BkNlRItr.js.br +0 -0
- package/build/client/_app/immutable/nodes/21.BkNlRItr.js.gz +0 -0
- package/build/client/_app/immutable/nodes/25.DW1_vMxq.js.br +0 -0
- package/build/client/_app/immutable/nodes/25.DW1_vMxq.js.gz +0 -0
- package/build/client/_app/immutable/nodes/3.3Z4QUsQQ.js.br +0 -0
- package/build/client/_app/immutable/nodes/3.3Z4QUsQQ.js.gz +0 -0
- package/build/client/_app/immutable/nodes/5.DmA9lTA-.js.br +0 -1
- package/build/client/_app/immutable/nodes/5.DmA9lTA-.js.gz +0 -0
- package/build/client/_app/immutable/nodes/6.D6WLqCgl.js.br +0 -0
- package/build/client/_app/immutable/nodes/6.D6WLqCgl.js.gz +0 -0
- package/build/client/_app/immutable/nodes/7.CNuRjkv2.js.br +0 -0
- package/build/client/_app/immutable/nodes/7.CNuRjkv2.js.gz +0 -0
- package/build/server/chunks/outcome-DNrffAXp.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api.js","names":["sharedDefault"],"sources":["../../../../platform/src/definitions/bodies.ts","../../../../platform/src/projects/schemas.ts","../../../../platform/src/shareLinks/schemas.ts","../../../../server/src/compute/idempotency.ts","../../../../server/src/api/request.ts","../../../../server/src/api/scope.ts","../../../../server/src/api/rate-limit.ts","../../../../server/src/api/idempotency-http.ts","../../../../server/src/api/idempotency.ts","../../../../server/src/api/respond.ts","../../../../server/src/api/bodies.ts","../../../../server/src/api/responses-schema.ts"],"sourcesContent":["import { z } from 'zod';\nimport { DefinitionStatusSchema, GuidSchema } from './schemas.js';\n\n/** HTTP-body validator for new-definition input. */\nexport const CreateDefinitionInputSchema = z.object({\n\tdisplayName: z.string().trim().min(1, 'Display name is required').max(256),\n\tdescription: z.string().max(2000).optional(),\n\tcoverImage: z.string().max(2048).optional(),\n\tcategory: z.string().max(128).optional(),\n\ttags: z.array(z.string().max(64)).max(20).optional(),\n\tprojectId: GuidSchema,\n\tcomputeServerId: GuidSchema.optional()\n});\n\n/**\n * PATCH validator. Field semantics match `DefinitionRecordPatch`:\n * - missing / `undefined` — leave unchanged\n * - `null` — clear (only on nullable fields)\n * - value — set\n */\nexport const UpdateMetadataInputSchema = z.object({\n\tdisplayName: z.string().trim().min(1, 'Display name is required').max(256).optional(),\n\tdescription: z.string().max(2000).nullable().optional(),\n\tcoverImage: z.string().max(2048).nullable().optional(),\n\tcategory: z.string().max(128).nullable().optional(),\n\ttags: z.array(z.string().max(64)).max(20).nullable().optional(),\n\tprojectId: GuidSchema.optional(),\n\tcomputeServerId: GuidSchema.nullable().optional(),\n\t// Bounded so a settings typo can't request a runaway quota.\n\tsolveCacheLimit: z.number().int().min(0).max(100_000).nullable().optional(),\n\tstatus: DefinitionStatusSchema.optional()\n});\n\nexport type UpdateMetadataInput = z.infer<typeof UpdateMetadataInputSchema>;\n\n/** Body for publishing a version; without `versionId`, the current draft goes live. */\nexport const PublishVersionInputSchema = z\n\t.object({\n\t\tversionId: GuidSchema.optional()\n\t})\n\t.default({});\n","import { z } from 'zod';\n\nexport const ProjectVisibilitySchema = z.enum(['public', 'org', 'private', 'platform']);\nexport type ProjectVisibility = z.infer<typeof ProjectVisibilitySchema>;\n\nexport const ProjectRoleSchema = z.enum(['owner', 'editor', 'viewer']);\nexport type ProjectRole = z.infer<typeof ProjectRoleSchema>;\n\n/** Cross-field check for PATCH flows. Call on the merged post-patch shape. */\nexport function validateProjectFlags(merged: {\n\tvisibility: ProjectVisibility;\n\tautoJoinOnUpload?: boolean;\n}): { path: string; message: string }[] {\n\tif (!merged.autoJoinOnUpload) return [];\n\tif (merged.visibility === 'platform') {\n\t\treturn [\n\t\t\t{ path: 'autoJoinOnUpload', message: 'autoJoinOnUpload is not allowed on platform projects' }\n\t\t];\n\t}\n\tif (merged.visibility !== 'public') {\n\t\treturn [{ path: 'autoJoinOnUpload', message: 'autoJoinOnUpload requires visibility=public' }];\n\t}\n\treturn [];\n}\n","import { z } from 'zod';\nimport { DefinitionChannelSchema } from '../definitions/schemas.js';\n\n/** HTTP body for minting a share link. */\nexport const CreateShareLinkInputSchema = z.object({\n\tchannel: DefinitionChannelSchema.default('live'),\n\tname: z.string().max(128).optional(),\n\tallowSolve: z.boolean().default(true),\n\t/**\n\t * Null is the minter's deliberate \"uncap\" choice. Omitted stays undefined here:\n\t * the mint handler applies `DEFAULT_SHARE_LINK_MAX_SOLVES`.\n\t */\n\tmaxSolves: z.number().int().min(1).nullable().optional(),\n\texpiresAt: z.iso.datetime().nullable().optional()\n});\n\nexport type CreateShareLinkInput = z.infer<typeof CreateShareLinkInputSchema>;\n","/**\n * Idempotency store for the solve endpoint: a repeat of the same request within\n * the TTL replays the first response instead of re-solving.\n *\n * **This absorbs client retries; it is not a result cache.** The TTL is short\n * and the store is process-local, so a retry that lands on another instance\n * (or after the TTL) re-solves — a duplicate solve costs compute, not\n * correctness. What it must never do is return one caller's result to another,\n * hence the caller identity in the key.\n *\n * The store holds a **promise**, reserved before the work starts, because a\n * client that retries on timeout usually retries while the first solve is still\n * running: the second request awaits the first instead of starting a second solve.\n *\n * Sweep and cap are both driven by `run` rather than a timer — a timer would keep\n * the event loop alive and give this module a lifecycle its callers don't have.\n */\n\nexport interface IdempotencyStoreConfig {\n\t/** How long a completed response stays replayable, in ms. */\n\tttlMs: number;\n\t/**\n\t * Max retained entries; once exceeded, the ones nearest expiry are evicted.\n\t * Evicting only costs a re-solve on a retry, so size this above the plausible\n\t * number of in-flight + recent keys. Defaults to\n\t * {@link DEFAULT_IDEMPOTENCY_MAX_KEYS}.\n\t */\n\tmaxKeys?: number;\n\t/**\n\t * How often (ms) to sweep expired entries, amortized onto `run`. Defaults to\n\t * `ttlMs`. `0` disables the sweep, leaving only the cap (test seam).\n\t */\n\tsweepIntervalMs?: number;\n\t/**\n\t * Max total weight of completed entries, as measured by the store's `weigh`.\n\t * The key cap alone doesn't bound memory when one entry can be a 100 MB\n\t * solve. Over budget, the entries nearest expiry go first.\n\t */\n\tmaxWeight?: number;\n}\n\n/** Default {@link IdempotencyStoreConfig.maxKeys}. */\nexport const DEFAULT_IDEMPOTENCY_MAX_KEYS = 10_000;\n\nexport interface IdempotencyOutcome<T> {\n\tvalue: T;\n\t/** True when this call awaited an existing entry rather than running `fn`. */\n\treplayed: boolean;\n}\n\nexport interface IdempotencyStore<T> {\n\t/**\n\t * Run `fn` under `key`, or join/replay the entry already stored there. The\n\t * entry is reserved before `fn` starts, so a concurrent retry awaits the first\n\t * run; a rejection drops the reservation.\n\t */\n\trun(key: string, fn: () => Promise<T>): Promise<IdempotencyOutcome<T>>;\n\t/** Test seam — wipes in-memory state. Production code never calls this. */\n\treset(): void;\n\t/** Retained entry count, including entries not yet swept. */\n\tsize(): number;\n\treadonly config: Readonly<IdempotencyStoreConfig>;\n}\n\ninterface Entry<T> {\n\tpromise: Promise<T>;\n\t/**\n\t * Set when the promise settles. While in flight the entry is un-expirable —\n\t * a long solve must not have its reservation swept out from under the\n\t * retries that are already awaiting it.\n\t */\n\texpiresAt: number | null;\n\t/** Counted against `maxWeight` once settled; 0 while in flight. */\n\tweight: number;\n}\n\n/**\n * `T` is whatever the caller replays. It must not be a `Response` — a body can\n * only be read once, so the solve route stores a serialized snapshot instead.\n * `weigh` measures a completed value for `maxWeight`.\n */\nexport function createIdempotencyStore<T>(\n\tconfig: IdempotencyStoreConfig,\n\tweigh: (value: T) => number = () => 0\n): IdempotencyStore<T> {\n\tconst ttlMs = Math.max(0, Math.floor(config.ttlMs));\n\tconst maxKeys = Math.max(1, Math.floor(config.maxKeys ?? DEFAULT_IDEMPOTENCY_MAX_KEYS));\n\tconst sweepIntervalMs = Math.max(0, Math.floor(config.sweepIntervalMs ?? ttlMs));\n\tconst maxWeight = config.maxWeight ?? Number.POSITIVE_INFINITY;\n\tconst resolvedConfig: Readonly<IdempotencyStoreConfig> = Object.freeze({\n\t\t...config,\n\t\tttlMs,\n\t\tmaxKeys,\n\t\tsweepIntervalMs\n\t});\n\n\tconst entries = new Map<string, Entry<T>>();\n\tlet nextSweepAt = Number.POSITIVE_INFINITY;\n\tlet totalWeight = 0;\n\n\tfunction drop(key: string): void {\n\t\tconst entry = entries.get(key);\n\t\tif (!entry) return;\n\t\ttotalWeight -= entry.weight;\n\t\tentries.delete(key);\n\t}\n\n\t/** Settled entries only, nearest expiry first: in-flight ones have retries awaiting them. */\n\tfunction shedWeight(): void {\n\t\tif (totalWeight <= maxWeight) return;\n\t\tconst settled = [...entries.entries()]\n\t\t\t.filter(([, e]) => e.expiresAt !== null)\n\t\t\t.sort((a, b) => a[1].expiresAt! - b[1].expiresAt!);\n\t\tfor (const [key] of settled) {\n\t\t\tif (totalWeight <= maxWeight) break;\n\t\t\tdrop(key);\n\t\t}\n\t}\n\n\tfunction maybeSweep(now: number, headroom = 0): void {\n\t\tconst budget = Math.max(0, maxKeys - headroom);\n\t\tconst dueForSweep = sweepIntervalMs > 0 && now >= nextSweepAt;\n\t\tif (!dueForSweep && entries.size <= budget) return;\n\n\t\tfor (const [key, entry] of entries) {\n\t\t\tif (entry.expiresAt !== null && now > entry.expiresAt) drop(key);\n\t\t}\n\t\tif (sweepIntervalMs > 0) nextSweepAt = now + sweepIntervalMs;\n\n\t\tif (entries.size > budget) {\n\t\t\t// In-flight entries sort last: evicting one would orphan the retries\n\t\t\t// awaiting it, so they are given up only when nothing else is left.\n\t\t\tconst byExpiryAsc = [...entries.entries()].sort(\n\t\t\t\t(a, b) => (a[1].expiresAt ?? Infinity) - (b[1].expiresAt ?? Infinity)\n\t\t\t);\n\t\t\tfor (let i = 0; i < byExpiryAsc.length - budget; i++) drop(byExpiryAsc[i][0]);\n\t\t}\n\t}\n\n\treturn {\n\t\tconfig: resolvedConfig,\n\t\tasync run(key: string, fn: () => Promise<T>): Promise<IdempotencyOutcome<T>> {\n\t\t\tconst now = Date.now();\n\t\t\tconst existing = entries.get(key);\n\t\t\tif (existing && (existing.expiresAt === null || now <= existing.expiresAt)) {\n\t\t\t\treturn { value: await existing.promise, replayed: true };\n\t\t\t}\n\n\t\t\tmaybeSweep(now, entries.has(key) ? 0 : 1);\n\n\t\t\tconst promise = fn();\n\t\t\tconst entry: Entry<T> = { promise, expiresAt: null, weight: 0 };\n\t\t\tdrop(key);\n\t\t\tentries.set(key, entry);\n\t\t\tif (sweepIntervalMs > 0 && nextSweepAt === Number.POSITIVE_INFINITY) {\n\t\t\t\tnextSweepAt = now + sweepIntervalMs;\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tconst value = await promise;\n\t\t\t\tentry.expiresAt = Date.now() + ttlMs;\n\t\t\t\tif (entries.get(key) === entry) {\n\t\t\t\t\tentry.weight = weigh(value);\n\t\t\t\t\ttotalWeight += entry.weight;\n\t\t\t\t\tshedWeight();\n\t\t\t\t}\n\t\t\t\treturn { value, replayed: false };\n\t\t\t} catch (err) {\n\t\t\t\t// A failed solve is retryable — drop the reservation rather than\n\t\t\t\t// replaying the error to every retry for the whole TTL. Only drop our\n\t\t\t\t// own entry: a later `run` may already have replaced it.\n\t\t\t\tif (entries.get(key) === entry) drop(key);\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t},\n\t\treset(): void {\n\t\t\tentries.clear();\n\t\t\ttotalWeight = 0;\n\t\t\tnextSweepAt = Number.POSITIVE_INFINITY;\n\t\t},\n\t\tsize(): number {\n\t\t\treturn entries.size;\n\t\t}\n\t};\n}\n","/**\n * Reading a request: path params, JSON bodies, multipart uploads.\n *\n * Every helper here fails by throwing `ApiError`, so a handler using them names\n * no web framework. They were written against SvelteKit's `error()` and moved\n * once the handlers themselves became transport-free — the logic never depended\n * on the framework, only the throw did.\n *\n * `requireCaller` reads identity off `ApiRequest`, never off a host's `locals`\n * — a host maps its own session shape onto `ctx`/`user` when it builds the\n * request, and nothing below this line knows how it did that.\n */\n\nimport type { AuthUser, RequestContext } from '@selvajs/platform';\nimport type { ZodError, ZodType } from 'zod';\nimport { apiError, ApiErrorCode } from './errors.js';\nimport type { ApiRequest } from './types.js';\n\n/**\n * The authenticated caller, or a 401.\n *\n * `ctx` and `user` are optional on `ApiRequest` because a host builds one for\n * anonymous requests too (share-token solves reach handlers with a `ctx` and no\n * `user`). Every handler that needs an identity narrows it here rather than\n * asserting the fields non-null, so the unauthenticated path fails as a denial\n * instead of a crash.\n */\nexport function requireCaller(req: ApiRequest): { ctx: RequestContext; user: AuthUser } {\n\tif (!req.ctx || !req.user) {\n\t\tapiError(401, ApiErrorCode.UNAUTHORIZED, 'Unauthorized');\n\t}\n\treturn { ctx: req.ctx, user: req.user };\n}\n\n/**\n * Refuse an API key: for actions whose effect outlives the key (members,\n * invites, keys themselves), so revoking a leaked key ends what it did.\n */\nexport function requireSession(req: ApiRequest, message: string): void {\n\tif (req.ctx?.apiScope) apiError(403, ApiErrorCode.FORBIDDEN, message);\n}\n\n/**\n * Fail with a Zod error's messages, one per field.\n *\n * The top-level `message` names the first problem so a human reading the\n * response learns something without parsing `fields`.\n */\nexport function throwZodError(err: ZodError): never {\n\tconst fields: Record<string, string> = {};\n\tfor (const issue of err.issues) {\n\t\tconst key = issue.path.length ? issue.path.join('.') : '_';\n\t\t// First message per field wins; later issues on the same path are\n\t\t// usually redundant refinements.\n\t\tif (!(key in fields)) fields[key] = issue.message;\n\t}\n\tconst first = err.issues[0];\n\tconst path = first.path.length ? `${first.path.join('.')}: ` : '';\n\tapiError(400, ApiErrorCode.VALIDATION_FAILED, `${path}${first.message}`, fields);\n}\n\n// ============================================================================\n// Path params\n// ============================================================================\n\n/**\n * Read required path params, 400ing on any that is missing or blank.\n *\n * A router types every param as `string`, but a route can be reached with an\n * empty segment — this catches that instead of letting a stale non-null\n * assertion paper over it.\n *\n * Does **not** validate format — a guid-shaped param still goes through a\n * schema where the route cares. Replaces the `if (!id) apiError(...)` preamble,\n * not the schema check.\n */\nexport function requireParams<K extends string>(\n\tparams: Partial<Record<string, string>>,\n\t...names: K[]\n): Record<K, string> {\n\tconst out = {} as Record<K, string>;\n\tconst missing: string[] = [];\n\n\tfor (const name of names) {\n\t\tconst value = params[name];\n\t\tif (!value) {\n\t\t\tmissing.push(name);\n\t\t\tcontinue;\n\t\t}\n\t\tout[name] = value;\n\t}\n\n\tif (missing.length) {\n\t\tapiError(\n\t\t\t400,\n\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t`Missing path parameter${missing.length > 1 ? 's' : ''}: ${missing.join(', ')}`\n\t\t);\n\t}\n\treturn out;\n}\n\n/**\n * Read a path param through a Zod schema, 400ing on a bad value.\n *\n * The format-checking counterpart to `requireParams` — for guids, enum-shaped\n * segments, anything where \"present\" isn't the same as \"valid\".\n */\nexport function parseParam<T>(value: string | undefined, schema: ZodType<T>, name: string): T {\n\tconst parsed = schema.safeParse(value);\n\tif (!parsed.success) {\n\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, `Invalid or missing ${name}`);\n\t}\n\treturn parsed.data;\n}\n\n// ============================================================================\n// Request bodies\n// ============================================================================\n\n/**\n * Parse and validate a JSON body. Broken JSON is a 400, not a 500 from\n * `request.json()`.\n *\n * `missingAs` covers endpoints whose fields are all optional: passing `{}` lets\n * an empty body mean \"no changes\" instead of a validation failure. Only an\n * empty body: a truncated `{\"versionId\":…` read as \"no changes\" would publish\n * the draft instead of rolling back.\n */\nexport async function parseBody<T>(\n\trequest: Request,\n\tschema: ZodType<T>,\n\t{ missingAs }: { missingAs?: unknown } = {}\n): Promise<T> {\n\tconst text = await request.text().catch(() => '');\n\tlet raw: unknown = null;\n\tif (text.trim()) {\n\t\ttry {\n\t\t\traw = JSON.parse(text);\n\t\t} catch {\n\t\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, 'The request body is not valid JSON.');\n\t\t}\n\t}\n\tconst parsed = schema.safeParse(raw ?? missingAs ?? null);\n\tif (!parsed.success) throwZodError(parsed.error);\n\treturn parsed.data;\n}\n\n// ============================================================================\n// Uploads\n// ============================================================================\n\nconst parsedForms = new WeakMap<Request, Promise<FormData>>();\n\n/**\n * The request's form body, parsed once: the idempotency fingerprint reads it\n * before the handler does, and a definition upload is too large to buffer twice.\n * On an idempotent route, `request.formData()` throws: the body is already used.\n * A conformance test keeps handlers off it.\n */\nexport function readForm(request: Request): Promise<FormData> {\n\tlet form = parsedForms.get(request);\n\tif (!form) {\n\t\tform = request\n\t\t\t.formData()\n\t\t\t.catch(() =>\n\t\t\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, 'The request body is not a valid form.')\n\t\t\t);\n\t\tparsedForms.set(request, form);\n\t}\n\treturn form;\n}\n\n/**\n * Pull a required file out of a multipart body and check its size and, where\n * given, its extension.\n *\n * A second line of defence, not the first: a host's body-size guard should\n * reject an oversized request before it is buffered. This catches a file that\n * is individually too large inside a request that isn't.\n *\n * Caps are passed in rather than read here — they are deployment config, and a\n * package that resolved them would pin every host to one source of truth.\n */\nexport function requireUpload(\n\tform: FormData,\n\tfield: string,\n\t{\n\t\tmaxBytes,\n\t\textensions,\n\t\tcontentTypes,\n\t\tlabel = 'File'\n\t}: {\n\t\tmaxBytes: number;\n\t\textensions?: readonly string[];\n\t\tcontentTypes?: { allowed: ReadonlySet<string>; message: string };\n\t\tlabel?: string;\n\t}\n): { file: File; extension: string } {\n\tconst file = form.get(field);\n\tif (!(file instanceof File) || file.size === 0) {\n\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, `A ${label.toLowerCase()} is required`);\n\t}\n\n\tconst extension = file.name.slice(file.name.lastIndexOf('.')).toLowerCase();\n\tif (extensions && !extensions.includes(extension)) {\n\t\tapiError(\n\t\t\t400,\n\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t`File type not allowed. Allowed: ${extensions.join(', ')}`\n\t\t);\n\t}\n\n\tif (contentTypes && !contentTypes.allowed.has(file.type)) {\n\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, contentTypes.message);\n\t}\n\n\tif (file.size > maxBytes) {\n\t\tapiError(\n\t\t\t400,\n\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t`${label} too large. Max size: ${maxBytes / (1024 * 1024)} MB`\n\t\t);\n\t}\n\n\treturn { file, extension };\n}\n\n/** A multipart text field, trimmed and length-capped. Absent stays `undefined`. */\nexport function formText(\n\tform: FormData,\n\tfield: string,\n\t{ maxLength }: { maxLength?: number } = {}\n): string | undefined {\n\tconst raw = form.get(field);\n\tif (typeof raw !== 'string') return undefined;\n\tconst trimmed = raw.trim();\n\tif (!trimmed) return undefined;\n\treturn maxLength ? trimmed.slice(0, maxLength) : trimmed;\n}\n","import type { ApiScopeAction, RequestContext, ScopeTarget } from '@selvajs/platform';\nimport { apiScopeActionCovers, outsideTokenOrg, scopeAllows } from '@selvajs/platform';\nimport { apiError, ApiErrorCode } from './errors.js';\nimport type { ApiRequest } from './types.js';\n\n/** The default action for a method: reads are `read`, everything else `write`. */\nexport function actionForMethod(method: string): ApiScopeAction {\n\treturn method === 'GET' || method === 'HEAD' ? 'read' : 'write';\n}\n\n/**\n * Refuse an API-token request its scopes don't cover, with 403 naming the\n * scope that would have passed. Browser sessions always pass.\n *\n * `runHandler` calls this for every mounted route. A route that builds its own\n * `Response` must call it itself.\n */\nexport function assertScope(\n\tctx: RequestContext | undefined,\n\taction: ApiScopeAction,\n\ttarget?: ScopeTarget\n): void {\n\tif (!ctx?.apiScope || scopeAllows(ctx, action, target)) return;\n\trecordRefusal(ctx.apiScope.tokenId);\n\tapiError(403, ApiErrorCode.FORBIDDEN, `This API token doesn't allow ${action} here.`, undefined, {\n\t\trequiredScope: requiredScope(ctx, action, target)\n\t});\n}\n\n/**\n * Refuse an API-token request whose key holds `action` on nothing at all. For\n * routes that act only on the caller's own solves and streams, which name no\n * project: a key that may solve in one project must still cancel and watch\n * those solves.\n */\nexport function assertScopeAnywhere(ctx: RequestContext | undefined, action: ApiScopeAction): void {\n\tif (!ctx?.apiScope) return;\n\tif (ctx.apiScope.scopes.some((s) => apiScopeActionCovers(s.action, action))) return;\n\trecordRefusal(ctx.apiScope.tokenId);\n\tapiError(403, ApiErrorCode.FORBIDDEN, `This API token doesn't allow ${action}.`);\n}\n\n// Per process and per UTC day, so the token page can flag a misconfigured\n// integration. Kept in memory on purpose: refusals are not audited.\nconst refusals = new Map<string, { day: string; count: number }>();\n\nconst utcDay = () => new Date().toISOString().slice(0, 10);\n\nfunction recordRefusal(tokenId: string): void {\n\tconst day = utcDay();\n\tconst entry = refusals.get(tokenId);\n\tif (entry?.day === day) entry.count++;\n\telse refusals.set(tokenId, { day, count: 1 });\n}\n\n/** Scope refusals for `tokenId` since midnight UTC, in this process. */\nexport function scopeRefusalsToday(tokenId: string): number {\n\tconst entry = refusals.get(tokenId);\n\treturn entry?.day === utcDay() ? entry.count : 0;\n}\n\nfunction requiredScope(ctx: RequestContext, action: ApiScopeAction, target?: ScopeTarget): string {\n\tif (target?.projectId) return `${action}:project:${target.projectId}`;\n\tif (target?.definitionId) return `${action}:definition:${target.definitionId}`;\n\treturn `${action}:org:${ctx.actingOrgId}`;\n}\n\n/** Scope target for routes addressed by a project id param. */\nexport function projectScopeTarget(param = 'id') {\n\treturn (req: ApiRequest): ScopeTarget => ({ projectId: req.params[param] });\n}\n\n/**\n * Scope target for routes addressed by a definition guid param. Loads the\n * record so a project-scoped key reaches the definitions inside its project.\n *\n * A definition outside the key's org resolves like a missing one: otherwise the\n * 403 detail would confirm the guid exists and name its project.\n */\nexport function definitionScopeTarget(param = 'guid') {\n\treturn async (req: ApiRequest): Promise<ScopeTarget> => {\n\t\tconst definitionId = req.params[param];\n\t\tif (!definitionId || !req.ctx) return { definitionId };\n\t\tconst record = await req.deps.definitionMeta.get(req.ctx, definitionId);\n\t\tconst project = record ? await req.deps.projects.getProject(req.ctx, record.projectId) : null;\n\t\tif (!project || outsideTokenOrg(req.ctx, project.orgId)) return { definitionId };\n\t\treturn { definitionId, projectId: project.id };\n\t};\n}\n","/**\n * The general per-token request limit `runHandler` applies to every API-token\n * request. Browser sessions are not charged: their abuse surface is the\n * per-user compute bucket and the login limiter, not request volume.\n *\n * Solves charge this bucket and the owner's `user:{id}` compute bucket, so ten\n * keys of one user never buy ten times the compute.\n *\n * The default limiter is process-local (fixed window over\n * `createComputeRateLimiter`), so N instances admit N times the rate. A host\n * that needs one shared budget implements `ApiRateLimiter` over its own store.\n */\n\nimport type { ILogger, RequestContext } from '@selvajs/platform';\nimport { NoopLogger } from '@selvajs/platform';\nimport type { EnvRecord } from '@selvajs/platform/config';\nimport { createComputeRateLimiter } from '../compute/rate-limit.js';\nimport { readSettings } from '../config/read-settings.js';\nimport { API_TOKEN_RATE_LIMIT_SETTING } from '../config/settings.js';\nimport { ApiError, ApiErrorCode, toErrorBody } from './errors.js';\n\nexport interface ApiRateLimitVerdict {\n\tallowed: boolean;\n\t/** Requests admitted per window. */\n\tlimit: number;\n\t/** Requests left in the current window after this one. */\n\tremaining: number;\n\t/** Seconds until the window resets, when refused. */\n\tretryAfter?: number;\n}\n\n/** Records one request against `key`. Async so a shared-store implementation fits. */\nexport interface ApiRateLimiter {\n\thit(key: string): ApiRateLimitVerdict | Promise<ApiRateLimitVerdict>;\n}\n\nexport interface ApiRateLimitConfig {\n\twindowMs: number;\n\t/** `0` disables the limit. */\n\tmaxPerWindow: number;\n}\n\nexport const DEFAULT_API_RATE_LIMIT: Readonly<ApiRateLimitConfig> = Object.freeze({\n\twindowMs: 60_000,\n\tmaxPerWindow: API_TOKEN_RATE_LIMIT_SETTING.default\n});\n\n/** Read `API_TOKEN_RATE_LIMIT_MAX` (requests per window, `0` = off) from an injected env map. */\nexport function resolveApiRateLimitConfig(\n\tenv: EnvRecord,\n\tlogger: ILogger = new NoopLogger()\n): ApiRateLimitConfig {\n\tconst values = readSettings([API_TOKEN_RATE_LIMIT_SETTING], env, logger);\n\treturn {\n\t\twindowMs: DEFAULT_API_RATE_LIMIT.windowMs,\n\t\tmaxPerWindow: values.API_TOKEN_RATE_LIMIT_MAX as number\n\t};\n}\n\n/** Process-local fixed-window limiter. Returns `null` when `maxPerWindow` is 0. */\nexport function createApiRateLimiter(\n\tconfig: ApiRateLimitConfig = DEFAULT_API_RATE_LIMIT\n): ApiRateLimiter | null {\n\tif (config.maxPerWindow <= 0) return null;\n\tconst inner = createComputeRateLimiter(config);\n\tconst limit = config.maxPerWindow;\n\treturn {\n\t\thit(key) {\n\t\t\tconst result = inner.check(key);\n\t\t\treturn {\n\t\t\t\tallowed: result.allowed,\n\t\t\t\tlimit,\n\t\t\t\tremaining: Math.max(0, limit - inner.count(key)),\n\t\t\t\tretryAfter: result.retryAfter\n\t\t\t};\n\t\t}\n\t};\n}\n\nlet sharedDefault: ApiRateLimiter | null | undefined;\n\n/**\n * The limiter `depsFromConfig` wires when the host passes none. One per\n * process: deps are rebuilt per request, and a limiter per request counts\n * nothing.\n */\nexport function defaultApiRateLimiter(): ApiRateLimiter | null {\n\tif (sharedDefault === undefined) sharedDefault = createApiRateLimiter();\n\treturn sharedDefault;\n}\n\n/**\n * Projects one owner may create through API keys per window. A browser\n * session isn't counted. Process-local like the request limit.\n */\nexport const DEFAULT_PROJECT_CREATE_LIMIT: Readonly<ApiRateLimitConfig> = Object.freeze({\n\twindowMs: 60 * 60_000,\n\tmaxPerWindow: 20\n});\n\nlet sharedProjectCreate: ApiRateLimiter | null | undefined;\n\nexport function defaultProjectCreateLimiter(): ApiRateLimiter | null {\n\tif (sharedProjectCreate === undefined) {\n\t\tsharedProjectCreate = createApiRateLimiter(DEFAULT_PROJECT_CREATE_LIMIT);\n\t}\n\treturn sharedProjectCreate;\n}\n\n/**\n * Charge one request to the caller's token. `undefined` for a session caller\n * or when no limiter is wired.\n */\nexport async function chargeApiRateLimit(\n\tctx: RequestContext | undefined,\n\tlimiter: ApiRateLimiter | null | undefined\n): Promise<ApiRateLimitVerdict | undefined> {\n\tif (!ctx?.apiScope || !limiter) return undefined;\n\treturn limiter.hit(`token:${ctx.apiScope.tokenId}`);\n}\n\nexport function rateLimitHeaders(verdict: ApiRateLimitVerdict): Record<string, string> {\n\tconst headers: Record<string, string> = {\n\t\t'RateLimit-Limit': String(verdict.limit),\n\t\t'RateLimit-Remaining': String(verdict.remaining)\n\t};\n\tif (!verdict.allowed) headers['Retry-After'] = String(verdict.retryAfter ?? 1);\n\treturn headers;\n}\n\n/** The 429 envelope, with `Retry-After` and the `RateLimit-*` headers. */\nexport function rateLimitedResponse(\n\tverdict: ApiRateLimitVerdict,\n\tmessage = `Too many requests for this API token. Retry in ${verdict.retryAfter ?? 1}s.`\n): Response {\n\tconst retryAfter = String(verdict.retryAfter ?? 1);\n\tconst err = new ApiError(429, ApiErrorCode.RATE_LIMITED, message, undefined, { retryAfter });\n\treturn new Response(JSON.stringify(toErrorBody(err)), {\n\t\tstatus: 429,\n\t\theaders: { 'content-type': 'application/json', ...rateLimitHeaders(verdict) }\n\t});\n}\n\n/** Stamp the `RateLimit-*` headers onto a response. No-op without a verdict. */\nexport function withRateLimitHeaders(\n\tres: Response,\n\tverdict: ApiRateLimitVerdict | undefined\n): Response {\n\tif (!verdict) return res;\n\tconst headers = rateLimitHeaders(verdict);\n\ttry {\n\t\tfor (const [k, v] of Object.entries(headers)) res.headers.set(k, v);\n\t\treturn res;\n\t} catch {\n\t\t// A fetched or otherwise immutable response: rewrap rather than drop the headers.\n\t\tconst copy = new Headers(res.headers);\n\t\tfor (const [k, v] of Object.entries(headers)) copy.set(k, v);\n\t\treturn new Response(res.body, {\n\t\t\tstatus: res.status,\n\t\t\tstatusText: res.statusText,\n\t\t\theaders: copy\n\t\t});\n\t}\n}\n","/**\n * The HTTP layer over {@link createIdempotencyStore}: how a replayed response\n * is keyed, snapshotted, and identified on the wire.\n *\n * The store itself is generic over `T` and knows nothing about requests. This\n * is the part two hosts must agree on to implement the same `Idempotency-Key`\n * contract, and the part each would otherwise reinvent:\n *\n * - **The key namespaces by caller.** `Idempotency-Key` is client-chosen, so\n * two tenants can pick the same string. Without the caller in the key one\n * would replay the other's result — that is the whole security property\n * here, and a host that got it wrong would leak across tenants with\n * nothing failing at build time.\n * - **The response round-trips through a snapshot.** A `Response` body reads\n * exactly once, so storing the object itself replays an empty body.\n * - **A replay says so**, via `Idempotency-Replayed`. A client that cannot\n * tell a replay from a fresh run cannot tell a successful retry from a\n * second execution.\n *\n * How long a response stays replayable is *not* here: that trades a client's\n * retry window against serving a stale result after the underlying resource\n * moves, and only the host knows its own deadlines.\n */\n\n/** Header stamped on a replayed response, so a client can distinguish one. */\nexport const IDEMPOTENCY_REPLAYED_HEADER = 'Idempotency-Replayed';\n\n/**\n * A response flattened into something storable. Kept instead of the `Response`\n * because a body can only be read once.\n */\nexport interface StoredResponse {\n\tstatus: number;\n\theaders: [string, string][];\n\tbody: ArrayBuffer;\n}\n\n/**\n * Namespace a client-chosen key by its caller.\n *\n * `callerId` should be the narrowest identity available — a token id rather\n * than a user id where the host issues per-token credentials, so two tokens\n * held by one user do not share replays.\n */\nexport function idempotencyKey(callerId: string, clientKey: string): string {\n\treturn `${callerId} ${clientKey}`;\n}\n\n/** Flatten a response so it can be replayed. Consumes the body. */\nexport async function toStoredResponse(res: Response): Promise<StoredResponse> {\n\treturn {\n\t\tstatus: res.status,\n\t\theaders: [...res.headers.entries()],\n\t\tbody: await res.arrayBuffer()\n\t};\n}\n\n/** Rebuild a live `Response` from a snapshot, marking it when it is a replay. */\nexport function fromStoredResponse(stored: StoredResponse, replayed: boolean): Response {\n\tconst headers = new Headers(stored.headers);\n\tif (replayed) headers.set(IDEMPOTENCY_REPLAYED_HEADER, 'true');\n\treturn new Response(stored.body, { status: stored.status, headers });\n}\n","/**\n * `Idempotency-Key` for mounted routes that opt in with `idempotent: true`.\n *\n * Built on the generic store (`../compute/idempotency.ts`) and the wire\n * contract (`./idempotency-http.ts`). The store absorbs in-flight and near-term\n * retries in this process; it is not a durable record. A create that must never duplicate also needs the key on\n * the created row under a unique constraint, written in the same transaction.\n *\n * Each entry carries a fingerprint of method, path, query and body, so a client that\n * reuses a key for a different request gets 422 instead of someone else's\n * replay. Only responses below 400 are kept: a failed attempt frees the key so\n * a corrected retry can run.\n */\n\nimport { createHash } from 'node:crypto';\nimport type { RequestContext } from '@selvajs/platform';\nimport { createIdempotencyStore, type IdempotencyStore } from '../compute/idempotency.js';\nimport {\n\tfromStoredResponse,\n\tidempotencyKey,\n\ttoStoredResponse,\n\ttype StoredResponse\n} from './idempotency-http.js';\nimport { apiError, ApiErrorCode } from './errors.js';\nimport { readForm } from './request.js';\n\nexport const IDEMPOTENCY_KEY_HEADER = 'Idempotency-Key';\nexport const MAX_IDEMPOTENCY_KEY_LENGTH = 255;\n/** Covers a client's retry-on-timeout window without turning into a result cache. */\nexport const DEFAULT_API_IDEMPOTENCY_TTL_MS = 5 * 60_000;\n/**\n * Replayable response bytes one store keeps. A solve response can run to\n * hundreds of MB, so the key cap alone would let a client that sends a fresh\n * key per solve hold gigabytes for the whole TTL. Evicting costs a re-run.\n */\nexport const DEFAULT_API_IDEMPOTENCY_MAX_BYTES = 256 * 1024 * 1024;\n\nconst CLIENT_CLOSED_REQUEST = 499;\n\nexport interface IdempotentEntry {\n\tfingerprint: string;\n\tresponse: StoredResponse;\n}\n\nexport type ApiIdempotencyStore = IdempotencyStore<IdempotentEntry>;\n\nexport function createApiIdempotencyStore(\n\tttlMs = DEFAULT_API_IDEMPOTENCY_TTL_MS,\n\tmaxBytes = DEFAULT_API_IDEMPOTENCY_MAX_BYTES\n): ApiIdempotencyStore {\n\treturn createIdempotencyStore<IdempotentEntry>(\n\t\t{ ttlMs, maxWeight: maxBytes },\n\t\t(entry) => entry.response.body.byteLength\n\t);\n}\n\nlet sharedDefault: ApiIdempotencyStore | undefined;\n\n/** The store `depsFromConfig` wires when the host passes none. One per process. */\nexport function defaultApiIdempotencyStore(): ApiIdempotencyStore {\n\treturn (sharedDefault ??= createApiIdempotencyStore());\n}\n\n/**\n * The narrowest identity a key is namespaced by: the token for a token\n * request, so two keys of one user never share replays, else the user.\n */\nexport function idempotencyCallerId(ctx: RequestContext): string {\n\treturn ctx.apiScope ? `token:${ctx.apiScope.tokenId}` : `user:${ctx.userId}`;\n}\n\n/** Read and validate the client's key. `null` when the header is absent. */\nexport function readIdempotencyKey(request: Request): string | null {\n\tconst key = request.headers.get(IDEMPOTENCY_KEY_HEADER);\n\tif (key === null) return null;\n\tif (key.length === 0 || key.length > MAX_IDEMPOTENCY_KEY_LENGTH) {\n\t\tapiError(\n\t\t\t400,\n\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t`${IDEMPOTENCY_KEY_HEADER} must be 1 to ${MAX_IDEMPOTENCY_KEY_LENGTH} characters.`\n\t\t);\n\t}\n\treturn key;\n}\n\nasync function sha256Hex(bytes: BufferSource): Promise<string> {\n\tconst digest = await crypto.subtle.digest('SHA-256', bytes);\n\treturn Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join('');\n}\n\n/** SHA-256 over method, path with query, and body, hex. */\nexport async function requestFingerprint(\n\tmethod: string,\n\turl: URL,\n\tbody: ArrayBuffer | string\n): Promise<string> {\n\tconst head = new TextEncoder().encode(`${method.toUpperCase()} ${url.pathname}${url.search}\\n`);\n\tconst tail = typeof body === 'string' ? new TextEncoder().encode(body) : new Uint8Array(body);\n\tconst bytes = new Uint8Array(head.length + tail.length);\n\tbytes.set(head);\n\tbytes.set(tail, head.length);\n\treturn sha256Hex(bytes);\n}\n\nasync function fileSha256Hex(file: Blob): Promise<string> {\n\tconst hash = createHash('sha256');\n\tfor await (const chunk of file.stream()) hash.update(chunk);\n\treturn hash.digest('hex');\n}\n\n/**\n * The body `requestFingerprint` should hash. The handler can still read it: a\n * JSON body comes from a clone, a form through `readForm`, which parses it once\n * for both.\n *\n * Multipart is canonicalized to its fields and file contents: clients pick a\n * fresh random boundary per request, so the raw bytes of an identical retry\n * never match.\n */\nexport async function fingerprintBody(request: Request): Promise<ArrayBuffer | string> {\n\tconst type = request.headers.get('content-type') ?? '';\n\tif (!type.toLowerCase().startsWith('multipart/form-data')) {\n\t\treturn request.clone().arrayBuffer();\n\t}\n\tlet form: FormData;\n\ttry {\n\t\tform = await readForm(request);\n\t} catch {\n\t\t// The handler's own read fails the same way, and a failure is never replayed.\n\t\treturn 'malformed multipart';\n\t}\n\tconst parts: [string, string | { file: string; type: string; sha256: string }][] = [];\n\tfor (const [name, value] of form) {\n\t\tparts.push([\n\t\t\tname,\n\t\t\ttypeof value === 'string'\n\t\t\t\t? value\n\t\t\t\t: { file: value.name, type: value.type, sha256: await fileSha256Hex(value) }\n\t\t]);\n\t}\n\treturn JSON.stringify(parts);\n}\n\nclass NotReplayable {\n\tconstructor(\n\t\treadonly fingerprint: string,\n\t\treadonly response: StoredResponse\n\t) {}\n}\n\nfunction assertSameRequest(stored: string, fingerprint: string): void {\n\tif (stored !== fingerprint) {\n\t\tapiError(\n\t\t\t422,\n\t\t\tApiErrorCode.UNPROCESSABLE,\n\t\t\t`This ${IDEMPOTENCY_KEY_HEADER} was already used for a different request.`\n\t\t);\n\t}\n}\n\n/**\n * Run `fn` once per `(callerId, clientKey)`, replaying its response to repeats\n * with `Idempotency-Replayed: true`. Throws 422 when the key was used for a\n * different request. Errors `fn` throws propagate and free the key.\n */\nexport async function runIdempotent(\n\t{\n\t\tstore,\n\t\tcallerId,\n\t\tclientKey,\n\t\tfingerprint\n\t}: { store: ApiIdempotencyStore; callerId: string; clientKey: string; fingerprint: string },\n\tfn: () => Promise<Response>\n): Promise<Response> {\n\tlet outcome;\n\tlet ranHere = false;\n\ttry {\n\t\toutcome = await store.run(idempotencyKey(callerId, clientKey), async () => {\n\t\t\tranHere = true;\n\t\t\tconst res = await fn();\n\t\t\tconst response = await toStoredResponse(res);\n\t\t\tif (res.status >= 400) throw new NotReplayable(fingerprint, response);\n\t\t\treturn { fingerprint, response };\n\t\t});\n\t} catch (err) {\n\t\tif (!(err instanceof NotReplayable)) throw err;\n\t\tassertSameRequest(err.fingerprint, fingerprint);\n\t\t// 499 is the first client hanging up, which says nothing about this one:\n\t\t// its retry is the case the store exists for, so it runs on its own.\n\t\tif (!ranHere && err.response.status === CLIENT_CLOSED_REQUEST) {\n\t\t\treturn runIdempotent({ store, callerId, clientKey, fingerprint }, fn);\n\t\t}\n\t\t// A concurrent retry joining the failed attempt receives the same failure.\n\t\treturn fromStoredResponse(err.response, false);\n\t}\n\tassertSameRequest(outcome.value.fingerprint, fingerprint);\n\treturn fromStoredResponse(outcome.value.response, outcome.replayed);\n}\n","/**\n * Turn a handler result — or a thrown `ApiError` — into a web-standard\n * `Response`.\n *\n * This is the whole serialization boundary. A host framework that speaks\n * `Request`/`Response` (SvelteKit, Next route handlers, Hono, Remix) needs only\n * to build an `ApiRequest` and call `runHandler`; one that does not can reuse\n * `toErrorBody` and serialize itself.\n */\n\nimport { ApiError, ApiErrorCode, isApiError, toErrorBody } from './errors.js';\nimport type { ApiScopeAction, ScopeTarget } from '@selvajs/platform';\nimport type { ApiHandler, ApiRequest, ApiResponse } from './types.js';\nimport { actionForMethod, assertScope } from './scope.js';\nimport {\n\tchargeApiRateLimit,\n\tdefaultApiRateLimiter,\n\trateLimitedResponse,\n\twithRateLimitHeaders\n} from './rate-limit.js';\nimport {\n\tdefaultApiIdempotencyStore,\n\tfingerprintBody,\n\tidempotencyCallerId,\n\treadIdempotencyKey,\n\trequestFingerprint,\n\trunIdempotent\n} from './idempotency.js';\n\nexport { toErrorBody, type ApiErrorBody } from './errors.js';\n\nfunction toResponse(result: ApiResponse | Response): Response {\n\tif (result instanceof Response) return result;\n\n\tconst { status, body, headers } = result;\n\tif (body === undefined) return new Response(null, { status: status ?? 204, headers });\n\n\treturn new Response(JSON.stringify(body), {\n\t\tstatus: status ?? 200,\n\t\theaders: { 'content-type': 'application/json', ...headers }\n\t});\n}\n\nexport interface RunHandlerOptions {\n\t/** The 500 message when the handler throws something unmapped. */\n\tfallback: string;\n\t/**\n\t * Folds a host's own domain errors into the envelope before the 500 fallback.\n\t * The Selva app maps `ProviderError`, `SchemaExtractionError` and\n\t * `ComputeServerUnconfiguredError` this way, none of which belong here.\n\t */\n\tmapError?: (err: unknown) => ApiError | undefined;\n\t/**\n\t * What the route does, for API-token scope checks. Defaults from the method:\n\t * `GET`/`HEAD` are `read`, everything else `write`. Solve routes say `solve`.\n\t */\n\taction?: ApiScopeAction;\n\t/**\n\t * The project or definition the route touches. Without it the scope check is\n\t * org-level, which project- and definition-scoped keys never pass.\n\t */\n\tscopeTarget?: (req: ApiRequest) => ScopeTarget | Promise<ScopeTarget>;\n\t/**\n\t * Skip the scope check: every API token may call the route, whatever its\n\t * scopes. Only for a route whose whole effect is on the calling key itself.\n\t */\n\tanyScope?: boolean;\n\t/**\n\t * Honour `Idempotency-Key`: a repeat from the same caller replays the first\n\t * response, and a key reused with a different body gets 422. Opt in per\n\t * route; what is safe to replay differs.\n\t */\n\tidempotent?: boolean;\n}\n\nfunction errorResponse(err: ApiError): Response {\n\tconst retryAfter = err.details?.retryAfter;\n\treturn toResponse({\n\t\tstatus: err.status,\n\t\tbody: toErrorBody(err),\n\t\t...(retryAfter !== undefined ? { headers: { 'Retry-After': String(retryAfter) } } : {})\n\t});\n}\n\n/** Run a handler and serialize whatever comes out, including failures. */\nexport async function runHandler(\n\thandler: ApiHandler,\n\treq: ApiRequest,\n\t{ fallback, mapError, action, scopeTarget, anyScope, idempotent }: RunHandlerOptions\n): Promise<Response> {\n\tconst fail = (err: unknown): Response => {\n\t\tconst known = isApiError(err) ? err : mapError?.(err);\n\t\tif (known) return errorResponse(known);\n\n\t\t// Never `console.error(…, err)`: provider adapters stash connection\n\t\t// details on `cause`, and a raw console call hands the whole object to\n\t\t// stdout where redaction never runs.\n\t\treq.log.error(`[API] ${fallback}`, {\n\t\t\tcomponent: 'api',\n\t\t\terr: err instanceof Error ? (err.stack ?? err.message) : String(err)\n\t\t});\n\n\t\treturn toResponse({\n\t\t\tstatus: 500,\n\t\t\tbody: { message: fallback, code: ApiErrorCode.INTERNAL }\n\t\t});\n\t};\n\n\tlet verdict;\n\ttry {\n\t\t// Charged before the scope check: `scopeTarget` may read the database,\n\t\t// and a throttled key must not reach it.\n\t\tconst limiter =\n\t\t\treq.deps.apiRateLimiter === undefined ? defaultApiRateLimiter() : req.deps.apiRateLimiter;\n\t\tverdict = await chargeApiRateLimit(req.ctx, limiter);\n\t\tif (verdict && !verdict.allowed) return rateLimitedResponse(verdict);\n\t} catch (err) {\n\t\treturn fail(err);\n\t}\n\n\tlet res: Response;\n\ttry {\n\t\tif (req.ctx?.apiScope && !anyScope) {\n\t\t\tassertScope(\n\t\t\t\treq.ctx,\n\t\t\t\taction ?? actionForMethod(req.request.method),\n\t\t\t\tscopeTarget ? await scopeTarget(req) : undefined\n\t\t\t);\n\t\t}\n\t\tconst run = async () => {\n\t\t\ttry {\n\t\t\t\treturn toResponse(await handler(req));\n\t\t\t} catch (err) {\n\t\t\t\treturn fail(err);\n\t\t\t}\n\t\t};\n\t\tconst clientKey = idempotent && req.ctx ? readIdempotencyKey(req.request) : null;\n\t\tif (clientKey && req.ctx) {\n\t\t\tconst fingerprint = await requestFingerprint(\n\t\t\t\treq.request.method,\n\t\t\t\treq.url,\n\t\t\t\tawait fingerprintBody(req.request)\n\t\t\t);\n\t\t\tres = await runIdempotent(\n\t\t\t\t{\n\t\t\t\t\tstore: req.deps.idempotency ?? defaultApiIdempotencyStore(),\n\t\t\t\t\tcallerId: idempotencyCallerId(req.ctx),\n\t\t\t\t\tclientKey,\n\t\t\t\t\tfingerprint\n\t\t\t\t},\n\t\t\t\trun\n\t\t\t);\n\t\t} else {\n\t\t\tres = await run();\n\t\t}\n\t} catch (err) {\n\t\tres = fail(err);\n\t}\n\treturn withRateLimitHeaders(res, verdict);\n}\n","/**\n * Request-body validators for the API routes that take JSON.\n *\n * They live apart from their handlers so a spec generator can import them\n * without loading a host's route module — in Selva's case a `+server.ts` imports\n * `./$types`, which only resolves inside a SvelteKit build.\n *\n * **A JSON body accepted by an API route belongs in this file.** Adding one\n * inline is invisible to the generator, so the endpoint documents an empty body.\n * Multipart handlers are the exception — `FormData` has no Zod schema to derive\n * from, so their fields are described in the spec directly.\n */\n\nimport { z } from 'zod';\nimport {\n\tProjectVisibilitySchema,\n\tProjectRoleSchema,\n\tOrgRoleSchema,\n\tOrgPermissionSchema,\n\tPlatformPermissionSchema,\n\tApiScopeStringSchema,\n\tAPI_TOKEN_LIFETIME_DAYS,\n\tCreateShareLinkInputSchema,\n\tDefinitionChannelSchema,\n\tPublishVersionInputSchema,\n\tUpdateMetadataInputSchema\n} from '@selvajs/platform';\n\n// ============================================================================\n// Definitions\n// ============================================================================\n\nexport const SolveBodySchema = z.object({\n\t/** Ignored: the solve reads the inputs from the version's stored schema. */\n\tinputs: z.array(z.unknown()).optional().meta({ deprecated: true }),\n\tvalues: z.record(z.string(), z.unknown()).default({}),\n\tchannel: DefinitionChannelSchema.default('live'),\n\tversionId: z.string().optional(),\n\t/** Must name this same definition, or the route 400s instead of solving a different one. */\n\tdefinitionUrl: z.string().optional()\n});\n\nexport const UpdateDefinitionBodySchema = UpdateMetadataInputSchema;\nexport const PublishVersionBodySchema = PublishVersionInputSchema;\nexport const CreateShareLinkBodySchema = CreateShareLinkInputSchema;\n\n// ============================================================================\n// Projects\n// ============================================================================\n\nexport const CreateProjectBodySchema = z.object({\n\tname: z.string().min(1, 'Project name is required').max(128).trim(),\n\tdescription: z.string().max(2000).optional(),\n\tvisibility: ProjectVisibilitySchema.default('private'),\n\tautoJoinOnUpload: z.boolean().optional()\n});\n\nexport const UpdateProjectBodySchema = z\n\t.object({\n\t\tname: z.string().min(1).max(128).trim(),\n\t\tdescription: z.string().max(2000).nullish(),\n\t\tvisibility: ProjectVisibilitySchema,\n\t\tautoJoinOnUpload: z.boolean()\n\t})\n\t.partial();\n\nexport const AddProjectMemberBodySchema = z.object({\n\tuserId: z.string().min(1, 'userId is required'),\n\trole: ProjectRoleSchema\n});\n\nexport const UpdateProjectMemberBodySchema = z.object({ role: ProjectRoleSchema });\n\n// ============================================================================\n// Orgs\n// ============================================================================\n\n/** Platform-scope entries are dropped downstream — an invite only grants org rights. */\nconst FlatPermissionSchema = z.union([PlatformPermissionSchema, OrgPermissionSchema]);\n\nexport const CreateInviteBodySchema = z.object({\n\temail: z.email('Valid email is required').transform((s) => s.toLowerCase().trim()),\n\torgRole: OrgRoleSchema.default('member'),\n\tpermissions: z.array(FlatPermissionSchema).default([])\n});\n\n/**\n * `apiKey` is tri-state: **omitted** keeps the stored key, **null** clears it, a\n * string replaces it. `.optional().nullable()` — not `.nullish()` — because the\n * two must stay distinguishable after parsing, or a request that just omits the\n * field would silently wipe the stored credential.\n */\nconst IncomingComputeServerSchema = z.object({\n\tid: z.string().min(1),\n\tlabel: z.string().min(1),\n\tserverUrl: z.string().min(1),\n\tapiKey: z.string().nullable().optional()\n});\n\nexport const OrgComputePatchBodySchema = z.object({\n\tservers: z.array(IncomingComputeServerSchema),\n\t/** May name any server visible to the org. `null` clears the override; omitted leaves it untouched. */\n\tdefaultServerId: z.string().nullable().optional()\n});\n\nexport const UpdateOrgMemberBodySchema = z\n\t.object({\n\t\trole: OrgRoleSchema.optional(),\n\t\tpermissions: z.array(OrgPermissionSchema).optional()\n\t})\n\t.refine((b) => b.role !== undefined || b.permissions !== undefined, {\n\t\tmessage: 'Provide at least one of role, permissions'\n\t});\n\n// ============================================================================\n// API tokens\n// ============================================================================\n\nexport const CreateApiTokenBodySchema = z.object({\n\tname: z.string().trim().min(1, 'Name is required').max(100),\n\tscopes: z.array(ApiScopeStringSchema).min(1, 'Pick at least one scope').max(20),\n\texpiresInDays: z.union(API_TOKEN_LIFETIME_DAYS.map((d) => z.literal(d)))\n});\n","/**\n * Response schemas for the v1 payloads that must not carry a stored secret.\n *\n * Four store types hold a credential next to fields a client legitimately\n * reads: `ShareLink.tokenHash`, `Invite.tokenHash` and `ApiToken.tokenHash` are HMACs of a token,\n * `ComputeServerCommon.apiKey` is a live Rhino.Compute key. Handlers used to\n * strip them by destructuring — `const { tokenHash: _omit, ...rest } = invite`\n * — which works until someone adds a field to the stored type or edits the line\n * away. Nothing fails at build time; the credential just starts appearing in a\n * response.\n *\n * Parsing through these schemas inverts the default: the response carries only\n * what the schema names, so a new field on the stored type is invisible to\n * clients until added here on purpose. Use them via `shaped`/`shapedCollection`\n * in `./route.ts`.\n *\n * These describe **responses**, not stored records — where the two differ (an\n * invite's one-time `acceptUrl`, a share link's `hasToken` sentinel) the\n * response is the authority.\n */\n\nimport { z } from 'zod';\nimport { DefinitionChannelSchema } from '@selvajs/platform';\n\n// ============================================================================\n// Share links\n// ============================================================================\n\nexport const ShareLinkResponseSchema = z.object({\n\tid: z.string(),\n\tdefinitionId: z.string(),\n\tchannel: DefinitionChannelSchema,\n\tname: z.string().optional(),\n\tcreatedBy: z.string(),\n\tcreatedAt: z.string(),\n\texpiresAt: z.string().nullish(),\n\trevokedAt: z.string().nullish(),\n\tallowSolve: z.boolean(),\n\tmaxSolves: z.number().nullish(),\n\tsolveCount: z.number(),\n\t/** Sentinel replacing `tokenHash`: a token exists, its hash is not yours. */\n\thasToken: z.literal(true)\n});\n\nexport type ShareLinkResponse = z.infer<typeof ShareLinkResponseSchema>;\n\n/** The mint response. `token` is the plaintext, returned exactly once. */\nexport const CreatedShareLinkResponseSchema = z.object({\n\tlink: ShareLinkResponseSchema,\n\ttoken: z.string()\n});\n\n// ============================================================================\n// Invites\n// ============================================================================\n\nexport const InviteResponseSchema = z.object({\n\tid: z.string(),\n\temail: z.string(),\n\torgId: z.string(),\n\torgRole: z.string(),\n\torgPermissions: z.array(z.string()),\n\tplatformPermissions: z.array(z.string()).default([]),\n\tinvitedBy: z.string(),\n\tcreatedAt: z.string(),\n\texpiresAt: z.string(),\n\tacceptedAt: z.string().optional(),\n\tacceptedByUserId: z.string().optional()\n});\n\n/**\n * The create response: the invite plus the link to send, built per request.\n *\n * `acceptUrl` is returned whatever `delivery` says — mail is best-effort, and\n * manual sharing is the fallback when it is off or the send failed.\n */\nexport const CreatedInviteResponseSchema = InviteResponseSchema.extend({\n\tacceptUrl: z.string(),\n\tdelivery: z.enum(['sent', 'not-configured', 'failed'])\n});\n\n// ============================================================================\n// Org compute\n// ============================================================================\n\n/**\n * An org-owned compute server. `apiKey` is replaced by `hasApiKey`, so a picker\n * can render \"key set\" without any store decrypting a secret to throw away.\n */\nexport const OrgComputeServerResponseSchema = z.object({\n\tid: z.string(),\n\tlabel: z.string(),\n\tserverUrl: z.string(),\n\tscope: z.literal('org'),\n\townerOrgId: z.string(),\n\thasApiKey: z.boolean()\n});\n\n/** A server this org may select but not edit. Never carries a key either. */\nexport const ComputeCatalogEntrySchema = z.object({\n\tid: z.string(),\n\tlabel: z.string(),\n\tserverUrl: z.string(),\n\tscope: z.enum(['platform', 'org']),\n\tsource: z.enum(['platform', 'org'])\n});\n\nexport const OrgComputeResponseSchema = z.object({\n\tservers: z.array(OrgComputeServerResponseSchema),\n\tdefaultServerId: z.string().nullish(),\n\tglobalDefaultServerId: z.string().nullish(),\n\tcatalog: z.array(ComputeCatalogEntrySchema)\n});\n\n// ============================================================================\n// API tokens\n// ============================================================================\n\nexport const ApiTokenResponseSchema = z.object({\n\tid: z.string(),\n\tuserId: z.string(),\n\tcreatedBy: z.string().nullable(),\n\torgId: z.string(),\n\tname: z.string(),\n\tscopes: z.array(z.string()),\n\tcreatedAt: z.string(),\n\texpiresAt: z.string(),\n\tlastUsedAt: z.string().nullable(),\n\trevokedAt: z.string().nullable(),\n\t/** Scope refusals since midnight UTC, counted in this process only. */\n\trefusedToday: z.number()\n});\n\n/** The mint response. `secret` is the raw key, returned exactly once. */\nexport const CreatedApiTokenResponseSchema = z.object({\n\ttoken: ApiTokenResponseSchema,\n\tsecret: z.string()\n});\n"],"mappings":";;;;;;;;;;AAIA,IAAa,8BAA8B,EAAE,OAAO;CACnD,aAAa,EAAE,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,GAAG,0BAA0B,CAAC,CAAC,IAAI,GAAG;CACzE,aAAa,EAAE,OAAO,CAAC,CAAC,IAAI,GAAI,CAAC,CAAC,SAAS;CAC3C,YAAY,EAAE,OAAO,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,SAAS;CAC1C,UAAU,EAAE,OAAO,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,SAAS;CACvC,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,SAAS;CACnD,WAAW;CACX,iBAAiB,WAAW,SAAS;AACtC,CAAC;;;;;;;AAQD,IAAa,4BAA4B,EAAE,OAAO;CACjD,aAAa,EAAE,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,GAAG,0BAA0B,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,SAAS;CACpF,aAAa,EAAE,OAAO,CAAC,CAAC,IAAI,GAAI,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS;CACtD,YAAY,EAAE,OAAO,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS;CACrD,UAAU,EAAE,OAAO,CAAC,CAAC,I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1B,WAAW,EAAE,OAAO;CACpB,WAAW,EAAE,OAAO;CACpB,YAAY,EAAE,OAAO,CAAC,CAAC,SAAS;CAChC,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;;CAE/B,cAAc,EAAE,OAAO;AACxB,CAAC;;AAGD,IAAa,gCAAgC,EAAE,OAAO;CACrD,OAAO;CACP,QAAQ,EAAE,OAAO;AAClB,CAAC"}
|
|
1
|
+
{"version":3,"file":"api.js","names":["sharedDefault"],"sources":["../../../../platform/src/definitions/bodies.ts","../../../../platform/src/projects/schemas.ts","../../../../platform/src/shareLinks/schemas.ts","../../../../server/src/compute/idempotency.ts","../../../../server/src/api/request.ts","../../../../server/src/api/scope.ts","../../../../server/src/api/rate-limit.ts","../../../../server/src/api/idempotency-http.ts","../../../../server/src/api/idempotency.ts","../../../../server/src/api/respond.ts","../../../../server/src/api/bodies.ts","../../../../server/src/api/responses-schema.ts"],"sourcesContent":["import { z } from 'zod';\nimport { DefinitionStatusSchema, GuidSchema } from './schemas.js';\n\n/** HTTP-body validator for new-definition input. */\nexport const CreateDefinitionInputSchema = z.object({\n\tdisplayName: z.string().trim().min(1, 'Display name is required').max(256),\n\tdescription: z.string().max(2000).optional(),\n\tcoverImage: z.string().max(2048).optional(),\n\tcategory: z.string().max(128).optional(),\n\ttags: z.array(z.string().max(64)).max(20).optional(),\n\tprojectId: GuidSchema,\n\tcomputeServerId: GuidSchema.optional()\n});\n\n/**\n * PATCH validator. Field semantics match `DefinitionRecordPatch`:\n * - missing / `undefined` — leave unchanged\n * - `null` — clear (only on nullable fields)\n * - value — set\n */\nexport const UpdateMetadataInputSchema = z.object({\n\tdisplayName: z.string().trim().min(1, 'Display name is required').max(256).optional(),\n\tdescription: z.string().max(2000).nullable().optional(),\n\tcoverImage: z.string().max(2048).nullable().optional(),\n\tcategory: z.string().max(128).nullable().optional(),\n\ttags: z.array(z.string().max(64)).max(20).nullable().optional(),\n\tprojectId: GuidSchema.optional(),\n\tcomputeServerId: GuidSchema.nullable().optional(),\n\t// Bounded so a settings typo can't request a runaway quota.\n\tsolveCacheLimit: z.number().int().min(0).max(100_000).nullable().optional(),\n\tstatus: DefinitionStatusSchema.optional()\n});\n\nexport type UpdateMetadataInput = z.infer<typeof UpdateMetadataInputSchema>;\n\n/** Body for publishing a version; without `versionId`, the current draft goes live. */\nexport const PublishVersionInputSchema = z\n\t.object({\n\t\tversionId: GuidSchema.optional()\n\t})\n\t.default({});\n","import { z } from 'zod';\n\nexport const ProjectVisibilitySchema = z.enum(['public', 'org', 'private', 'platform']);\nexport type ProjectVisibility = z.infer<typeof ProjectVisibilitySchema>;\n\nexport const ProjectRoleSchema = z.enum(['owner', 'editor', 'viewer']);\nexport type ProjectRole = z.infer<typeof ProjectRoleSchema>;\n\n/** Cross-field check for PATCH flows. Call on the merged post-patch shape. */\nexport function validateProjectFlags(merged: {\n\tvisibility: ProjectVisibility;\n\tautoJoinOnUpload?: boolean;\n}): { path: string; message: string }[] {\n\tif (!merged.autoJoinOnUpload) return [];\n\tif (merged.visibility === 'platform') {\n\t\treturn [\n\t\t\t{ path: 'autoJoinOnUpload', message: 'autoJoinOnUpload is not allowed on platform projects' }\n\t\t];\n\t}\n\tif (merged.visibility !== 'public') {\n\t\treturn [{ path: 'autoJoinOnUpload', message: 'autoJoinOnUpload requires visibility=public' }];\n\t}\n\treturn [];\n}\n","import { z } from 'zod';\nimport { DefinitionChannelSchema } from '../definitions/schemas.js';\n\n/** HTTP body for minting a share link. */\nexport const CreateShareLinkInputSchema = z.object({\n\tchannel: DefinitionChannelSchema.default('live'),\n\tname: z.string().max(128).optional(),\n\tallowSolve: z.boolean().default(true),\n\t/**\n\t * Null is the minter's deliberate \"uncap\" choice. Omitted stays undefined here:\n\t * the mint handler applies `DEFAULT_SHARE_LINK_MAX_SOLVES`.\n\t */\n\tmaxSolves: z.number().int().min(1).nullable().optional(),\n\texpiresAt: z.iso.datetime().nullable().optional()\n});\n\nexport type CreateShareLinkInput = z.infer<typeof CreateShareLinkInputSchema>;\n","/**\n * Idempotency store for the solve endpoint: a repeat of the same request within\n * the TTL replays the first response instead of re-solving.\n *\n * **This absorbs client retries; it is not a result cache.** The TTL is short\n * and the store is process-local, so a retry that lands on another instance\n * (or after the TTL) re-solves — a duplicate solve costs compute, not\n * correctness. What it must never do is return one caller's result to another,\n * hence the caller identity in the key.\n *\n * The store holds a **promise**, reserved before the work starts, because a\n * client that retries on timeout usually retries while the first solve is still\n * running: the second request awaits the first instead of starting a second solve.\n *\n * Sweep and cap are both driven by `run` rather than a timer — a timer would keep\n * the event loop alive and give this module a lifecycle its callers don't have.\n */\n\nexport interface IdempotencyStoreConfig {\n\t/** How long a completed response stays replayable, in ms. */\n\tttlMs: number;\n\t/**\n\t * Max retained entries; once exceeded, the ones nearest expiry are evicted.\n\t * Evicting only costs a re-solve on a retry, so size this above the plausible\n\t * number of in-flight + recent keys. Defaults to\n\t * {@link DEFAULT_IDEMPOTENCY_MAX_KEYS}.\n\t */\n\tmaxKeys?: number;\n\t/**\n\t * How often (ms) to sweep expired entries, amortized onto `run`. Defaults to\n\t * `ttlMs`. `0` disables the sweep, leaving only the cap (test seam).\n\t */\n\tsweepIntervalMs?: number;\n\t/**\n\t * Max total weight of completed entries, as measured by the store's `weigh`.\n\t * The key cap alone doesn't bound memory when one entry can be a 100 MB\n\t * solve. Over budget, the entries nearest expiry go first.\n\t */\n\tmaxWeight?: number;\n}\n\n/** Default {@link IdempotencyStoreConfig.maxKeys}. */\nexport const DEFAULT_IDEMPOTENCY_MAX_KEYS = 10_000;\n\nexport interface IdempotencyOutcome<T> {\n\tvalue: T;\n\t/** True when this call awaited an existing entry rather than running `fn`. */\n\treplayed: boolean;\n}\n\nexport interface IdempotencyStore<T> {\n\t/**\n\t * Run `fn` under `key`, or join/replay the entry already stored there. The\n\t * entry is reserved before `fn` starts, so a concurrent retry awaits the first\n\t * run; a rejection drops the reservation.\n\t */\n\trun(key: string, fn: () => Promise<T>): Promise<IdempotencyOutcome<T>>;\n\t/** Test seam — wipes in-memory state. Production code never calls this. */\n\treset(): void;\n\t/** Retained entry count, including entries not yet swept. */\n\tsize(): number;\n\treadonly config: Readonly<IdempotencyStoreConfig>;\n}\n\ninterface Entry<T> {\n\tpromise: Promise<T>;\n\t/**\n\t * Set when the promise settles. While in flight the entry is un-expirable —\n\t * a long solve must not have its reservation swept out from under the\n\t * retries that are already awaiting it.\n\t */\n\texpiresAt: number | null;\n\t/** Counted against `maxWeight` once settled; 0 while in flight. */\n\tweight: number;\n}\n\n/**\n * `T` is whatever the caller replays. It must not be a `Response` — a body can\n * only be read once, so the solve route stores a serialized snapshot instead.\n * `weigh` measures a completed value for `maxWeight`.\n */\nexport function createIdempotencyStore<T>(\n\tconfig: IdempotencyStoreConfig,\n\tweigh: (value: T) => number = () => 0\n): IdempotencyStore<T> {\n\tconst ttlMs = Math.max(0, Math.floor(config.ttlMs));\n\tconst maxKeys = Math.max(1, Math.floor(config.maxKeys ?? DEFAULT_IDEMPOTENCY_MAX_KEYS));\n\tconst sweepIntervalMs = Math.max(0, Math.floor(config.sweepIntervalMs ?? ttlMs));\n\tconst maxWeight = config.maxWeight ?? Number.POSITIVE_INFINITY;\n\tconst resolvedConfig: Readonly<IdempotencyStoreConfig> = Object.freeze({\n\t\t...config,\n\t\tttlMs,\n\t\tmaxKeys,\n\t\tsweepIntervalMs\n\t});\n\n\tconst entries = new Map<string, Entry<T>>();\n\tlet nextSweepAt = Number.POSITIVE_INFINITY;\n\tlet totalWeight = 0;\n\n\tfunction drop(key: string): void {\n\t\tconst entry = entries.get(key);\n\t\tif (!entry) return;\n\t\ttotalWeight -= entry.weight;\n\t\tentries.delete(key);\n\t}\n\n\t/** Settled entries only, nearest expiry first: in-flight ones have retries awaiting them. */\n\tfunction shedWeight(): void {\n\t\tif (totalWeight <= maxWeight) return;\n\t\tconst settled = [...entries.entries()]\n\t\t\t.filter(([, e]) => e.expiresAt !== null)\n\t\t\t.sort((a, b) => a[1].expiresAt! - b[1].expiresAt!);\n\t\tfor (const [key] of settled) {\n\t\t\tif (totalWeight <= maxWeight) break;\n\t\t\tdrop(key);\n\t\t}\n\t}\n\n\tfunction maybeSweep(now: number, headroom = 0): void {\n\t\tconst budget = Math.max(0, maxKeys - headroom);\n\t\tconst dueForSweep = sweepIntervalMs > 0 && now >= nextSweepAt;\n\t\tif (!dueForSweep && entries.size <= budget) return;\n\n\t\tfor (const [key, entry] of entries) {\n\t\t\tif (entry.expiresAt !== null && now > entry.expiresAt) drop(key);\n\t\t}\n\t\tif (sweepIntervalMs > 0) nextSweepAt = now + sweepIntervalMs;\n\n\t\tif (entries.size > budget) {\n\t\t\t// In-flight entries sort last: evicting one would orphan the retries\n\t\t\t// awaiting it, so they are given up only when nothing else is left.\n\t\t\tconst byExpiryAsc = [...entries.entries()].sort(\n\t\t\t\t(a, b) => (a[1].expiresAt ?? Infinity) - (b[1].expiresAt ?? Infinity)\n\t\t\t);\n\t\t\tfor (let i = 0; i < byExpiryAsc.length - budget; i++) drop(byExpiryAsc[i][0]);\n\t\t}\n\t}\n\n\treturn {\n\t\tconfig: resolvedConfig,\n\t\tasync run(key: string, fn: () => Promise<T>): Promise<IdempotencyOutcome<T>> {\n\t\t\tconst now = Date.now();\n\t\t\tconst existing = entries.get(key);\n\t\t\tif (existing && (existing.expiresAt === null || now <= existing.expiresAt)) {\n\t\t\t\treturn { value: await existing.promise, replayed: true };\n\t\t\t}\n\n\t\t\tmaybeSweep(now, entries.has(key) ? 0 : 1);\n\n\t\t\tconst promise = fn();\n\t\t\tconst entry: Entry<T> = { promise, expiresAt: null, weight: 0 };\n\t\t\tdrop(key);\n\t\t\tentries.set(key, entry);\n\t\t\tif (sweepIntervalMs > 0 && nextSweepAt === Number.POSITIVE_INFINITY) {\n\t\t\t\tnextSweepAt = now + sweepIntervalMs;\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tconst value = await promise;\n\t\t\t\tentry.expiresAt = Date.now() + ttlMs;\n\t\t\t\tif (entries.get(key) === entry) {\n\t\t\t\t\tentry.weight = weigh(value);\n\t\t\t\t\ttotalWeight += entry.weight;\n\t\t\t\t\tshedWeight();\n\t\t\t\t}\n\t\t\t\treturn { value, replayed: false };\n\t\t\t} catch (err) {\n\t\t\t\t// A failed solve is retryable — drop the reservation rather than\n\t\t\t\t// replaying the error to every retry for the whole TTL. Only drop our\n\t\t\t\t// own entry: a later `run` may already have replaced it.\n\t\t\t\tif (entries.get(key) === entry) drop(key);\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t},\n\t\treset(): void {\n\t\t\tentries.clear();\n\t\t\ttotalWeight = 0;\n\t\t\tnextSweepAt = Number.POSITIVE_INFINITY;\n\t\t},\n\t\tsize(): number {\n\t\t\treturn entries.size;\n\t\t}\n\t};\n}\n","/**\n * Reading a request: path params, JSON bodies, multipart uploads.\n *\n * Every helper here fails by throwing `ApiError`, so a handler using them names\n * no web framework. They were written against SvelteKit's `error()` and moved\n * once the handlers themselves became transport-free — the logic never depended\n * on the framework, only the throw did.\n *\n * `requireCaller` reads identity off `ApiRequest`, never off a host's `locals`\n * — a host maps its own session shape onto `ctx`/`user` when it builds the\n * request, and nothing below this line knows how it did that.\n */\n\nimport type { AuthUser, RequestContext } from '@selvajs/platform';\nimport type { ZodError, ZodType } from 'zod';\nimport { apiError, ApiErrorCode } from './errors.js';\nimport type { ApiRequest } from './types.js';\n\n/**\n * The authenticated caller, or a 401.\n *\n * `ctx` and `user` are optional on `ApiRequest` because a host builds one for\n * anonymous requests too (share-token solves reach handlers with a `ctx` and no\n * `user`). Every handler that needs an identity narrows it here rather than\n * asserting the fields non-null, so the unauthenticated path fails as a denial\n * instead of a crash.\n */\nexport function requireCaller(req: ApiRequest): { ctx: RequestContext; user: AuthUser } {\n\tif (!req.ctx || !req.user) {\n\t\tapiError(401, ApiErrorCode.UNAUTHORIZED, 'Unauthorized');\n\t}\n\treturn { ctx: req.ctx, user: req.user };\n}\n\n/**\n * Refuse an API key: for actions whose effect outlives the key (members,\n * invites, keys themselves), so revoking a leaked key ends what it did.\n */\nexport function requireSession(req: ApiRequest, message: string): void {\n\tif (req.ctx?.apiScope) apiError(403, ApiErrorCode.FORBIDDEN, message);\n}\n\n/**\n * Fail with a Zod error's messages, one per field.\n *\n * The top-level `message` names the first problem so a human reading the\n * response learns something without parsing `fields`.\n */\nexport function throwZodError(err: ZodError): never {\n\tconst fields: Record<string, string> = {};\n\tfor (const issue of err.issues) {\n\t\tconst key = issue.path.length ? issue.path.join('.') : '_';\n\t\t// First message per field wins; later issues on the same path are\n\t\t// usually redundant refinements.\n\t\tif (!(key in fields)) fields[key] = issue.message;\n\t}\n\tconst first = err.issues[0];\n\tconst path = first.path.length ? `${first.path.join('.')}: ` : '';\n\tapiError(400, ApiErrorCode.VALIDATION_FAILED, `${path}${first.message}`, fields);\n}\n\n// ============================================================================\n// Path params\n// ============================================================================\n\n/**\n * Read required path params, 400ing on any that is missing or blank.\n *\n * A router types every param as `string`, but a route can be reached with an\n * empty segment — this catches that instead of letting a stale non-null\n * assertion paper over it.\n *\n * Does **not** validate format — a guid-shaped param still goes through a\n * schema where the route cares. Replaces the `if (!id) apiError(...)` preamble,\n * not the schema check.\n */\nexport function requireParams<K extends string>(\n\tparams: Partial<Record<string, string>>,\n\t...names: K[]\n): Record<K, string> {\n\tconst out = {} as Record<K, string>;\n\tconst missing: string[] = [];\n\n\tfor (const name of names) {\n\t\tconst value = params[name];\n\t\tif (!value) {\n\t\t\tmissing.push(name);\n\t\t\tcontinue;\n\t\t}\n\t\tout[name] = value;\n\t}\n\n\tif (missing.length) {\n\t\tapiError(\n\t\t\t400,\n\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t`Missing path parameter${missing.length > 1 ? 's' : ''}: ${missing.join(', ')}`\n\t\t);\n\t}\n\treturn out;\n}\n\n/**\n * Read a path param through a Zod schema, 400ing on a bad value.\n *\n * The format-checking counterpart to `requireParams` — for guids, enum-shaped\n * segments, anything where \"present\" isn't the same as \"valid\".\n */\nexport function parseParam<T>(value: string | undefined, schema: ZodType<T>, name: string): T {\n\tconst parsed = schema.safeParse(value);\n\tif (!parsed.success) {\n\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, `Invalid or missing ${name}`);\n\t}\n\treturn parsed.data;\n}\n\n// ============================================================================\n// Request bodies\n// ============================================================================\n\n/**\n * Parse and validate a JSON body. Broken JSON is a 400, not a 500 from\n * `request.json()`.\n *\n * `missingAs` covers endpoints whose fields are all optional: passing `{}` lets\n * an empty body mean \"no changes\" instead of a validation failure. Only an\n * empty body: a truncated `{\"versionId\":…` read as \"no changes\" would publish\n * the draft instead of rolling back.\n */\nexport async function parseBody<T>(\n\trequest: Request,\n\tschema: ZodType<T>,\n\t{ missingAs }: { missingAs?: unknown } = {}\n): Promise<T> {\n\tconst text = await request.text().catch(() => '');\n\tlet raw: unknown = null;\n\tif (text.trim()) {\n\t\ttry {\n\t\t\traw = JSON.parse(text);\n\t\t} catch {\n\t\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, 'The request body is not valid JSON.');\n\t\t}\n\t}\n\tconst parsed = schema.safeParse(raw ?? missingAs ?? null);\n\tif (!parsed.success) throwZodError(parsed.error);\n\treturn parsed.data;\n}\n\n// ============================================================================\n// Uploads\n// ============================================================================\n\nconst parsedForms = new WeakMap<Request, Promise<FormData>>();\n\n/**\n * The request's form body, parsed once: the idempotency fingerprint reads it\n * before the handler does, and a definition upload is too large to buffer twice.\n * On an idempotent route, `request.formData()` throws: the body is already used.\n * A conformance test keeps handlers off it.\n */\nexport function readForm(request: Request): Promise<FormData> {\n\tlet form = parsedForms.get(request);\n\tif (!form) {\n\t\tform = request\n\t\t\t.formData()\n\t\t\t.catch(() =>\n\t\t\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, 'The request body is not a valid form.')\n\t\t\t);\n\t\tparsedForms.set(request, form);\n\t}\n\treturn form;\n}\n\n/**\n * Pull a required file out of a multipart body and check its size and, where\n * given, its extension.\n *\n * A second line of defence, not the first: a host's body-size guard should\n * reject an oversized request before it is buffered. This catches a file that\n * is individually too large inside a request that isn't.\n *\n * Caps are passed in rather than read here — they are deployment config, and a\n * package that resolved them would pin every host to one source of truth.\n */\nexport function requireUpload(\n\tform: FormData,\n\tfield: string,\n\t{\n\t\tmaxBytes,\n\t\textensions,\n\t\tcontentTypes,\n\t\tlabel = 'File'\n\t}: {\n\t\tmaxBytes: number;\n\t\textensions?: readonly string[];\n\t\tcontentTypes?: { allowed: ReadonlySet<string>; message: string };\n\t\tlabel?: string;\n\t}\n): { file: File; extension: string } {\n\tconst file = form.get(field);\n\tif (!(file instanceof File) || file.size === 0) {\n\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, `A ${label.toLowerCase()} is required`);\n\t}\n\n\tconst extension = file.name.slice(file.name.lastIndexOf('.')).toLowerCase();\n\tif (extensions && !extensions.includes(extension)) {\n\t\tapiError(\n\t\t\t400,\n\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t`File type not allowed. Allowed: ${extensions.join(', ')}`\n\t\t);\n\t}\n\n\tif (contentTypes && !contentTypes.allowed.has(file.type)) {\n\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, contentTypes.message);\n\t}\n\n\tif (file.size > maxBytes) {\n\t\tapiError(\n\t\t\t400,\n\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t`${label} too large. Max size: ${maxBytes / (1024 * 1024)} MB`\n\t\t);\n\t}\n\n\treturn { file, extension };\n}\n\n/** A multipart text field, trimmed and length-capped. Absent stays `undefined`. */\nexport function formText(\n\tform: FormData,\n\tfield: string,\n\t{ maxLength }: { maxLength?: number } = {}\n): string | undefined {\n\tconst raw = form.get(field);\n\tif (typeof raw !== 'string') return undefined;\n\tconst trimmed = raw.trim();\n\tif (!trimmed) return undefined;\n\treturn maxLength ? trimmed.slice(0, maxLength) : trimmed;\n}\n","import type { ApiScopeAction, RequestContext, ScopeTarget } from '@selvajs/platform';\nimport { apiScopeActionCovers, outsideTokenOrg, scopeAllows } from '@selvajs/platform';\nimport { apiError, ApiErrorCode } from './errors.js';\nimport type { ApiRequest } from './types.js';\n\n/** The default action for a method: reads are `read`, everything else `write`. */\nexport function actionForMethod(method: string): ApiScopeAction {\n\treturn method === 'GET' || method === 'HEAD' ? 'read' : 'write';\n}\n\n/**\n * Refuse an API-token request its scopes don't cover, with 403 naming the\n * scope that would have passed. Browser sessions always pass.\n *\n * `runHandler` calls this for every mounted route. A route that builds its own\n * `Response` must call it itself.\n */\nexport function assertScope(\n\tctx: RequestContext | undefined,\n\taction: ApiScopeAction,\n\ttarget?: ScopeTarget\n): void {\n\tif (!ctx?.apiScope || scopeAllows(ctx, action, target)) return;\n\trecordRefusal(ctx.apiScope.tokenId);\n\tapiError(403, ApiErrorCode.FORBIDDEN, `This API token doesn't allow ${action} here.`, undefined, {\n\t\trequiredScope: requiredScope(ctx, action, target)\n\t});\n}\n\n/**\n * Refuse an API-token request whose key holds `action` on nothing at all. For\n * routes that act only on the caller's own solves and streams, which name no\n * project: a key that may solve in one project must still cancel and watch\n * those solves.\n */\nexport function assertScopeAnywhere(ctx: RequestContext | undefined, action: ApiScopeAction): void {\n\tif (!ctx?.apiScope) return;\n\tif (ctx.apiScope.scopes.some((s) => apiScopeActionCovers(s.action, action))) return;\n\trecordRefusal(ctx.apiScope.tokenId);\n\tapiError(403, ApiErrorCode.FORBIDDEN, `This API token doesn't allow ${action}.`);\n}\n\n// Per process and per UTC day, so the token page can flag a misconfigured\n// integration. Kept in memory on purpose: refusals are not audited.\nconst refusals = new Map<string, { day: string; count: number }>();\n\nconst utcDay = () => new Date().toISOString().slice(0, 10);\n\nfunction recordRefusal(tokenId: string): void {\n\tconst day = utcDay();\n\tconst entry = refusals.get(tokenId);\n\tif (entry?.day === day) entry.count++;\n\telse refusals.set(tokenId, { day, count: 1 });\n}\n\n/** Scope refusals for `tokenId` since midnight UTC, in this process. */\nexport function scopeRefusalsToday(tokenId: string): number {\n\tconst entry = refusals.get(tokenId);\n\treturn entry?.day === utcDay() ? entry.count : 0;\n}\n\nfunction requiredScope(ctx: RequestContext, action: ApiScopeAction, target?: ScopeTarget): string {\n\tif (target?.projectId) return `${action}:project:${target.projectId}`;\n\tif (target?.definitionId) return `${action}:definition:${target.definitionId}`;\n\treturn `${action}:org:${ctx.actingOrgId}`;\n}\n\n/** Scope target for routes addressed by a project id param. */\nexport function projectScopeTarget(param = 'id') {\n\treturn (req: ApiRequest): ScopeTarget => ({ projectId: req.params[param] });\n}\n\n/**\n * Scope target for routes addressed by a definition guid param. Loads the\n * record so a project-scoped key reaches the definitions inside its project.\n *\n * A definition outside the key's org resolves like a missing one: otherwise the\n * 403 detail would confirm the guid exists and name its project.\n */\nexport function definitionScopeTarget(param = 'guid') {\n\treturn async (req: ApiRequest): Promise<ScopeTarget> => {\n\t\tconst definitionId = req.params[param];\n\t\tif (!definitionId || !req.ctx) return { definitionId };\n\t\tconst record = await req.deps.definitionMeta.get(req.ctx, definitionId);\n\t\tconst project = record ? await req.deps.projects.getProject(req.ctx, record.projectId) : null;\n\t\tif (!project || outsideTokenOrg(req.ctx, project.orgId)) return { definitionId };\n\t\treturn { definitionId, projectId: project.id };\n\t};\n}\n","/**\n * The general per-token request limit `runHandler` applies to every API-token\n * request. Browser sessions are not charged: their abuse surface is the\n * per-user compute bucket and the login limiter, not request volume.\n *\n * Solves charge this bucket and the owner's `user:{id}` compute bucket, so ten\n * keys of one user never buy ten times the compute.\n *\n * The default limiter is process-local (fixed window over\n * `createComputeRateLimiter`), so N instances admit N times the rate. A host\n * that needs one shared budget implements `ApiRateLimiter` over its own store.\n */\n\nimport type { ILogger, RequestContext } from '@selvajs/platform';\nimport { NoopLogger } from '@selvajs/platform';\nimport type { EnvRecord } from '@selvajs/platform/config';\nimport { createComputeRateLimiter } from '../compute/rate-limit.js';\nimport { readSettings } from '../config/read-settings.js';\nimport { API_TOKEN_RATE_LIMIT_SETTING } from '../config/settings.js';\nimport { ApiError, ApiErrorCode, toErrorBody } from './errors.js';\n\nexport interface ApiRateLimitVerdict {\n\tallowed: boolean;\n\t/** Requests admitted per window. */\n\tlimit: number;\n\t/** Requests left in the current window after this one. */\n\tremaining: number;\n\t/** Seconds until the window resets, when refused. */\n\tretryAfter?: number;\n}\n\n/** Records one request against `key`. Async so a shared-store implementation fits. */\nexport interface ApiRateLimiter {\n\thit(key: string): ApiRateLimitVerdict | Promise<ApiRateLimitVerdict>;\n}\n\nexport interface ApiRateLimitConfig {\n\twindowMs: number;\n\t/** `0` disables the limit. */\n\tmaxPerWindow: number;\n}\n\nexport const DEFAULT_API_RATE_LIMIT: Readonly<ApiRateLimitConfig> = Object.freeze({\n\twindowMs: 60_000,\n\tmaxPerWindow: API_TOKEN_RATE_LIMIT_SETTING.default\n});\n\n/** Read `API_TOKEN_RATE_LIMIT_MAX` (requests per window, `0` = off) from an injected env map. */\nexport function resolveApiRateLimitConfig(\n\tenv: EnvRecord,\n\tlogger: ILogger = new NoopLogger()\n): ApiRateLimitConfig {\n\tconst values = readSettings([API_TOKEN_RATE_LIMIT_SETTING], env, logger);\n\treturn {\n\t\twindowMs: DEFAULT_API_RATE_LIMIT.windowMs,\n\t\tmaxPerWindow: values.API_TOKEN_RATE_LIMIT_MAX as number\n\t};\n}\n\n/** Process-local fixed-window limiter. Returns `null` when `maxPerWindow` is 0. */\nexport function createApiRateLimiter(\n\tconfig: ApiRateLimitConfig = DEFAULT_API_RATE_LIMIT\n): ApiRateLimiter | null {\n\tif (config.maxPerWindow <= 0) return null;\n\tconst inner = createComputeRateLimiter(config);\n\tconst limit = config.maxPerWindow;\n\treturn {\n\t\thit(key) {\n\t\t\tconst result = inner.check(key);\n\t\t\treturn {\n\t\t\t\tallowed: result.allowed,\n\t\t\t\tlimit,\n\t\t\t\tremaining: Math.max(0, limit - inner.count(key)),\n\t\t\t\tretryAfter: result.retryAfter\n\t\t\t};\n\t\t}\n\t};\n}\n\nlet sharedDefault: ApiRateLimiter | null | undefined;\n\n/**\n * The limiter `depsFromConfig` wires when the host passes none. One per\n * process: deps are rebuilt per request, and a limiter per request counts\n * nothing.\n */\nexport function defaultApiRateLimiter(): ApiRateLimiter | null {\n\tif (sharedDefault === undefined) sharedDefault = createApiRateLimiter();\n\treturn sharedDefault;\n}\n\n/**\n * Projects one owner may create through API keys per window. A browser\n * session isn't counted. Process-local like the request limit.\n */\nexport const DEFAULT_PROJECT_CREATE_LIMIT: Readonly<ApiRateLimitConfig> = Object.freeze({\n\twindowMs: 60 * 60_000,\n\tmaxPerWindow: 20\n});\n\nlet sharedProjectCreate: ApiRateLimiter | null | undefined;\n\nexport function defaultProjectCreateLimiter(): ApiRateLimiter | null {\n\tif (sharedProjectCreate === undefined) {\n\t\tsharedProjectCreate = createApiRateLimiter(DEFAULT_PROJECT_CREATE_LIMIT);\n\t}\n\treturn sharedProjectCreate;\n}\n\n/**\n * Charge one request to the caller's token. `undefined` for a session caller\n * or when no limiter is wired.\n */\nexport async function chargeApiRateLimit(\n\tctx: RequestContext | undefined,\n\tlimiter: ApiRateLimiter | null | undefined\n): Promise<ApiRateLimitVerdict | undefined> {\n\tif (!ctx?.apiScope || !limiter) return undefined;\n\treturn limiter.hit(`token:${ctx.apiScope.tokenId}`);\n}\n\nexport function rateLimitHeaders(verdict: ApiRateLimitVerdict): Record<string, string> {\n\tconst headers: Record<string, string> = {\n\t\t'RateLimit-Limit': String(verdict.limit),\n\t\t'RateLimit-Remaining': String(verdict.remaining)\n\t};\n\tif (!verdict.allowed) headers['Retry-After'] = String(verdict.retryAfter ?? 1);\n\treturn headers;\n}\n\n/** The 429 envelope, with `Retry-After` and the `RateLimit-*` headers. */\nexport function rateLimitedResponse(\n\tverdict: ApiRateLimitVerdict,\n\tmessage = `Too many requests for this API token. Retry in ${verdict.retryAfter ?? 1}s.`\n): Response {\n\tconst retryAfter = String(verdict.retryAfter ?? 1);\n\tconst err = new ApiError(429, ApiErrorCode.RATE_LIMITED, message, undefined, { retryAfter });\n\treturn new Response(JSON.stringify(toErrorBody(err)), {\n\t\tstatus: 429,\n\t\theaders: { 'content-type': 'application/json', ...rateLimitHeaders(verdict) }\n\t});\n}\n\n/** Stamp the `RateLimit-*` headers onto a response. No-op without a verdict. */\nexport function withRateLimitHeaders(\n\tres: Response,\n\tverdict: ApiRateLimitVerdict | undefined\n): Response {\n\tif (!verdict) return res;\n\tconst headers = rateLimitHeaders(verdict);\n\ttry {\n\t\tfor (const [k, v] of Object.entries(headers)) res.headers.set(k, v);\n\t\treturn res;\n\t} catch {\n\t\t// A fetched or otherwise immutable response: rewrap rather than drop the headers.\n\t\tconst copy = new Headers(res.headers);\n\t\tfor (const [k, v] of Object.entries(headers)) copy.set(k, v);\n\t\treturn new Response(res.body, {\n\t\t\tstatus: res.status,\n\t\t\tstatusText: res.statusText,\n\t\t\theaders: copy\n\t\t});\n\t}\n}\n","/**\n * The HTTP layer over {@link createIdempotencyStore}: how a replayed response\n * is keyed, snapshotted, and identified on the wire.\n *\n * The store itself is generic over `T` and knows nothing about requests. This\n * is the part two hosts must agree on to implement the same `Idempotency-Key`\n * contract, and the part each would otherwise reinvent:\n *\n * - **The key namespaces by caller.** `Idempotency-Key` is client-chosen, so\n * two tenants can pick the same string. Without the caller in the key one\n * would replay the other's result — that is the whole security property\n * here, and a host that got it wrong would leak across tenants with\n * nothing failing at build time.\n * - **The response round-trips through a snapshot.** A `Response` body reads\n * exactly once, so storing the object itself replays an empty body.\n * - **A replay says so**, via `Idempotency-Replayed`. A client that cannot\n * tell a replay from a fresh run cannot tell a successful retry from a\n * second execution.\n *\n * How long a response stays replayable is *not* here: that trades a client's\n * retry window against serving a stale result after the underlying resource\n * moves, and only the host knows its own deadlines.\n */\n\n/** Header stamped on a replayed response, so a client can distinguish one. */\nexport const IDEMPOTENCY_REPLAYED_HEADER = 'Idempotency-Replayed';\n\n/**\n * A response flattened into something storable. Kept instead of the `Response`\n * because a body can only be read once.\n */\nexport interface StoredResponse {\n\tstatus: number;\n\theaders: [string, string][];\n\tbody: ArrayBuffer;\n}\n\n/**\n * Namespace a client-chosen key by its caller.\n *\n * `callerId` should be the narrowest identity available — a token id rather\n * than a user id where the host issues per-token credentials, so two tokens\n * held by one user do not share replays.\n */\nexport function idempotencyKey(callerId: string, clientKey: string): string {\n\treturn `${callerId} ${clientKey}`;\n}\n\n/** Flatten a response so it can be replayed. Consumes the body. */\nexport async function toStoredResponse(res: Response): Promise<StoredResponse> {\n\treturn {\n\t\tstatus: res.status,\n\t\theaders: [...res.headers.entries()],\n\t\tbody: await res.arrayBuffer()\n\t};\n}\n\n/** Rebuild a live `Response` from a snapshot, marking it when it is a replay. */\nexport function fromStoredResponse(stored: StoredResponse, replayed: boolean): Response {\n\tconst headers = new Headers(stored.headers);\n\tif (replayed) headers.set(IDEMPOTENCY_REPLAYED_HEADER, 'true');\n\treturn new Response(stored.body, { status: stored.status, headers });\n}\n","/**\n * `Idempotency-Key` for mounted routes that opt in with `idempotent: true`.\n *\n * Built on the generic store (`../compute/idempotency.ts`) and the wire\n * contract (`./idempotency-http.ts`). The store absorbs in-flight and near-term\n * retries in this process; it is not a durable record. A create that must never duplicate also needs the key on\n * the created row under a unique constraint, written in the same transaction.\n *\n * Each entry carries a fingerprint of method, path, query and body, so a client that\n * reuses a key for a different request gets 422 instead of someone else's\n * replay. Only responses below 400 are kept: a failed attempt frees the key so\n * a corrected retry can run.\n */\n\nimport { createHash } from 'node:crypto';\nimport type { RequestContext } from '@selvajs/platform';\nimport { createIdempotencyStore, type IdempotencyStore } from '../compute/idempotency.js';\nimport {\n\tfromStoredResponse,\n\tidempotencyKey,\n\ttoStoredResponse,\n\ttype StoredResponse\n} from './idempotency-http.js';\nimport { apiError, ApiErrorCode } from './errors.js';\nimport { readForm } from './request.js';\n\nexport const IDEMPOTENCY_KEY_HEADER = 'Idempotency-Key';\nexport const MAX_IDEMPOTENCY_KEY_LENGTH = 255;\n/** Covers a client's retry-on-timeout window without turning into a result cache. */\nexport const DEFAULT_API_IDEMPOTENCY_TTL_MS = 5 * 60_000;\n/**\n * Replayable response bytes one store keeps. A solve response can run to\n * hundreds of MB, so the key cap alone would let a client that sends a fresh\n * key per solve hold gigabytes for the whole TTL. Evicting costs a re-run.\n */\nexport const DEFAULT_API_IDEMPOTENCY_MAX_BYTES = 256 * 1024 * 1024;\n\nconst CLIENT_CLOSED_REQUEST = 499;\n\nexport interface IdempotentEntry {\n\tfingerprint: string;\n\tresponse: StoredResponse;\n}\n\nexport type ApiIdempotencyStore = IdempotencyStore<IdempotentEntry>;\n\nexport function createApiIdempotencyStore(\n\tttlMs = DEFAULT_API_IDEMPOTENCY_TTL_MS,\n\tmaxBytes = DEFAULT_API_IDEMPOTENCY_MAX_BYTES\n): ApiIdempotencyStore {\n\treturn createIdempotencyStore<IdempotentEntry>(\n\t\t{ ttlMs, maxWeight: maxBytes },\n\t\t(entry) => entry.response.body.byteLength\n\t);\n}\n\nlet sharedDefault: ApiIdempotencyStore | undefined;\n\n/** The store `depsFromConfig` wires when the host passes none. One per process. */\nexport function defaultApiIdempotencyStore(): ApiIdempotencyStore {\n\treturn (sharedDefault ??= createApiIdempotencyStore());\n}\n\n/**\n * The narrowest identity a key is namespaced by: the token for a token\n * request, so two keys of one user never share replays, else the user.\n */\nexport function idempotencyCallerId(ctx: RequestContext): string {\n\treturn ctx.apiScope ? `token:${ctx.apiScope.tokenId}` : `user:${ctx.userId}`;\n}\n\n/** Read and validate the client's key. `null` when the header is absent. */\nexport function readIdempotencyKey(request: Request): string | null {\n\tconst key = request.headers.get(IDEMPOTENCY_KEY_HEADER);\n\tif (key === null) return null;\n\tif (key.length === 0 || key.length > MAX_IDEMPOTENCY_KEY_LENGTH) {\n\t\tapiError(\n\t\t\t400,\n\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t`${IDEMPOTENCY_KEY_HEADER} must be 1 to ${MAX_IDEMPOTENCY_KEY_LENGTH} characters.`\n\t\t);\n\t}\n\treturn key;\n}\n\nasync function sha256Hex(bytes: BufferSource): Promise<string> {\n\tconst digest = await crypto.subtle.digest('SHA-256', bytes);\n\treturn Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join('');\n}\n\n/** SHA-256 over method, path with query, and body, hex. */\nexport async function requestFingerprint(\n\tmethod: string,\n\turl: URL,\n\tbody: ArrayBuffer | string\n): Promise<string> {\n\tconst head = new TextEncoder().encode(`${method.toUpperCase()} ${url.pathname}${url.search}\\n`);\n\tconst tail = typeof body === 'string' ? new TextEncoder().encode(body) : new Uint8Array(body);\n\tconst bytes = new Uint8Array(head.length + tail.length);\n\tbytes.set(head);\n\tbytes.set(tail, head.length);\n\treturn sha256Hex(bytes);\n}\n\nasync function fileSha256Hex(file: Blob): Promise<string> {\n\tconst hash = createHash('sha256');\n\tfor await (const chunk of file.stream()) hash.update(chunk);\n\treturn hash.digest('hex');\n}\n\n/**\n * The body `requestFingerprint` should hash. The handler can still read it: a\n * JSON body comes from a clone, a form through `readForm`, which parses it once\n * for both.\n *\n * Multipart is canonicalized to its fields and file contents: clients pick a\n * fresh random boundary per request, so the raw bytes of an identical retry\n * never match.\n */\nexport async function fingerprintBody(request: Request): Promise<ArrayBuffer | string> {\n\tconst type = request.headers.get('content-type') ?? '';\n\tif (!type.toLowerCase().startsWith('multipart/form-data')) {\n\t\treturn request.clone().arrayBuffer();\n\t}\n\tlet form: FormData;\n\ttry {\n\t\tform = await readForm(request);\n\t} catch {\n\t\t// The handler's own read fails the same way, and a failure is never replayed.\n\t\treturn 'malformed multipart';\n\t}\n\tconst parts: [string, string | { file: string; type: string; sha256: string }][] = [];\n\tfor (const [name, value] of form) {\n\t\tparts.push([\n\t\t\tname,\n\t\t\ttypeof value === 'string'\n\t\t\t\t? value\n\t\t\t\t: { file: value.name, type: value.type, sha256: await fileSha256Hex(value) }\n\t\t]);\n\t}\n\treturn JSON.stringify(parts);\n}\n\nclass NotReplayable {\n\tconstructor(\n\t\treadonly fingerprint: string,\n\t\treadonly response: StoredResponse\n\t) {}\n}\n\nfunction assertSameRequest(stored: string, fingerprint: string): void {\n\tif (stored !== fingerprint) {\n\t\tapiError(\n\t\t\t422,\n\t\t\tApiErrorCode.UNPROCESSABLE,\n\t\t\t`This ${IDEMPOTENCY_KEY_HEADER} was already used for a different request.`\n\t\t);\n\t}\n}\n\n/**\n * Run `fn` once per `(callerId, clientKey)`, replaying its response to repeats\n * with `Idempotency-Replayed: true`. Throws 422 when the key was used for a\n * different request. Errors `fn` throws propagate and free the key.\n */\nexport async function runIdempotent(\n\t{\n\t\tstore,\n\t\tcallerId,\n\t\tclientKey,\n\t\tfingerprint\n\t}: { store: ApiIdempotencyStore; callerId: string; clientKey: string; fingerprint: string },\n\tfn: () => Promise<Response>\n): Promise<Response> {\n\tlet outcome;\n\tlet ranHere = false;\n\ttry {\n\t\toutcome = await store.run(idempotencyKey(callerId, clientKey), async () => {\n\t\t\tranHere = true;\n\t\t\tconst res = await fn();\n\t\t\tconst response = await toStoredResponse(res);\n\t\t\tif (res.status >= 400) throw new NotReplayable(fingerprint, response);\n\t\t\treturn { fingerprint, response };\n\t\t});\n\t} catch (err) {\n\t\tif (!(err instanceof NotReplayable)) throw err;\n\t\tassertSameRequest(err.fingerprint, fingerprint);\n\t\t// 499 is the first client hanging up, which says nothing about this one:\n\t\t// its retry is the case the store exists for, so it runs on its own.\n\t\tif (!ranHere && err.response.status === CLIENT_CLOSED_REQUEST) {\n\t\t\treturn runIdempotent({ store, callerId, clientKey, fingerprint }, fn);\n\t\t}\n\t\t// A concurrent retry joining the failed attempt receives the same failure.\n\t\treturn fromStoredResponse(err.response, false);\n\t}\n\tassertSameRequest(outcome.value.fingerprint, fingerprint);\n\treturn fromStoredResponse(outcome.value.response, outcome.replayed);\n}\n","/**\n * Turn a handler result — or a thrown `ApiError` — into a web-standard\n * `Response`.\n *\n * This is the whole serialization boundary. A host framework that speaks\n * `Request`/`Response` (SvelteKit, Next route handlers, Hono, Remix) needs only\n * to build an `ApiRequest` and call `runHandler`; one that does not can reuse\n * `toErrorBody` and serialize itself.\n */\n\nimport { ApiError, ApiErrorCode, isApiError, toErrorBody } from './errors.js';\nimport type { ApiScopeAction, ScopeTarget } from '@selvajs/platform';\nimport type { ApiHandler, ApiRequest, ApiResponse } from './types.js';\nimport { actionForMethod, assertScope } from './scope.js';\nimport {\n\tchargeApiRateLimit,\n\tdefaultApiRateLimiter,\n\trateLimitedResponse,\n\twithRateLimitHeaders\n} from './rate-limit.js';\nimport {\n\tdefaultApiIdempotencyStore,\n\tfingerprintBody,\n\tidempotencyCallerId,\n\treadIdempotencyKey,\n\trequestFingerprint,\n\trunIdempotent\n} from './idempotency.js';\n\nexport { toErrorBody, type ApiErrorBody } from './errors.js';\n\nfunction toResponse(result: ApiResponse | Response): Response {\n\tif (result instanceof Response) return result;\n\n\tconst { status, body, headers } = result;\n\tif (body === undefined) return new Response(null, { status: status ?? 204, headers });\n\n\treturn new Response(JSON.stringify(body), {\n\t\tstatus: status ?? 200,\n\t\theaders: { 'content-type': 'application/json', ...headers }\n\t});\n}\n\nexport interface RunHandlerOptions {\n\t/** The 500 message when the handler throws something unmapped. */\n\tfallback: string;\n\t/**\n\t * Folds a host's own domain errors into the envelope before the 500 fallback.\n\t * The Selva app maps `ProviderError`, `SchemaExtractionError` and\n\t * `ComputeServerUnconfiguredError` this way, none of which belong here.\n\t */\n\tmapError?: (err: unknown) => ApiError | undefined;\n\t/**\n\t * What the route does, for API-token scope checks. Defaults from the method:\n\t * `GET`/`HEAD` are `read`, everything else `write`. Solve routes say `solve`.\n\t */\n\taction?: ApiScopeAction;\n\t/**\n\t * The project or definition the route touches. Without it the scope check is\n\t * org-level, which project- and definition-scoped keys never pass.\n\t */\n\tscopeTarget?: (req: ApiRequest) => ScopeTarget | Promise<ScopeTarget>;\n\t/**\n\t * Skip the scope check: every API token may call the route, whatever its\n\t * scopes. Only for a route whose whole effect is on the calling key itself.\n\t */\n\tanyScope?: boolean;\n\t/**\n\t * Honour `Idempotency-Key`: a repeat from the same caller replays the first\n\t * response, and a key reused with a different body gets 422. Opt in per\n\t * route; what is safe to replay differs.\n\t */\n\tidempotent?: boolean;\n}\n\nfunction errorResponse(err: ApiError): Response {\n\tconst retryAfter = err.details?.retryAfter;\n\treturn toResponse({\n\t\tstatus: err.status,\n\t\tbody: toErrorBody(err),\n\t\t...(retryAfter !== undefined ? { headers: { 'Retry-After': String(retryAfter) } } : {})\n\t});\n}\n\n/** Run a handler and serialize whatever comes out, including failures. */\nexport async function runHandler(\n\thandler: ApiHandler,\n\treq: ApiRequest,\n\t{ fallback, mapError, action, scopeTarget, anyScope, idempotent }: RunHandlerOptions\n): Promise<Response> {\n\tconst fail = (err: unknown): Response => {\n\t\tconst known = isApiError(err) ? err : mapError?.(err);\n\t\tif (known) return errorResponse(known);\n\n\t\t// Never `console.error(…, err)`: provider adapters stash connection\n\t\t// details on `cause`, and a raw console call hands the whole object to\n\t\t// stdout where redaction never runs.\n\t\treq.log.error(`[API] ${fallback}`, {\n\t\t\tcomponent: 'api',\n\t\t\terr: err instanceof Error ? (err.stack ?? err.message) : String(err)\n\t\t});\n\n\t\treturn toResponse({\n\t\t\tstatus: 500,\n\t\t\tbody: { message: fallback, code: ApiErrorCode.INTERNAL }\n\t\t});\n\t};\n\n\tlet verdict;\n\ttry {\n\t\t// Charged before the scope check: `scopeTarget` may read the database,\n\t\t// and a throttled key must not reach it.\n\t\tconst limiter =\n\t\t\treq.deps.apiRateLimiter === undefined ? defaultApiRateLimiter() : req.deps.apiRateLimiter;\n\t\tverdict = await chargeApiRateLimit(req.ctx, limiter);\n\t\tif (verdict && !verdict.allowed) return rateLimitedResponse(verdict);\n\t} catch (err) {\n\t\treturn fail(err);\n\t}\n\n\tlet res: Response;\n\ttry {\n\t\tif (req.ctx?.apiScope && !anyScope) {\n\t\t\tassertScope(\n\t\t\t\treq.ctx,\n\t\t\t\taction ?? actionForMethod(req.request.method),\n\t\t\t\tscopeTarget ? await scopeTarget(req) : undefined\n\t\t\t);\n\t\t}\n\t\tconst run = async () => {\n\t\t\ttry {\n\t\t\t\treturn toResponse(await handler(req));\n\t\t\t} catch (err) {\n\t\t\t\treturn fail(err);\n\t\t\t}\n\t\t};\n\t\tconst clientKey = idempotent && req.ctx ? readIdempotencyKey(req.request) : null;\n\t\tif (clientKey && req.ctx) {\n\t\t\tconst fingerprint = await requestFingerprint(\n\t\t\t\treq.request.method,\n\t\t\t\treq.url,\n\t\t\t\tawait fingerprintBody(req.request)\n\t\t\t);\n\t\t\tres = await runIdempotent(\n\t\t\t\t{\n\t\t\t\t\tstore: req.deps.idempotency ?? defaultApiIdempotencyStore(),\n\t\t\t\t\tcallerId: idempotencyCallerId(req.ctx),\n\t\t\t\t\tclientKey,\n\t\t\t\t\tfingerprint\n\t\t\t\t},\n\t\t\t\trun\n\t\t\t);\n\t\t} else {\n\t\t\tres = await run();\n\t\t}\n\t} catch (err) {\n\t\tres = fail(err);\n\t}\n\treturn withRateLimitHeaders(res, verdict);\n}\n","/**\n * Request-body validators for the API routes that take JSON.\n *\n * They live apart from their handlers so a spec generator can import them\n * without loading a host's route module — in Selva's case a `+server.ts` imports\n * `./$types`, which only resolves inside a SvelteKit build.\n *\n * **A JSON body accepted by an API route belongs in this file.** Adding one\n * inline is invisible to the generator, so the endpoint documents an empty body.\n * Multipart handlers are the exception — `FormData` has no Zod schema to derive\n * from, so their fields are described in the spec directly.\n */\n\nimport { z } from 'zod';\nimport {\n\tProjectVisibilitySchema,\n\tProjectRoleSchema,\n\tOrgRoleSchema,\n\tOrgPermissionSchema,\n\tPlatformPermissionSchema,\n\tApiScopeStringSchema,\n\tAPI_TOKEN_LIFETIME_DAYS,\n\tCreateShareLinkInputSchema,\n\tDefinitionChannelSchema,\n\tPublishVersionInputSchema,\n\tUpdateMetadataInputSchema\n} from '@selvajs/platform';\n\n// ============================================================================\n// Definitions\n// ============================================================================\n\nexport const SolveModeSchema = z.enum(['preview', 'full']);\n\nexport const SolveBodySchema = z.object({\n\t/** Ignored: the solve reads the inputs from the version's stored schema. */\n\tinputs: z.array(z.unknown()).optional().meta({ deprecated: true }),\n\tvalues: z.record(z.string(), z.unknown()).default({}),\n\tchannel: DefinitionChannelSchema.default('live'),\n\tversionId: z.string().optional(),\n\t/** Must name this same definition, or the route 400s instead of solving a different one. */\n\tdefinitionUrl: z.string().optional(),\n\t/**\n\t * `preview` skips the files only a Download output needs, when the definition turns\n\t * `previewSolves` on; the response's outcome lists them as `deferred`. A `full` solve of the\n\t * same values makes them.\n\t */\n\tmode: SolveModeSchema.default('full')\n});\n\nexport const UpdateDefinitionBodySchema = UpdateMetadataInputSchema;\nexport const PublishVersionBodySchema = PublishVersionInputSchema;\nexport const CreateShareLinkBodySchema = CreateShareLinkInputSchema;\n\n// ============================================================================\n// Projects\n// ============================================================================\n\nexport const CreateProjectBodySchema = z.object({\n\tname: z.string().min(1, 'Project name is required').max(128).trim(),\n\tdescription: z.string().max(2000).optional(),\n\tvisibility: ProjectVisibilitySchema.default('private'),\n\tautoJoinOnUpload: z.boolean().optional()\n});\n\nexport const UpdateProjectBodySchema = z\n\t.object({\n\t\tname: z.string().min(1).max(128).trim(),\n\t\tdescription: z.string().max(2000).nullish(),\n\t\tvisibility: ProjectVisibilitySchema,\n\t\tautoJoinOnUpload: z.boolean()\n\t})\n\t.partial();\n\nexport const AddProjectMemberBodySchema = z.object({\n\tuserId: z.string().min(1, 'userId is required'),\n\trole: ProjectRoleSchema\n});\n\nexport const UpdateProjectMemberBodySchema = z.object({ role: ProjectRoleSchema });\n\n// ============================================================================\n// Orgs\n// ============================================================================\n\n/** Platform-scope entries are dropped downstream — an invite only grants org rights. */\nconst FlatPermissionSchema = z.union([PlatformPermissionSchema, OrgPermissionSchema]);\n\nexport const CreateInviteBodySchema = z.object({\n\temail: z.email('Valid email is required').transform((s) => s.toLowerCase().trim()),\n\torgRole: OrgRoleSchema.default('member'),\n\tpermissions: z.array(FlatPermissionSchema).default([])\n});\n\n/**\n * `apiKey` is tri-state: **omitted** keeps the stored key, **null** clears it, a\n * string replaces it. `.optional().nullable()` — not `.nullish()` — because the\n * two must stay distinguishable after parsing, or a request that just omits the\n * field would silently wipe the stored credential.\n */\nconst IncomingComputeServerSchema = z.object({\n\tid: z.string().min(1),\n\tlabel: z.string().min(1),\n\tserverUrl: z.string().min(1),\n\tapiKey: z.string().nullable().optional()\n});\n\nexport const OrgComputePatchBodySchema = z.object({\n\tservers: z.array(IncomingComputeServerSchema),\n\t/** May name any server visible to the org. `null` clears the override; omitted leaves it untouched. */\n\tdefaultServerId: z.string().nullable().optional()\n});\n\nexport const UpdateOrgMemberBodySchema = z\n\t.object({\n\t\trole: OrgRoleSchema.optional(),\n\t\tpermissions: z.array(OrgPermissionSchema).optional()\n\t})\n\t.refine((b) => b.role !== undefined || b.permissions !== undefined, {\n\t\tmessage: 'Provide at least one of role, permissions'\n\t});\n\n// ============================================================================\n// API tokens\n// ============================================================================\n\nexport const CreateApiTokenBodySchema = z.object({\n\tname: z.string().trim().min(1, 'Name is required').max(100),\n\tscopes: z.array(ApiScopeStringSchema).min(1, 'Pick at least one scope').max(20),\n\texpiresInDays: z.union(API_TOKEN_LIFETIME_DAYS.map((d) => z.literal(d)))\n});\n","/**\n * Response schemas for the v1 payloads that must not carry a stored secret.\n *\n * Four store types hold a credential next to fields a client legitimately\n * reads: `ShareLink.tokenHash`, `Invite.tokenHash` and `ApiToken.tokenHash` are HMACs of a token,\n * `ComputeServerCommon.apiKey` is a live Rhino.Compute key. Handlers used to\n * strip them by destructuring — `const { tokenHash: _omit, ...rest } = invite`\n * — which works until someone adds a field to the stored type or edits the line\n * away. Nothing fails at build time; the credential just starts appearing in a\n * response.\n *\n * Parsing through these schemas inverts the default: the response carries only\n * what the schema names, so a new field on the stored type is invisible to\n * clients until added here on purpose. Use them via `shaped`/`shapedCollection`\n * in `./route.ts`.\n *\n * These describe **responses**, not stored records — where the two differ (an\n * invite's one-time `acceptUrl`, a share link's `hasToken` sentinel) the\n * response is the authority.\n */\n\nimport { z } from 'zod';\nimport { DefinitionChannelSchema } from '@selvajs/platform';\n\n// ============================================================================\n// Share links\n// ============================================================================\n\nexport const ShareLinkResponseSchema = z.object({\n\tid: z.string(),\n\tdefinitionId: z.string(),\n\tchannel: DefinitionChannelSchema,\n\tname: z.string().optional(),\n\tcreatedBy: z.string(),\n\tcreatedAt: z.string(),\n\texpiresAt: z.string().nullish(),\n\trevokedAt: z.string().nullish(),\n\tallowSolve: z.boolean(),\n\tmaxSolves: z.number().nullish(),\n\tsolveCount: z.number(),\n\t/** Sentinel replacing `tokenHash`: a token exists, its hash is not yours. */\n\thasToken: z.literal(true)\n});\n\nexport type ShareLinkResponse = z.infer<typeof ShareLinkResponseSchema>;\n\n/** The mint response. `token` is the plaintext, returned exactly once. */\nexport const CreatedShareLinkResponseSchema = z.object({\n\tlink: ShareLinkResponseSchema,\n\ttoken: z.string()\n});\n\n// ============================================================================\n// Invites\n// ============================================================================\n\nexport const InviteResponseSchema = z.object({\n\tid: z.string(),\n\temail: z.string(),\n\torgId: z.string(),\n\torgRole: z.string(),\n\torgPermissions: z.array(z.string()),\n\tplatformPermissions: z.array(z.string()).default([]),\n\tinvitedBy: z.string(),\n\tcreatedAt: z.string(),\n\texpiresAt: z.string(),\n\tacceptedAt: z.string().optional(),\n\tacceptedByUserId: z.string().optional()\n});\n\n/**\n * The create response: the invite plus the link to send, built per request.\n *\n * `acceptUrl` is returned whatever `delivery` says — mail is best-effort, and\n * manual sharing is the fallback when it is off or the send failed.\n */\nexport const CreatedInviteResponseSchema = InviteResponseSchema.extend({\n\tacceptUrl: z.string(),\n\tdelivery: z.enum(['sent', 'not-configured', 'failed'])\n});\n\n// ============================================================================\n// Org compute\n// ============================================================================\n\n/**\n * An org-owned compute server. `apiKey` is replaced by `hasApiKey`, so a picker\n * can render \"key set\" without any store decrypting a secret to throw away.\n */\nexport const OrgComputeServerResponseSchema = z.object({\n\tid: z.string(),\n\tlabel: z.string(),\n\tserverUrl: z.string(),\n\tscope: z.literal('org'),\n\townerOrgId: z.string(),\n\thasApiKey: z.boolean()\n});\n\n/** A server this org may select but not edit. Never carries a key either. */\nexport const ComputeCatalogEntrySchema = z.object({\n\tid: z.string(),\n\tlabel: z.string(),\n\tserverUrl: z.string(),\n\tscope: z.enum(['platform', 'org']),\n\tsource: z.enum(['platform', 'org'])\n});\n\nexport const OrgComputeResponseSchema = z.object({\n\tservers: z.array(OrgComputeServerResponseSchema),\n\tdefaultServerId: z.string().nullish(),\n\tglobalDefaultServerId: z.string().nullish(),\n\tcatalog: z.array(ComputeCatalogEntrySchema)\n});\n\n// ============================================================================\n// API tokens\n// ============================================================================\n\nexport const ApiTokenResponseSchema = z.object({\n\tid: z.string(),\n\tuserId: z.string(),\n\tcreatedBy: z.string().nullable(),\n\torgId: z.string(),\n\tname: z.string(),\n\tscopes: z.array(z.string()),\n\tcreatedAt: z.string(),\n\texpiresAt: z.string(),\n\tlastUsedAt: z.string().nullable(),\n\trevokedAt: z.string().nullable(),\n\t/** Scope refusals since midnight UTC, counted in this process only. */\n\trefusedToday: z.number()\n});\n\n/** The mint response. `secret` is the raw key, returned exactly once. */\nexport const CreatedApiTokenResponseSchema = z.object({\n\ttoken: ApiTokenResponseSchema,\n\tsecret: z.string()\n});\n"],"mappings":";;;;;;;;;;AAIA,IAAa,8BAA8B,EAAE,OAAO;CACnD,aAAa,EAAE,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,GAAG,0BAA0B,CAAC,CAAC,IAAI,GAAG;CACzE,aAAa,EAAE,OAAO,CAAC,CAAC,IAAI,GAAI,CAAC,CAAC,SAAS;CAC3C,YAAY,EAAE,OAAO,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,SAAS;CAC1C,UAAU,EAAE,OAAO,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,SAAS;CACvC,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,SAAS;CACnD,WAAW;CACX,iBAAiB,WAAW,SAAS;AACtC,CAAC;;;;;;;AAQD,IAAa,4BAA4B,EAAE,OAAO;CACjD,aAAa,EAAE,OAAO,C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AAO;CAChD,SAAS,EAAE,MAAM,8BAA8B;CAC/C,iBAAiB,EAAE,OAAO,CAAC,CAAC,QAAQ;CACpC,uBAAuB,EAAE,OAAO,CAAC,CAAC,QAAQ;CAC1C,SAAS,EAAE,MAAM,yBAAyB;AAC3C,CAAC;AAMD,IAAa,yBAAyB,EAAE,OAAO;CAC9C,IAAI,EAAE,OAAO;CACb,QAAQ,EAAE,OAAO;CACjB,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;CAC/B,OAAO,EAAE,OAAO;CAChB,MAAM,EAAE,OAAO;CACf,QAAQ,EAAE,MAAM,EAAE,OAAO,CAAC;CAC1B,WAAW,EAAE,OAAO;CACpB,WAAW,EAAE,OAAO;CACpB,YAAY,EAAE,OAAO,CAAC,CAAC,SAAS;CAChC,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;;CAE/B,cAAc,EAAE,OAAO;AACxB,CAAC;;AAGD,IAAa,gCAAgC,EAAE,OAAO;CACrD,OAAO;CACP,QAAQ,EAAE,OAAO;AAClB,CAAC"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { w as lazyLogger } from "./providers.server.js";
|
|
2
2
|
import { n as env } from "./previous-key.js";
|
|
3
|
-
import {
|
|
3
|
+
import { O as createApiRateLimiter, j as resolveApiRateLimitConfig } from "./api.js";
|
|
4
4
|
import { t as createComputeRateLimiter } from "./rate-limit.js";
|
|
5
5
|
import "./compute.js";
|
|
6
6
|
import { c as RATE_LIMIT_WINDOW_MS, s as RATE_LIMIT_MAX_REQUESTS } from "./computeLimits.js";
|
|
@@ -21,12 +21,12 @@ var engine = new SolveEngine({
|
|
|
21
21
|
}
|
|
22
22
|
});
|
|
23
23
|
/** Get (or create) the warm client + scheduler for a resolved compute server. */
|
|
24
|
-
function getClient(serverConfig
|
|
24
|
+
function getClient(serverConfig) {
|
|
25
25
|
return engine.getClient({
|
|
26
26
|
id: serverConfig.id,
|
|
27
27
|
serverUrl: serverConfig.serverUrl,
|
|
28
28
|
apiKey: serverConfig.apiKey
|
|
29
|
-
}
|
|
29
|
+
});
|
|
30
30
|
}
|
|
31
31
|
/** Drop the warm client for a server whose config just changed (URL/key rotation or deletion). */
|
|
32
32
|
function evictComputeClient(id) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"engine.server.js","names":[],"sources":["../../../src/lib/server/compute/engine.server.ts"],"sourcesContent":["/**\n * App-wide `SolveEngine` instance (`@selvajs/solve/server`) — backs the warm\n * client cache, the definition-byte cache, and solve coalescing for the whole app.\n */\n\nimport { SolveEngine, type CachedClient } from '@selvajs/solve/server';\nimport { env } from '#lib/server/env.js';\nimport { getLogger } from '#lib/server/providers.server.js';\nimport { computeLimits } from '#lib/server/computeLimits.js';\nimport { computeDebugMode } from '#lib/server/config/settings.js';\nimport type { ComputeServerConfig } from '@selvajs/platform';\n\n// `verbose` adds lib-level request logs and Compute's raw error bodies, and implies `on`.\nconst COMPUTE_DEBUG_MODE = computeDebugMode(env);\n\nexport const COMPUTE_DEBUG = COMPUTE_DEBUG_MODE !== 'off';\nexport const COMPUTE_DEBUG_VERBOSE = COMPUTE_DEBUG_MODE === 'verbose';\n\nexport const engine = new SolveEngine({\n\tlimits: computeLimits,\n\tdebug: COMPUTE_DEBUG ? (COMPUTE_DEBUG_VERBOSE ? 'verbose' : true) : false,\n\tonDebugLog: (message) => getLogger().debug(message, { component: 'Compute/client-cache' }),\n\tonSolveCoalesced: (key) => {\n\t\tif (COMPUTE_DEBUG) {\n\t\t\t// key = version:server:tree-json — truncate the tree tail for the log.\n\t\t\tgetLogger().debug('Coalesced onto in-flight solve', {\n\t\t\t\tcomponent: 'Compute/single-flight',\n\t\t\t\tkey: `${key.slice(0, 96)}…`\n\t\t\t});\n\t\t}\n\t}\n});\n\n/** Get (or create) the warm client + scheduler for a resolved compute server. */\nexport function getClient(
|
|
1
|
+
{"version":3,"file":"engine.server.js","names":[],"sources":["../../../src/lib/server/compute/engine.server.ts"],"sourcesContent":["/**\n * App-wide `SolveEngine` instance (`@selvajs/solve/server`) — backs the warm\n * client cache, the definition-byte cache, and solve coalescing for the whole app.\n */\n\nimport { SolveEngine, type CachedClient } from '@selvajs/solve/server';\nimport { env } from '#lib/server/env.js';\nimport { getLogger } from '#lib/server/providers.server.js';\nimport { computeLimits } from '#lib/server/computeLimits.js';\nimport { computeDebugMode } from '#lib/server/config/settings.js';\nimport type { ComputeServerConfig } from '@selvajs/platform';\n\n// `verbose` adds lib-level request logs and Compute's raw error bodies, and implies `on`.\nconst COMPUTE_DEBUG_MODE = computeDebugMode(env);\n\nexport const COMPUTE_DEBUG = COMPUTE_DEBUG_MODE !== 'off';\nexport const COMPUTE_DEBUG_VERBOSE = COMPUTE_DEBUG_MODE === 'verbose';\n\nexport const engine = new SolveEngine({\n\tlimits: computeLimits,\n\tdebug: COMPUTE_DEBUG ? (COMPUTE_DEBUG_VERBOSE ? 'verbose' : true) : false,\n\tonDebugLog: (message) => getLogger().debug(message, { component: 'Compute/client-cache' }),\n\tonSolveCoalesced: (key) => {\n\t\tif (COMPUTE_DEBUG) {\n\t\t\t// key = version:server:tree-json — truncate the tree tail for the log.\n\t\t\tgetLogger().debug('Coalesced onto in-flight solve', {\n\t\t\t\tcomponent: 'Compute/single-flight',\n\t\t\t\tkey: `${key.slice(0, 96)}…`\n\t\t\t});\n\t\t}\n\t}\n});\n\n/** Get (or create) the warm client + scheduler for a resolved compute server. */\nexport function getClient(serverConfig: ComputeServerConfig): Promise<CachedClient> {\n\treturn engine.getClient({\n\t\tid: serverConfig.id,\n\t\tserverUrl: serverConfig.serverUrl,\n\t\tapiKey: serverConfig.apiKey\n\t});\n}\n\n/** Drop the warm client for a server whose config just changed (URL/key rotation or deletion). */\nexport function evictComputeClient(id: string): void {\n\tengine.evictServer(id);\n}\n\n/**\n * Drop cached solve results held by this Selva process (every warm client's\n * scheduler). Separate from the compute server's own `cache/purge`: that one\n * clears Rhino's `cachesolve`, this one clears the layer in front of it.\n */\nexport function clearSolveResultCache(): void {\n\tengine.clearSolveCaches();\n}\n\n/** Drop the `.gh` bytes this Selva process is holding. Costs a storage re-read, nothing more. */\nexport function clearDefinitionCache(): void {\n\tengine.clearDefinitionCache();\n}\n\n/** Solve-cache counters for the admin panel's hit rate. */\nexport function solveCacheStats() {\n\treturn engine.stats().client;\n}\n\n/** Definition-byte-cache counters (hits/misses/evictions/entries/bytes) for admin/debug surfaces. */\nexport function definitionByteCacheStats() {\n\treturn engine.stats().definitionBytes;\n}\n\n/** Materialize a version's bytes through the shared byte cache (render/IO path). */\nexport function loadDefinitionBytes(\n\tversionId: string,\n\tload: () => Promise<Uint8Array>\n): Promise<Uint8Array> {\n\treturn engine.definitionRef(versionId, load).load();\n}\n\nexport type { CachedClient };\n"],"mappings":";;;;;;;;AAaA,IAAM,qBAAqB,iBAAiB,GAAG;AAE/C,IAAa,gBAAgB,uBAAuB;AACpD,IAAa,wBAAwB,uBAAuB;AAE5D,IAAa,SAAS,IAAI,YAAY;CACrC,QAAQ;CACR,OAAO,gBAAiB,wBAAwB,YAAY,OAAQ;CACpE,aAAa,YAAY,UAAU,CAAC,CAAC,MAAM,SAAS,EAAE,WAAW,uBAAuB,CAAC;CACzF,mBAAmB,QAAQ;EAC1B,IAAI,eAEH,UAAU,CAAC,CAAC,MAAM,kCAAkC;GACnD,WAAW;GACX,KAAK,GAAG,IAAI,MAAM,GAAG,EAAE,EAAE;EAC1B,CAAC;CAEH;AACD,CAAC;;AAGD,SAAgB,UAAU,cAA0D;CACnF,OAAO,OAAO,UAAU;EACvB,IAAI,aAAa;EACjB,WAAW,aAAa;EACxB,QAAQ,aAAa;CACtB,CAAC;AACF;;AAGA,SAAgB,mBAAmB,IAAkB;CACpD,OAAO,YAAY,EAAE;AACtB;;;;;;AAOA,SAAgB,wBAA8B;CAC7C,OAAO,iBAAiB;AACzB;;AAGA,SAAgB,uBAA6B;CAC5C,OAAO,qBAAqB;AAC7B;;AAGA,SAAgB,kBAAkB;CACjC,OAAO,OAAO,MAAM,CAAC,CAAC;AACvB;;AAGA,SAAgB,2BAA2B;CAC1C,OAAO,OAAO,MAAM,CAAC,CAAC;AACvB"}
|