@selvajs/selva 4.21.0-beta.6 → 4.21.0-beta.8
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/assets/0.CqqJCiiV.css +2 -0
- package/build/client/_app/immutable/assets/0.CqqJCiiV.css.br +0 -0
- package/build/client/_app/immutable/assets/0.CqqJCiiV.css.gz +0 -0
- package/build/client/_app/immutable/chunks/{BepzH9eI.js → DptnDNFA.js} +60 -55
- package/build/client/_app/immutable/chunks/DptnDNFA.js.br +0 -0
- package/build/client/_app/immutable/chunks/{BepzH9eI.js.gz → DptnDNFA.js.gz} +0 -0
- package/build/client/_app/immutable/chunks/DvJo0Zn0.js +1 -0
- package/build/client/_app/immutable/chunks/DvJo0Zn0.js.br +1 -0
- package/build/client/_app/immutable/chunks/DvJo0Zn0.js.gz +0 -0
- package/build/client/_app/immutable/entry/{app.DblLep9O.js → app.DPVyoSCt.js} +2 -2
- package/build/client/_app/immutable/entry/app.DPVyoSCt.js.br +0 -0
- package/build/client/_app/immutable/entry/app.DPVyoSCt.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{15.BXIV1QfS.js → 15.0NRg5Hm0.js} +1 -1
- package/build/client/_app/immutable/nodes/15.0NRg5Hm0.js.br +0 -0
- package/build/client/_app/immutable/nodes/15.0NRg5Hm0.js.gz +0 -0
- package/build/client/_app/immutable/nodes/21.DpKe0-GH.js +1 -0
- package/build/client/_app/immutable/nodes/21.DpKe0-GH.js.br +0 -0
- package/build/client/_app/immutable/nodes/21.DpKe0-GH.js.gz +0 -0
- package/build/client/_app/immutable/nodes/24.DkL5kHzA.js +3 -0
- package/build/client/_app/immutable/nodes/24.DkL5kHzA.js.br +0 -0
- package/build/client/_app/immutable/nodes/24.DkL5kHzA.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 +20 -34
- package/build/server/_app/immutable/assets/_layout.CqqJCiiV.css +2 -0
- package/build/server/chunks/api-errors.js +18 -3
- package/build/server/chunks/api-errors.js.map +1 -1
- package/build/server/chunks/boot.server.js +1 -1
- package/build/server/chunks/computeRateLimit.server.js +1 -1
- package/build/server/chunks/delete-with-blobs.js +1 -1
- package/build/server/chunks/engine.server.js +50 -3
- package/build/server/chunks/engine.server.js.map +1 -1
- package/build/server/chunks/grasshopper.js +1 -1
- package/build/server/chunks/handlers.js +24 -20
- package/build/server/chunks/handlers.js.map +1 -1
- package/build/server/chunks/http2.js +1 -1
- package/build/server/chunks/instance.js +3 -3
- package/build/server/chunks/internal.js +1 -1
- package/build/server/chunks/{abort-Bfrdupaj.js → keepalive-vtcjhAV3.js} +6 -3
- package/build/server/chunks/keepalive-vtcjhAV3.js.map +1 -0
- package/build/server/chunks/oauth.js +70 -24
- package/build/server/chunks/oauth.js.map +1 -1
- package/build/server/chunks/package.js +1 -1
- package/build/server/chunks/package.js.map +1 -1
- package/build/server/chunks/permissions.server.js +1 -1
- package/build/server/chunks/providers.server.js +72 -3
- package/build/server/chunks/providers.server.js.map +1 -1
- package/build/server/chunks/resolve-server.js +1 -1
- package/build/server/chunks/schema-extraction.js +75 -8
- package/build/server/chunks/schema-extraction.js.map +1 -1
- package/build/server/chunks/server-config-write.js +1 -1
- package/build/server/chunks/server2.js +2 -2
- package/build/server/chunks/server2.js.map +1 -1
- package/build/server/chunks/serverStats.server.js +1 -1
- package/build/server/chunks/solve.server.js +4 -5
- package/build/server/chunks/solve.server.js.map +1 -1
- package/build/server/chunks/sveltekit.js +3 -4
- package/build/server/chunks/sveltekit.js.map +1 -1
- package/build/server/entries/endpoints/.well-known/oauth-authorization-server/_server.ts.js +6 -3
- package/build/server/entries/endpoints/.well-known/oauth-authorization-server/_server.ts.js.map +1 -1
- package/build/server/entries/endpoints/.well-known/oauth-protected-resource/_server.ts.js +6 -3
- package/build/server/entries/endpoints/.well-known/oauth-protected-resource/_server.ts.js.map +1 -1
- package/build/server/entries/endpoints/.well-known/oauth-protected-resource/mcp/_server.ts.js +6 -3
- package/build/server/entries/endpoints/.well-known/oauth-protected-resource/mcp/_server.ts.js.map +1 -1
- package/build/server/entries/endpoints/api/admin/compute/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/admin/compute/actions/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/admin/compute/status/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/admin/system/health/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/admin/system/update/_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/files/_...path_/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/compute/_server.ts.js +10 -5
- 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 +2 -2
- package/build/server/entries/endpoints/api/v1/definitions/_guid_/solve/_server.ts.js +3 -3
- package/build/server/entries/endpoints/mcp/_server.ts.js +43 -13
- package/build/server/entries/endpoints/mcp/_server.ts.js.map +1 -1
- package/build/server/entries/endpoints/oauth/register/_server.ts.js +1 -1
- package/build/server/entries/endpoints/oauth/token/_server.ts.js +1 -1
- package/build/server/entries/hooks.server.js +1 -1
- package/build/server/entries/pages/admin/compute/_page.server.ts.js +1 -2
- package/build/server/entries/pages/admin/compute/_page.server.ts.js.map +1 -1
- package/build/server/entries/pages/admin/system/_page.server.ts.js +3 -3
- package/build/server/entries/pages/admin/system/_page.server.ts.js.map +1 -1
- package/build/server/entries/pages/admin/system/_page.svelte.js +1 -1
- package/build/server/entries/pages/admin/system/_page.svelte.js.map +1 -1
- package/build/server/entries/pages/library/_guid_/_page.server.ts.js +198 -99
- package/build/server/entries/pages/library/_guid_/_page.server.ts.js.map +1 -1
- package/build/server/entries/pages/library/_guid_/_page.svelte.js +462 -30
- package/build/server/entries/pages/library/_guid_/_page.svelte.js.map +1 -1
- package/build/server/entries/pages/oauth/authorize/_page.server.ts.js +3 -2
- package/build/server/entries/pages/oauth/authorize/_page.server.ts.js.map +1 -1
- package/build/server/entries/pages/oauth/authorize/_page.svelte.js +8 -1
- package/build/server/entries/pages/oauth/authorize/_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/0.js +2 -2
- package/build/server/nodes/15.js +1 -1
- package/build/server/nodes/21.js +1 -1
- package/build/server/nodes/24.js +1 -1
- package/build/server/server.js +1 -1
- package/package.json +7 -7
- package/templates/.env.example +5 -3
- package/build/client/_app/immutable/assets/0.2jDm0bqh.css +0 -2
- package/build/client/_app/immutable/assets/0.2jDm0bqh.css.br +0 -0
- package/build/client/_app/immutable/assets/0.2jDm0bqh.css.gz +0 -0
- package/build/client/_app/immutable/chunks/BepzH9eI.js.br +0 -0
- package/build/client/_app/immutable/chunks/BmoT9ksD.js +0 -1
- package/build/client/_app/immutable/chunks/BmoT9ksD.js.br +0 -1
- package/build/client/_app/immutable/chunks/BmoT9ksD.js.gz +0 -0
- 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/15.BXIV1QfS.js.br +0 -0
- package/build/client/_app/immutable/nodes/15.BXIV1QfS.js.gz +0 -0
- package/build/client/_app/immutable/nodes/21.DvC40Ypm.js +0 -1
- 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/24.CPSunfJJ.js +0 -3
- package/build/client/_app/immutable/nodes/24.CPSunfJJ.js.br +0 -0
- package/build/client/_app/immutable/nodes/24.CPSunfJJ.js.gz +0 -0
- package/build/server/_app/immutable/assets/_layout.2jDm0bqh.css +0 -2
- package/build/server/chunks/abort-Bfrdupaj.js.map +0 -1
- package/build/server/chunks/computeLimits.js +0 -33
- package/build/server/chunks/computeLimits.js.map +0 -1
- /package/build/client/_app/immutable/nodes/{0.CYdyv5To.js → 0.Ds0zeDAg.js} +0 -0
- /package/build/client/_app/immutable/nodes/{0.CYdyv5To.js.br → 0.Ds0zeDAg.js.br} +0 -0
- /package/build/client/_app/immutable/nodes/{0.CYdyv5To.js.gz → 0.Ds0zeDAg.js.gz} +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { a as resolveServerForOrg$1 } from "./utils.js";
|
|
2
|
-
import {
|
|
2
|
+
import { u as ComputeServerUnconfiguredError } from "./schema-extraction.js";
|
|
3
3
|
// ../server/src/compute/resolve-server.ts
|
|
4
4
|
/**
|
|
5
5
|
* Pick the right Rhino.Compute server for an (org, definition) pair.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as
|
|
1
|
+
import { a as fetchParsedDefinitionIO, o as normalizeUISchemaCasing, s as readSchemaResults$1 } from "./grasshopper.js";
|
|
2
2
|
import { t as UI_SCHEMA_VERSION } from "./schema.js";
|
|
3
3
|
// ../server/src/compute/errors.ts
|
|
4
4
|
/**
|
|
@@ -21,6 +21,44 @@ var ComputeServerUnconfiguredError = class extends Error {
|
|
|
21
21
|
this.name = "ComputeServerUnconfiguredError";
|
|
22
22
|
}
|
|
23
23
|
};
|
|
24
|
+
// ../server/src/definitions/saved-values.ts
|
|
25
|
+
function savedValuesFrom(inputs) {
|
|
26
|
+
const values = /* @__PURE__ */ new Map();
|
|
27
|
+
for (const input of inputs) {
|
|
28
|
+
if (input.id === void 0 || input.default === void 0) continue;
|
|
29
|
+
values.set(input.id, input.paramType === "Color" ? colorToHex(input.default) : input.default);
|
|
30
|
+
}
|
|
31
|
+
return values;
|
|
32
|
+
}
|
|
33
|
+
/** `schema` with each input's `default` replaced by its saved value, where it has one. */
|
|
34
|
+
function applySavedValues(schema, values) {
|
|
35
|
+
return {
|
|
36
|
+
...schema,
|
|
37
|
+
inputs: schema.inputs.map((input) => values.has(input.id) ? {
|
|
38
|
+
...input,
|
|
39
|
+
default: values.get(input.id)
|
|
40
|
+
} : input)
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
function colorToHex(value) {
|
|
44
|
+
const parts = String(value).split(",").map((s) => parseInt(s.trim(), 10));
|
|
45
|
+
const hex = (n) => n.toString(16).padStart(2, "0");
|
|
46
|
+
if (parts.length === 3) return `#${hex(parts[0])}${hex(parts[1])}${hex(parts[2])}`;
|
|
47
|
+
if (parts.length === 4) return `#${hex(parts[1])}${hex(parts[2])}${hex(parts[3])}`;
|
|
48
|
+
return value;
|
|
49
|
+
}
|
|
50
|
+
// ../server/src/definitions/with-timeout.ts
|
|
51
|
+
/**
|
|
52
|
+
* Settles with `work`, or rejects with `onTimeout()` after `ms`. `work` is not cancelled: it runs
|
|
53
|
+
* on, and its later rejection stays handled.
|
|
54
|
+
*/
|
|
55
|
+
function withTimeout(work, ms, onTimeout) {
|
|
56
|
+
let timer;
|
|
57
|
+
const timeout = new Promise((_, reject) => {
|
|
58
|
+
timer = setTimeout(() => reject(onTimeout()), ms);
|
|
59
|
+
});
|
|
60
|
+
return Promise.race([work, timeout]).finally(() => clearTimeout(timer));
|
|
61
|
+
}
|
|
24
62
|
// ../server/src/definitions/schema-extraction.ts
|
|
25
63
|
/** Thin re-export of @selvajs/compute's unwrap, typed to `UISchema`. */
|
|
26
64
|
function readSchemaResults(raw) {
|
|
@@ -78,18 +116,25 @@ function parseSemver(version) {
|
|
|
78
116
|
] : null;
|
|
79
117
|
}
|
|
80
118
|
/**
|
|
119
|
+
* Orders a schema format version against the app's `UI_SCHEMA_VERSION`: -1 older, 0 current,
|
|
120
|
+
* 1 newer, null unparseable. A missing version is older: plugins before 2.12.0 emitted none.
|
|
121
|
+
*/
|
|
122
|
+
function compareSchemaVersion(version) {
|
|
123
|
+
if (!version) return -1;
|
|
124
|
+
const extracted = parseSemver(version);
|
|
125
|
+
const supported = parseSemver(UI_SCHEMA_VERSION);
|
|
126
|
+
if (!extracted || !supported) return null;
|
|
127
|
+
for (let i = 0; i < 3; i++) if (extracted[i] !== supported[i]) return extracted[i] < supported[i] ? -1 : 1;
|
|
128
|
+
return 0;
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
81
131
|
* Rejects a schema from a NEWER plugin than this app was built against — its
|
|
82
132
|
* shape may contain constructs the renderer doesn't know. Older (or missing)
|
|
83
133
|
* versions pass: the compute-side C# migrator always emits its own current
|
|
84
134
|
* version, and an older shape only lacks optional additions.
|
|
85
135
|
*/
|
|
86
136
|
function assertSupportedSchemaVersion(schema) {
|
|
87
|
-
|
|
88
|
-
if (!version) return;
|
|
89
|
-
const extracted = parseSemver(version);
|
|
90
|
-
const supported = parseSemver(UI_SCHEMA_VERSION);
|
|
91
|
-
if (!extracted || !supported) return;
|
|
92
|
-
if (extracted[0] > supported[0] || extracted[0] === supported[0] && (extracted[1] > supported[1] || extracted[1] === supported[1] && extracted[2] > supported[2])) throw new SchemaExtractionError("unsupported", `This definition was authored with a newer Selva plugin (schema format ${version}); this server supports schema format ≤ ${UI_SCHEMA_VERSION}. Update the server, or re-save the definition with a matching plugin version.`);
|
|
137
|
+
if (compareSchemaVersion(schema.schemaVersion) === 1) throw new SchemaExtractionError("unsupported", `This definition was authored with a newer Selva plugin (schema format ${schema.schemaVersion}); this server supports schema format ≤ ${UI_SCHEMA_VERSION}. Update the server, or re-save the definition with a matching plugin version.`);
|
|
93
138
|
}
|
|
94
139
|
/**
|
|
95
140
|
* POSTs a multipart form to Rhino Compute's `/grasshopper/schema` endpoint (no
|
|
@@ -136,6 +181,28 @@ async function fetchSchemaFromCompute(definitionBytes, server) {
|
|
|
136
181
|
assertCamelCaseSchema(schemas[0]);
|
|
137
182
|
return schemas[0];
|
|
138
183
|
}
|
|
139
|
-
|
|
184
|
+
/**
|
|
185
|
+
* How long an upload waits for the saved values once the schema is in. Missing them costs only
|
|
186
|
+
* the first render its defaults: the render path reads them behind that render.
|
|
187
|
+
*/
|
|
188
|
+
var SAVED_VALUES_GRACE_MS = 5e3;
|
|
189
|
+
var SAVED_VALUES_TIMEOUT_MS = 12e4;
|
|
190
|
+
/**
|
|
191
|
+
* `fetchSchemaFromCompute` with the values saved in the file as input defaults, so the stored
|
|
192
|
+
* schema renders without asking Compute again. The values are read beside the schema,
|
|
193
|
+
* best-effort: only the schema gates the upload.
|
|
194
|
+
*/
|
|
195
|
+
async function extractSchemaForUpload(definitionBytes, server) {
|
|
196
|
+
const values = fetchParsedDefinitionIO(definitionBytes, {
|
|
197
|
+
serverUrl: server.serverUrl,
|
|
198
|
+
...server.apiKey && { apiKey: server.apiKey },
|
|
199
|
+
timeoutMs: SAVED_VALUES_TIMEOUT_MS
|
|
200
|
+
}).then((io) => savedValuesFrom(io.inputs));
|
|
201
|
+
values.catch(() => {});
|
|
202
|
+
const schema = await fetchSchemaFromCompute(definitionBytes, server);
|
|
203
|
+
const saved = await withTimeout(values, SAVED_VALUES_GRACE_MS, () => /* @__PURE__ */ new Error("saved values not read in time")).catch(() => null);
|
|
204
|
+
return saved ? applySavedValues(schema, saved) : schema;
|
|
205
|
+
}
|
|
206
|
+
export { fetchSchemaFromCompute as a, applySavedValues as c, extractSchemaForUpload as i, savedValuesFrom as l, assertCamelCaseSchema as n, postSchemaFormData as o, compareSchemaVersion as r, withTimeout as s, SchemaExtractionError as t, ComputeServerUnconfiguredError as u };
|
|
140
207
|
|
|
141
208
|
//# sourceMappingURL=schema-extraction.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schema-extraction.js","names":["readWrapper"],"sources":["../../../../server/src/compute/errors.ts","../../../../server/src/definitions/schema-extraction.ts"],"sourcesContent":["/**\n * Compute error types, kept in a leaf module with no imports.\n *\n * Separate from the function that throws them on purpose: an error mapper needs\n * nothing but the class to `instanceof` against, and importing it from beside\n * the throw site drags that module's dependencies into every mapper. Anything\n * an error mapper imports belongs here.\n */\n\n/**\n * Thrown when no compute server is configured or visible for the org — a\n * misconfiguration an operator must fix in `/admin/compute`, not a bug. Routes\n * map this to 503 instead of letting the pure helper's plain `Error` surface as\n * a generic 500.\n */\nexport class ComputeServerUnconfiguredError extends Error {\n\tconstructor(\n\t\tmessage = 'No compute server configured. Ask an admin to add one in /admin/compute.'\n\t) {\n\t\tsuper(message);\n\t\tthis.name = 'ComputeServerUnconfiguredError';\n\t}\n}\n","// Extraction IS validation: a `.gh` with no valid \"Schema\" output, or an\n// unreachable compute server, throws here — which is what makes this the upload\n// gate as well as the render path's fallback for un-cached or stale versions.\n\nimport {\n\tnormalizeUISchemaCasing,\n\treadSchemaResults as readWrapper,\n\ttype SchemaEndpointResult\n} from '@selvajs/compute/grasshopper';\nimport { UI_SCHEMA_VERSION, type UISchema } from '@selvajs/schemas';\nimport type { ComputeServerConfig } from '@selvajs/platform';\n\n/** One entry of the compute schema endpoint's response, typed to our `UISchema`. */\nexport type SchemaExtractionResult = SchemaEndpointResult<UISchema>;\n\n/** Thin re-export of @selvajs/compute's unwrap, typed to `UISchema`. */\nexport function readSchemaResults(raw: unknown): SchemaExtractionResult[] {\n\treturn readWrapper<UISchema>(raw);\n}\n\n/** Thrown when compute is reachable but the definition yields no usable schema. */\nexport class SchemaExtractionError extends Error {\n\tconstructor(\n\t\tpublic readonly kind: 'unreachable' | 'invalid' | 'unsupported' | 'malformed',\n\t\tmessage: string\n\t) {\n\t\tsuper(message);\n\t\tthis.name = 'SchemaExtractionError';\n\t}\n}\n\n/**\n * Rejects a schema whose keys are not camelCase by the time it reaches a consumer.\n *\n * Compute serializes the plugin's `UISchema` POCO, whose camelCase names live in\n * `[JsonProperty]` attributes. `Selva.gha` ILRepack-merges Newtonsoft, so those\n * attributes have type `Selva!Newtonsoft.Json.JsonPropertyAttribute`; a compute\n * server serializing with its OWN Newtonsoft does not recognize them, reads no\n * attributes, and falls back to raw CLR member names — `Inputs`, `Layout`.\n * Nothing throws on the wire: every consumer just reads `schema.inputs` as\n * undefined and renders a definition with no inputs.\n *\n * `postSchemaFormData` repairs that casing via `normalizeUISchemaCasing`, so a\n * schema fresh off the wire never trips this. It stays because schemas are also\n * PERSISTED: a row cached before the normalizer existed still holds PascalCase,\n * and it reaches consumers without passing through `postSchemaFormData` again.\n * A schema with no `inputs` in any casing lands here too. It is a backstop, not\n * the primary defense — which is why it names the missing key rather than telling\n * the operator to go update their compute server.\n *\n * Checked structurally rather than by plugin version, because the casing depends\n * on which assembly serialized the schema, not on any version number.\n */\nexport function assertCamelCaseSchema(schema: UISchema): void {\n\tconst raw = schema as unknown as Record<string, unknown>;\n\tif (Array.isArray(raw.inputs)) return;\n\n\tconst pascalKeys = ['Inputs', 'Outputs', 'Layout', 'SchemaVersion'].filter((k) => k in raw);\n\tif (pascalKeys.length > 0) {\n\t\tthrow new SchemaExtractionError(\n\t\t\t'malformed',\n\t\t\t`Schema keys are PascalCase (found ${pascalKeys.join(', ')}), so every property name ` +\n\t\t\t\t`is wrong and the definition would render with no inputs. Compute serialized it with ` +\n\t\t\t\t`its own Newtonsoft instead of the one merged into Selva.gha. Fresh responses are ` +\n\t\t\t\t`normalized, so this is most likely a schema cached before that fix — re-save the ` +\n\t\t\t\t`definition version to re-extract it.`\n\t\t);\n\t}\n\n\tthrow new SchemaExtractionError(\n\t\t'malformed',\n\t\t`Compute returned a schema with no 'inputs' array (got keys: ${Object.keys(raw)\n\t\t\t.slice(0, 12)\n\t\t\t.join(', ')}).`\n\t);\n}\n\nfunction parseSemver(version: string): [number, number, number] | null {\n\tconst m = /^(\\d+)\\.(\\d+)\\.(\\d+)$/.exec(version);\n\treturn m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;\n}\n\n/**\n * Rejects a schema from a NEWER plugin than this app was built against — its\n * shape may contain constructs the renderer doesn't know. Older (or missing)\n * versions pass: the compute-side C# migrator always emits its own current\n * version, and an older shape only lacks optional additions.\n */\nexport function assertSupportedSchemaVersion(schema: UISchema): void {\n\tconst version = schema.schemaVersion;\n\tif (!version) return; // pre-2.12.0 plugin — older than the app, fine\n\tconst extracted = parseSemver(version);\n\tconst supported = parseSemver(UI_SCHEMA_VERSION);\n\tif (!extracted || !supported) return;\n\tconst newer =\n\t\textracted[0] > supported[0] ||\n\t\t(extracted[0] === supported[0] &&\n\t\t\t(extracted[1] > supported[1] ||\n\t\t\t\t(extracted[1] === supported[1] && extracted[2] > supported[2])));\n\tif (newer) {\n\t\tthrow new SchemaExtractionError(\n\t\t\t'unsupported',\n\t\t\t`This definition was authored with a newer Selva plugin (schema format ${version}); ` +\n\t\t\t\t`this server supports schema format ≤ ${UI_SCHEMA_VERSION}. Update the server, or ` +\n\t\t\t\t`re-save the definition with a matching plugin version.`\n\t\t);\n\t}\n}\n\n/**\n * POSTs a multipart form to Rhino Compute's `/grasshopper/schema` endpoint (no\n * solve required). Throws 'unreachable' on a network failure or non-2xx. The\n * per-file `error` Compute reports on its 200-with-no-schemas case is left to\n * the caller — single-file and multi-file callers want different messages.\n */\nexport async function postSchemaFormData(\n\tformData: FormData,\n\tserver: ComputeServerConfig\n): Promise<SchemaExtractionResult[]> {\n\tconst schemaUrl = new URL('/grasshopper/schema', server.serverUrl).toString();\n\n\tconst headers: Record<string, string> = {};\n\tif (server.apiKey) {\n\t\theaders['RhinoComputeKey'] = server.apiKey;\n\t}\n\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(schemaUrl, { method: 'POST', headers, body: formData });\n\t} catch (err) {\n\t\tthrow new SchemaExtractionError(\n\t\t\t'unreachable',\n\t\t\t`Compute server is unreachable: ${err instanceof Error ? err.message : String(err)}`\n\t\t);\n\t}\n\n\tif (!response.ok) {\n\t\tthrow new SchemaExtractionError(\n\t\t\t'unreachable',\n\t\t\t`Schema endpoint returned ${response.status}: ${response.statusText}`\n\t\t);\n\t}\n\n\t// Normalize here rather than in each caller: the upload/validation route reads\n\t// `postSchemaFormData` directly, so a fix applied only inside\n\t// `fetchSchemaFromCompute` would leave that path serving PascalCase schemas.\n\tconst results = readSchemaResults(await response.json());\n\treturn results.map((result) => ({\n\t\t...result,\n\t\tschemas: result.schemas?.map((schema) => normalizeUISchemaCasing(schema))\n\t}));\n}\n\n/**\n * Throws `SchemaExtractionError` so callers can map to the right HTTP status:\n * 503 unreachable / 422 invalid or unsupported.\n */\nexport async function fetchSchemaFromCompute(\n\tdefinitionBytes: Uint8Array,\n\tserver: ComputeServerConfig\n): Promise<UISchema> {\n\tconst formData = new FormData();\n\tconst blob = new Blob([new Uint8Array(definitionBytes)], { type: 'application/octet-stream' });\n\tformData.append('file', blob, 'definition.gh');\n\n\tconst results = await postSchemaFormData(formData, server);\n\tconst schemas = results.flatMap((r) => r.schemas ?? []);\n\n\tif (schemas.length === 0) {\n\t\t// Compute answers 200 while reporting a per-file `error`, so the\n\t\t// !response.ok guard never fires for it. Surface that message verbatim: it\n\t\t// names the actual cause (bad Schema source, no embedded schema, ...),\n\t\t// which the generic fallback below cannot.\n\t\tconst diagnosis = results.map((r) => r.error).filter(Boolean);\n\t\tif (diagnosis.length > 0) {\n\t\t\tthrow new SchemaExtractionError('invalid', diagnosis.join('\\n'));\n\t\t}\n\n\t\tthrow new SchemaExtractionError(\n\t\t\t'invalid',\n\t\t\t'No schemas found in definition.\\n\\n' +\n\t\t\t\t'In Grasshopper, verify a Context Bake component with the output name \"Schema\" is present and wired to the solver.'\n\t\t);\n\t}\n\n\tassertSupportedSchemaVersion(schemas[0]);\n\tassertCamelCaseSchema(schemas[0]);\n\treturn schemas[0];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAeA,IAAa,iCAAb,cAAoD,MAAM;CACzD,YACC,UAAU,4EACT;EACD,MAAM,OAAO;EACb,KAAK,OAAO;CACb;AACD;;;ACNA,SAAgB,kBAAkB,KAAwC;CACzE,OAAOA,oBAAsB,GAAG;AACjC;;AAGA,IAAa,wBAAb,cAA2C,MAAM;CAE/B;CADjB,YACC,MACA,SACC;EACD,MAAM,OAAO;E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AAI;EACH,WAAW,MAAM,MAAM,WAAW;GAAE,QAAQ;GAAQ;GAAS,MAAM;EAAS,CAAC;CAC9E,SAAS,KAAK;EACb,MAAM,IAAI,sBACT,eACA,kCAAkC,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,GAClF;CACD;CAEA,IAAI,CAAC,SAAS,IACb,MAAM,IAAI,sBACT,eACA,4BAA4B,SAAS,OAAO,IAAI,SAAS,YAC1D;CAOD,OADgB,kBAAkB,MAAM,SAAS,KAAK,CAC/C,CAAA,CAAQ,KAAK,YAAY;EAC/B,GAAG;EACH,SAAS,OAAO,SAAS,KAAK,WAAW,wBAAwB,MAAM,CAAC;CACzE,EAAE;AACH;;;;;AAMA,eAAsB,uBACrB,iBACA,QACoB;CACpB,MAAM,WAAW,IAAI,SAAS;CAC9B,MAAM,OAAO,IAAI,KAAK,CAAC,IAAI,WAAW,eAAe,CAAC,GAAG,EAAE,MAAM,2BAA2B,CAAC;CAC7F,SAAS,OAAO,QAAQ,MAAM,eAAe;CAE7C,MAAM,UAAU,MAAM,mBAAmB,UAAU,MAAM;CACzD,MAAM,UAAU,QAAQ,SAAS,MAAM,EAAE,WAAW,CAAC,CAAC;CAEtD,IAAI,QAAQ,WAAW,GAAG;EAKzB,MAAM,YAAY,QAAQ,KAAK,MAAM,EAAE,KAAK,CAAC,CAAC,OAAO,OAAO;EAC5D,IAAI,UAAU,SAAS,GACtB,MAAM,IAAI,sBAAsB,WAAW,UAAU,KAAK,IAAI,CAAC;EAGhE,MAAM,IAAI,sBACT,WACA,wJAED;CACD;CAEA,6BAA6B,QAAQ,EAAE;CACvC,sBAAsB,QAAQ,EAAE;CAChC,OAAO,QAAQ;AAChB"}
|
|
1
|
+
{"version":3,"file":"schema-extraction.js","names":["readWrapper"],"sources":["../../../../server/src/compute/errors.ts","../../../../server/src/definitions/saved-values.ts","../../../../server/src/definitions/with-timeout.ts","../../../../server/src/definitions/schema-extraction.ts"],"sourcesContent":["/**\n * Compute error types, kept in a leaf module with no imports.\n *\n * Separate from the function that throws them on purpose: an error mapper needs\n * nothing but the class to `instanceof` against, and importing it from beside\n * the throw site drags that module's dependencies into every mapper. Anything\n * an error mapper imports belongs here.\n */\n\n/**\n * Thrown when no compute server is configured or visible for the org — a\n * misconfiguration an operator must fix in `/admin/compute`, not a bug. Routes\n * map this to 503 instead of letting the pure helper's plain `Error` surface as\n * a generic 500.\n */\nexport class ComputeServerUnconfiguredError extends Error {\n\tconstructor(\n\t\tmessage = 'No compute server configured. Ask an admin to add one in /admin/compute.'\n\t) {\n\t\tsuper(message);\n\t\tthis.name = 'ComputeServerUnconfiguredError';\n\t}\n}\n","// The embedded schema carries input values from the author's last schema sync. Compute's `/io`\n// reads the values saved in the file, which can be newer, and those are what a form must start\n// from. A version's bytes never change, so neither do its saved values.\n\nimport type { UISchema } from '@selvajs/schemas';\n\n/** Each input's saved value, keyed by param id. */\nexport type SavedValues = ReadonlyMap<string, unknown>;\n\nexport function savedValuesFrom(\n\tinputs: ReadonlyArray<{ id?: string; paramType?: string; default?: unknown }>\n): SavedValues {\n\tconst values = new Map<string, unknown>();\n\tfor (const input of inputs) {\n\t\tif (input.id === undefined || input.default === undefined) continue;\n\t\tvalues.set(input.id, input.paramType === 'Color' ? colorToHex(input.default) : input.default);\n\t}\n\treturn values;\n}\n\n/** `schema` with each input's `default` replaced by its saved value, where it has one. */\nexport function applySavedValues(schema: UISchema, values: SavedValues): UISchema {\n\treturn {\n\t\t...schema,\n\t\tinputs: schema.inputs.map((input) =>\n\t\t\tvalues.has(input.id) ? { ...input, default: values.get(input.id) } : input\n\t\t)\n\t};\n}\n\n// Compute sends colors as \"r,g,b\" or \"a,r,g,b\"; the color picker takes hex.\nfunction colorToHex(value: unknown): unknown {\n\tconst parts = String(value)\n\t\t.split(',')\n\t\t.map((s) => parseInt(s.trim(), 10));\n\tconst hex = (n: number) => n.toString(16).padStart(2, '0');\n\tif (parts.length === 3) return `#${hex(parts[0])}${hex(parts[1])}${hex(parts[2])}`;\n\tif (parts.length === 4) return `#${hex(parts[1])}${hex(parts[2])}${hex(parts[3])}`;\n\treturn value;\n}\n","/**\n * Settles with `work`, or rejects with `onTimeout()` after `ms`. `work` is not cancelled: it runs\n * on, and its later rejection stays handled.\n */\nexport function withTimeout<T>(work: Promise<T>, ms: number, onTimeout: () => Error): Promise<T> {\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tconst timeout = new Promise<never>((_, reject) => {\n\t\ttimer = setTimeout(() => reject(onTimeout()), ms);\n\t});\n\treturn Promise.race([work, timeout]).finally(() => clearTimeout(timer));\n}\n","// Extraction IS validation: a `.gh` with no valid \"Schema\" output, or an\n// unreachable compute server, throws here — which is what makes this the upload\n// gate as well as the render path's fallback for un-cached or stale versions.\n\nimport {\n\tfetchParsedDefinitionIO,\n\tnormalizeUISchemaCasing,\n\treadSchemaResults as readWrapper,\n\ttype SchemaEndpointResult\n} from '@selvajs/compute/grasshopper';\nimport { UI_SCHEMA_VERSION, type UISchema } from '@selvajs/schemas';\nimport type { ComputeServerConfig } from '@selvajs/platform';\nimport { applySavedValues, savedValuesFrom } from './saved-values.js';\nimport { withTimeout } from './with-timeout.js';\n\n/** One entry of the compute schema endpoint's response, typed to our `UISchema`. */\nexport type SchemaExtractionResult = SchemaEndpointResult<UISchema>;\n\n/** Thin re-export of @selvajs/compute's unwrap, typed to `UISchema`. */\nexport function readSchemaResults(raw: unknown): SchemaExtractionResult[] {\n\treturn readWrapper<UISchema>(raw);\n}\n\n/** Thrown when compute is reachable but the definition yields no usable schema. */\nexport class SchemaExtractionError extends Error {\n\tconstructor(\n\t\tpublic readonly kind: 'unreachable' | 'invalid' | 'unsupported' | 'malformed',\n\t\tmessage: string\n\t) {\n\t\tsuper(message);\n\t\tthis.name = 'SchemaExtractionError';\n\t}\n}\n\n/**\n * Rejects a schema whose keys are not camelCase by the time it reaches a consumer.\n *\n * Compute serializes the plugin's `UISchema` POCO, whose camelCase names live in\n * `[JsonProperty]` attributes. `Selva.gha` ILRepack-merges Newtonsoft, so those\n * attributes have type `Selva!Newtonsoft.Json.JsonPropertyAttribute`; a compute\n * server serializing with its OWN Newtonsoft does not recognize them, reads no\n * attributes, and falls back to raw CLR member names — `Inputs`, `Layout`.\n * Nothing throws on the wire: every consumer just reads `schema.inputs` as\n * undefined and renders a definition with no inputs.\n *\n * `postSchemaFormData` repairs that casing via `normalizeUISchemaCasing`, so a\n * schema fresh off the wire never trips this. It stays because schemas are also\n * PERSISTED: a row cached before the normalizer existed still holds PascalCase,\n * and it reaches consumers without passing through `postSchemaFormData` again.\n * A schema with no `inputs` in any casing lands here too. It is a backstop, not\n * the primary defense — which is why it names the missing key rather than telling\n * the operator to go update their compute server.\n *\n * Checked structurally rather than by plugin version, because the casing depends\n * on which assembly serialized the schema, not on any version number.\n */\nexport function assertCamelCaseSchema(schema: UISchema): void {\n\tconst raw = schema as unknown as Record<string, unknown>;\n\tif (Array.isArray(raw.inputs)) return;\n\n\tconst pascalKeys = ['Inputs', 'Outputs', 'Layout', 'SchemaVersion'].filter((k) => k in raw);\n\tif (pascalKeys.length > 0) {\n\t\tthrow new SchemaExtractionError(\n\t\t\t'malformed',\n\t\t\t`Schema keys are PascalCase (found ${pascalKeys.join(', ')}), so every property name ` +\n\t\t\t\t`is wrong and the definition would render with no inputs. Compute serialized it with ` +\n\t\t\t\t`its own Newtonsoft instead of the one merged into Selva.gha. Fresh responses are ` +\n\t\t\t\t`normalized, so this is most likely a schema cached before that fix — re-save the ` +\n\t\t\t\t`definition version to re-extract it.`\n\t\t);\n\t}\n\n\tthrow new SchemaExtractionError(\n\t\t'malformed',\n\t\t`Compute returned a schema with no 'inputs' array (got keys: ${Object.keys(raw)\n\t\t\t.slice(0, 12)\n\t\t\t.join(', ')}).`\n\t);\n}\n\nfunction parseSemver(version: string): [number, number, number] | null {\n\tconst m = /^(\\d+)\\.(\\d+)\\.(\\d+)$/.exec(version);\n\treturn m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;\n}\n\n/**\n * Orders a schema format version against the app's `UI_SCHEMA_VERSION`: -1 older, 0 current,\n * 1 newer, null unparseable. A missing version is older: plugins before 2.12.0 emitted none.\n */\nexport function compareSchemaVersion(version: string | undefined): -1 | 0 | 1 | null {\n\tif (!version) return -1;\n\tconst extracted = parseSemver(version);\n\tconst supported = parseSemver(UI_SCHEMA_VERSION);\n\tif (!extracted || !supported) return null;\n\tfor (let i = 0; i < 3; i++) {\n\t\tif (extracted[i] !== supported[i]) return extracted[i] < supported[i] ? -1 : 1;\n\t}\n\treturn 0;\n}\n\n/**\n * Rejects a schema from a NEWER plugin than this app was built against — its\n * shape may contain constructs the renderer doesn't know. Older (or missing)\n * versions pass: the compute-side C# migrator always emits its own current\n * version, and an older shape only lacks optional additions.\n */\nexport function assertSupportedSchemaVersion(schema: UISchema): void {\n\tif (compareSchemaVersion(schema.schemaVersion) === 1) {\n\t\tthrow new SchemaExtractionError(\n\t\t\t'unsupported',\n\t\t\t`This definition was authored with a newer Selva plugin (schema format ${schema.schemaVersion}); ` +\n\t\t\t\t`this server supports schema format ≤ ${UI_SCHEMA_VERSION}. Update the server, or ` +\n\t\t\t\t`re-save the definition with a matching plugin version.`\n\t\t);\n\t}\n}\n\n/**\n * POSTs a multipart form to Rhino Compute's `/grasshopper/schema` endpoint (no\n * solve required). Throws 'unreachable' on a network failure or non-2xx. The\n * per-file `error` Compute reports on its 200-with-no-schemas case is left to\n * the caller — single-file and multi-file callers want different messages.\n */\nexport async function postSchemaFormData(\n\tformData: FormData,\n\tserver: ComputeServerConfig\n): Promise<SchemaExtractionResult[]> {\n\tconst schemaUrl = new URL('/grasshopper/schema', server.serverUrl).toString();\n\n\tconst headers: Record<string, string> = {};\n\tif (server.apiKey) {\n\t\theaders['RhinoComputeKey'] = server.apiKey;\n\t}\n\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(schemaUrl, { method: 'POST', headers, body: formData });\n\t} catch (err) {\n\t\tthrow new SchemaExtractionError(\n\t\t\t'unreachable',\n\t\t\t`Compute server is unreachable: ${err instanceof Error ? err.message : String(err)}`\n\t\t);\n\t}\n\n\tif (!response.ok) {\n\t\tthrow new SchemaExtractionError(\n\t\t\t'unreachable',\n\t\t\t`Schema endpoint returned ${response.status}: ${response.statusText}`\n\t\t);\n\t}\n\n\t// Normalize here rather than in each caller: the upload/validation route reads\n\t// `postSchemaFormData` directly, so a fix applied only inside\n\t// `fetchSchemaFromCompute` would leave that path serving PascalCase schemas.\n\tconst results = readSchemaResults(await response.json());\n\treturn results.map((result) => ({\n\t\t...result,\n\t\tschemas: result.schemas?.map((schema) => normalizeUISchemaCasing(schema))\n\t}));\n}\n\n/**\n * Throws `SchemaExtractionError` so callers can map to the right HTTP status:\n * 503 unreachable / 422 invalid or unsupported.\n */\nexport async function fetchSchemaFromCompute(\n\tdefinitionBytes: Uint8Array,\n\tserver: ComputeServerConfig\n): Promise<UISchema> {\n\tconst formData = new FormData();\n\tconst blob = new Blob([new Uint8Array(definitionBytes)], { type: 'application/octet-stream' });\n\tformData.append('file', blob, 'definition.gh');\n\n\tconst results = await postSchemaFormData(formData, server);\n\tconst schemas = results.flatMap((r) => r.schemas ?? []);\n\n\tif (schemas.length === 0) {\n\t\t// Compute answers 200 while reporting a per-file `error`, so the\n\t\t// !response.ok guard never fires for it. Surface that message verbatim: it\n\t\t// names the actual cause (bad Schema source, no embedded schema, ...),\n\t\t// which the generic fallback below cannot.\n\t\tconst diagnosis = results.map((r) => r.error).filter(Boolean);\n\t\tif (diagnosis.length > 0) {\n\t\t\tthrow new SchemaExtractionError('invalid', diagnosis.join('\\n'));\n\t\t}\n\n\t\tthrow new SchemaExtractionError(\n\t\t\t'invalid',\n\t\t\t'No schemas found in definition.\\n\\n' +\n\t\t\t\t'In Grasshopper, verify a Context Bake component with the output name \"Schema\" is present and wired to the solver.'\n\t\t);\n\t}\n\n\tassertSupportedSchemaVersion(schemas[0]);\n\tassertCamelCaseSchema(schemas[0]);\n\treturn schemas[0];\n}\n\n/**\n * How long an upload waits for the saved values once the schema is in. Missing them costs only\n * the first render its defaults: the render path reads them behind that render.\n */\nconst SAVED_VALUES_GRACE_MS = 5_000;\n\n// Bounds the `/io` request itself, which outlives an upload that stopped waiting for it.\nconst SAVED_VALUES_TIMEOUT_MS = 120_000;\n\n/**\n * `fetchSchemaFromCompute` with the values saved in the file as input defaults, so the stored\n * schema renders without asking Compute again. The values are read beside the schema,\n * best-effort: only the schema gates the upload.\n */\nexport async function extractSchemaForUpload(\n\tdefinitionBytes: Uint8Array,\n\tserver: ComputeServerConfig\n): Promise<UISchema> {\n\tconst values = fetchParsedDefinitionIO(definitionBytes, {\n\t\tserverUrl: server.serverUrl,\n\t\t...(server.apiKey && { apiKey: server.apiKey }),\n\t\ttimeoutMs: SAVED_VALUES_TIMEOUT_MS\n\t}).then((io) => savedValuesFrom(io.inputs));\n\tvalues.catch(() => {});\n\n\tconst schema = await fetchSchemaFromCompute(definitionBytes, server);\n\tconst saved = await withTimeout(\n\t\tvalues,\n\t\tSAVED_VALUES_GRACE_MS,\n\t\t() => new Error('saved values not read in time')\n\t).catch(() => null);\n\treturn saved ? applySavedValues(schema, saved) : schema;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAeA,IAAa,iCAAb,cAAoD,MAAM;CACzD,YACC,UAAU,4EACT;EACD,MAAM,OAAO;EACb,KAAK,OAAO;CACb;AACD;;ACbA,SAAgB,gBACf,QACc;CACd,MAAM,yBAAS,IAAI,IAAqB;CACxC,KAAK,MAAM,SAAS,QAAQ;EAC3B,IAAI,MAAM,OAAO,KAAA,KAAa,MAAM,YAAY,KAAA,GAAW;EAC3D,OAAO,IAAI,MAAM,IAAI,MAAM,cAAc,UAAU,WAAW,MAAM,OAAO,IAAI,MAAM,OAAO;CAC7F;CACA,OAAO;AACR;;AAGA,SAAgB,iBAAiB,QAAkB,QAA+B;CACjF,OAAO;EACN,GAAG;EACH,QAAQ,OAAO,OAAO,KAAK,UAC1B,OAAO,IAAI,MAAM,EAAE,IAAI;GAAE,GAAG;GAA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B,OAAO,QAAQ,iBAAiB,QAAQ,KAAK,IAAI;AAClD"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { V as isEncryptedSecret } from "./providers.server.js";
|
|
2
2
|
import { A as apiError, it as trimTrailing, k as ApiErrorCode } from "./access.js";
|
|
3
3
|
import { r as GuidSchema } from "./schemas.js";
|
|
4
4
|
import { n as isLinkLocalUrl } from "./safe-url.js";
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { s as createOAuthServer, t as CODE_TTL_MS } from "./oauth.js";
|
|
2
1
|
import { t as hmacKeys } from "./keys.server.js";
|
|
3
2
|
import { t as createComputeRateLimiter } from "./rate-limit.js";
|
|
4
3
|
import { t as assertSafeRemoteDefinitionUrl } from "./safe-url.js";
|
|
5
4
|
import { n as readBodyWithCap } from "./remote-definition.js";
|
|
6
5
|
import "./compute.js";
|
|
6
|
+
import { a as createOAuthServer, t as CODE_TTL_MS } from "./oauth.js";
|
|
7
7
|
import "./tokens.js";
|
|
8
8
|
import { json } from "@sveltejs/kit";
|
|
9
9
|
// src/lib/server/oauth/server.ts
|
|
@@ -101,6 +101,6 @@ var DISCOVERY_HEADERS = {
|
|
|
101
101
|
"Access-Control-Allow-Origin": "*",
|
|
102
102
|
"Cache-Control": "public, max-age=3600"
|
|
103
103
|
};
|
|
104
|
-
export {
|
|
104
|
+
export { oauthUnavailable as a, oauthServer as i, expectRedemption as n, oauthRateLimited as r, DISCOVERY_HEADERS as t };
|
|
105
105
|
|
|
106
106
|
//# sourceMappingURL=server2.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server2.js","names":[],"sources":["../../../src/lib/server/oauth/server.ts"],"sourcesContent":["/**\n * This instance's OAuth authorization server for MCP clients. The protocol lives\n * in `@selvajs/server/oauth`; this file supplies the secret, the SSRF-guarded\n * metadata fetch and the per-IP limit the endpoints share.\n */\n\nimport { json, type RequestEvent } from '@sveltejs/kit';\nimport { hmacKeys } from '#lib/server/keys.server.js';\nimport {\n\tassertSafeRemoteDefinitionUrl,\n\tcreateComputeRateLimiter,\n\treadBodyWithCap\n} from '@selvajs/server/compute';\nimport { CODE_TTL_MS, createOAuthServer, type OAuthServer } from '@selvajs/server/oauth';\nimport { MIN_TOKEN_SECRET_LENGTH } from '@selvajs/server/tokens';\n\nconst METADATA_TIMEOUT_MS = 5_000;\nconst METADATA_MAX_BYTES = 64 * 1024;\n\n// One slot, as for `/mcp`: the origin comes from the request, so a map would grow\n// with whatever hosts a caller sends. Re-keyed on the secret, like the token codecs.\nlet cached: { origin: string; secret: string; server: OAuthServer } | null = null;\n// Outlives `cached`, so rebuilding the server for another origin can't forget a redeemed code.\nconst redeemedCodes = new Map<string, number>();\n\n// The key is minted at consent, before its code is redeemed. A client that never\n// exchanges the code would leave a live key nobody holds, so it is revoked once\n// the code can no longer be redeemed. Lost on restart: best effort.\nconst ABANDON_AFTER_MS = CODE_TTL_MS + 60_000;\nconst unredeemed = new Map<string, ReturnType<typeof setTimeout>>();\n\n/** Revoke `tokenId` with `revoke` unless its code is redeemed in time. */\nexport function expectRedemption(tokenId: string, revoke: () => Promise<void>): void {\n\tconst timer = setTimeout(() => {\n\t\tunredeemed.delete(tokenId);\n\t\trevoke().catch(() => {});\n\t}, ABANDON_AFTER_MS);\n\ttimer.unref?.();\n\tunredeemed.set(tokenId, timer);\n}\n\nfunction onRedeemed(tokenId: string): void {\n\tclearTimeout(unredeemed.get(tokenId));\n\tunredeemed.delete(tokenId);\n}\n\n/** Whether `oauthServer` would build one, without building it. */\
|
|
1
|
+
{"version":3,"file":"server2.js","names":[],"sources":["../../../src/lib/server/oauth/server.ts"],"sourcesContent":["/**\n * This instance's OAuth authorization server for MCP clients. The protocol lives\n * in `@selvajs/server/oauth`; this file supplies the secret, the SSRF-guarded\n * metadata fetch and the per-IP limit the endpoints share.\n */\n\nimport { json, type RequestEvent } from '@sveltejs/kit';\nimport { hmacKeys } from '#lib/server/keys.server.js';\nimport {\n\tassertSafeRemoteDefinitionUrl,\n\tcreateComputeRateLimiter,\n\treadBodyWithCap\n} from '@selvajs/server/compute';\nimport { CODE_TTL_MS, createOAuthServer, type OAuthServer } from '@selvajs/server/oauth';\nimport { MIN_TOKEN_SECRET_LENGTH } from '@selvajs/server/tokens';\n\nconst METADATA_TIMEOUT_MS = 5_000;\nconst METADATA_MAX_BYTES = 64 * 1024;\n\n// One slot, as for `/mcp`: the origin comes from the request, so a map would grow\n// with whatever hosts a caller sends. Re-keyed on the secret, like the token codecs.\nlet cached: { origin: string; secret: string; server: OAuthServer } | null = null;\n// Outlives `cached`, so rebuilding the server for another origin can't forget a redeemed code.\nconst redeemedCodes = new Map<string, number>();\n\n// The key is minted at consent, before its code is redeemed. A client that never\n// exchanges the code would leave a live key nobody holds, so it is revoked once\n// the code can no longer be redeemed. Lost on restart: best effort.\nconst ABANDON_AFTER_MS = CODE_TTL_MS + 60_000;\nconst unredeemed = new Map<string, ReturnType<typeof setTimeout>>();\n\n/** Revoke `tokenId` with `revoke` unless its code is redeemed in time. */\nexport function expectRedemption(tokenId: string, revoke: () => Promise<void>): void {\n\tconst timer = setTimeout(() => {\n\t\tunredeemed.delete(tokenId);\n\t\trevoke().catch(() => {});\n\t}, ABANDON_AFTER_MS);\n\ttimer.unref?.();\n\tunredeemed.set(tokenId, timer);\n}\n\nfunction onRedeemed(tokenId: string): void {\n\tclearTimeout(unredeemed.get(tokenId));\n\tunredeemed.delete(tokenId);\n}\n\n/** Whether `oauthServer` would build one, without building it. */\nfunction oauthConfigured(): boolean {\n\tconst secret = hmacKeys().current;\n\treturn Boolean(secret && secret.length >= MIN_TOKEN_SECRET_LENGTH);\n}\n\n/** Undefined without a usable SELVA_HMAC_KEY: the endpoints then answer 503. */\nexport function oauthServer(origin: string): OAuthServer | undefined {\n\tif (!oauthConfigured()) return undefined;\n\tconst { current, previous } = hmacKeys();\n\tconst secret = current!;\n\tconst cacheKey = `${secret}\\n${previous ?? ''}`;\n\tif (cached?.origin !== origin || cached.secret !== cacheKey) {\n\t\tcached = {\n\t\t\torigin,\n\t\t\tsecret: cacheKey,\n\t\t\tserver: createOAuthServer({\n\t\t\t\torigin,\n\t\t\t\tsecret,\n\t\t\t\t...(previous ? { previousSecret: previous } : {}),\n\t\t\t\tfetchClientMetadata,\n\t\t\t\tredeemedCodes,\n\t\t\t\tonRedeemed\n\t\t\t})\n\t\t};\n\t}\n\treturn cached.server;\n}\n\n/** The URL is an unknown client's, so it goes through the same guard as remote definitions. */\nasync function fetchClientMetadata(url: string): Promise<unknown> {\n\tawait assertSafeRemoteDefinitionUrl(url);\n\tconst controller = new AbortController();\n\tconst timer = setTimeout(() => controller.abort(), METADATA_TIMEOUT_MS);\n\ttry {\n\t\tconst res = await fetch(url, {\n\t\t\theaders: { Accept: 'application/json' },\n\t\t\tredirect: 'error',\n\t\t\tsignal: controller.signal\n\t\t});\n\t\tif (!res.ok) throw new Error(`HTTP ${res.status}`);\n\t\t// Counted while streaming: a body with no or a lying Content-Length must not buffer whole.\n\t\tconst bytes = await readBodyWithCap(res, METADATA_MAX_BYTES, controller);\n\t\treturn JSON.parse(new TextDecoder().decode(bytes));\n\t} finally {\n\t\tclearTimeout(timer);\n\t}\n}\n\n// Registration and token exchange take no credential, so the IP is the only key.\nconst limiter = createComputeRateLimiter({ windowMs: 60_000, maxPerWindow: 30 });\n\n/** A 429 response when the caller's IP is over the limit, else undefined. */\nexport function oauthRateLimited(event: RequestEvent): Response | undefined {\n\tconst verdict = limiter.check(`oauth:${event.getClientAddress()}`);\n\tif (verdict.allowed) return undefined;\n\treturn json(\n\t\t{ error: 'slow_down', error_description: 'Too many requests. Try again shortly.' },\n\t\t{ status: 429, headers: { 'Retry-After': String(verdict.retryAfter ?? 60) } }\n\t);\n}\n\nexport function oauthUnavailable(): Response {\n\treturn json(\n\t\t{ error: 'temporarily_unavailable', error_description: 'OAuth is not configured here.' },\n\t\t{ status: 503 }\n\t);\n}\n\n/** Discovery documents are read by browser-based clients too. */\nexport const DISCO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AK;GAC5B,SAAS,EAAE,QAAQ,mBAAmB;GACtC,UAAU;GACV,QAAQ,WAAW;EACpB,CAAC;EACD,IAAI,CAAC,IAAI,IAAI,MAAM,IAAI,MAAM,QAAQ,IAAI,QAAQ;EAEjD,MAAM,QAAQ,MAAM,gBAAgB,KAAK,oBAAoB,UAAU;EACvE,OAAO,KAAK,MAAM,IAAI,YAAY,CAAC,CAAC,OAAO,KAAK,CAAC;CAClD,UAAU;EACT,aAAa,KAAK;CACnB;AACD;AAGA,IAAM,UAAU,yBAAyB;CAAE,UAAU;CAAQ,cAAc;AAAG,CAAC;;AAG/E,SAAgB,iBAAiB,OAA2C;CAC3E,MAAM,UAAU,QAAQ,MAAM,SAAS,MAAM,iBAAiB,GAAG;CACjE,IAAI,QAAQ,SAAS,OAAO,KAAA;CAC5B,OAAO,KACN;EAAE,OAAO;EAAa,mBAAmB;CAAwC,GACjF;EAAE,QAAQ;EAAK,SAAS,EAAE,eAAe,OAAO,QAAQ,cAAc,EAAE,EAAE;CAAE,CAC7E;AACD;AAEA,SAAgB,mBAA6B;CAC5C,OAAO,KACN;EAAE,OAAO;EAA2B,mBAAmB;CAAgC,GACvF,EAAE,QAAQ,IAAI,CACf;AACD;;AAGA,IAAa,oBAAoB;CAChC,+BAA+B;CAC/B,iBAAiB;AAClB"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { d as ErrorCodes, t as ComputeServerStats, u as ComputeError } from "./grasshopper.js";
|
|
2
2
|
// src/lib/server/compute/serverStats.server.ts
|
|
3
3
|
/**
|
|
4
4
|
* `ComputeServerStats` for a stored server. An unusable stored URL or key is the operator's to fix,
|
|
@@ -1,16 +1,15 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { I as postedServerSourcedIds, N as MAX_SOLVE_DEADLINE_MS, R as solveInputsFromSchema, T as providers, b as getSolveMetricSink, w as lazyLogger, x as getStorageProvider } from "./providers.server.js";
|
|
2
2
|
import { E as scoped, M as isApiError, N as toErrorBody, O as ApiError, d as requireCanEditDefinition, h as requireCanSolve, k as ApiErrorCode } from "./access.js";
|
|
3
3
|
import { t as hmacKeys } from "./keys.server.js";
|
|
4
4
|
import { A as rateLimitedResponse, D as chargeApiRateLimit, M as withRateLimitHeaders, N as assertScope } from "./api.js";
|
|
5
5
|
import { t as createRemoteDefinitionFetcher } from "./remote-definition.js";
|
|
6
|
-
import { a as
|
|
6
|
+
import { a as fetchSchemaFromCompute, u as ComputeServerUnconfiguredError } from "./schema-extraction.js";
|
|
7
7
|
import "./compute.js";
|
|
8
8
|
import { n as renderThrown } from "./definitions.js";
|
|
9
|
-
import {
|
|
9
|
+
import { d as ErrorCodes, u as ComputeError } from "./grasshopper.js";
|
|
10
10
|
import { t as apiError } from "./api-errors.js";
|
|
11
11
|
import "./access2.server.js";
|
|
12
|
-
import {
|
|
13
|
-
import { n as COMPUTE_DEBUG_VERBOSE, o as engine, t as COMPUTE_DEBUG } from "./engine.server.js";
|
|
12
|
+
import { S as REMOTE_DEFINITION_MAX_BYTES, b as REMOTE_DEFINITION_CACHE_TTL_MS, n as COMPUTE_DEBUG_VERBOSE, s as engine, t as COMPUTE_DEBUG, x as REMOTE_DEFINITION_FETCH_TIMEOUT_MS } from "./engine.server.js";
|
|
14
13
|
import { t as serverResolver } from "./serverResolver.server.js";
|
|
15
14
|
import { n as checkComputeRateLimit, t as apiRateLimiter } from "./computeRateLimit.server.js";
|
|
16
15
|
import { n as liveOwnerKey, r as solveEndedKind, t as bindLiveSolve } from "./liveSolve.server.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"solve.server.js","names":[],"sources":["../../../src/lib/server/compute/sessionId.server.ts","../../../src/lib/server/compute/errorLogFields.ts","../../../src/lib/server/compute/remoteDefinition.server.ts","../../../src/lib/server/compute/solve.server.ts"],"sourcesContent":["import { createHmac } from 'node:crypto';\nimport { hmacKeys } from '#lib/server/keys.server.js';\nimport type { SolveAccess } from '#lib/server/compute/solve.server.js';\n\n/**\n * Share links have no caller identity, and a remote URL (no `guid`) is caller-chosen, so varying\n * its query string would mint ids: neither gets one, and both route as if compute had no sessions.\n */\nexport function solveSessionId(access: SolveAccess, guid: string | null): string | undefined {\n\tif (access.kind !== 'user' || !access.ctx.userId || !guid) return undefined;\n\treturn computeSessionId(access.ctx.userId, guid);\n}\n\n/**\n * The `X-Session-Id` for one user's solves of one definition: the compute fork routes them back\n * to the child holding that user's warm document. Derived rather than stored, so every Selva\n * instance computes the same id with no shared state, and the browser can't mint ids to fill\n * compute's claim cap. Keyed, so a compute operator can't recover the user id from it.\n *\n * Undefined without `SELVA_HMAC_KEY`: a routing hint never fails a solve. Rotating the key moves\n * every session to a new id, so each solves cold once.\n */\nexport function computeSessionId(userId: string, definitionKey: string): string | undefined {\n\tconst key = hmacKeys().current;\n\tif (!key) return undefined;\n\treturn createHmac('sha256', key)\n\t\t.update(`compute-session\\0${userId}\\0${definitionKey}`)\n\t\t.digest('hex')\n\t\t.slice(0, 32);\n}\n","import { ComputeError } from '@selvajs/compute/core';\n\n/**\n * Log fields for a failed solve. Compute's raw error body can quote what was solved, and erasure\n * can't reach a log line, so it goes out only when an operator asked for raw bodies. The request id\n * ties the line to the server's own logs.\n */\nexport function computeErrorLogFields(\n\terr: unknown,\n\tincludeBody: boolean\n): Record<string, string | number> {\n\tif (!(err instanceof ComputeError)) return {};\n\tconst { requestId, responseBody } = err.context ?? {};\n\treturn {\n\t\t...(typeof requestId === 'string' && { computeRequestId: requestId }),\n\t\t...(typeof responseBody === 'string' && {\n\t\t\tcomputeBodyChars: responseBody.length,\n\t\t\t...(includeBody && { computeResponseBody: responseBody })\n\t\t})\n\t};\n}\n","/**\n * App-wide instance of the remote-definition fetcher (SSRF guard, size cap,\n * deadline, TTL cache all live in `@selvajs/server`'s `createRemoteDefinitionFetcher`).\n */\n\nimport { createRemoteDefinitionFetcher } from '@selvajs/server/compute';\nimport {\n\tREMOTE_DEFINITION_MAX_BYTES,\n\tREMOTE_DEFINITION_FETCH_TIMEOUT_MS,\n\tREMOTE_DEFINITION_CACHE_TTL_MS\n} from '#lib/server/computeLimits.js';\n// Module-scope init runs before the root logger is fully swapped in, so this\n// needs the forwarding logger, not a snapshot that would pin the boot placeholder.\nimport { lazyLogger } from '#lib/server/providers.server.js';\n\nconst fetcher = createRemoteDefinitionFetcher({\n\tmaxBytes: REMOTE_DEFINITION_MAX_BYTES,\n\tfetchTimeoutMs: REMOTE_DEFINITION_FETCH_TIMEOUT_MS,\n\tcacheTtlMs: REMOTE_DEFINITION_CACHE_TTL_MS,\n\tnow: () => Date.now(),\n\tlogger: lazyLogger\n});\n\n/** Fetch (or return cached) remote `.gh` bytes. Throws on unsafe host / oversized / timeout. */\nexport function loadRemoteDefinition(url: string): Promise<Uint8Array> {\n\treturn fetcher.load(url);\n}\n","/**\n * The body-independent core of a solve request, shared by `POST /api/v1/compute`\n * (share-token and remote-URL capable) and `POST /api/v1/definitions/{guid}/solve`\n * (tenant-scoped, cookie or PAT).\n *\n * **Share-token resolution stays outside this module, in the route.** The caller\n * hands in an already-decided `SolveAccess`; the definition-addressed route only\n * ever constructs the `user` variant, so it cannot inherit the anonymous branch\n * by accident. Adding a token lookup here would silently give it one.\n *\n * What lives here: rate limiting, definition/version resolution, access checks,\n * compute-server routing, schema backfill, the engine call, metric recording, the\n * debug breakdown. What stays in a route: parsing its own body shape and deciding\n * who the caller is.\n */\n\nimport { apiError, ApiErrorCode } from '#lib/server/api-errors.js';\nimport {\n\tApiError,\n\tassertScope,\n\tchargeApiRateLimit,\n\tisApiError,\n\trateLimitedResponse,\n\ttoErrorBody,\n\twithRateLimitHeaders\n} from '@selvajs/server/api';\nimport { isHttpError } from '@sveltejs/kit';\nimport { ComputeError, ErrorCodes } from '@selvajs/compute/core';\nimport type { SolveMode } from '@selvajs/compute/grasshopper';\nimport type { ComputeServerConfig, RequestContext, SolveFailureKind } from '@selvajs/platform';\nimport { ComputeServerUnconfiguredError } from '@selvajs/server/compute';\nimport { serverResolver } from './serverResolver.server';\nimport { engine, COMPUTE_DEBUG, COMPUTE_DEBUG_VERBOSE } from '#lib/server/compute/engine.server.js';\nimport { solveSessionId } from '#lib/server/compute/sessionId.server.js';\nimport { computeErrorLogFields } from '#lib/server/compute/errorLogFields.js';\nimport { loadRemoteDefinition } from '#lib/server/compute/remoteDefinition.server.js';\nimport {\n\tpostedServerSourcedIds,\n\tsolveInputsFromSchema,\n\ttype ByteCacheRef,\n\ttype SolveDefinition,\n\ttype SolveEnvelope,\n\ttype SolveInput\n} from '@selvajs/solve/server';\nimport type { UISchema } from '@selvajs/schemas';\nimport { apiRateLimiter, checkComputeRateLimit } from '#lib/server/computeRateLimit.server.js';\nimport { getStorageProvider, getSolveMetricSink, providers } from '#lib/server/providers.server.js';\nimport { requireCanSolve, requireCanEditDefinition, scoped } from '#lib/server/access.server.js';\nimport { fetchSchemaFromCompute } from '@selvajs/server/definitions';\nimport { renderThrown } from '@selvajs/server/logging';\nimport type { ShareLink } from '@selvajs/platform';\nimport { MAX_SOLVE_DEADLINE_MS } from '@selvajs/solve/server';\nimport {\n\tbindLiveSolve,\n\tliveOwnerKey,\n\tsolveEndedKind\n} from '#lib/server/solveEvents/liveSolve.server.js';\n\nexport type SolveChannel = 'live' | 'draft';\n\n/**\n * Who is solving, and under whose authority.\n *\n * `user` — a logged-in caller; the per-definition access rules run.\n * `share` — a share-link token; the token already encodes the grant, so the\n * rules are skipped and the link's solve cap is charged instead.\n */\nexport type SolveAccess =\n\t| { kind: 'user'; ctx: RequestContext; rateLimitKey: string }\n\t| { kind: 'share'; ctx: RequestContext; link: ShareLink; rateLimitKey: string };\n\nexport interface SolveParams {\n\taccess: SolveAccess;\n\tdefinitionUrl: string;\n\t/**\n\t * The request body's inputs, read for a remote URL only. A stored definition's come from its\n\t * version's schema: a caller, a share-link visitor included, must not choose its ids, types or\n\t * bounds.\n\t */\n\tinputs?: unknown;\n\tvalues: Record<string, unknown>;\n\tchannel: SolveChannel;\n\t/** Explicit version pick; editor-only, never share-token accessible. */\n\tversionId: string | null;\n\trequest: Request;\n\t/** Typed loosely: two route trees with different generated `$types` both call this. */\n\tlocals: App.Locals;\n\t/** `performance.now()` at the very start of the request, before body parse. */\n\tloadStart: number;\n\t/** Prep sub-phase timings recorded before this call (body parse, token). */\n\tprepMarks: [string, number][];\n\t/**\n\t * The caller's live-event stream (`GET /api/v1/solve-events?streamId=`). When it is open\n\t * and theirs, this solve is bound to it: the server emits start/end, and the compute\n\t * request carries a callback so the definition can emit mid-solve. Ignored otherwise.\n\t */\n\tstreamId?: string | null;\n\t/** See `SolveBodySchema.mode`. */\n\tsolveMode?: SolveMode;\n\t/**\n\t * Report an access refusal as 404 instead of 403.\n\t *\n\t * The definition-addressed route needs this: a guid is guessable, so\n\t * 403-vs-404 there tells a caller whether a definition they cannot reach\n\t * exists. `/api/v1/compute` leaves it off — its callers navigated to the\n\t * definition, and a 403 is the more useful answer.\n\t */\n\tconcealAccessFailure?: boolean;\n\t/**\n\t * The route already charged the key's request bucket, ahead of any idempotent\n\t * replay that would skip this function, so it must not be charged twice.\n\t */\n\ttokenCharged?: boolean;\n}\n\nfunction readRemoteInputs(inputs: unknown): SolveInput[] {\n\tconst valid =\n\t\tArray.isArray(inputs) &&\n\t\tinputs.every(\n\t\t\t(input) =>\n\t\t\t\ttypeof input === 'object' &&\n\t\t\t\tinput !== null &&\n\t\t\t\ttypeof (input as SolveInput).id === 'string' &&\n\t\t\t\ttypeof (input as SolveInput).nickname === 'string'\n\t\t);\n\tif (!valid) {\n\t\tapiError(\n\t\t\t400,\n\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t'A remote definitionUrl needs inputs: a list of { id, nickname, paramType }.'\n\t\t);\n\t}\n\treturn inputs as SolveInput[];\n}\n\nfunction admittedSolveInputs(\n\tschema: UISchema | undefined,\n\tinputs: unknown,\n\tvalues: Record<string, unknown>\n): SolveInput[] {\n\tconst solveInputs = schema ? solveInputsFromSchema(schema) : readRemoteInputs(inputs);\n\tconst serverOnly = postedServerSourcedIds(solveInputs, values);\n\tif (serverOnly.length > 0) {\n\t\tapiError(\n\t\t\t400,\n\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t`These inputs are filled on the server and may not be posted in values: ${serverOnly.join(', ')}.`\n\t\t);\n\t}\n\treturn solveInputs;\n}\n\n/**\n * Run a solve and return the HTTP response.\n *\n * Throws `HttpError` (via `apiError`) for every refusal, and lets engine/network\n * failures propagate for the caller's outer catch to map — the two routes share\n * that mapping through `mapSolveError`.\n */\nexport async function runSolve(params: SolveParams): Promise<Response> {\n\tconst {\n\t\taccess,\n\t\tdefinitionUrl,\n\t\tinputs,\n\t\tvalues,\n\t\tchannel,\n\t\tversionId: explicitVersionId,\n\t\trequest,\n\t\tlocals,\n\t\tloadStart,\n\t\tprepMarks,\n\t\tconcealAccessFailure = false,\n\t\tstreamId = null,\n\t\tsolveMode = 'full',\n\t\ttokenCharged = false\n\t} = params;\n\tconst storage = getStorageProvider();\n\tconst sharedAccess = access.kind === 'share' ? access : null;\n\tconst solveCtx = access.ctx;\n\n\tlet prevMark = performance.now();\n\tconst mark = (label: string) => {\n\t\tprepMarks.push([label, performance.now() - prevMark]);\n\t\tprevMark = performance.now();\n\t};\n\n\t// Local definitions solve by reference: a byte-cache `DefinitionRef` whose\n\t// bytes the scheduler loads ONLY when an upload is unavoidable (pointer-known\n\t// re-solves move zero bytes). Remote-URL definitions carry raw fetched bytes.\n\tlet definitionSource: SolveDefinition;\n\t// `.load()` materializes bytes for schema backfill; `.outcome` drives the\n\t// `def_bytes` Server-Timing verdict. Null for remote-URL solves.\n\tlet localDefinitionRef: ByteCacheRef | null = null;\n\tlet localVersionForBackfill: { id: string; hasSchema: boolean } | null = null;\n\tlet storedSchema: UISchema | undefined;\n\t// BYO compute routing per org; null for remote definitions.\n\tlet solveOrgId: string | null = null;\n\tlet definitionPin: string | null = null;\n\t// Started once the project is known; null for remote definitions.\n\tlet pendingServer: Promise<ComputeServerConfig> | null = null;\n\t// Solve-metric attribution; null for remote-URL solves.\n\tlet metricDefinitionId: string | null = null;\n\tlet metricVersionId: string | null = null;\n\n\tconst isLocal = definitionUrl.startsWith('local:');\n\tconst guid = isLocal ? definitionUrl.substring(6) : null;\n\n\t// One row per solve attempt, including attempts rejected before the solve\n\t// runs — reads the attribution `let`s at call time, so definition/version\n\t// are null when a record fires pre-resolution. Fire-and-forget: the sink\n\t// never throws (ISolveMetricSink contract).\n\tconst recordMetric = (\n\t\tfailureKind: SolveFailureKind,\n\t\textra: { durationMs?: number; errorCount?: number; warningCount?: number } = {}\n\t) => {\n\t\tgetSolveMetricSink()\n\t\t\t.record(solveCtx, {\n\t\t\t\tdefinitionUrl,\n\t\t\t\tdefinitionId: metricDefinitionId,\n\t\t\t\tversionId: metricVersionId,\n\t\t\t\tchannel,\n\t\t\t\torgId: solveOrgId,\n\t\t\t\tdurationMs: extra.durationMs ?? 0,\n\t\t\t\tok: failureKind === 'ok',\n\t\t\t\tfailureKind,\n\t\t\t\terrorCount: extra.errorCount ?? 0,\n\t\t\t\twarningCount: extra.warningCount ?? 0\n\t\t\t})\n\t\t\t// Sinks are contracted not to throw, but nothing enforces it — a bad sink\n\t\t\t// must surface as a log line, not an unhandled rejection.\n\t\t\t.catch((err) =>\n\t\t\t\tlocals.log.error('Solve-metric record failed', {\n\t\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\t\terr: renderThrown(err)\n\t\t\t\t})\n\t\t\t);\n\t};\n\n\t// Both limits run before DB reads so throttled callers don't burn quota. A\n\t// token pays its own request bucket and its owner's compute bucket, so ten\n\t// keys of one user never buy ten times the compute.\n\tconst tokenVerdict = tokenCharged\n\t\t? undefined\n\t\t: await chargeApiRateLimit(access.ctx, apiRateLimiter);\n\tif (tokenVerdict && !tokenVerdict.allowed) {\n\t\trecordMetric('rate_limited');\n\t\treturn rateLimitedResponse(tokenVerdict);\n\t}\n\tconst rateLimit = checkComputeRateLimit(access.rateLimitKey);\n\tif (!rateLimit.allowed) {\n\t\trecordMetric('rate_limited');\n\t\tconst retryAfter = String(rateLimit.retryAfter ?? 1);\n\t\tconst err = new ApiError(\n\t\t\t429,\n\t\t\tApiErrorCode.RATE_LIMITED,\n\t\t\t`Too many compute requests. Retry in ${retryAfter}s.`,\n\t\t\tundefined,\n\t\t\t{ retryAfter }\n\t\t);\n\t\treturn withRateLimitHeaders(\n\t\t\tnew Response(JSON.stringify(toErrorBody(err)), {\n\t\t\t\tstatus: 429,\n\t\t\t\theaders: { 'Content-Type': 'application/json', 'Retry-After': retryAfter }\n\t\t\t}),\n\t\t\ttokenVerdict\n\t\t);\n\t}\n\n\tif (isLocal && guid) {\n\t\tlet record;\n\t\ttry {\n\t\t\trecord = await providers.data.definitions.get(solveCtx, guid);\n\t\t} catch (err) {\n\t\t\tlocals.log.error('Failed to load local definition', {\n\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\tguid,\n\t\t\t\terr: renderThrown(err)\n\t\t\t});\n\t\t\tapiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' not found`);\n\t\t}\n\t\tif (!record) apiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' not found`);\n\t\tmark('defRecord');\n\n\t\t// The version and the server need only the record and its project, so they are read\n\t\t// while access is checked, and awaited after it in their old order: a caller refused\n\t\t// access learns nothing from a missing version or server.\n\t\tconst versionId =\n\t\t\texplicitVersionId ?? (channel === 'live' ? record.liveVersionId : record.draftVersionId);\n\t\tconst pendingVersion = versionId\n\t\t\t? providers.data.definitions.getVersion(solveCtx, versionId)\n\t\t\t: null;\n\t\tpendingVersion?.catch(() => {});\n\t\tconst project = await providers.data.projects.getProject(solveCtx, record.projectId);\n\t\tsolveOrgId = project?.orgId ?? null;\n\t\tdefinitionPin = record.computeServerId ?? null;\n\t\tpendingServer = serverResolver.resolve(\n\t\t\tsolveCtx,\n\t\t\tsolveOrgId,\n\t\t\tlocals.providers.data.computeServer,\n\t\t\t{ definitionPin }\n\t\t);\n\t\tpendingServer.catch(() => {});\n\t\tmark('project');\n\n\t\tif (!sharedAccess) {\n\t\t\ttry {\n\t\t\t\tassertScope(access.ctx, 'solve', { projectId: record.projectId, definitionId: guid });\n\t\t\t\tif (channel === 'draft' || explicitVersionId) {\n\t\t\t\t\tawait requireCanEditDefinition(scoped(locals), record.projectId, guid, {\n\t\t\t\t\t\tproject,\n\t\t\t\t\t\tdefinition: record\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tawait requireCanSolve(scoped(locals), record.projectId, project ?? undefined);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\t// The guards raise `ApiError`, but `requireCanEditDefinition` may still\n\t\t\t\t// surface an `HttpError` — matching only one shape would let the\n\t\t\t\t// other's 403 leak through, confirming a guid the caller can't reach.\n\t\t\t\tconst status = isApiError(err) ? err.status : isHttpError(err) ? err.status : undefined;\n\t\t\t\tif (concealAccessFailure && status === 403) {\n\t\t\t\t\tapiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' not found`);\n\t\t\t\t}\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t}\n\t\tmark('access');\n\n\t\tif (!versionId || !pendingVersion) {\n\t\t\tapiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' has no ${channel} version yet`);\n\t\t}\n\t\tconst version = await pendingVersion;\n\t\tif (!version || version.definitionId !== guid) {\n\t\t\tapiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' version is missing`);\n\t\t}\n\t\tlocalVersionForBackfill = { id: version.id, hasSchema: version.schema !== undefined };\n\t\tstoredSchema = version.schema;\n\t\tmetricDefinitionId = guid;\n\t\tmetricVersionId = version.id;\n\t\tmark('version');\n\n\t\t// Keyed on the immutable version id, NEVER the fileKey — a\n\t\t// delete-latest-then-reupload can reuse a fileKey for different content.\n\t\t// A missing blob surfaces at solve time (compute_error → 500) rather than\n\t\t// an upfront 404, since it's no longer read eagerly here.\n\t\tlocalDefinitionRef = engine.definitionRef(version.id, async () => {\n\t\t\tconst bytes = await storage.get(version.fileKey);\n\t\t\tif (!bytes) throw new Error(`Version blob missing: ${version.fileKey}`);\n\t\t\treturn bytes;\n\t\t});\n\t\tdefinitionSource = localDefinitionRef;\n\t\tmark('blob');\n\t} else {\n\t\t// A remote URL names no project, so only an org-wide key may solve it.\n\t\tassertScope(access.ctx, 'solve');\n\t\treadRemoteInputs(inputs);\n\t\ttry {\n\t\t\tdefinitionSource = await loadRemoteDefinition(definitionUrl);\n\t\t} catch (err) {\n\t\t\tlocals.log.error('Failed to fetch remote definition', {\n\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\tdefinitionUrl,\n\t\t\t\terr: renderThrown(err)\n\t\t\t});\n\t\t\tapiError(\n\t\t\t\t400,\n\t\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t\t`Failed to load definition: ${err instanceof Error ? err.message : String(err)}`\n\t\t\t);\n\t\t}\n\t\tmark('remoteDef');\n\t}\n\n\t// Everything above (auth, DB, blob/remote fetch) is the \"load\" phase; tree\n\t// build and solve are measured inside the pipeline.\n\tconst defLoadMs = performance.now() - loadStart;\n\n\t// Checked before the share cap, so a request refused for its values spends no\n\t// solve. A version without a stored schema is checked after the backfill below.\n\tlet solveInputs =\n\t\tstoredSchema || !isLocal ? admittedSolveInputs(storedSchema, inputs, values) : null;\n\n\t// Atomic check-and-increment; runs before solve to avoid wasting compute.\n\tif (sharedAccess) {\n\t\tconst next = await providers.data.shareLinks.tryIncrementSolveCount(\n\t\t\tsolveCtx,\n\t\t\tsharedAccess.link.id\n\t\t);\n\t\tif (next === null) {\n\t\t\trecordMetric('share_cap');\n\t\t\tapiError(429, ApiErrorCode.RATE_LIMITED, 'Share link solve cap reached.');\n\t\t}\n\t\tmark('shareCap');\n\t}\n\n\tconst serverConfig = await (pendingServer ??\n\t\tserverResolver.resolve(solveCtx, solveOrgId, locals.providers.data.computeServer, {\n\t\t\tdefinitionPin\n\t\t}));\n\tmark('resolveServer');\n\n\t// BRIDGE: remove ~2026-09 — lazy backfill for versions uploaded before schema\n\t// caching existed. Best-effort. Removing it: delete this block, tighten\n\t// `DefinitionVersion.schema` to required in platform types + Zod, and drop the\n\t// live-fetch fallback in loadForRender.server.ts.\n\tif (localVersionForBackfill && !localVersionForBackfill.hasSchema && localDefinitionRef) {\n\t\tconst versionId = localVersionForBackfill.id;\n\t\ttry {\n\t\t\t// Warms the byte-cache entry the upcoming solve's `load()` would hit anyway.\n\t\t\tconst bytes = await localDefinitionRef.load();\n\t\t\tstoredSchema = await fetchSchemaFromCompute(bytes, serverConfig);\n\t\t\tawait providers.data.definitions.setVersionSchema(solveCtx, versionId, storedSchema);\n\t\t} catch (err) {\n\t\t\tlocals.log.warn('Schema backfill failed', {\n\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\tversionId,\n\t\t\t\terr: renderThrown(err)\n\t\t\t});\n\t\t}\n\t\t// Backfill calls the compute server — seconds when it fires. If this shows\n\t\t// up repeatedly for the same definition, setVersionSchema isn't sticking.\n\t\tmark('schemaBackfill');\n\t}\n\n\tif (isLocal && !storedSchema) {\n\t\tapiError(\n\t\t\t503,\n\t\t\tApiErrorCode.COMPUTE_UNAVAILABLE,\n\t\t\t\"This version's inputs could not be read. Retry shortly.\"\n\t\t);\n\t}\n\tsolveInputs ??= admittedSolveInputs(storedSchema, inputs, values);\n\n\t// `SolveEngine.solve` owns warm-client lookup, input-tree build, single-flight\n\t// coalescing (a coalesced solve aborts only when its last caller leaves), and\n\t// per-caller encoding. Remote-URL solves have no version id, so the URL stands\n\t// in as coalesce-key identity (`definitionKey`); local solves already carry\n\t// that identity on `localDefinitionRef.key`.\n\tconst live = bindLiveSolve({\n\t\townerKey: liveOwnerKey(access.kind === 'user' ? access.ctx.userId : null),\n\t\tstreamId,\n\t\trequest,\n\t\t// Outlives any server's deadline by a margin, so a callback racing the response is not\n\t\t// refused. Minted before the warm client that knows this server's deadline.\n\t\ttokenTtlMs: MAX_SOLVE_DEADLINE_MS + 60_000\n\t});\n\n\tlet outcome: Awaited<ReturnType<typeof engine.solve>> | undefined;\n\ttry {\n\t\toutcome = await engine.solve({\n\t\t\tserver: serverConfig,\n\t\t\tdefinitionSource,\n\t\t\tdefinitionKey: isLocal ? undefined : definitionUrl,\n\t\t\tinputs: solveInputs,\n\t\t\tvalues,\n\t\t\tsignal: request.signal,\n\t\t\tacceptEncoding: request.headers.get('accept-encoding') ?? '',\n\t\t\tdefinitionGuid: guid ?? undefined,\n\t\t\tloadStartMs: loadStart,\n\t\t\tdefLoadMs,\n\t\t\tprepMarks,\n\t\t\tselvaEvents: live.selvaEvents,\n\t\t\tsessionId: solveSessionId(access, guid),\n\t\t\tsolveMode\n\t\t});\n\t} finally {\n\t\tlive.end(outcome ? solveEndedKind(outcome) : 'error');\n\t}\n\tmark('solve');\n\n\t// Metric recording is app policy — the engine only maps outcome to HTTP.\n\t// These branches don't return; `engine.toWebResponse` below does.\n\tif (outcome.kind === 'timeout') {\n\t\trecordMetric('timeout', { durationMs: outcome.durationMs });\n\t} else if (outcome.kind === 'client_abort') {\n\t\trecordMetric('client_abort', { durationMs: outcome.durationMs });\n\t} else if (outcome.kind === 'too_large') {\n\t\trecordMetric('too_large');\n\t} else if (outcome.kind === 'shed') {\n\t\trecordMetric('shed', { durationMs: outcome.durationMs });\n\t} else if (outcome.kind === 'compute_error') {\n\t\trecordMetric('compute_error', { durationMs: outcome.durationMs });\n\t} else if (outcome.kind === 'ok') {\n\t\trecordMetric('ok', {\n\t\t\tdurationMs: outcome.solveMs,\n\t\t\terrorCount: outcome.errorCount,\n\t\t\twarningCount: outcome.warningCount\n\t\t});\n\t\t// Best-effort: the solve already succeeded, so a failed counter write\n\t\t// must not turn into a request error. Local definitions only — remote\n\t\t// URLs have no record to bump.\n\t\tif (metricDefinitionId) {\n\t\t\tproviders.data.definitions.incrementSolveCount(solveCtx, metricDefinitionId).catch((err) =>\n\t\t\t\tlocals.log.warn('solveCount increment failed', {\n\t\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\t\tdefinitionId: metricDefinitionId,\n\t\t\t\t\terr: renderThrown(err)\n\t\t\t\t})\n\t\t\t);\n\t\t}\n\n\t\tif (COMPUTE_DEBUG) logDebugBreakdown(locals, request, outcome, defLoadMs, prepMarks);\n\t}\n\n\t// Builds the Response itself (incl. `Retry-After` on a rejected `shed`,\n\t// which `apiError` cannot set) and still throws `compute_error` through to\n\t// the caller's outer catch.\n\treturn withRateLimitHeaders(engine.toWebResponse(outcome), tokenVerdict);\n}\n\n/**\n * Both solve routes share this so they cannot drift on which failures read as\n * \"compute is down\" (503) versus a server bug (500).\n */\nexport function mapSolveError(err: unknown, locals: App.Locals): never {\n\tif (isHttpError(err)) throw err;\n\t// A guard's own refusal, not a failed solve — converted rather than\n\t// re-thrown. These routes return their Response directly instead of going\n\t// through `mount`, so an `ApiError` escaping here would reach SvelteKit,\n\t// which gives anything that isn't an `HttpError` a 500, turning a working\n\t// permission check into an operator error page.\n\tif (isApiError(err)) {\n\t\tapiError(err.status, err.code, err.message, err.fields, err.details);\n\t}\n\n\tif (err instanceof ComputeServerUnconfiguredError) {\n\t\tapiError(503, ApiErrorCode.COMPUTE_UNAVAILABLE, err.message);\n\t}\n\n\tconst message = err instanceof Error ? err.message : 'Unknown error';\n\tlocals.log.error('Solve request failed', {\n\t\tcomponent: 'API/Compute',\n\t\terr: renderThrown(err),\n\t\t...computeErrorLogFields(err, COMPUTE_DEBUG_VERBOSE)\n\t});\n\n\t// The compute transport classifies its failures — map the classes the caller\n\t// can act on. Unreachable/credentials/saturation are operator problems (503),\n\t// a deadline is 504; only a genuine solve failure stays 500.\n\tif (err instanceof ComputeError) {\n\t\tif (err.code === ErrorCodes.NETWORK_ERROR || err.code === ErrorCodes.CORS_ERROR) {\n\t\t\tapiError(503, ApiErrorCode.COMPUTE_UNAVAILABLE, 'Compute server is unreachable');\n\t\t}\n\t\tif (err.code === ErrorCodes.AUTH_ERROR) {\n\t\t\tapiError(\n\t\t\t\t503,\n\t\t\t\tApiErrorCode.COMPUTE_UNAVAILABLE,\n\t\t\t\t\"Compute server rejected this deployment's credentials — check the compute API key configuration.\"\n\t\t\t);\n\t\t}\n\t\tif (err.code === ErrorCodes.RATE_LIMIT) {\n\t\t\tapiError(\n\t\t\t\t503,\n\t\t\t\tApiErrorCode.COMPUTE_UNAVAILABLE,\n\t\t\t\t'Compute server is rate-limiting requests. Retry shortly.'\n\t\t\t);\n\t\t}\n\t\tif (err.code === ErrorCodes.TIMEOUT_ERROR) {\n\t\t\tapiError(\n\t\t\t\t504,\n\t\t\t\tApiErrorCode.COMPUTE_UNAVAILABLE,\n\t\t\t\t'Compute server timed out running the solve.'\n\t\t\t);\n\t\t}\n\t}\n\n\t// A transport-layer fetch failure means the compute server is unreachable,\n\t// not an internal error. (Raw TypeError only from fetches outside the compute\n\t// transport — the transport wraps its own into ComputeError NETWORK_ERROR.)\n\tif (err instanceof TypeError && message === 'fetch failed') {\n\t\tapiError(503, ApiErrorCode.COMPUTE_UNAVAILABLE, 'Compute server is unreachable');\n\t}\n\n\tapiError(500, ApiErrorCode.INTERNAL, message);\n}\n\n/**\n * DEBUG (SELVA_FLAG_COMPUTE_DEBUG): the server-side overhead the solve metric's\n * `durationMs` doesn't capture. `load` = auth + DB + definition fetch; `tree` =\n * input tree build; `serialize` = JSON.stringify of the result.\n */\nfunction logDebugBreakdown(\n\tlocals: App.Locals,\n\trequest: Request,\n\toutcome: { envelope: SolveEnvelope },\n\tdefLoadMs: number,\n\tprepMarks: [string, number][]\n): void {\n\tconst { metrics } = outcome.envelope;\n\tlocals.log.debug('Solve server-side phase breakdown', {\n\t\tcomponent: 'Compute/server',\n\t\tloadMs: Math.round(defLoadMs),\n\t\ttreeBuildMs: Math.round(metrics.treeBuildMs),\n\t\tsolveMs: Math.round(metrics.solveMs),\n\t\tserializeMs: Math.round(metrics.serializeMs),\n\t\tgzipMs: Math.round(metrics.gzipMs),\n\t\tserverTotalMs: Math.round(metrics.serverTotalMs),\n\t\tserializedBytes: metrics.serializedBytes\n\t});\n\tif (metrics.compressedBytes !== null) {\n\t\tlocals.log.debug('Response gzipped', {\n\t\t\tcomponent: 'Compute/server',\n\t\t\tserializedBytes: metrics.serializedBytes,\n\t\t\tcompressedBytes: metrics.compressedBytes,\n\t\t\tratio: Number((metrics.serializedBytes / metrics.compressedBytes).toFixed(1))\n\t\t});\n\t} else {\n\t\t// If this fires for browser requests, a proxy in front is stripping\n\t\t// Accept-Encoding, making compression impossible end-to-end.\n\t\tconst acceptEncoding = request.headers.get('accept-encoding') ?? '';\n\t\tlocals.log.debug('Compression skipped', {\n\t\t\tcomponent: 'Compute/server',\n\t\t\tacceptEncoding,\n\t\t\thasAcceptEncoding: acceptEncoding !== ''\n\t\t});\n\t}\n\t// Names the step a `load` (or pre-solve) spike hides in.\n\tlocals.log.debug('Prep breakdown', {\n\t\tcomponent: 'Compute/server',\n\t\t...Object.fromEntries(prepMarks.map(([label, ms]) => [`p_${label}Ms`, Math.round(ms)]))\n\t});\n\t// The only place evictions surface — per-request Server-Timing only carries\n\t// hit/miss verdicts.\n\tconst db = engine.stats().definitionBytes;\n\tlocals.log.debug('Definition byte-cache counters', {\n\t\tcomponent: 'Compute/def-bytes',\n\t\thits: db.hits,\n\t\tmisses: db.misses,\n\t\tevictions: db.evictions,\n\t\tentries: db.entries,\n\t\tretainedBytes: db.bytes\n\t});\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAQA,SAAgB,eAAe,QAAqB,MAAyC;CAC5F,IAAI,OAAO,SAAS,UAAU,CAAC,OAAO,IAAI,UAAU,CAAC,MAAM,OAAO,KAAA;CAClE,OAAO,iBAAiB,OAAO,IAAI,QAAQ,IAAI;AAChD;;;;;;;;;;AAWA,SAAgB,iBAAiB,QAAgB,eAA2C;CAC3F,MAAM,MAAM,SAAS,CAAC,CAAC;CACvB,IAAI,CAAC,KAAK,OAAO,KAAA;CACjB,OAAO,WAAW,UAAU,GAAG,CAAC,CAC9B,OAAO,oBAAoB,OAAO,IAAI,eAAe,CAAC,CACtD,OAAO,KAAK,CAAC,CAC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,WAAW;EACX,MAAM,GAAG;EACT,QAAQ,GAAG;EACX,WAAW,GAAG;EACd,SAAS,GAAG;EACZ,eAAe,GAAG;CACnB,CAAC;AACF"}
|
|
1
|
+
{"version":3,"file":"solve.server.js","names":[],"sources":["../../../src/lib/server/compute/sessionId.server.ts","../../../src/lib/server/compute/errorLogFields.ts","../../../src/lib/server/compute/remoteDefinition.server.ts","../../../src/lib/server/compute/solve.server.ts"],"sourcesContent":["import { createHmac } from 'node:crypto';\nimport { hmacKeys } from '#lib/server/keys.server.js';\nimport type { SolveAccess } from '#lib/server/compute/solve.server.js';\n\n/**\n * Share links have no caller identity, and a remote URL (no `guid`) is caller-chosen, so varying\n * its query string would mint ids: neither gets one, and both route as if compute had no sessions.\n */\nexport function solveSessionId(access: SolveAccess, guid: string | null): string | undefined {\n\tif (access.kind !== 'user' || !access.ctx.userId || !guid) return undefined;\n\treturn computeSessionId(access.ctx.userId, guid);\n}\n\n/**\n * The `X-Session-Id` for one user's solves of one definition: the compute fork routes them back\n * to the child holding that user's warm document. Derived rather than stored, so every Selva\n * instance computes the same id with no shared state, and the browser can't mint ids to fill\n * compute's claim cap. Keyed, so a compute operator can't recover the user id from it.\n *\n * Undefined without `SELVA_HMAC_KEY`: a routing hint never fails a solve. Rotating the key moves\n * every session to a new id, so each solves cold once.\n */\nexport function computeSessionId(userId: string, definitionKey: string): string | undefined {\n\tconst key = hmacKeys().current;\n\tif (!key) return undefined;\n\treturn createHmac('sha256', key)\n\t\t.update(`compute-session\\0${userId}\\0${definitionKey}`)\n\t\t.digest('hex')\n\t\t.slice(0, 32);\n}\n","import { ComputeError } from '@selvajs/compute/core';\n\n/**\n * Log fields for a failed solve. Compute's raw error body can quote what was solved, and erasure\n * can't reach a log line, so it goes out only when an operator asked for raw bodies. The request id\n * ties the line to the server's own logs.\n */\nexport function computeErrorLogFields(\n\terr: unknown,\n\tincludeBody: boolean\n): Record<string, string | number> {\n\tif (!(err instanceof ComputeError)) return {};\n\tconst { requestId, responseBody } = err.context ?? {};\n\treturn {\n\t\t...(typeof requestId === 'string' && { computeRequestId: requestId }),\n\t\t...(typeof responseBody === 'string' && {\n\t\t\tcomputeBodyChars: responseBody.length,\n\t\t\t...(includeBody && { computeResponseBody: responseBody })\n\t\t})\n\t};\n}\n","/**\n * App-wide instance of the remote-definition fetcher (SSRF guard, size cap,\n * deadline, TTL cache all live in `@selvajs/server`'s `createRemoteDefinitionFetcher`).\n */\n\nimport { createRemoteDefinitionFetcher } from '@selvajs/server/compute';\nimport {\n\tREMOTE_DEFINITION_MAX_BYTES,\n\tREMOTE_DEFINITION_FETCH_TIMEOUT_MS,\n\tREMOTE_DEFINITION_CACHE_TTL_MS\n} from '#lib/server/computeLimits.js';\n// Module-scope init runs before the root logger is fully swapped in, so this\n// needs the forwarding logger, not a snapshot that would pin the boot placeholder.\nimport { lazyLogger } from '#lib/server/providers.server.js';\n\nconst fetcher = createRemoteDefinitionFetcher({\n\tmaxBytes: REMOTE_DEFINITION_MAX_BYTES,\n\tfetchTimeoutMs: REMOTE_DEFINITION_FETCH_TIMEOUT_MS,\n\tcacheTtlMs: REMOTE_DEFINITION_CACHE_TTL_MS,\n\tnow: () => Date.now(),\n\tlogger: lazyLogger\n});\n\n/** Fetch (or return cached) remote `.gh` bytes. Throws on unsafe host / oversized / timeout. */\nexport function loadRemoteDefinition(url: string): Promise<Uint8Array> {\n\treturn fetcher.load(url);\n}\n","/**\n * The body-independent core of a solve request, shared by `POST /api/v1/compute`\n * (share-token and remote-URL capable) and `POST /api/v1/definitions/{guid}/solve`\n * (tenant-scoped, cookie or PAT).\n *\n * **Share-token resolution stays outside this module, in the route.** The caller\n * hands in an already-decided `SolveAccess`; the definition-addressed route only\n * ever constructs the `user` variant, so it cannot inherit the anonymous branch\n * by accident. Adding a token lookup here would silently give it one.\n *\n * What lives here: rate limiting, definition/version resolution, access checks,\n * compute-server routing, schema backfill, the engine call, metric recording, the\n * debug breakdown. What stays in a route: parsing its own body shape and deciding\n * who the caller is.\n */\n\nimport { apiError, ApiErrorCode } from '#lib/server/api-errors.js';\nimport {\n\tApiError,\n\tassertScope,\n\tchargeApiRateLimit,\n\tisApiError,\n\trateLimitedResponse,\n\ttoErrorBody,\n\twithRateLimitHeaders\n} from '@selvajs/server/api';\nimport { isHttpError } from '@sveltejs/kit';\nimport { ComputeError, ErrorCodes } from '@selvajs/compute/core';\nimport type { SolveMode } from '@selvajs/compute/grasshopper';\nimport type { ComputeServerConfig, RequestContext, SolveFailureKind } from '@selvajs/platform';\nimport { ComputeServerUnconfiguredError } from '@selvajs/server/compute';\nimport { serverResolver } from './serverResolver.server';\nimport { engine, COMPUTE_DEBUG, COMPUTE_DEBUG_VERBOSE } from '#lib/server/compute/engine.server.js';\nimport { solveSessionId } from '#lib/server/compute/sessionId.server.js';\nimport { computeErrorLogFields } from '#lib/server/compute/errorLogFields.js';\nimport { loadRemoteDefinition } from '#lib/server/compute/remoteDefinition.server.js';\nimport {\n\tpostedServerSourcedIds,\n\tsolveInputsFromSchema,\n\ttype ByteCacheRef,\n\ttype SolveDefinition,\n\ttype SolveEnvelope,\n\ttype SolveInput\n} from '@selvajs/solve/server';\nimport type { UISchema } from '@selvajs/schemas';\nimport { apiRateLimiter, checkComputeRateLimit } from '#lib/server/computeRateLimit.server.js';\nimport { getStorageProvider, getSolveMetricSink, providers } from '#lib/server/providers.server.js';\nimport { requireCanSolve, requireCanEditDefinition, scoped } from '#lib/server/access.server.js';\nimport { fetchSchemaFromCompute } from '@selvajs/server/definitions';\nimport { renderThrown } from '@selvajs/server/logging';\nimport type { ShareLink } from '@selvajs/platform';\nimport { MAX_SOLVE_DEADLINE_MS } from '@selvajs/solve/server';\nimport {\n\tbindLiveSolve,\n\tliveOwnerKey,\n\tsolveEndedKind\n} from '#lib/server/solveEvents/liveSolve.server.js';\n\nexport type SolveChannel = 'live' | 'draft';\n\n/**\n * Who is solving, and under whose authority.\n *\n * `user` — a logged-in caller; the per-definition access rules run.\n * `share` — a share-link token; the token already encodes the grant, so the\n * rules are skipped and the link's solve cap is charged instead.\n */\nexport type SolveAccess =\n\t| { kind: 'user'; ctx: RequestContext; rateLimitKey: string }\n\t| { kind: 'share'; ctx: RequestContext; link: ShareLink; rateLimitKey: string };\n\nexport interface SolveParams {\n\taccess: SolveAccess;\n\tdefinitionUrl: string;\n\t/**\n\t * The request body's inputs, read for a remote URL only. A stored definition's come from its\n\t * version's schema: a caller, a share-link visitor included, must not choose its ids, types or\n\t * bounds.\n\t */\n\tinputs?: unknown;\n\tvalues: Record<string, unknown>;\n\tchannel: SolveChannel;\n\t/** Explicit version pick; editor-only, never share-token accessible. */\n\tversionId: string | null;\n\trequest: Request;\n\t/** Typed loosely: two route trees with different generated `$types` both call this. */\n\tlocals: App.Locals;\n\t/** `performance.now()` at the very start of the request, before body parse. */\n\tloadStart: number;\n\t/** Prep sub-phase timings recorded before this call (body parse, token). */\n\tprepMarks: [string, number][];\n\t/**\n\t * The caller's live-event stream (`GET /api/v1/solve-events?streamId=`). When it is open\n\t * and theirs, this solve is bound to it: the server emits start/end, and the compute\n\t * request carries a callback so the definition can emit mid-solve. Ignored otherwise.\n\t */\n\tstreamId?: string | null;\n\t/** See `SolveBodySchema.mode`. */\n\tsolveMode?: SolveMode;\n\t/**\n\t * Report an access refusal as 404 instead of 403.\n\t *\n\t * The definition-addressed route needs this: a guid is guessable, so\n\t * 403-vs-404 there tells a caller whether a definition they cannot reach\n\t * exists. `/api/v1/compute` leaves it off — its callers navigated to the\n\t * definition, and a 403 is the more useful answer.\n\t */\n\tconcealAccessFailure?: boolean;\n\t/**\n\t * The route already charged the key's request bucket, ahead of any idempotent\n\t * replay that would skip this function, so it must not be charged twice.\n\t */\n\ttokenCharged?: boolean;\n}\n\nfunction readRemoteInputs(inputs: unknown): SolveInput[] {\n\tconst valid =\n\t\tArray.isArray(inputs) &&\n\t\tinputs.every(\n\t\t\t(input) =>\n\t\t\t\ttypeof input === 'object' &&\n\t\t\t\tinput !== null &&\n\t\t\t\ttypeof (input as SolveInput).id === 'string' &&\n\t\t\t\ttypeof (input as SolveInput).nickname === 'string'\n\t\t);\n\tif (!valid) {\n\t\tapiError(\n\t\t\t400,\n\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t'A remote definitionUrl needs inputs: a list of { id, nickname, paramType }.'\n\t\t);\n\t}\n\treturn inputs as SolveInput[];\n}\n\nfunction admittedSolveInputs(\n\tschema: UISchema | undefined,\n\tinputs: unknown,\n\tvalues: Record<string, unknown>\n): SolveInput[] {\n\tconst solveInputs = schema ? solveInputsFromSchema(schema) : readRemoteInputs(inputs);\n\tconst serverOnly = postedServerSourcedIds(solveInputs, values);\n\tif (serverOnly.length > 0) {\n\t\tapiError(\n\t\t\t400,\n\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t`These inputs are filled on the server and may not be posted in values: ${serverOnly.join(', ')}.`\n\t\t);\n\t}\n\treturn solveInputs;\n}\n\n/**\n * Run a solve and return the HTTP response.\n *\n * Throws `HttpError` (via `apiError`) for every refusal, and lets engine/network\n * failures propagate for the caller's outer catch to map — the two routes share\n * that mapping through `mapSolveError`.\n */\nexport async function runSolve(params: SolveParams): Promise<Response> {\n\tconst {\n\t\taccess,\n\t\tdefinitionUrl,\n\t\tinputs,\n\t\tvalues,\n\t\tchannel,\n\t\tversionId: explicitVersionId,\n\t\trequest,\n\t\tlocals,\n\t\tloadStart,\n\t\tprepMarks,\n\t\tconcealAccessFailure = false,\n\t\tstreamId = null,\n\t\tsolveMode = 'full',\n\t\ttokenCharged = false\n\t} = params;\n\tconst storage = getStorageProvider();\n\tconst sharedAccess = access.kind === 'share' ? access : null;\n\tconst solveCtx = access.ctx;\n\n\tlet prevMark = performance.now();\n\tconst mark = (label: string) => {\n\t\tprepMarks.push([label, performance.now() - prevMark]);\n\t\tprevMark = performance.now();\n\t};\n\n\t// Local definitions solve by reference: a byte-cache `DefinitionRef` whose\n\t// bytes the scheduler loads ONLY when an upload is unavoidable (pointer-known\n\t// re-solves move zero bytes). Remote-URL definitions carry raw fetched bytes.\n\tlet definitionSource: SolveDefinition;\n\t// `.load()` materializes bytes for schema backfill; `.outcome` drives the\n\t// `def_bytes` Server-Timing verdict. Null for remote-URL solves.\n\tlet localDefinitionRef: ByteCacheRef | null = null;\n\tlet localVersionForBackfill: { id: string; hasSchema: boolean } | null = null;\n\tlet storedSchema: UISchema | undefined;\n\t// BYO compute routing per org; null for remote definitions.\n\tlet solveOrgId: string | null = null;\n\tlet definitionPin: string | null = null;\n\t// Started once the project is known; null for remote definitions.\n\tlet pendingServer: Promise<ComputeServerConfig> | null = null;\n\t// Solve-metric attribution; null for remote-URL solves.\n\tlet metricDefinitionId: string | null = null;\n\tlet metricVersionId: string | null = null;\n\n\tconst isLocal = definitionUrl.startsWith('local:');\n\tconst guid = isLocal ? definitionUrl.substring(6) : null;\n\n\t// One row per solve attempt, including attempts rejected before the solve\n\t// runs — reads the attribution `let`s at call time, so definition/version\n\t// are null when a record fires pre-resolution. Fire-and-forget: the sink\n\t// never throws (ISolveMetricSink contract).\n\tconst recordMetric = (\n\t\tfailureKind: SolveFailureKind,\n\t\textra: { durationMs?: number; errorCount?: number; warningCount?: number } = {}\n\t) => {\n\t\tgetSolveMetricSink()\n\t\t\t.record(solveCtx, {\n\t\t\t\tdefinitionUrl,\n\t\t\t\tdefinitionId: metricDefinitionId,\n\t\t\t\tversionId: metricVersionId,\n\t\t\t\tchannel,\n\t\t\t\torgId: solveOrgId,\n\t\t\t\tdurationMs: extra.durationMs ?? 0,\n\t\t\t\tok: failureKind === 'ok',\n\t\t\t\tfailureKind,\n\t\t\t\terrorCount: extra.errorCount ?? 0,\n\t\t\t\twarningCount: extra.warningCount ?? 0\n\t\t\t})\n\t\t\t// Sinks are contracted not to throw, but nothing enforces it — a bad sink\n\t\t\t// must surface as a log line, not an unhandled rejection.\n\t\t\t.catch((err) =>\n\t\t\t\tlocals.log.error('Solve-metric record failed', {\n\t\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\t\terr: renderThrown(err)\n\t\t\t\t})\n\t\t\t);\n\t};\n\n\t// Both limits run before DB reads so throttled callers don't burn quota. A\n\t// token pays its own request bucket and its owner's compute bucket, so ten\n\t// keys of one user never buy ten times the compute.\n\tconst tokenVerdict = tokenCharged\n\t\t? undefined\n\t\t: await chargeApiRateLimit(access.ctx, apiRateLimiter);\n\tif (tokenVerdict && !tokenVerdict.allowed) {\n\t\trecordMetric('rate_limited');\n\t\treturn rateLimitedResponse(tokenVerdict);\n\t}\n\tconst rateLimit = checkComputeRateLimit(access.rateLimitKey);\n\tif (!rateLimit.allowed) {\n\t\trecordMetric('rate_limited');\n\t\tconst retryAfter = String(rateLimit.retryAfter ?? 1);\n\t\tconst err = new ApiError(\n\t\t\t429,\n\t\t\tApiErrorCode.RATE_LIMITED,\n\t\t\t`Too many compute requests. Retry in ${retryAfter}s.`,\n\t\t\tundefined,\n\t\t\t{ retryAfter }\n\t\t);\n\t\treturn withRateLimitHeaders(\n\t\t\tnew Response(JSON.stringify(toErrorBody(err)), {\n\t\t\t\tstatus: 429,\n\t\t\t\theaders: { 'Content-Type': 'application/json', 'Retry-After': retryAfter }\n\t\t\t}),\n\t\t\ttokenVerdict\n\t\t);\n\t}\n\n\tif (isLocal && guid) {\n\t\tlet record;\n\t\ttry {\n\t\t\trecord = await providers.data.definitions.get(solveCtx, guid);\n\t\t} catch (err) {\n\t\t\tlocals.log.error('Failed to load local definition', {\n\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\tguid,\n\t\t\t\terr: renderThrown(err)\n\t\t\t});\n\t\t\tapiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' not found`);\n\t\t}\n\t\tif (!record) apiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' not found`);\n\t\tmark('defRecord');\n\n\t\t// The version and the server need only the record and its project, so they are read\n\t\t// while access is checked, and awaited after it in their old order: a caller refused\n\t\t// access learns nothing from a missing version or server.\n\t\tconst versionId =\n\t\t\texplicitVersionId ?? (channel === 'live' ? record.liveVersionId : record.draftVersionId);\n\t\tconst pendingVersion = versionId\n\t\t\t? providers.data.definitions.getVersion(solveCtx, versionId)\n\t\t\t: null;\n\t\tpendingVersion?.catch(() => {});\n\t\tconst project = await providers.data.projects.getProject(solveCtx, record.projectId);\n\t\tsolveOrgId = project?.orgId ?? null;\n\t\tdefinitionPin = record.computeServerId ?? null;\n\t\tpendingServer = serverResolver.resolve(\n\t\t\tsolveCtx,\n\t\t\tsolveOrgId,\n\t\t\tlocals.providers.data.computeServer,\n\t\t\t{ definitionPin }\n\t\t);\n\t\tpendingServer.catch(() => {});\n\t\tmark('project');\n\n\t\tif (!sharedAccess) {\n\t\t\ttry {\n\t\t\t\tassertScope(access.ctx, 'solve', { projectId: record.projectId, definitionId: guid });\n\t\t\t\tif (channel === 'draft' || explicitVersionId) {\n\t\t\t\t\tawait requireCanEditDefinition(scoped(locals), record.projectId, guid, {\n\t\t\t\t\t\tproject,\n\t\t\t\t\t\tdefinition: record\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tawait requireCanSolve(scoped(locals), record.projectId, project ?? undefined);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\t// The guards raise `ApiError`, but `requireCanEditDefinition` may still\n\t\t\t\t// surface an `HttpError` — matching only one shape would let the\n\t\t\t\t// other's 403 leak through, confirming a guid the caller can't reach.\n\t\t\t\tconst status = isApiError(err) ? err.status : isHttpError(err) ? err.status : undefined;\n\t\t\t\tif (concealAccessFailure && status === 403) {\n\t\t\t\t\tapiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' not found`);\n\t\t\t\t}\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t}\n\t\tmark('access');\n\n\t\tif (!versionId || !pendingVersion) {\n\t\t\tapiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' has no ${channel} version yet`);\n\t\t}\n\t\tconst version = await pendingVersion;\n\t\tif (!version || version.definitionId !== guid) {\n\t\t\tapiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' version is missing`);\n\t\t}\n\t\tlocalVersionForBackfill = { id: version.id, hasSchema: version.schema !== undefined };\n\t\tstoredSchema = version.schema;\n\t\tmetricDefinitionId = guid;\n\t\tmetricVersionId = version.id;\n\t\tmark('version');\n\n\t\t// Keyed on the immutable version id, NEVER the fileKey — a\n\t\t// delete-latest-then-reupload can reuse a fileKey for different content.\n\t\t// A missing blob surfaces at solve time (compute_error → 500) rather than\n\t\t// an upfront 404, since it's no longer read eagerly here.\n\t\tlocalDefinitionRef = engine.definitionRef(version.id, async () => {\n\t\t\tconst bytes = await storage.get(version.fileKey);\n\t\t\tif (!bytes) throw new Error(`Version blob missing: ${version.fileKey}`);\n\t\t\treturn bytes;\n\t\t});\n\t\tdefinitionSource = localDefinitionRef;\n\t\tmark('blob');\n\t} else {\n\t\t// A remote URL names no project, so only an org-wide key may solve it.\n\t\tassertScope(access.ctx, 'solve');\n\t\treadRemoteInputs(inputs);\n\t\ttry {\n\t\t\tdefinitionSource = await loadRemoteDefinition(definitionUrl);\n\t\t} catch (err) {\n\t\t\tlocals.log.error('Failed to fetch remote definition', {\n\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\tdefinitionUrl,\n\t\t\t\terr: renderThrown(err)\n\t\t\t});\n\t\t\tapiError(\n\t\t\t\t400,\n\t\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t\t`Failed to load definition: ${err instanceof Error ? err.message : String(err)}`\n\t\t\t);\n\t\t}\n\t\tmark('remoteDef');\n\t}\n\n\t// Everything above (auth, DB, blob/remote fetch) is the \"load\" phase; tree\n\t// build and solve are measured inside the pipeline.\n\tconst defLoadMs = performance.now() - loadStart;\n\n\t// Checked before the share cap, so a request refused for its values spends no\n\t// solve. A version without a stored schema is checked after the backfill below.\n\tlet solveInputs =\n\t\tstoredSchema || !isLocal ? admittedSolveInputs(storedSchema, inputs, values) : null;\n\n\t// Atomic check-and-increment; runs before solve to avoid wasting compute.\n\tif (sharedAccess) {\n\t\tconst next = await providers.data.shareLinks.tryIncrementSolveCount(\n\t\t\tsolveCtx,\n\t\t\tsharedAccess.link.id\n\t\t);\n\t\tif (next === null) {\n\t\t\trecordMetric('share_cap');\n\t\t\tapiError(429, ApiErrorCode.RATE_LIMITED, 'Share link solve cap reached.');\n\t\t}\n\t\tmark('shareCap');\n\t}\n\n\tconst serverConfig = await (pendingServer ??\n\t\tserverResolver.resolve(solveCtx, solveOrgId, locals.providers.data.computeServer, {\n\t\t\tdefinitionPin\n\t\t}));\n\tmark('resolveServer');\n\n\t// BRIDGE: remove ~2026-09 — lazy backfill for versions uploaded before schema\n\t// caching existed. Best-effort. Removing it: delete this block, tighten\n\t// `DefinitionVersion.schema` to required in platform types + Zod, and drop the\n\t// live-fetch fallback in loadForRender.server.ts.\n\tif (localVersionForBackfill && !localVersionForBackfill.hasSchema && localDefinitionRef) {\n\t\tconst versionId = localVersionForBackfill.id;\n\t\ttry {\n\t\t\t// Warms the byte-cache entry the upcoming solve's `load()` would hit anyway.\n\t\t\tconst bytes = await localDefinitionRef.load();\n\t\t\tstoredSchema = await fetchSchemaFromCompute(bytes, serverConfig);\n\t\t\tawait providers.data.definitions.setVersionSchema(solveCtx, versionId, storedSchema);\n\t\t} catch (err) {\n\t\t\tlocals.log.warn('Schema backfill failed', {\n\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\tversionId,\n\t\t\t\terr: renderThrown(err)\n\t\t\t});\n\t\t}\n\t\t// Backfill calls the compute server — seconds when it fires. If this shows\n\t\t// up repeatedly for the same definition, setVersionSchema isn't sticking.\n\t\tmark('schemaBackfill');\n\t}\n\n\tif (isLocal && !storedSchema) {\n\t\tapiError(\n\t\t\t503,\n\t\t\tApiErrorCode.COMPUTE_UNAVAILABLE,\n\t\t\t\"This version's inputs could not be read. Retry shortly.\"\n\t\t);\n\t}\n\tsolveInputs ??= admittedSolveInputs(storedSchema, inputs, values);\n\n\t// `SolveEngine.solve` owns warm-client lookup, input-tree build, single-flight\n\t// coalescing (a coalesced solve aborts only when its last caller leaves), and\n\t// per-caller encoding. Remote-URL solves have no version id, so the URL stands\n\t// in as coalesce-key identity (`definitionKey`); local solves already carry\n\t// that identity on `localDefinitionRef.key`.\n\tconst live = bindLiveSolve({\n\t\townerKey: liveOwnerKey(access.kind === 'user' ? access.ctx.userId : null),\n\t\tstreamId,\n\t\trequest,\n\t\t// Outlives any server's deadline by a margin, so a callback racing the response is not\n\t\t// refused. Minted before the warm client that knows this server's deadline.\n\t\ttokenTtlMs: MAX_SOLVE_DEADLINE_MS + 60_000\n\t});\n\n\tlet outcome: Awaited<ReturnType<typeof engine.solve>> | undefined;\n\ttry {\n\t\toutcome = await engine.solve({\n\t\t\tserver: serverConfig,\n\t\t\tdefinitionSource,\n\t\t\tdefinitionKey: isLocal ? undefined : definitionUrl,\n\t\t\tinputs: solveInputs,\n\t\t\tvalues,\n\t\t\tsignal: request.signal,\n\t\t\tacceptEncoding: request.headers.get('accept-encoding') ?? '',\n\t\t\tdefinitionGuid: guid ?? undefined,\n\t\t\tloadStartMs: loadStart,\n\t\t\tdefLoadMs,\n\t\t\tprepMarks,\n\t\t\tselvaEvents: live.selvaEvents,\n\t\t\tsessionId: solveSessionId(access, guid),\n\t\t\tsolveMode\n\t\t});\n\t} finally {\n\t\tlive.end(outcome ? solveEndedKind(outcome) : 'error');\n\t}\n\tmark('solve');\n\n\t// Metric recording is app policy — the engine only maps outcome to HTTP.\n\t// These branches don't return; `engine.toWebResponse` below does.\n\tif (outcome.kind === 'timeout') {\n\t\trecordMetric('timeout', { durationMs: outcome.durationMs });\n\t} else if (outcome.kind === 'client_abort') {\n\t\trecordMetric('client_abort', { durationMs: outcome.durationMs });\n\t} else if (outcome.kind === 'too_large') {\n\t\trecordMetric('too_large');\n\t} else if (outcome.kind === 'shed') {\n\t\trecordMetric('shed', { durationMs: outcome.durationMs });\n\t} else if (outcome.kind === 'compute_error') {\n\t\trecordMetric('compute_error', { durationMs: outcome.durationMs });\n\t} else if (outcome.kind === 'ok') {\n\t\trecordMetric('ok', {\n\t\t\tdurationMs: outcome.solveMs,\n\t\t\terrorCount: outcome.errorCount,\n\t\t\twarningCount: outcome.warningCount\n\t\t});\n\t\t// Best-effort: the solve already succeeded, so a failed counter write\n\t\t// must not turn into a request error. Local definitions only — remote\n\t\t// URLs have no record to bump.\n\t\tif (metricDefinitionId) {\n\t\t\tproviders.data.definitions.incrementSolveCount(solveCtx, metricDefinitionId).catch((err) =>\n\t\t\t\tlocals.log.warn('solveCount increment failed', {\n\t\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\t\tdefinitionId: metricDefinitionId,\n\t\t\t\t\terr: renderThrown(err)\n\t\t\t\t})\n\t\t\t);\n\t\t}\n\n\t\tif (COMPUTE_DEBUG) logDebugBreakdown(locals, request, outcome, defLoadMs, prepMarks);\n\t}\n\n\t// Builds the Response itself (incl. `Retry-After` on a rejected `shed`,\n\t// which `apiError` cannot set) and still throws `compute_error` through to\n\t// the caller's outer catch.\n\treturn withRateLimitHeaders(engine.toWebResponse(outcome), tokenVerdict);\n}\n\n/**\n * Both solve routes share this so they cannot drift on which failures read as\n * \"compute is down\" (503) versus a server bug (500).\n */\nexport function mapSolveError(err: unknown, locals: App.Locals): never {\n\tif (isHttpError(err)) throw err;\n\t// A guard's own refusal, not a failed solve — converted rather than\n\t// re-thrown. These routes return their Response directly instead of going\n\t// through `mount`, so an `ApiError` escaping here would reach SvelteKit,\n\t// which gives anything that isn't an `HttpError` a 500, turning a working\n\t// permission check into an operator error page.\n\tif (isApiError(err)) {\n\t\tapiError(err.status, err.code, err.message, err.fields, err.details);\n\t}\n\n\tif (err instanceof ComputeServerUnconfiguredError) {\n\t\tapiError(503, ApiErrorCode.COMPUTE_UNAVAILABLE, err.message);\n\t}\n\n\tconst message = err instanceof Error ? err.message : 'Unknown error';\n\tlocals.log.error('Solve request failed', {\n\t\tcomponent: 'API/Compute',\n\t\terr: renderThrown(err),\n\t\t...computeErrorLogFields(err, COMPUTE_DEBUG_VERBOSE)\n\t});\n\n\t// The compute transport classifies its failures — map the classes the caller\n\t// can act on. Unreachable/credentials/saturation are operator problems (503),\n\t// a deadline is 504; only a genuine solve failure stays 500.\n\tif (err instanceof ComputeError) {\n\t\tif (err.code === ErrorCodes.NETWORK_ERROR || err.code === ErrorCodes.CORS_ERROR) {\n\t\t\tapiError(503, ApiErrorCode.COMPUTE_UNAVAILABLE, 'Compute server is unreachable');\n\t\t}\n\t\tif (err.code === ErrorCodes.AUTH_ERROR) {\n\t\t\tapiError(\n\t\t\t\t503,\n\t\t\t\tApiErrorCode.COMPUTE_UNAVAILABLE,\n\t\t\t\t\"Compute server rejected this deployment's credentials — check the compute API key configuration.\"\n\t\t\t);\n\t\t}\n\t\tif (err.code === ErrorCodes.RATE_LIMIT) {\n\t\t\tapiError(\n\t\t\t\t503,\n\t\t\t\tApiErrorCode.COMPUTE_UNAVAILABLE,\n\t\t\t\t'Compute server is rate-limiting requests. Retry shortly.'\n\t\t\t);\n\t\t}\n\t\tif (err.code === ErrorCodes.TIMEOUT_ERROR) {\n\t\t\tapiError(\n\t\t\t\t504,\n\t\t\t\tApiErrorCode.COMPUTE_UNAVAILABLE,\n\t\t\t\t'Compute server timed out running the solve.'\n\t\t\t);\n\t\t}\n\t}\n\n\t// A transport-layer fetch failure means the compute server is unreachable,\n\t// not an internal error. (Raw TypeError only from fetches outside the compute\n\t// transport — the transport wraps its own into ComputeError NETWORK_ERROR.)\n\tif (err instanceof TypeError && message === 'fetch failed') {\n\t\tapiError(503, ApiErrorCode.COMPUTE_UNAVAILABLE, 'Compute server is unreachable');\n\t}\n\n\tapiError(500, ApiErrorCode.INTERNAL, message);\n}\n\n/**\n * DEBUG (SELVA_FLAG_COMPUTE_DEBUG): the server-side overhead the solve metric's\n * `durationMs` doesn't capture. `load` = auth + DB + definition fetch; `tree` =\n * input tree build; `serialize` = JSON.stringify of the result.\n */\nfunction logDebugBreakdown(\n\tlocals: App.Locals,\n\trequest: Request,\n\toutcome: { envelope: SolveEnvelope },\n\tdefLoadMs: number,\n\tprepMarks: [string, number][]\n): void {\n\tconst { metrics } = outcome.envelope;\n\tlocals.log.debug('Solve server-side phase breakdown', {\n\t\tcomponent: 'Compute/server',\n\t\tloadMs: Math.round(defLoadMs),\n\t\ttreeBuildMs: Math.round(metrics.treeBuildMs),\n\t\tsolveMs: Math.round(metrics.solveMs),\n\t\tserializeMs: Math.round(metrics.serializeMs),\n\t\tgzipMs: Math.round(metrics.gzipMs),\n\t\tserverTotalMs: Math.round(metrics.serverTotalMs),\n\t\tserializedBytes: metrics.serializedBytes\n\t});\n\tif (metrics.compressedBytes !== null) {\n\t\tlocals.log.debug('Response gzipped', {\n\t\t\tcomponent: 'Compute/server',\n\t\t\tserializedBytes: metrics.serializedBytes,\n\t\t\tcompressedBytes: metrics.compressedBytes,\n\t\t\tratio: Number((metrics.serializedBytes / metrics.compressedBytes).toFixed(1))\n\t\t});\n\t} else {\n\t\t// If this fires for browser requests, a proxy in front is stripping\n\t\t// Accept-Encoding, making compression impossible end-to-end.\n\t\tconst acceptEncoding = request.headers.get('accept-encoding') ?? '';\n\t\tlocals.log.debug('Compression skipped', {\n\t\t\tcomponent: 'Compute/server',\n\t\t\tacceptEncoding,\n\t\t\thasAcceptEncoding: acceptEncoding !== ''\n\t\t});\n\t}\n\t// Names the step a `load` (or pre-solve) spike hides in.\n\tlocals.log.debug('Prep breakdown', {\n\t\tcomponent: 'Compute/server',\n\t\t...Object.fromEntries(prepMarks.map(([label, ms]) => [`p_${label}Ms`, Math.round(ms)]))\n\t});\n\t// The only place evictions surface — per-request Server-Timing only carries\n\t// hit/miss verdicts.\n\tconst db = engine.stats().definitionBytes;\n\tlocals.log.debug('Definition byte-cache counters', {\n\t\tcomponent: 'Compute/def-bytes',\n\t\thits: db.hits,\n\t\tmisses: db.misses,\n\t\tevictions: db.evictions,\n\t\tentries: db.entries,\n\t\tretainedBytes: db.bytes\n\t});\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAQA,SAAgB,eAAe,QA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AQ,QAAQ,IAAI,iBAAiB,KAAK;EACjE,OAAO,IAAI,MAAM,uBAAuB;GACvC,WAAW;GACX;GACA,mBAAmB,mBAAmB;EACvC,CAAC;CACF;CAEA,OAAO,IAAI,MAAM,kBAAkB;EAClC,WAAW;EACX,GAAG,OAAO,YAAY,UAAU,KAAK,CAAC,OAAO,QAAQ,CAAC,KAAK,MAAM,KAAK,KAAK,MAAM,EAAE,CAAC,CAAC,CAAC;CACvF,CAAC;CAGD,MAAM,KAAK,OAAO,MAAM,CAAC,CAAC;CAC1B,OAAO,IAAI,MAAM,kCAAkC;EAClD,WAAW;EACX,MAAM,GAAG;EACT,QAAQ,GAAG;EACX,WAAW,GAAG;EACd,SAAS,GAAG;EACZ,eAAe,GAAG;CACnB,CAAC;AACF"}
|
|
@@ -1,11 +1,10 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { G as NoopEventSink, c as getDefinitionService, i as getBranding, m as getOrgAssetService, p as getNotificationProvider } from "./providers.server.js";
|
|
2
2
|
import { O as ApiError, j as codeForStatus, k as ApiErrorCode, z as isFlagEnabled } from "./access.js";
|
|
3
3
|
import { i as ProviderError } from "./context.js";
|
|
4
4
|
import { A as rateLimitedResponse, D as chargeApiRateLimit, M as withRateLimitHeaders, x as runHandler } from "./api.js";
|
|
5
|
-
import {
|
|
5
|
+
import { t as SchemaExtractionError, u as ComputeServerUnconfiguredError } from "./schema-extraction.js";
|
|
6
6
|
import { t as publicUrl } from "./origin.js";
|
|
7
|
-
import {
|
|
8
|
-
import { s as evictComputeClient } from "./engine.server.js";
|
|
7
|
+
import { _ as MAX_IMAGE_FILE_SIZE, c as evictComputeClient, g as MAX_DEFINITION_FILE_SIZE } from "./engine.server.js";
|
|
9
8
|
import { t as serverResolver } from "./serverResolver.server.js";
|
|
10
9
|
import { n as apiTokenResolutions, t as apiTokenCodec } from "./token2.server.js";
|
|
11
10
|
import { r as shareLinkCodec } from "./token3.server.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sveltekit.js","names":[],"sources":["../../../../server/src/api/deps.ts","../../../../server/src/api/map-core-error.ts","../../../src/lib/server/api/sveltekit.ts"],"sourcesContent":["/**\n * Everything an API handler talks to, as one injected value.\n *\n * Handlers used to reach module-global getters (`getProjectProvider()`,\n * `getDefinitionService()`, …) from the Selva app's composition root — 77 call\n * sites across the v1 routes. That welded them to one app's boot: a second app\n * on a different provider set could not call them at all.\n *\n * Most fields are sub-stores of `IDataProvider`, so a host that already built a\n * `SelvaConfig` gets them via `depsFromConfig`. `services` stays host-defined:\n * `DefinitionService` and friends are composed rather than resolved, and a host\n * may supply its own.\n */\n\nimport { isFlagEnabled, NoopEventSink } from '@selvajs/platform';\nimport type { DefinitionService } from '../definitions/definition-service.js';\nimport type { OrgAssetService } from '../organizations/org-asset-service.js';\nimport type { TokenCodec } from '../tokens/token-codec.js';\nimport type { ApiTokenCodec } from '../tokens/api-token-codec.js';\nimport type { ApiTokenHolderPolicy } from '../tokens/api-token-holder.js';\nimport type { ApiTokenResolutionCache } from '../http/api-token.js';\nimport type { ApiRateLimiter } from './rate-limit.js';\nimport type { ApiIdempotencyStore } from './idempotency.js';\nimport type {\n\tIAuthProvider,\n\tIDataProvider,\n\tIEventSink,\n\tINotificationProvider,\n\tIStorageProvider,\n\tSelvaConfig,\n\tSelvaFlags\n} from '@selvajs/platform';\n\nexport interface SelvaDeps {\n\tauth: IAuthProvider;\n\tstorage: IStorageProvider;\n\tdata: IDataProvider;\n\t/** `data.orgs` — hoisted because 18 v1 call sites read it directly. */\n\torgs: IDataProvider['orgs'];\n\t/** `data.projects` — 18 call sites. */\n\tprojects: IDataProvider['projects'];\n\t/** `data.definitions` — the definition metadata store. */\n\tdefinitionMeta: IDataProvider['definitions'];\n\tcomputeServer: IDataProvider['computeServer'];\n\tuserProfile: IDataProvider['userProfile'];\n\tshareLinks: IDataProvider['shareLinks'];\n\tinvites: IDataProvider['invites'];\n\tpermissions: IDataProvider['permissions'];\n\tplatformProjectGrants: IDataProvider['platformProjectGrants'];\n\t/**\n\t * Audit sink. Never optional here even though `SelvaConfig.events` is:\n\t * handlers emit escalation events (`project.reclaimed`,\n\t * `org_member.removed_orphaning_projects`) that the audit trail depends on,\n\t * and a handler deciding for itself what a missing sink means is how one of\n\t * them ends up silently unlogged. `depsFromConfig` substitutes\n\t * `NoopEventSink`, which discards explicitly.\n\t */\n\tevents: IEventSink;\n\t/**\n\t * Feature flags, as a predicate rather than a record: an omitted flag must\n\t * read as false, and keeping that in `isFlagEnabled` stops each caller from\n\t * re-deciding what a missing flag means.\n\t */\n\tflag: (name: keyof SelvaFlags) => boolean;\n\t/**\n\t * Token codecs, one per family, keyed by what they mint.\n\t *\n\t * Injected rather than resolved because the codec is built from an\n\t * instance-wide HMAC secret, and reading that secret is the host's job — a\n\t * package that reached for `process.env.SELVA_HMAC_KEY` itself would pin\n\t * every host to one env var name and one way of loading it. Rotating a\n\t * secret invalidates that family's outstanding tokens, so the two families\n\t * are separate values rather than one shared codec.\n\t *\n\t * Optional: a host with no sharing and no invites wires neither. The\n\t * handlers that need one fail loudly if it is absent rather than minting a\n\t * token nobody can verify.\n\t */\n\ttokens: {\n\t\tshareLinks?: TokenCodec;\n\t\tinvites?: TokenCodec;\n\t\t/** Without it, minting answers 503 `API_TOKENS_UNAVAILABLE`. */\n\t\tapiTokens?: ApiTokenCodec;\n\t\t/** Who may mint and use API tokens. Absent: the platform permission `manage_api_tokens`. */\n\t\tmayHoldApiTokens?: ApiTokenHolderPolicy;\n\t\t/** How long one sign-in lasts before minting needs a new one (`resolveSignInMaxAgeMs`). Absent: no limit. */\n\t\tsignInMaxAgeMs?: number;\n\t\t/**\n\t\t * The cache the host hands `resolveApiToken`, so a revoke through these handlers drops\n\t\t * the key from it at once. Absent: nothing to drop.\n\t\t */\n\t\tresolutionCache?: ApiTokenResolutionCache;\n\t};\n\t/**\n\t * Upload caps, in bytes.\n\t *\n\t * Deployment config, so the host resolves them — a package reading its own\n\t * env would pin every host to one variable name. Defaults apply when the\n\t * host says nothing, because a missing cap must not read as \"unlimited\":\n\t * `requireUpload` compares against this number, and `undefined` would let\n\t * any size through.\n\t */\n\tuploadLimits: {\n\t\tmaxDefinitionFileSize: number;\n\t\tmaxImageFileSize: number;\n\t};\n\t/**\n\t * Outbound mail, and the instance name to fall back to when a record has no\n\t * name of its own.\n\t *\n\t * Optional because mail is best-effort by design: an invite row is committed\n\t * before delivery is attempted, and the caller still holds the accept URL to\n\t * share by hand. A host with no mail configured wires nothing and the\n\t * handlers report `not-configured` rather than failing the write.\n\t */\n\tnotifications?: INotificationProvider;\n\t/**\n\t * Per-token request limit `runHandler` charges. Absent: the process-wide\n\t * default (`DEFAULT_API_RATE_LIMIT`). `null`: no limit. A host's own limiter\n\t * must outlive the request, since deps are rebuilt per request.\n\t */\n\tapiRateLimiter?: ApiRateLimiter | null;\n\t/**\n\t * Projects one owner may create through API keys, across all their keys.\n\t * Absent: the process-wide default (`DEFAULT_PROJECT_CREATE_LIMIT`). `null`:\n\t * no limit.\n\t */\n\tprojectCreateLimiter?: ApiRateLimiter | null;\n\t/** Replay store for routes mounted with `idempotent: true`. Absent: the process-wide default. */\n\tidempotency?: ApiIdempotencyStore;\n\t/** Instance display name, used where a record has none. */\n\tinstanceName: string;\n\t/** Where a person manages their API tokens, linked from the new-key email. Host-relative. */\n\tapiTokenSettingsPath: string;\n\t/**\n\t * Drop the host's warm compute client for one server id.\n\t *\n\t * A warm client caches on server `id`, so a rotated URL or key keeps the\n\t * same cache key with stale connection details and never ages out. The\n\t * config-write handlers evict through this rather than importing a cache:\n\t * which cache holds them is the host's decision, and importing one would\n\t * pull a whole solve engine into every consumer.\n\t *\n\t * Defaults to a no-op — a host with no client cache has nothing to evict,\n\t * and the handler must not have to know which kind of host it is running on.\n\t */\n\tevictComputeClient: (id: string) => void;\n\t/**\n\t * Called after every compute-config save, so a host remembering resolved servers\n\t * (`createServerResolver`) reads the config again. Defaults to a no-op.\n\t */\n\tonComputeConfigSaved: () => void;\n\t/**\n\t * Composed services the host supplies.\n\t *\n\t * The named ones are typed because handlers call them — leaving a service\n\t * `unknown` pushes a cast into every call site, and a cast is exactly where\n\t * a second host's differently-shaped service would slip through unnoticed.\n\t * The index signature keeps host-specific extras possible without naming\n\t * them here.\n\t */\n\tservices: {\n\t\tdefinitions?: DefinitionService;\n\t\torgAssets?: OrgAssetService;\n\t} & Record<string, unknown>;\n}\n\n/**\n * Build deps from a resolved `SelvaConfig`, plus whatever services and token\n * codecs the host composed on top. The hoisted fields are aliases into `data`,\n * not copies.\n *\n * `services` stays positional — every existing caller passes it there — and\n * `tokens` arrives in an options object rather than as a third positional, so\n * the two composed bags cannot be swapped at a call site.\n */\nexport function depsFromConfig(\n\tconfig: SelvaConfig,\n\tservices: SelvaDeps['services'] = {},\n\t{\n\t\ttokens = {},\n\t\tuploadLimits,\n\t\tevictComputeClient = () => {},\n\t\tonComputeConfigSaved = () => {},\n\t\tnotifications,\n\t\tinstanceName = 'Selva',\n\t\tapiTokenSettingsPath = '/settings/tokens',\n\t\tapiRateLimiter,\n\t\tprojectCreateLimiter,\n\t\tidempotency\n\t}: {\n\t\ttokens?: SelvaDeps['tokens'];\n\t\tuploadLimits?: Partial<SelvaDeps['uploadLimits']>;\n\t\tevictComputeClient?: SelvaDeps['evictComputeClient'];\n\t\tonComputeConfigSaved?: SelvaDeps['onComputeConfigSaved'];\n\t\tnotifications?: INotificationProvider;\n\t\tinstanceName?: string;\n\t\tapiTokenSettingsPath?: string;\n\t\tapiRateLimiter?: ApiRateLimiter | null;\n\t\tprojectCreateLimiter?: ApiRateLimiter | null;\n\t\tidempotency?: ApiIdempotencyStore;\n\t} = {}\n): SelvaDeps {\n\tconst { data } = config;\n\treturn {\n\t\tauth: config.auth,\n\t\tstorage: config.storage,\n\t\tdata,\n\t\torgs: data.orgs,\n\t\tprojects: data.projects,\n\t\tdefinitionMeta: data.definitions,\n\t\tcomputeServer: data.computeServer,\n\t\tuserProfile: data.userProfile,\n\t\tshareLinks: data.shareLinks,\n\t\tinvites: data.invites,\n\t\tpermissions: data.permissions,\n\t\tplatformProjectGrants: data.platformProjectGrants,\n\t\tevents: config.events ?? new NoopEventSink(),\n\t\tflag: (name) => isFlagEnabled(config, name),\n\t\ttokens,\n\t\t// Same defaults `resolveComputeLimits` applies, repeated rather than\n\t\t// imported: pulling that in would make every host resolving deps also\n\t\t// resolve compute limits from env, which is the coupling this avoids.\n\t\tuploadLimits: {\n\t\t\tmaxDefinitionFileSize: uploadLimits?.maxDefinitionFileSize ?? 50 * 1024 * 1024,\n\t\t\tmaxImageFileSize: uploadLimits?.maxImageFileSize ?? 10 * 1024 * 1024\n\t\t},\n\t\tevictComputeClient,\n\t\tonComputeConfigSaved,\n\t\tnotifications,\n\t\tinstanceName,\n\t\tapiTokenSettingsPath,\n\t\tapiRateLimiter,\n\t\tprojectCreateLimiter,\n\t\tidempotency,\n\t\tservices\n\t};\n}\n","/**\n * The domain errors this package's own handlers raise, folded into the envelope.\n *\n * A host's `mapError` should call this first and add only its own error types.\n * These rules cannot live solely in a host: the handler that throws them ships\n * from here, so a host that forgot one would serve 500 where every other host\n * serves 503 — the same API answering differently depending on who mounted it.\n *\n * Postgres surfaces a unique-constraint name verbatim, which is useless to an\n * end user, so the constraints this package's handlers can trip are translated\n * here rather than left to each host.\n */\n\nimport { ApiError, ApiErrorCode, codeForStatus } from './errors.js';\nimport { ComputeServerUnconfiguredError } from '../compute/errors.js';\nimport { SchemaExtractionError } from '../definitions/schema-extraction.js';\nimport { ProviderError } from '@selvajs/platform';\n\nconst UNIQUE_CONSTRAINT_MESSAGES: Record<string, string> = {\n\tprojects_org_name_unique: 'A project with that name already exists in this organization.',\n\tprojects_org_id_slug_key: 'A project with that name already exists in this organization.',\n\torgs_slug_key: 'An organization with that slug already exists.',\n\tdefinitions_pkey: 'A definition with that ID already exists.'\n};\n\nfunction friendlyConstraintMessage(raw: string): string | null {\n\tfor (const [name, msg] of Object.entries(UNIQUE_CONSTRAINT_MESSAGES)) {\n\t\tif (raw.includes(name)) return msg;\n\t}\n\treturn null;\n}\n\n/**\n * Compute unreachable or serving an unreadable schema is operator-side (503); a\n * schema the parser cannot read is the caller's file (422).\n */\nexport function mapCoreError(err: unknown): ApiError | undefined {\n\tif (err instanceof SchemaExtractionError) {\n\t\treturn err.kind === 'unreachable' || err.kind === 'malformed'\n\t\t\t? new ApiError(503, ApiErrorCode.COMPUTE_UNAVAILABLE, err.message)\n\t\t\t: new ApiError(422, ApiErrorCode.UNPROCESSABLE, err.message);\n\t}\n\tif (err instanceof ComputeServerUnconfiguredError) {\n\t\treturn new ApiError(503, ApiErrorCode.COMPUTE_UNAVAILABLE, err.message);\n\t}\n\tif (err instanceof ProviderError) {\n\t\tconst friendly = friendlyConstraintMessage(err.message);\n\t\treturn new ApiError(err.statusCode, codeForStatus(err.statusCode), friendly ?? err.message);\n\t}\n\treturn undefined;\n}\n","/**\n * The SvelteKit binding for the transport-free handlers in `@selvajs/server/api`.\n *\n * The only file in the app that knows both worlds: it turns a `RequestEvent`\n * into an `ApiRequest` and folds this app's domain errors into the shared\n * envelope. A handler mounted through here names no framework, so the same\n * handler runs under Next or Hono behind a sibling adapter roughly this size.\n */\n\nimport { isHttpError, json, type RequestEvent } from '@sveltejs/kit';\nimport { publicUrl } from '#lib/server/origin.js';\nimport {\n\tApiError,\n\tApiErrorCode,\n\tchargeApiRateLimit,\n\tcodeForStatus,\n\tdepsFromConfig,\n\tmapCoreError,\n\trateLimitedResponse,\n\trunHandler,\n\twithRateLimitHeaders,\n\ttype ApiHandler,\n\ttype ApiRequest,\n\ttype RunHandlerOptions,\n\ttype SelvaDeps\n} from '@selvajs/server/api';\nimport {\n\tgetBranding,\n\tgetDefinitionService,\n\tgetNotificationProvider,\n\tgetOrgAssetService\n} from '../providers.server';\nimport { shareLinkCodec } from '../shareLinks/token.server';\nimport { inviteCodec } from '../invites/token.server';\nimport { apiTokenCodec, apiTokenResolutions } from '../apiTokens/token.server';\nimport { MAX_DEFINITION_FILE_SIZE, MAX_IMAGE_FILE_SIZE } from '../computeLimits';\nimport { evictComputeClient } from '../compute/engine.server';\nimport { serverResolver } from '../compute/serverResolver.server';\nimport { apiRateLimiter } from '../computeRateLimit.server';\nimport { signInMaxAgeMs } from '../signInMaxAge.server';\n\n/**\n * This app's own errors, folded into the shared envelope.\n *\n * SvelteKit's `HttpError` is the only one left here — everything else the v1\n * handlers throw ships from `@selvajs/server`, so `mapCoreError` owns those\n * rules and a second host gets the same statuses without copying them.\n */\nexport function mapAppError(err: unknown): ApiError | undefined {\n\t// Access guards in `access.server.ts` throw SvelteKit's error() and must\n\t// keep doing so — page loads share them and need SvelteKit to render the\n\t// failure. Without this branch every guard 403 falls through to the 500\n\t// fallback, a downgrade no type check catches.\n\tif (isHttpError(err)) {\n\t\t// Guards throw `error(status, 'string')`; `apiError` throws the object\n\t\t// form with `fields` (Zod's per-field detail) — both are live, so this\n\t\t// reads the body rather than just the status.\n\t\tconst body = err.body as\n\t\t\t| {\n\t\t\t\t\tmessage?: string;\n\t\t\t\t\tcode?: ApiErrorCode;\n\t\t\t\t\tfields?: Record<string, string>;\n\t\t\t\t\tdetails?: Record<string, string>;\n\t\t\t }\n\t\t\t| string;\n\t\tif (typeof body === 'string') {\n\t\t\treturn new ApiError(err.status, codeForStatus(err.status), body);\n\t\t}\n\t\treturn new ApiError(\n\t\t\terr.status,\n\t\t\tbody?.code ?? codeForStatus(err.status),\n\t\t\tbody?.message ?? 'Request failed',\n\t\t\tbody?.fields,\n\t\t\tbody?.details\n\t\t);\n\t}\n\treturn mapCoreError(err);\n}\n\n// Providers resolve lazily and memoize, so building deps per request costs a\n// few property reads — no provider is constructed here.\nfunction buildDeps(event: RequestEvent): SelvaDeps {\n\treturn depsFromConfig(\n\t\tevent.locals.providers,\n\t\t{\n\t\t\tdefinitions: getDefinitionService(),\n\t\t\torgAssets: getOrgAssetService()\n\t\t},\n\t\t{\n\t\t\t// Resolved per request, not captured: both codecs re-key on the secret,\n\t\t\t// so a rotated SELVA_HMAC_KEY takes effect without a restart.\n\t\t\ttokens: {\n\t\t\t\tshareLinks: shareLinkCodec(),\n\t\t\t\tinvites: inviteCodec(),\n\t\t\t\tapiTokens: apiTokenCodec(),\n\t\t\t\tsignInMaxAgeMs,\n\t\t\t\tresolutionCache: apiTokenResolutions\n\t\t\t},\n\t\t\t// Passed explicitly — depsFromConfig's defaults would silently ignore\n\t\t\t// this deployment's MAX_*_FILE_SIZE_BYTES.\n\t\t\tuploadLimits: {\n\t\t\t\tmaxDefinitionFileSize: MAX_DEFINITION_FILE_SIZE,\n\t\t\t\tmaxImageFileSize: MAX_IMAGE_FILE_SIZE\n\t\t\t},\n\t\t\t// Cache is keyed on server id; without this a compute-config write\n\t\t\t// leaves a warm client holding a rotated URL or key.\n\t\t\tevictComputeClient,\n\t\t\tonComputeConfigSaved: () => serverResolver.forget(),\n\t\t\tnotifications: getNotificationProvider(),\n\t\t\tinstanceName: getBranding().name,\n\t\t\tapiTokenSettingsPath: '/team/tokens',\n\t\t\t// Module singleton: the limiter must outlive this per-request deps object.\n\t\t\tapiRateLimiter\n\t\t}\n\t);\n}\n\nexport function toApiRequest(event: RequestEvent): ApiRequest {\n\treturn {\n\t\tctx: event.locals.ctx,\n\t\tuser: event.locals.user,\n\t\tprofile: event.locals.profile,\n\t\tlog: event.locals.log,\n\t\tparams: event.params,\n\t\turl: publicUrl(event.url),\n\t\trequest: event.request,\n\t\tdeps: buildDeps(event)\n\t};\n}\n\n/**\n * Mount a transport-free handler as a SvelteKit `RequestHandler`.\n *\n * Routes addressed by a project or definition pass `scopeTarget`, so a key\n * scoped to that project or definition can reach them; solve routes pass\n * `action: 'solve'`; creates pass `idempotent: true`.\n */\nexport function mount(\n\tfallback: string,\n\thandler: ApiHandler,\n\topts: Pick<RunHandlerOptions, 'action' | 'scopeTarget' | 'anyScope' | 'idempotent'> = {}\n) {\n\treturn (event: RequestEvent): Promise<Response> =>\n\t\trunHandler(handler, toApiRequest(event), { fallback, mapError: mapAppError, ...opts });\n}\n\n/**\n * The per-token rate limit for a route that builds its own `Response` instead\n * of going through `mount`: charged before the handler runs, and `RateLimit-*`\n * on every token response, thrown errors included.\n */\nexport function withApiRateLimit<E extends RequestEvent>(\n\thandler: (event: E) => Promise<Response>\n): (event: E) => Promise<Response> {\n\treturn async (event) => {\n\t\tconst verdict = await chargeApiRateLimit(event.locals.ctx, apiRateLimiter);\n\t\tif (verdict && !verdict.allowed) return rateLimitedResponse(verdict);\n\t\ttry {\n\t\t\treturn withRateLimitHeaders(await handler(event), verdict);\n\t\t} catch (err) {\n\t\t\tif (!verdict || !isHttpError(err)) throw err;\n\t\t\treturn withRateLimitHeaders(json(err.body, { status: err.status }), verdict);\n\t\t}\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgLA,SAAgB,eACf,QACA,WAAkC,CAAC,GACnC,EACC,SAAS,CAAC,GACV,cACA,2BAA2B,CAAC,GAC5B,6BAA6B,CAAC,GAC9B,eACA,eAAe,SACf,uBAAuB,oBACvB,gBACA,sBACA,gBAYG,CAAC,GACO;CACZ,MAAM,EAAE,SAAS;CACjB,OAAO;EACN,MAAM,OAAO;EACb,SAAS,OAAO;EAChB;EACA,MAAM,KAAK;EACX,UAAU,KAAK;EACf,gBAAgB,KAAK;EACrB,eAAe,KAAK;EACpB,aAAa,KAAK;EAClB,YAAY,KAAK;EACjB,SAAS,KAAK;EACd,aAAa,KAAK;EAClB,uBAAuB,KAAK;EAC5B,QAAQ,OAAO,UAAU,IAAI,cAAc;EAC3C,OAAO,SAAS,cAAc,QAAQ,IAAI;EAC1C;EAIA,cAAc;GACb,uBAAuB,cAAc,yBAAyB;GAC9D,kBAAkB,cAAc,oBAAoB;EACrD;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACD;AACD;;;;;;;;;;;;;;AC3NA,IAAM,6BAAqD;CAC1D,0BAA0B;CAC1B,0BAA0B;CAC1B,eAAe;CACf,kBAAkB;AACnB;AAE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,CAAC,CAAC;EAC5B,sBAAsB;EAEtB;CACD,CACD;AACD;AAEA,SAAgB,aAAa,OAAiC;CAC7D,OAAO;EACN,KAAK,MAAM,OAAO;EAClB,MAAM,MAAM,OAAO;EACnB,SAAS,MAAM,OAAO;EACtB,KAAK,MAAM,OAAO;EAClB,QAAQ,MAAM;EACd,KAAK,UAAU,MAAM,GAAG;EACxB,SAAS,MAAM;EACf,MAAM,UAAU,KAAK;CACtB;AACD;;;;;;;;AASA,SAAgB,MACf,UACA,SACA,OAAsF,CAAC,GACtF;CACD,QAAQ,UACP,WAAW,SAAS,aAAa,KAAK,GAAG;EAAE;EAAU,UAAU;EAAa,GAAG;CAAK,CAAC;AACvF;;;;;;AAOA,SAAgB,iBACf,SACkC;CAClC,OAAO,OAAO,UAAU;EACvB,MAAM,UAAU,MAAM,mBAAmB,MAAM,OAAO,KAAK,cAAc;EACzE,IAAI,WAAW,CAAC,QAAQ,SAAS,OAAO,oBAAoB,OAAO;EACnE,IAAI;GACH,OAAO,qBAAqB,MAAM,QAAQ,KAAK,GAAG,OAAO;EAC1D,SAAS,KAAK;GACb,IAAI,CAAC,WAAW,CAAC,YAAY,GAAG,GAAG,MAAM;GACzC,OAAO,qBAAqB,KAAK,IAAI,MAAM,EAAE,QAAQ,IAAI,OAAO,CAAC,GAAG,OAAO;EAC5E;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"sveltekit.js","names":[],"sources":["../../../../server/src/api/deps.ts","../../../../server/src/api/map-core-error.ts","../../../src/lib/server/api/sveltekit.ts"],"sourcesContent":["/**\n * Everything an API handler talks to, as one injected value.\n *\n * Handlers used to reach module-global getters (`getProjectProvider()`,\n * `getDefinitionService()`, …) from the Selva app's composition root — 77 call\n * sites across the v1 routes. That welded them to one app's boot: a second app\n * on a different provider set could not call them at all.\n *\n * Most fields are sub-stores of `IDataProvider`, so a host that already built a\n * `SelvaConfig` gets them via `depsFromConfig`. `services` stays host-defined:\n * `DefinitionService` and friends are composed rather than resolved, and a host\n * may supply its own.\n */\n\nimport { isFlagEnabled, NoopEventSink } from '@selvajs/platform';\nimport type { DefinitionService } from '../definitions/definition-service.js';\nimport type { OrgAssetService } from '../organizations/org-asset-service.js';\nimport type { TokenCodec } from '../tokens/token-codec.js';\nimport type { ApiTokenCodec } from '../tokens/api-token-codec.js';\nimport type { ApiTokenHolderPolicy } from '../tokens/api-token-holder.js';\nimport type { ApiTokenResolutionCache } from '../http/api-token.js';\nimport type { ApiRateLimiter } from './rate-limit.js';\nimport type { ApiIdempotencyStore } from './idempotency.js';\nimport type {\n\tIAuthProvider,\n\tIDataProvider,\n\tIEventSink,\n\tINotificationProvider,\n\tIStorageProvider,\n\tSelvaConfig,\n\tSelvaFlags\n} from '@selvajs/platform';\n\nexport interface SelvaDeps {\n\tauth: IAuthProvider;\n\tstorage: IStorageProvider;\n\tdata: IDataProvider;\n\t/** `data.orgs` — hoisted because 18 v1 call sites read it directly. */\n\torgs: IDataProvider['orgs'];\n\t/** `data.projects` — 18 call sites. */\n\tprojects: IDataProvider['projects'];\n\t/** `data.definitions` — the definition metadata store. */\n\tdefinitionMeta: IDataProvider['definitions'];\n\tcomputeServer: IDataProvider['computeServer'];\n\tuserProfile: IDataProvider['userProfile'];\n\tshareLinks: IDataProvider['shareLinks'];\n\tinvites: IDataProvider['invites'];\n\tpermissions: IDataProvider['permissions'];\n\tplatformProjectGrants: IDataProvider['platformProjectGrants'];\n\t/**\n\t * Audit sink. Never optional here even though `SelvaConfig.events` is:\n\t * handlers emit escalation events (`project.reclaimed`,\n\t * `org_member.removed_orphaning_projects`) that the audit trail depends on,\n\t * and a handler deciding for itself what a missing sink means is how one of\n\t * them ends up silently unlogged. `depsFromConfig` substitutes\n\t * `NoopEventSink`, which discards explicitly.\n\t */\n\tevents: IEventSink;\n\t/**\n\t * Feature flags, as a predicate rather than a record: an omitted flag must\n\t * read as false, and keeping that in `isFlagEnabled` stops each caller from\n\t * re-deciding what a missing flag means.\n\t */\n\tflag: (name: keyof SelvaFlags) => boolean;\n\t/**\n\t * Token codecs, one per family, keyed by what they mint.\n\t *\n\t * Injected rather than resolved because the codec is built from an\n\t * instance-wide HMAC secret, and reading that secret is the host's job — a\n\t * package that reached for `process.env.SELVA_HMAC_KEY` itself would pin\n\t * every host to one env var name and one way of loading it. Rotating a\n\t * secret invalidates that family's outstanding tokens, so the two families\n\t * are separate values rather than one shared codec.\n\t *\n\t * Optional: a host with no sharing and no invites wires neither. The\n\t * handlers that need one fail loudly if it is absent rather than minting a\n\t * token nobody can verify.\n\t */\n\ttokens: {\n\t\tshareLinks?: TokenCodec;\n\t\tinvites?: TokenCodec;\n\t\t/** Without it, minting answers 503 `API_TOKENS_UNAVAILABLE`. */\n\t\tapiTokens?: ApiTokenCodec;\n\t\t/** Who may mint and use API tokens. Absent: the platform permission `manage_api_tokens`. */\n\t\tmayHoldApiTokens?: ApiTokenHolderPolicy;\n\t\t/** How long one sign-in lasts before minting needs a new one (`resolveSignInMaxAgeMs`). Absent: no limit. */\n\t\tsignInMaxAgeMs?: number;\n\t\t/**\n\t\t * The cache the host hands `resolveApiToken`, so a revoke through these handlers drops\n\t\t * the key from it at once. Absent: nothing to drop.\n\t\t */\n\t\tresolutionCache?: ApiTokenResolutionCache;\n\t};\n\t/**\n\t * Upload caps, in bytes.\n\t *\n\t * Deployment config, so the host resolves them — a package reading its own\n\t * env would pin every host to one variable name. Defaults apply when the\n\t * host says nothing, because a missing cap must not read as \"unlimited\":\n\t * `requireUpload` compares against this number, and `undefined` would let\n\t * any size through.\n\t */\n\tuploadLimits: {\n\t\tmaxDefinitionFileSize: number;\n\t\tmaxImageFileSize: number;\n\t};\n\t/**\n\t * Outbound mail, and the instance name to fall back to when a record has no\n\t * name of its own.\n\t *\n\t * Optional because mail is best-effort by design: an invite row is committed\n\t * before delivery is attempted, and the caller still holds the accept URL to\n\t * share by hand. A host with no mail configured wires nothing and the\n\t * handlers report `not-configured` rather than failing the write.\n\t */\n\tnotifications?: INotificationProvider;\n\t/**\n\t * Per-token request limit `runHandler` charges. Absent: the process-wide\n\t * default (`DEFAULT_API_RATE_LIMIT`). `null`: no limit. A host's own limiter\n\t * must outlive the request, since deps are rebuilt per request.\n\t */\n\tapiRateLimiter?: ApiRateLimiter | null;\n\t/**\n\t * Projects one owner may create through API keys, across all their keys.\n\t * Absent: the process-wide default (`DEFAULT_PROJECT_CREATE_LIMIT`). `null`:\n\t * no limit.\n\t */\n\tprojectCreateLimiter?: ApiRateLimiter | null;\n\t/** Replay store for routes mounted with `idempotent: true`. Absent: the process-wide default. */\n\tidempotency?: ApiIdempotencyStore;\n\t/** Instance display name, used where a record has none. */\n\tinstanceName: string;\n\t/** Where a person manages their API tokens, linked from the new-key email. Host-relative. */\n\tapiTokenSettingsPath: string;\n\t/**\n\t * Drop the host's warm compute client for one server id.\n\t *\n\t * A warm client caches on server `id`, so a rotated URL or key keeps the\n\t * same cache key with stale connection details and never ages out. The\n\t * config-write handlers evict through this rather than importing a cache:\n\t * which cache holds them is the host's decision, and importing one would\n\t * pull a whole solve engine into every consumer.\n\t *\n\t * Defaults to a no-op — a host with no client cache has nothing to evict,\n\t * and the handler must not have to know which kind of host it is running on.\n\t */\n\tevictComputeClient: (id: string) => void;\n\t/**\n\t * Called after every compute-config save, so a host remembering resolved servers\n\t * (`createServerResolver`) reads the config again. Defaults to a no-op.\n\t */\n\tonComputeConfigSaved: () => void;\n\t/**\n\t * Composed services the host supplies.\n\t *\n\t * The named ones are typed because handlers call them — leaving a service\n\t * `unknown` pushes a cast into every call site, and a cast is exactly where\n\t * a second host's differently-shaped service would slip through unnoticed.\n\t * The index signature keeps host-specific extras possible without naming\n\t * them here.\n\t */\n\tservices: {\n\t\tdefinitions?: DefinitionService;\n\t\torgAssets?: OrgAssetService;\n\t} & Record<string, unknown>;\n}\n\n/**\n * Build deps from a resolved `SelvaConfig`, plus whatever services and token\n * codecs the host composed on top. The hoisted fields are aliases into `data`,\n * not copies.\n *\n * `services` stays positional — every existing caller passes it there — and\n * `tokens` arrives in an options object rather than as a third positional, so\n * the two composed bags cannot be swapped at a call site.\n */\nexport function depsFromConfig(\n\tconfig: SelvaConfig,\n\tservices: SelvaDeps['services'] = {},\n\t{\n\t\ttokens = {},\n\t\tuploadLimits,\n\t\tevictComputeClient = () => {},\n\t\tonComputeConfigSaved = () => {},\n\t\tnotifications,\n\t\tinstanceName = 'Selva',\n\t\tapiTokenSettingsPath = '/settings/tokens',\n\t\tapiRateLimiter,\n\t\tprojectCreateLimiter,\n\t\tidempotency\n\t}: {\n\t\ttokens?: SelvaDeps['tokens'];\n\t\tuploadLimits?: Partial<SelvaDeps['uploadLimits']>;\n\t\tevictComputeClient?: SelvaDeps['evictComputeClient'];\n\t\tonComputeConfigSaved?: SelvaDeps['onComputeConfigSaved'];\n\t\tnotifications?: INotificationProvider;\n\t\tinstanceName?: string;\n\t\tapiTokenSettingsPath?: string;\n\t\tapiRateLimiter?: ApiRateLimiter | null;\n\t\tprojectCreateLimiter?: ApiRateLimiter | null;\n\t\tidempotency?: ApiIdempotencyStore;\n\t} = {}\n): SelvaDeps {\n\tconst { data } = config;\n\treturn {\n\t\tauth: config.auth,\n\t\tstorage: config.storage,\n\t\tdata,\n\t\torgs: data.orgs,\n\t\tprojects: data.projects,\n\t\tdefinitionMeta: data.definitions,\n\t\tcomputeServer: data.computeServer,\n\t\tuserProfile: data.userProfile,\n\t\tshareLinks: data.shareLinks,\n\t\tinvites: data.invites,\n\t\tpermissions: data.permissions,\n\t\tplatformProjectGrants: data.platformProjectGrants,\n\t\tevents: config.events ?? new NoopEventSink(),\n\t\tflag: (name) => isFlagEnabled(config, name),\n\t\ttokens,\n\t\t// Same defaults `resolveComputeLimits` applies, repeated rather than\n\t\t// imported: pulling that in would make every host resolving deps also\n\t\t// resolve compute limits from env, which is the coupling this avoids.\n\t\tuploadLimits: {\n\t\t\tmaxDefinitionFileSize: uploadLimits?.maxDefinitionFileSize ?? 50 * 1024 * 1024,\n\t\t\tmaxImageFileSize: uploadLimits?.maxImageFileSize ?? 10 * 1024 * 1024\n\t\t},\n\t\tevictComputeClient,\n\t\tonComputeConfigSaved,\n\t\tnotifications,\n\t\tinstanceName,\n\t\tapiTokenSettingsPath,\n\t\tapiRateLimiter,\n\t\tprojectCreateLimiter,\n\t\tidempotency,\n\t\tservices\n\t};\n}\n","/**\n * The domain errors this package's own handlers raise, folded into the envelope.\n *\n * A host's `mapError` should call this first and add only its own error types.\n * These rules cannot live solely in a host: the handler that throws them ships\n * from here, so a host that forgot one would serve 500 where every other host\n * serves 503 — the same API answering differently depending on who mounted it.\n *\n * Postgres surfaces a unique-constraint name verbatim, which is useless to an\n * end user, so the constraints this package's handlers can trip are translated\n * here rather than left to each host.\n */\n\nimport { ApiError, ApiErrorCode, codeForStatus } from './errors.js';\nimport { ComputeServerUnconfiguredError } from '../compute/errors.js';\nimport { SchemaExtractionError } from '../definitions/schema-extraction.js';\nimport { ProviderError } from '@selvajs/platform';\n\nconst UNIQUE_CONSTRAINT_MESSAGES: Record<string, string> = {\n\tprojects_org_name_unique: 'A project with that name already exists in this organization.',\n\tprojects_org_id_slug_key: 'A project with that name already exists in this organization.',\n\torgs_slug_key: 'An organization with that slug already exists.',\n\tdefinitions_pkey: 'A definition with that ID already exists.'\n};\n\nfunction friendlyConstraintMessage(raw: string): string | null {\n\tfor (const [name, msg] of Object.entries(UNIQUE_CONSTRAINT_MESSAGES)) {\n\t\tif (raw.includes(name)) return msg;\n\t}\n\treturn null;\n}\n\n/**\n * Compute unreachable or serving an unreadable schema is operator-side (503); a\n * schema the parser cannot read is the caller's file (422).\n */\nexport function mapCoreError(err: unknown): ApiError | undefined {\n\tif (err instanceof SchemaExtractionError) {\n\t\treturn err.kind === 'unreachable' || err.kind === 'malformed'\n\t\t\t? new ApiError(503, ApiErrorCode.COMPUTE_UNAVAILABLE, err.message)\n\t\t\t: new ApiError(422, ApiErrorCode.UNPROCESSABLE, err.message);\n\t}\n\tif (err instanceof ComputeServerUnconfiguredError) {\n\t\treturn new ApiError(503, ApiErrorCode.COMPUTE_UNAVAILABLE, err.message);\n\t}\n\tif (err instanceof ProviderError) {\n\t\tconst friendly = friendlyConstraintMessage(err.message);\n\t\treturn new ApiError(err.statusCode, codeForStatus(err.statusCode), friendly ?? err.message);\n\t}\n\treturn undefined;\n}\n","/**\n * The SvelteKit binding for the transport-free handlers in `@selvajs/server/api`.\n *\n * The only file in the app that knows both worlds: it turns a `RequestEvent`\n * into an `ApiRequest` and folds this app's domain errors into the shared\n * envelope. A handler mounted through here names no framework, so the same\n * handler runs under Next or Hono behind a sibling adapter roughly this size.\n */\n\nimport { isHttpError, json, type RequestEvent } from '@sveltejs/kit';\nimport { publicUrl } from '#lib/server/origin.js';\nimport {\n\tApiError,\n\tApiErrorCode,\n\tchargeApiRateLimit,\n\tcodeForStatus,\n\tdepsFromConfig,\n\tmapCoreError,\n\trateLimitedResponse,\n\trunHandler,\n\twithRateLimitHeaders,\n\ttype ApiHandler,\n\ttype ApiRequest,\n\ttype RunHandlerOptions,\n\ttype SelvaDeps\n} from '@selvajs/server/api';\nimport {\n\tgetBranding,\n\tgetDefinitionService,\n\tgetNotificationProvider,\n\tgetOrgAssetService\n} from '../providers.server';\nimport { shareLinkCodec } from '../shareLinks/token.server';\nimport { inviteCodec } from '../invites/token.server';\nimport { apiTokenCodec, apiTokenResolutions } from '../apiTokens/token.server';\nimport { MAX_DEFINITION_FILE_SIZE, MAX_IMAGE_FILE_SIZE } from '../computeLimits';\nimport { evictComputeClient } from '../compute/engine.server';\nimport { serverResolver } from '../compute/serverResolver.server';\nimport { apiRateLimiter } from '../computeRateLimit.server';\nimport { signInMaxAgeMs } from '../signInMaxAge.server';\n\n/**\n * This app's own errors, folded into the shared envelope.\n *\n * SvelteKit's `HttpError` is the only one left here — everything else the v1\n * handlers throw ships from `@selvajs/server`, so `mapCoreError` owns those\n * rules and a second host gets the same statuses without copying them.\n */\nexport function mapAppError(err: unknown): ApiError | undefined {\n\t// Access guards in `access.server.ts` throw SvelteKit's error() and must\n\t// keep doing so — page loads share them and need SvelteKit to render the\n\t// failure. Without this branch every guard 403 falls through to the 500\n\t// fallback, a downgrade no type check catches.\n\tif (isHttpError(err)) {\n\t\t// Guards throw `error(status, 'string')`; `apiError` throws the object\n\t\t// form with `fields` (Zod's per-field detail) — both are live, so this\n\t\t// reads the body rather than just the status.\n\t\tconst body = err.body as\n\t\t\t| {\n\t\t\t\t\tmessage?: string;\n\t\t\t\t\tcode?: ApiErrorCode;\n\t\t\t\t\tfields?: Record<string, string>;\n\t\t\t\t\tdetails?: Record<string, string>;\n\t\t\t }\n\t\t\t| string;\n\t\tif (typeof body === 'string') {\n\t\t\treturn new ApiError(err.status, codeForStatus(err.status), body);\n\t\t}\n\t\treturn new ApiError(\n\t\t\terr.status,\n\t\t\tbody?.code ?? codeForStatus(err.status),\n\t\t\tbody?.message ?? 'Request failed',\n\t\t\tbody?.fields,\n\t\t\tbody?.details\n\t\t);\n\t}\n\treturn mapCoreError(err);\n}\n\n// Providers resolve lazily and memoize, so building deps per request costs a\n// few property reads — no provider is constructed here.\nfunction buildDeps(event: RequestEvent): SelvaDeps {\n\treturn depsFromConfig(\n\t\tevent.locals.providers,\n\t\t{\n\t\t\tdefinitions: getDefinitionService(),\n\t\t\torgAssets: getOrgAssetService()\n\t\t},\n\t\t{\n\t\t\t// Resolved per request, not captured: both codecs re-key on the secret,\n\t\t\t// so a rotated SELVA_HMAC_KEY takes effect without a restart.\n\t\t\ttokens: {\n\t\t\t\tshareLinks: shareLinkCodec(),\n\t\t\t\tinvites: inviteCodec(),\n\t\t\t\tapiTokens: apiTokenCodec(),\n\t\t\t\tsignInMaxAgeMs,\n\t\t\t\tresolutionCache: apiTokenResolutions\n\t\t\t},\n\t\t\t// Passed explicitly — depsFromConfig's defaults would silently ignore\n\t\t\t// this deployment's MAX_*_FILE_SIZE_BYTES.\n\t\t\tuploadLimits: {\n\t\t\t\tmaxDefinitionFileSize: MAX_DEFINITION_FILE_SIZE,\n\t\t\t\tmaxImageFileSize: MAX_IMAGE_FILE_SIZE\n\t\t\t},\n\t\t\t// Cache is keyed on server id; without this a compute-config write\n\t\t\t// leaves a warm client holding a rotated URL or key.\n\t\t\tevictComputeClient,\n\t\t\tonComputeConfigSaved: () => serverResolver.forget(),\n\t\t\tnotifications: getNotificationProvider(),\n\t\t\tinstanceName: getBranding().name,\n\t\t\tapiTokenSettingsPath: '/team/tokens',\n\t\t\t// Module singleton: the limiter must outlive this per-request deps object.\n\t\t\tapiRateLimiter\n\t\t}\n\t);\n}\n\nexport function toApiRequest(event: RequestEvent): ApiRequest {\n\treturn {\n\t\tctx: event.locals.ctx,\n\t\tuser: event.locals.user,\n\t\tprofile: event.locals.profile,\n\t\tlog: event.locals.log,\n\t\tparams: event.params,\n\t\turl: publicUrl(event.url),\n\t\trequest: event.request,\n\t\tdeps: buildDeps(event)\n\t};\n}\n\n/**\n * Mount a transport-free handler as a SvelteKit `RequestHandler`.\n *\n * Routes addressed by a project or definition pass `scopeTarget`, so a key\n * scoped to that project or definition can reach them; solve routes pass\n * `action: 'solve'`; creates pass `idempotent: true`.\n */\nexport function mount(\n\tfallback: string,\n\thandler: ApiHandler,\n\topts: Pick<RunHandlerOptions, 'action' | 'scopeTarget' | 'anyScope' | 'idempotent'> = {}\n) {\n\treturn (event: RequestEvent): Promise<Response> =>\n\t\trunHandler(handler, toApiRequest(event), { fallback, mapError: mapAppError, ...opts });\n}\n\n/**\n * The per-token rate limit for a route that builds its own `Response` instead\n * of going through `mount`: charged before the handler runs, and `RateLimit-*`\n * on every token response, thrown errors included.\n */\nexport function withApiRateLimit<E extends RequestEvent>(\n\thandler: (event: E) => Promise<Response>\n): (event: E) => Promise<Response> {\n\treturn async (event) => {\n\t\tconst verdict = await chargeApiRateLimit(event.locals.ctx, apiRateLimiter);\n\t\tif (verdict && !verdict.allowed) return rateLimitedResponse(verdict);\n\t\ttry {\n\t\t\treturn withRateLimitHeaders(await handler(event), verdict);\n\t\t} catch (err) {\n\t\t\tif (!verdict || !isHttpError(err)) throw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