@selvajs/selva 4.21.0-beta.26 → 4.21.0-beta.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/adapter-node.js +1 -1
- package/build/client/_app/immutable/chunks/BQZN0u9q.js +1 -0
- package/build/client/_app/immutable/chunks/BQZN0u9q.js.br +1 -0
- package/build/client/_app/immutable/chunks/BQZN0u9q.js.gz +0 -0
- package/build/client/_app/immutable/chunks/CLqXGk8r.js +6085 -0
- package/build/client/_app/immutable/chunks/CLqXGk8r.js.br +0 -0
- package/build/client/_app/immutable/chunks/CLqXGk8r.js.gz +0 -0
- package/build/client/_app/immutable/entry/{app.Bqmne5hV.js → app.DrB4p41y.js} +2 -2
- package/build/client/_app/immutable/entry/app.DrB4p41y.js.br +0 -0
- package/build/client/_app/immutable/entry/app.DrB4p41y.js.gz +0 -0
- package/build/client/_app/immutable/nodes/21.SQ-lrVC6.js +1 -0
- package/build/client/_app/immutable/nodes/21.SQ-lrVC6.js.br +0 -0
- package/build/client/_app/immutable/nodes/21.SQ-lrVC6.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/chunks/instance.js +3 -3
- package/build/server/chunks/internal.js +1 -1
- package/build/server/chunks/package.js +1 -1
- package/build/server/chunks/package.js.map +1 -1
- package/build/server/chunks/server.js +1 -0
- package/build/server/chunks/server.js.map +1 -1
- package/build/server/entries/endpoints/mcp/_server.ts.js +0 -1
- package/build/server/entries/endpoints/mcp/_server.ts.js.map +1 -1
- package/build/server/entries/pages/library/_guid_/_page.server.ts.js +9 -4
- package/build/server/entries/pages/library/_guid_/_page.server.ts.js.map +1 -1
- package/build/server/entries/pages/library/_guid_/_page.svelte.js +30 -21
- package/build/server/entries/pages/library/_guid_/_page.svelte.js.map +1 -1
- package/build/server/manifest-full.js +1 -1
- package/build/server/manifest.js +1 -1
- package/build/server/nodes/21.js +1 -1
- package/build/server/server.js +1 -1
- package/package.json +5 -5
- package/build/client/_app/immutable/chunks/BUxAHI7i.js +0 -1
- package/build/client/_app/immutable/chunks/BUxAHI7i.js.br +0 -1
- package/build/client/_app/immutable/chunks/BUxAHI7i.js.gz +0 -0
- package/build/client/_app/immutable/chunks/C4PDTpD1.js +0 -6085
- package/build/client/_app/immutable/chunks/C4PDTpD1.js.br +0 -0
- package/build/client/_app/immutable/chunks/C4PDTpD1.js.gz +0 -0
- package/build/client/_app/immutable/entry/app.Bqmne5hV.js.br +0 -0
- package/build/client/_app/immutable/entry/app.Bqmne5hV.js.gz +0 -0
- package/build/client/_app/immutable/nodes/21.Dv262ba8.js +0 -1
- package/build/client/_app/immutable/nodes/21.Dv262ba8.js.br +0 -1
- package/build/client/_app/immutable/nodes/21.Dv262ba8.js.gz +0 -0
|
@@ -187,13 +187,15 @@ function createDefinitionLoader(deps) {
|
|
|
187
187
|
if (options?.skipComputeDefaults && fresh) return {
|
|
188
188
|
...loaded,
|
|
189
189
|
schema: fresh,
|
|
190
|
-
defaultsPending: false
|
|
190
|
+
defaultsPending: false,
|
|
191
|
+
defaultsReading: false
|
|
191
192
|
};
|
|
192
193
|
const values = version.savedValues ? savedValuesFromRecord(version.savedValues) : savedValues.get(version.id);
|
|
193
194
|
if (fresh && values) return {
|
|
194
195
|
...loaded,
|
|
195
196
|
schema: applySavedValues(fresh, values),
|
|
196
|
-
defaultsPending: false
|
|
197
|
+
defaultsPending: false,
|
|
198
|
+
defaultsReading: false
|
|
197
199
|
};
|
|
198
200
|
const stored = fresh ?? servableStaleSchema(version);
|
|
199
201
|
if (stored) {
|
|
@@ -201,14 +203,16 @@ function createDefinitionLoader(deps) {
|
|
|
201
203
|
return {
|
|
202
204
|
...loaded,
|
|
203
205
|
schema: values ? applySavedValues(stored, values) : stored,
|
|
204
|
-
defaultsPending: !values
|
|
206
|
+
defaultsPending: !values,
|
|
207
|
+
defaultsReading: !values && reads.has(version.id)
|
|
205
208
|
};
|
|
206
209
|
}
|
|
207
210
|
const schema = await withTimeout(read(job), renderWaitMs, () => new DefinitionLoadError("connect", "Rhino.Compute is still reading this definition. Retry in a moment."));
|
|
208
211
|
return {
|
|
209
212
|
...loaded,
|
|
210
213
|
schema,
|
|
211
|
-
defaultsPending: false
|
|
214
|
+
defaultsPending: false,
|
|
215
|
+
defaultsReading: false
|
|
212
216
|
};
|
|
213
217
|
};
|
|
214
218
|
}
|
|
@@ -306,6 +310,7 @@ var load = (async ({ params, locals, request, url, depends }) => {
|
|
|
306
310
|
return {
|
|
307
311
|
schema: loaded.schema,
|
|
308
312
|
defaultsPending: loaded.defaultsPending,
|
|
313
|
+
defaultsReading: loaded.defaultsReading,
|
|
309
314
|
ghDefinition: clientDefUrl,
|
|
310
315
|
currentDefinition: guid,
|
|
311
316
|
serverLabel: loaded.computeServer.label,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"_page.server.ts.js","names":["load"],"sources":["../../../../../../../server/src/definitions/load-for-render.ts","../../../../../../src/lib/saved-values.ts","../../../../../../src/lib/server/definitions/loadForRender.server.ts","../../../../../../src/routes/library/[guid]/+page.server.ts"],"sourcesContent":["// Given a definition record, produces everything the client needs to render its\n// form and solve it.\n//\n// Access gating is deliberately NOT done here — the calling route decides\n// whether `ctx` may load this definition, since gates differ across routes\n// (project membership, segment ownership, share-token, admin override).\n//\n// Everything stateful is injected, so any app on the engine can wire its own\n// composition root.\n//\n// A render never waits on Compute when the version has a stored schema: it serves that and reads\n// Compute behind it. Only a version with nothing renderable stored waits, and not past\n// `renderWaitMs`. A large definition can keep Compute's `/io` busy for longer than a reverse\n// proxy holds a request.\n\nimport type { GrasshopperClient, GrasshopperParsedIO } from '@selvajs/compute/grasshopper';\nimport { UI_SCHEMA_VERSION, type UISchema } from '@selvajs/schemas';\nimport type {\n\tComputeServerConfig,\n\tDefinitionRecord,\n\tDefinitionVersion,\n\tIDefinitionStore,\n\tIProjectStore,\n\tIStorageProvider,\n\tRequestContext\n} from '@selvajs/platform';\nimport { NoopLogger, type ILogger } from '@selvajs/platform';\nimport {\n\tcompareSchemaVersion,\n\tfetchSchemaFromCompute,\n\tisOlderMinorSchemaVersion\n} from './schema-extraction.js';\nimport {\n\tapplySavedValues,\n\tsavedValuesFrom,\n\tsavedValuesFromRecord,\n\tsavedValuesToRecord,\n\ttype SavedValues\n} from './saved-values.js';\nimport { withTimeout } from './with-timeout.js';\n\nexport type DefinitionChannel = 'live' | 'draft';\n\nexport interface LoadedDefinition {\n\tversion: DefinitionVersion;\n\tdefinitionSource: Uint8Array;\n\tcomputeServer: ComputeServerConfig;\n\tschema: UISchema;\n\t/**\n\t * True when `schema` holds the stored defaults because the file's saved values are not read\n\t * yet. A later load carries them once the read behind this one lands.\n\t */\n\tdefaultsPending: boolean;\n}\n\n/**\n * Classified failure modes so callers can map to appropriate HTTP status:\n * - 'data': record references a version/blob that isn't there. (400)\n * - 'missing-config': no compute server resolvable for this org/definition. (503)\n * - 'connect': compute server is unreachable, or too slow to answer. (503)\n * - 'schema': compute responded but IO/schema phase failed. (500)\n */\nexport type DefinitionLoadErrorKind = 'data' | 'missing-config' | 'connect' | 'schema';\n\nexport class DefinitionLoadError extends Error {\n\tconstructor(\n\t\tpublic readonly kind: DefinitionLoadErrorKind,\n\t\tmessage: string,\n\t\tpublic readonly cause?: unknown\n\t) {\n\t\tsuper(message);\n\t\tthis.name = 'DefinitionLoadError';\n\t}\n}\n\nexport interface DefinitionLoaderDeps {\n\tstorage: Pick<IStorageProvider, 'get'>;\n\tdefinitions: Pick<IDefinitionStore, 'getVersion' | 'setVersionSchema' | 'setVersionSavedValues'>;\n\tprojects: Pick<IProjectStore, 'getProject'>;\n\t/** Resolution order: definition pin → org default override → global default. */\n\tresolveServer: (\n\t\tctx: RequestContext,\n\t\torgId: string | null,\n\t\topts: { definitionPin: string | null }\n\t) => Promise<ComputeServerConfig>;\n\t/** Shared warm-client cache, keyed by server id. */\n\tgetClient: (server: ComputeServerConfig) => Promise<{ client: GrasshopperClient }>;\n\t/** Schema extraction; defaults to `fetchSchemaFromCompute`. Injectable for tests. */\n\tfetchSchema?: (bytes: Uint8Array, server: ComputeServerConfig) => Promise<UISchema>;\n\t/**\n\t * Longest a load waits on Compute for a version with no renderable stored schema, before it\n\t * fails as 'connect'. Keep it under the reverse proxy's timeout, or the proxy answers 504\n\t * first. Default `DEFAULT_RENDER_WAIT_MS`.\n\t */\n\trenderWaitMs?: number;\n\t/**\n\t * When set, an unhealthy IO result also dumps the raw /io wire shape, making\n\t * casing/serialization mismatches visible.\n\t */\n\tcomputeDebug?: boolean;\n\t/** Legacy diagnostic sink. When set it takes the warnings below instead of `logger`. */\n\tonWarn?: (message: string, detail?: string) => void;\n\t/**\n\t * Defaults to `NoopLogger`, so a consumer that wires nothing gets silence\n\t * rather than unsolicited stdout.\n\t */\n\tlogger?: ILogger;\n}\n\nexport interface DefinitionLoadOptions {\n\t/**\n\t * For callers that read only schema STRUCTURE (input ids, `source.key`,\n\t * widget types — anything persisted at upload). A fresh stored schema is then\n\t * returned as stored, and Compute is not read for it, not even in the\n\t * background: a page resolving several definitions would otherwise send each\n\t * file to Compute.\n\t */\n\tskipComputeDefaults?: boolean;\n}\n\nexport type DefinitionLoader = (\n\tctx: RequestContext,\n\trecord: DefinitionRecord,\n\tchannel: DefinitionChannel,\n\texplicitVersionId?: string | null,\n\toptions?: DefinitionLoadOptions\n) => Promise<LoadedDefinition>;\n\ninterface ComputeRead {\n\tctx: RequestContext;\n\trecord: DefinitionRecord;\n\tversion: DefinitionVersion;\n\tsource: Uint8Array;\n\tserver: ComputeServerConfig;\n}\n\n/**\n * The returned loader resolves the `channel` pointer (live/draft) by default.\n * `explicitVersionId` renders an arbitrary historical version instead — the\n * caller MUST gate that behind edit permission, as with the draft channel.\n */\nexport function createDefinitionLoader(deps: DefinitionLoaderDeps): DefinitionLoader {\n\tconst {\n\t\tstorage,\n\t\tdefinitions,\n\t\tprojects,\n\t\tresolveServer,\n\t\tgetClient,\n\t\tfetchSchema = fetchSchemaFromCompute,\n\t\trenderWaitMs = DEFAULT_RENDER_WAIT_MS,\n\t\tcomputeDebug = false,\n\t\tonWarn,\n\t\tlogger = new NoopLogger()\n\t} = deps;\n\n\t// Schemas extracted because the row had none usable, keyed by version id. The row write may\n\t// never land: a viewer or share-link context may not be able to write it (Supabase RLS turns\n\t// the UPDATE into a silent 0-row success), and then every load would call Compute. An older\n\t// format expires after `OLDER_SCHEMA_RECHECK_MS`.\n\tconst extracts = new Map<string, { schema: UISchema; extractedAt: string }>();\n\t// Read from Compute for a version stored without them, once per process: a context that\n\t// cannot write the row still needs them.\n\tconst savedValues = new Map<string, SavedValues>();\n\t// One Compute read per version at a time; loads arriving meanwhile share it.\n\tconst reads = new Map<string, Promise<UISchema>>();\n\t// When a version's last read failed, so a broken Compute isn't sent the file on every load.\n\tconst failedAt = new Map<string, number>();\n\n\tfunction warn(message: string, title: string, fields: Record<string, unknown>) {\n\t\tif (onWarn) onWarn(message);\n\t\telse logger.warn(title, { component: 'loadForRender', ...fields });\n\t}\n\n\tfunction cachedSchemaFor(version: DefinitionVersion): UISchema | null {\n\t\tconst row = version.schema as UISchema | undefined;\n\t\tif (row && isUsableCachedSchema(row, version.schemaExtractedAt)) return row;\n\t\tconst memo = extracts.get(version.id);\n\t\tif (!memo) return null;\n\t\tif (isUsableCachedSchema(memo.schema, memo.extractedAt)) return memo.schema;\n\t\textracts.delete(version.id);\n\t\treturn null;\n\t}\n\n\tasync function readFromCompute({\n\t\tctx,\n\t\trecord,\n\t\tversion,\n\t\tsource,\n\t\tserver\n\t}: ComputeRead): Promise<UISchema> {\n\t\tlet client: GrasshopperClient;\n\t\ttry {\n\t\t\tclient = (await getClient(server)).client;\n\t\t} catch (err) {\n\t\t\tthrow new DefinitionLoadError(\n\t\t\t\t'connect',\n\t\t\t\t`Failed to connect to Rhino Compute server: ${messageOf(err)}`,\n\t\t\t\terr\n\t\t\t);\n\t\t}\n\n\t\ttry {\n\t\t\t// The stored schema is a disposable cache (`isUsableCachedSchema`). Past it\n\t\t\t// (or on a pre-caching row with no schema) re-extract from compute, whose C#\n\t\t\t// SchemaMigrator emits its plugin's format — the web side never migrates\n\t\t\t// schemas itself.\n\t\t\tconst fresh = cachedSchemaFor(version);\n\t\t\tconst [io, extracted] = await Promise.all([\n\t\t\t\tclient.getIO(source),\n\t\t\t\tfresh ? Promise.resolve(fresh) : fetchSchema(source, server)\n\t\t\t]);\n\t\t\tif (!io) throw new Error(`Failed to get definition IO — server returned undefined`);\n\t\t\tassertHasInputs(extracted);\n\t\t\tawait reportUnhealthyIO(record, io, () => client.getRawIO(source));\n\n\t\t\tconst values = savedValuesFrom(io.inputs);\n\t\t\tsetBounded(savedValues, version.id, values);\n\t\t\t// Not an empty read: Compute may be missing a plugin, and a stored `{}` is never re-read.\n\t\t\tif (!version.savedValues && values.size > 0) persistSavedValues(ctx, version.id, values);\n\t\t\tconst schema = applySavedValues(extracted, values);\n\n\t\t\t// An older format (compute plugin behind the app) is warned about once per window, so\n\t\t\t// it costs one Compute call per instance per window.\n\t\t\tconst extractedAt = new Date().toISOString();\n\t\t\tif (!fresh) setBounded(extracts, version.id, { schema: extracted, extractedAt });\n\t\t\tif (!fresh && compareSchemaVersion(extracted.schemaVersion) === -1) {\n\t\t\t\twarn(\n\t\t\t\t\t`[loadForRender] compute's plugin emits schema format ${extracted.schemaVersion ?? '(none)'} ` +\n\t\t\t\t\t\t`for version ${version.id}, behind this app's ${UI_SCHEMA_VERSION}; serving it for ` +\n\t\t\t\t\t\t`${OLDER_SCHEMA_RECHECK_MS / 3_600_000} h before asking again. Update the plugin.`,\n\t\t\t\t\t'Compute plugin behind the app schema format',\n\t\t\t\t\t{ versionId: version.id, emitted: extracted.schemaVersion, expected: UI_SCHEMA_VERSION }\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst row = version.schema as UISchema | undefined;\n\t\t\tconst rowCurrent = fresh !== null && row !== undefined && sameDefaults(row, schema);\n\t\t\tif (!rowCurrent && isUsableCachedSchema(schema, extractedAt))\n\t\t\t\tpersist(ctx, version.id, schema);\n\t\t\treturn schema;\n\t\t} catch (err) {\n\t\t\tif (err instanceof DefinitionLoadError) throw err;\n\t\t\tthrow new DefinitionLoadError('schema', messageOf(err), err);\n\t\t}\n\t}\n\n\t// Best-effort — a viewer context may lack write access, and the next editor render or the\n\t// solve-time backfill will land it. Stores exactly what a read right after the write would\n\t// serve, so the two rules cannot drift.\n\tfunction persist(ctx: RequestContext, versionId: string, schema: UISchema) {\n\t\tdefinitions.setVersionSchema(ctx, versionId, schema).catch((err) => {\n\t\t\twarn(\n\t\t\t\t`[loadForRender] schema cache refresh failed for version ${versionId}: ${messageOf(err)}`,\n\t\t\t\t'Schema cache refresh failed',\n\t\t\t\t{ versionId, err: err instanceof Error ? (err.stack ?? err.message) : String(err) }\n\t\t\t);\n\t\t});\n\t}\n\n\t// Best-effort, like `persist`: the next load reads them from Compute again.\n\tfunction persistSavedValues(ctx: RequestContext, versionId: string, values: SavedValues) {\n\t\tdefinitions.setVersionSavedValues(ctx, versionId, savedValuesToRecord(values)).catch((err) => {\n\t\t\twarn(\n\t\t\t\t`[loadForRender] saved values write failed for version ${versionId}: ${messageOf(err)}`,\n\t\t\t\t'Saved values write failed',\n\t\t\t\t{ versionId, err: err instanceof Error ? (err.stack ?? err.message) : String(err) }\n\t\t\t);\n\t\t});\n\t}\n\n\t// Zero inputs or reported parse/load problems mean a definition that will\n\t// render wrong without saying why: an empty ValueList whose backing GH\n\t// component didn't resolve (\"Missing Definition Objects\"), or a PascalCase\n\t// /io response the parser silently dropped to []. Warning is always on —\n\t// it only fires on the unhappy path — while the raw wire dump costs an\n\t// extra round-trip and stays behind `computeDebug`.\n\tasync function reportUnhealthyIO(\n\t\trecord: DefinitionRecord,\n\t\tio: GrasshopperParsedIO,\n\t\treadRawIO: () => Promise<unknown>\n\t) {\n\t\tconst parseErrors = (io as { parseErrors?: unknown[] }).parseErrors ?? [];\n\t\tconst loadErrors = (io as { loadErrors?: unknown[] }).loadErrors ?? [];\n\t\tif (io.inputs.length > 0 && parseErrors.length === 0 && loadErrors.length === 0) return;\n\n\t\tconst health = {\n\t\t\tinputCount: io.inputs.length,\n\t\t\toutputCount: io.outputs?.length,\n\t\t\tparseErrors,\n\t\t\tloadErrors,\n\t\t\tloadWarnings: (io as { loadWarnings?: unknown }).loadWarnings\n\t\t};\n\t\tif (onWarn) onWarn(`[loadForRender] IO health for '${record.guid}':`, JSON.stringify(health));\n\t\telse\n\t\t\tlogger.warn('Definition IO looks unhealthy', {\n\t\t\t\tcomponent: 'loadForRender',\n\t\t\t\tdefinitionGuid: record.guid,\n\t\t\t\t...health\n\t\t\t});\n\n\t\tif (!computeDebug) return;\n\t\tconst rawIO = await readRawIO().catch((e) => ({ error: String(e) }));\n\t\tconst rendered = JSON.stringify(rawIO).slice(0, 3000);\n\t\tif (onWarn) onWarn('[loadForRender] raw /io:', rendered);\n\t\telse\n\t\t\tlogger.debug('Raw /io wire shape', {\n\t\t\t\tcomponent: 'loadForRender',\n\t\t\t\tdefinitionGuid: record.guid,\n\t\t\t\trawIO: rendered\n\t\t\t});\n\t}\n\n\tfunction read(job: ComputeRead): Promise<UISchema> {\n\t\tconst id = job.version.id;\n\t\tconst running = reads.get(id);\n\t\tif (running) return running;\n\n\t\tconst pending = withTimeout(\n\t\t\treadFromCompute(job),\n\t\t\tCOMPUTE_READ_TIMEOUT_MS,\n\t\t\t() =>\n\t\t\t\tnew DefinitionLoadError(\n\t\t\t\t\t'connect',\n\t\t\t\t\t`Rhino.Compute did not finish reading this definition within ${COMPUTE_READ_TIMEOUT_MS / 1000} s`\n\t\t\t\t)\n\t\t)\n\t\t\t.then(\n\t\t\t\t(schema) => {\n\t\t\t\t\tfailedAt.delete(id);\n\t\t\t\t\treturn schema;\n\t\t\t\t},\n\t\t\t\t(err) => {\n\t\t\t\t\tsetBounded(failedAt, id, Date.now());\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t)\n\t\t\t.finally(() => reads.delete(id));\n\t\treads.set(id, pending);\n\t\treturn pending;\n\t}\n\n\tfunction readInBackground(job: ComputeRead) {\n\t\tconst id = job.version.id;\n\t\tif (reads.has(id)) return;\n\t\tconst failed = failedAt.get(id);\n\t\tif (failed !== undefined && Date.now() - failed < READ_RETRY_MS) return;\n\n\t\tread(job).catch((err) => {\n\t\t\twarn(\n\t\t\t\t`[loadForRender] background read failed for version ${id}: ${messageOf(err)}`,\n\t\t\t\t'Background definition read failed',\n\t\t\t\t{ versionId: id, definitionGuid: job.record.guid, err: messageOf(err) }\n\t\t\t);\n\t\t});\n\t}\n\n\treturn async function loadDefinitionForRender(ctx, record, channel, explicitVersionId, options) {\n\t\tconst versionId =\n\t\t\texplicitVersionId ?? (channel === 'draft' ? record.draftVersionId : record.liveVersionId);\n\t\tif (!versionId)\n\t\t\tthrow new DefinitionLoadError(\n\t\t\t\t'data',\n\t\t\t\t`Definition '${record.guid}' has no ${channel} version`\n\t\t\t);\n\n\t\t// The server needs only the record, so it resolves while the version and file are read.\n\t\t// It is awaited after them, so a definition missing its data still fails as 'data'.\n\t\tconst pendingServer = (async (): Promise<ComputeServerConfig> => {\n\t\t\tconst project = await projects.getProject(ctx, record.projectId);\n\t\t\ttry {\n\t\t\t\treturn await resolveServer(ctx, project?.orgId ?? null, {\n\t\t\t\t\tdefinitionPin: record.computeServerId ?? null\n\t\t\t\t});\n\t\t\t} catch (err) {\n\t\t\t\tthrow new DefinitionLoadError(\n\t\t\t\t\t'missing-config',\n\t\t\t\t\t'No compute server configured for this definition',\n\t\t\t\t\terr\n\t\t\t\t);\n\t\t\t}\n\t\t})();\n\t\tpendingServer.catch(() => {});\n\n\t\tconst version = await definitions.getVersion(ctx, versionId);\n\t\tif (!version) throw new DefinitionLoadError('data', `version missing for '${record.guid}'`);\n\t\t// An explicitly requested version must belong to this definition.\n\t\tif (version.definitionId !== record.guid)\n\t\t\tthrow new DefinitionLoadError('data', `version does not belong to '${record.guid}'`);\n\n\t\tconst definitionSource = await storage.get(version.fileKey);\n\t\tif (!definitionSource)\n\t\t\tthrow new DefinitionLoadError(\n\t\t\t\t'data',\n\t\t\t\t`Definition file for '${record.guid}' not found on disk`\n\t\t\t);\n\n\t\tconst computeServer = await pendingServer;\n\t\tconst loaded = { version, definitionSource, computeServer };\n\t\tconst job: ComputeRead = {\n\t\t\tctx,\n\t\t\trecord,\n\t\t\tversion,\n\t\t\tsource: definitionSource,\n\t\t\tserver: computeServer\n\t\t};\n\n\t\tconst fresh = cachedSchemaFor(version);\n\t\tif (options?.skipComputeDefaults && fresh)\n\t\t\treturn { ...loaded, schema: fresh, defaultsPending: false };\n\n\t\tconst values = version.savedValues\n\t\t\t? savedValuesFromRecord(version.savedValues)\n\t\t\t: savedValues.get(version.id);\n\t\tif (fresh && values)\n\t\t\treturn { ...loaded, schema: applySavedValues(fresh, values), defaultsPending: false };\n\n\t\t// An older format past its recheck window still renders: serve it while Compute is asked.\n\t\tconst stored = fresh ?? servableStaleSchema(version);\n\t\tif (stored) {\n\t\t\treadInBackground(job);\n\t\t\treturn {\n\t\t\t\t...loaded,\n\t\t\t\tschema: values ? applySavedValues(stored, values) : stored,\n\t\t\t\tdefaultsPending: !values\n\t\t\t};\n\t\t}\n\n\t\t// The read carries on past the wait, so a retry finds it done.\n\t\tconst schema = await withTimeout(\n\t\t\tread(job),\n\t\t\trenderWaitMs,\n\t\t\t() =>\n\t\t\t\tnew DefinitionLoadError(\n\t\t\t\t\t'connect',\n\t\t\t\t\t'Rhino.Compute is still reading this definition. Retry in a moment.'\n\t\t\t\t)\n\t\t);\n\t\treturn { ...loaded, schema, defaultsPending: false };\n\t};\n}\n\n/**\n * How long a schema in an OLDER format serves from the cache before Compute is asked again. A\n * plugin behind the app re-emits that same format, so asking on every load only buys a Compute\n * round trip (10 s+ while a child starts); the window bounds how long a plugin upgrade waits.\n */\nexport const OLDER_SCHEMA_RECHECK_MS = 24 * 60 * 60 * 1000;\n\n/** Under nginx's default 60 s and the 30 s many load balancers use. */\nexport const DEFAULT_RENDER_WAIT_MS = 20_000;\n\n// Frees the per-version read slot when Compute hangs; the load waiting on it gave up long before.\nconst COMPUTE_READ_TIMEOUT_MS = 120_000;\n\n// After a failed read, background reads of that version pause this long.\nconst READ_RETRY_MS = 60_000;\n\n// Bounds each in-process memo; the oldest entry is evicted first.\nconst MEMO_MAX = 1000;\n\nfunction setBounded<V>(map: Map<string, V>, key: string, value: V) {\n\tif (map.size >= MEMO_MAX && !map.has(key)) map.delete(map.keys().next().value!);\n\tmap.set(key, value);\n}\n\n/**\n * A cached schema is usable when it is structurally sound and either the current format version,\n * an older minor of the current major (`isOlderMinorSchemaVersion`), or an older major (missing\n * counts, see `compareSchemaVersion`) extracted within `OLDER_SCHEMA_RECHECK_MS` of `now`,\n * either side: a future stamp from a skewed clock still expires. Without `extractedAt` an older\n * major never passes. The `inputs` check is the\n * PascalCase guard: a compute server that serialized with the wrong Newtonsoft emits `Inputs`, and\n * such a row must never be served. See `assertCamelCaseSchema`.\n */\nexport function isUsableCachedSchema(\n\tschema: UISchema,\n\textractedAt?: string,\n\tnow: number = Date.now()\n): boolean {\n\tif (!Array.isArray(schema.inputs)) return false;\n\tconst order = compareSchemaVersion(schema.schemaVersion);\n\tif (order === 0 || isOlderMinorSchemaVersion(schema.schemaVersion)) return true;\n\tif (order !== -1 || !extractedAt) return false;\n\tconst at = Date.parse(extractedAt);\n\treturn Number.isFinite(at) && Math.abs(now - at) < OLDER_SCHEMA_RECHECK_MS;\n}\n\n/** A stored older-format schema past its recheck window. Newer and PascalCase rows never render. */\nfunction servableStaleSchema(version: DefinitionVersion): UISchema | null {\n\tconst row = version.schema as UISchema | undefined;\n\tif (!row || !Array.isArray(row.inputs)) return null;\n\treturn compareSchemaVersion(row.schemaVersion) === -1 ? row : null;\n}\n\nfunction assertHasInputs(schema: UISchema) {\n\tif (Array.isArray(schema.inputs)) return;\n\tthrow new DefinitionLoadError(\n\t\t'schema',\n\t\t`Schema has no 'inputs' array (keys: ${Object.keys(schema as object)\n\t\t\t.slice(0, 12)\n\t\t\t.join(', ')}). A PascalCase shape here means compute serialized it with the wrong ` +\n\t\t\t`Newtonsoft — see assertCamelCaseSchema.`\n\t);\n}\n\nfunction sameDefaults(a: UISchema, b: UISchema): boolean {\n\tconst defaults = (schema: UISchema) =>\n\t\tJSON.stringify(schema.inputs.map((input) => input.default));\n\treturn Array.isArray(a.inputs) && defaults(a) === defaults(b);\n}\n\nfunction messageOf(err: unknown): string {\n\treturn err instanceof Error ? err.message : String(err);\n}\n","// A definition page renders before Compute has read the values saved in the file, so its form can\n// start from the stored defaults. The page repeats its load until the saved values are in the\n// schema, then puts them into the inputs the user has not changed.\n\nimport { getDefaultValue, type UISchema } from '@selvajs/schemas';\n\n/** What the definition page's load `depends` on, and the page invalidates to repeat it. */\nexport const SAVED_VALUES_DEPENDENCY = 'selva:saved-values';\n\n/**\n * Waits between repeated loads, about two minutes in all: the server gives a Compute read that\n * long before dropping it.\n */\nexport const SAVED_VALUES_RECHECK_MS = [2_000, 4_000, 8_000, 15_000, 30_000, 30_000, 30_000];\n\n/**\n * The saved values to load into a form built from `before`, now that `after` carries them: each\n * input whose default changed and whose value is still the one the form started with. An input\n * the user edited keeps its value, and so does a client-sourced input the form left empty.\n */\nexport function lateSavedValues(\n\tbefore: UISchema,\n\tafter: UISchema,\n\tcurrent: Readonly<Record<string, unknown>>\n): Record<string, unknown> {\n\tconst stored = new Map(before.inputs.map((input) => [input.id, input]));\n\tconst late: Record<string, unknown> = {};\n\tfor (const input of after.inputs) {\n\t\tconst old = stored.get(input.id);\n\t\tif (!old || !(input.id in current)) continue;\n\t\tif (input.default === undefined || same(input.default, old.default)) continue;\n\t\t// How the solve session built the value it started with.\n\t\tconst initial = old.default ?? getDefaultValue(old.paramType);\n\t\tif (same(current[input.id], initial)) late[input.id] = input.default;\n\t}\n\treturn late;\n}\n\nfunction same(a: unknown, b: unknown): boolean {\n\treturn JSON.stringify(a) === JSON.stringify(b);\n}\n","// `@selvajs/server/definitions` owns the loading pipeline (version resolution,\n// blob fetch, schema staleness check, default merging); this wires in the\n// app's providers, compute-server resolution, and warm-client cache. Access\n// gating stays with the calling route.\n\nimport {\n\tcreateDefinitionLoader,\n\tDefinitionLoadError,\n\ttype DefinitionChannel,\n\ttype DefinitionLoadErrorKind,\n\ttype LoadedDefinition\n} from '@selvajs/server/definitions';\nimport type { DefinitionRecord, RequestContext } from '@selvajs/platform';\nimport {\n\tgetStorageProvider,\n\tgetDefinitionMeta,\n\tgetProjectProvider,\n\tgetComputeServerConfigStore\n} from '../providers.server';\nimport { serverResolver } from '../compute/serverResolver.server';\nimport { getClient, COMPUTE_DEBUG } from '../compute/engine.server';\n\nexport { DefinitionLoadError };\nexport type { DefinitionChannel, DefinitionLoadErrorKind, LoadedDefinition };\n\n// One loader for the process. It keeps the saved values it read, the Compute read that loads\n// share and the pause after a failed read, so a loader per request sends the file to Compute on\n// every page load and never serves what came back. Providers are looked up per call.\nconst load = createDefinitionLoader({\n\tstorage: { get: (key) => getStorageProvider().get(key) },\n\tdefinitions: {\n\t\tgetVersion: (ctx, versionId) => getDefinitionMeta().getVersion(ctx, versionId),\n\t\tsetVersionSchema: (ctx, versionId, schema) =>\n\t\t\tgetDefinitionMeta().setVersionSchema(ctx, versionId, schema),\n\t\tsetVersionSavedValues: (ctx, versionId, values) =>\n\t\t\tgetDefinitionMeta().setVersionSavedValues(ctx, versionId, values)\n\t},\n\tprojects: { getProject: (ctx, projectId) => getProjectProvider().getProject(ctx, projectId) },\n\tresolveServer: (ctx, orgId, opts) =>\n\t\tserverResolver.resolve(ctx, orgId, getComputeServerConfigStore(), opts),\n\tgetClient,\n\tcomputeDebug: COMPUTE_DEBUG\n});\n\nexport function loadDefinitionForRender(\n\tctx: RequestContext,\n\trecord: DefinitionRecord,\n\tchannel: DefinitionChannel,\n\texplicitVersionId?: string | null\n): Promise<LoadedDefinition> {\n\treturn load(ctx, record, channel, explicitVersionId);\n}\n","import type { PageServerLoad } from './$types';\nimport { error } from '@sveltejs/kit';\nimport type { ILogger, RequestContext } from '@selvajs/platform';\nimport { renderThrown } from '@selvajs/server/logging';\nimport {\n\tgetDefinitionMeta,\n\tgetProjectProvider,\n\tgetOrganizationProvider\n} from '#lib/server/providers.server.js';\nimport { isApiError } from '@selvajs/server/api';\nimport { asHttpError, requireCanSolve, scoped } from '#lib/server/access.server.js';\nimport { readShareToken, tryResolveShareToken } from '#lib/server/shareLinks/resolve.server.js';\nimport { solveDeadlineFor } from '#lib/server/compute/engine.server.js';\nimport { SAVED_VALUES_DEPENDENCY } from '#lib/saved-values.js';\nimport {\n\tloadDefinitionForRender,\n\tDefinitionLoadError\n} from '#lib/server/definitions/loadForRender.server.js';\n\nexport const load = (async ({ params, locals, request, url, depends }) => {\n\tdepends(SAVED_VALUES_DEPENDENCY);\n\tconst meta = getDefinitionMeta();\n\n\tconst guid = params.guid;\n\tconst channel = url.searchParams.get('channel') === 'draft' ? 'draft' : 'live';\n\t// Explicit version pick (versioning tab \"Run\"): render an arbitrary version,\n\t// not just the live/draft pointer. Editor-only, never share-token accessible.\n\tconst explicitVersionId = url.searchParams.get('version');\n\tconst clientDefUrl = `local:${guid}`;\n\t// `shareToken` is forwarded to the page so the client can include it on\n\t// subsequent /api/compute/solve calls. null = user-authenticated session.\n\tlet shareToken: string | null = null;\n\n\ttry {\n\t\t// Draft channel and explicit-version picks are editor-only — share tokens\n\t\t// are always live channel on the pointer. A signed-in viewer who can solve\n\t\t// anyway ignores the token: a share-token solve gets no live events and\n\t\t// counts against the link's solve cap.\n\t\tconst sharedAccess =\n\t\t\tchannel === 'live' &&\n\t\t\t!explicitVersionId &&\n\t\t\treadShareToken(request, url) !== null &&\n\t\t\t!(await sessionCanSolve(locals, guid))\n\t\t\t\t? await tryResolveShareToken(request, url, guid, 'live', { requireSolve: false })\n\t\t\t\t: null;\n\t\tif (sharedAccess) {\n\t\t\tshareToken = url.searchParams.get('token');\n\t\t} else if (!locals.ctx || !locals.user) {\n\t\t\tthrow error(401, 'Unauthorized: You must be logged in to access definitions');\n\t\t}\n\n\t\tconst ctx: RequestContext = sharedAccess?.ctx ?? locals.ctx!;\n\n\t\tconst record = await meta.get(ctx, guid);\n\t\tif (!record) throw new Error(`Definition '${guid}' not found`);\n\n\t\t// User-auth path needs the canSolve gate; token-auth was already gated.\n\t\tif (!sharedAccess) await asHttpError(() => requireCanSolve(scoped(locals), record.projectId));\n\n\t\t// Draft channel and explicit-version picks require edit permission on top\n\t\t// of solve.\n\t\tif (channel === 'draft' || explicitVersionId) {\n\t\t\tconst { requireEditableDefinition } = await import('#lib/server/access.server.js');\n\t\t\tawait asHttpError(() => requireEditableDefinition(scoped(locals), guid));\n\t\t}\n\n\t\t// Owning org's logo, for viewer branding, read beside the definition load. Same\n\t\t// `ctx` already authorized to load this definition (user session or share-token\n\t\t// ctx, which carries actingOrgId). Best-effort: a missing project/org or read\n\t\t// failure just yields no logo — branding is non-essential and must never break a solve.\n\t\tconst [loaded, orgLogoUrl] = await Promise.all([\n\t\t\tloadDefinitionForRender(ctx, record, channel, explicitVersionId),\n\t\t\tresolveOrgLogo(ctx, record.projectId, locals.log)\n\t\t]);\n\n\t\tconst solveDeadlineMs = await solveDeadlineFor(loaded.computeServer);\n\n\t\treturn {\n\t\t\tschema: loaded.schema,\n\t\t\t// The page repeats this load until the file's saved values are in `schema`.\n\t\t\tdefaultsPending: loaded.defaultsPending,\n\t\t\tghDefinition: clientDefUrl,\n\t\t\tcurrentDefinition: guid,\n\t\t\tserverLabel: loaded.computeServer.label,\n\t\t\torgLogoUrl,\n\t\t\tchannel,\n\t\t\t// When rendering an explicit version, forward its id (so solve calls\n\t\t\t// target the same version) and number (for the preview badge).\n\t\t\tversionId: explicitVersionId,\n\t\t\tversionNumber: loaded.version.versionNumber,\n\t\t\t// Forward to the client so /api/compute/solve calls can include it.\n\t\t\t// Null when the request was user-authenticated (session cookie carries auth).\n\t\t\tshareToken,\n\t\t\t// The deadline this definition's compute server sets, so the browser's\n\t\t\t// AbortController doesn't stop a solve the server would still finish.\n\t\t\tsolveDeadlineMs\n\t\t};\n\t} catch (err) {\n\t\t// Let HttpError (from error() calls) bubble up.\n\t\tif (err instanceof Error && 'status' in err) throw err;\n\n\t\t// Translate classified load errors to the same HTTP statuses the route\n\t\t// used pre-extraction:\n\t\t// missing-config | connect → 503 (operator action needed)\n\t\t// schema → 500 (compute responded but IO/schema failed)\n\t\t// data → 400 (definition references missing version/blob)\n\t\tif (err instanceof DefinitionLoadError) {\n\t\t\tif (err.kind === 'missing-config') {\n\t\t\t\tthrow error(\n\t\t\t\t\t503,\n\t\t\t\t\t'No compute server configured. Ask an admin to add one in /admin/compute.'\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (err.kind === 'connect') {\n\t\t\t\tlocals.log.error('Compute server connection failed', {\n\t\t\t\t\tcomponent: 'PageLoad',\n\t\t\t\t\tguid,\n\t\t\t\t\terr: renderThrown(err)\n\t\t\t\t});\n\t\t\t\tthrow error(503, err.message);\n\t\t\t}\n\t\t\tif (err.kind === 'schema') {\n\t\t\t\tlocals.log.error('Definition loading failed', {\n\t\t\t\t\tcomponent: 'PageLoad',\n\t\t\t\t\tguid,\n\t\t\t\t\terr: renderThrown(err)\n\t\t\t\t});\n\n\t\t\t\tif (process.env.NODE_ENV === 'development') {\n\t\t\t\t\tconst hint = `\\n\\nTroubleshooting:\\n1. Check /api/health/compute to diagnose server connectivity\\n2. Check the browser console for more details`;\n\t\t\t\t\tthrow error(500, `Failed to load definition from ${clientDefUrl}: ${err.message}${hint}`);\n\t\t\t\t}\n\t\t\t\tthrow error(500, `Failed to load definition: ${err.message}`);\n\t\t\t}\n\t\t\t// kind === 'data' falls through to the 400 wrap below.\n\t\t}\n\n\t\tif (err instanceof Error) {\n\t\t\tlocals.log.warn('Failed to load definition', {\n\t\t\t\tcomponent: 'App Load',\n\t\t\t\tguid,\n\t\t\t\terr: renderThrown(err)\n\t\t\t});\n\t\t\tthrow error(400, `Failed to load definition '${guid}': ${err.message}`);\n\t\t}\n\t\tthrow err;\n\t}\n}) satisfies PageServerLoad;\n\nasync function sessionCanSolve(locals: App.Locals, guid: string): Promise<boolean> {\n\tif (!locals.ctx || !locals.user) return false;\n\tconst record = await getDefinitionMeta().get(locals.ctx, guid);\n\tif (!record) return false;\n\ttry {\n\t\tawait requireCanSolve(scoped(locals), record.projectId);\n\t\treturn true;\n\t} catch (err) {\n\t\tif (isApiError(err)) return false;\n\t\tthrow err;\n\t}\n}\n\n/**\n * Resolve the owning org's logo URL for viewer branding. definition → project →\n * org. Best-effort and self-contained: any miss or read error returns null so a\n * branding lookup can never fail the render path.\n */\nasync function resolveOrgLogo(\n\tctx: RequestContext,\n\tprojectId: string,\n\tlog: ILogger\n): Promise<string | null> {\n\ttry {\n\t\tconst project = await getProjectProvider().getProject(ctx, projectId);\n\t\tif (!project?.orgId) return null;\n\t\tconst org = await getOrganizationProvider().getOrg(ctx, project.orgId);\n\t\treturn org?.assets?.logo ?? null;\n\t} catch (err) {\n\t\tlog.warn('Failed to resolve org logo', {\n\t\t\tcomponent: 'App Load',\n\t\t\tprojectId,\n\t\t\terr: renderThrown(err)\n\t\t});\n\t\treturn null;\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;AAgEA,IAAa,sBAAb,cAAyC,MAAM;CAE7B;CAEA;CAHjB,YACC,MACA,SACA,OACC;EACD,MAAM,OAAO;EAJG,KAAA,OAAA;EAEA,KAAA,QAAA;EAGhB,KAAK,OAAO;CACb;AACD;;;;;;AAoEA,SAAgB,uBAAuB,MAA8C;CACpF,MAAM,EACL,SACA,aACA,UACA,eACA,WACA,cAAc,wBACd,eAAe,wBACf,eAAe,OACf,QACA,SAAS,IAAI,WAAW,MACrB;CAMJ,MAAM,2BAAW,IAAI,IAAuD;CAG5E,MAAM,8BAAc,IAAI,IAAyB;CAEjD,MAAM,wBAAQ,IAAI,IAA+B;CAEjD,MAAM,2BAAW,IAAI,IAAoB;CAEzC,SAAS,KAAK,SAAiB,OAAe,QAAiC;EAC9E,IAAI,Q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AAO;EAC5B,MAAM;CACP;AACD;;;;;;AAOA,eAAe,eACd,KACA,WACA,KACyB;CACzB,IAAI;EACH,MAAM,UAAU,MAAM,mBAAmB,CAAC,CAAC,WAAW,KAAK,SAAS;EACpE,IAAI,CAAC,SAAS,OAAO,OAAO;EAE5B,QAAO,MADW,wBAAwB,CAAC,CAAC,OAAO,KAAK,QAAQ,KAAK,EAAA,EACzD,QAAQ,QAAQ;CAC7B,SAAS,KAAK;EACb,IAAI,KAAK,8BAA8B;GACtC,WAAW;GACX;GACA,KAAK,aAAa,GAAG;EACtB,CAAC;EACD,OAAO;CACR;AACD"}
|
|
1
|
+
{"version":3,"file":"_page.server.ts.js","names":["load"],"sources":["../../../../../../../server/src/definitions/load-for-render.ts","../../../../../../src/lib/saved-values.ts","../../../../../../src/lib/server/definitions/loadForRender.server.ts","../../../../../../src/routes/library/[guid]/+page.server.ts"],"sourcesContent":["// Given a definition record, produces everything the client needs to render its\n// form and solve it.\n//\n// Access gating is deliberately NOT done here — the calling route decides\n// whether `ctx` may load this definition, since gates differ across routes\n// (project membership, segment ownership, share-token, admin override).\n//\n// Everything stateful is injected, so any app on the engine can wire its own\n// composition root.\n//\n// A render never waits on Compute when the version has a stored schema: it serves that and reads\n// Compute behind it. Only a version with nothing renderable stored waits, and not past\n// `renderWaitMs`. A large definition can keep Compute's `/io` busy for longer than a reverse\n// proxy holds a request.\n\nimport type { GrasshopperClient, GrasshopperParsedIO } from '@selvajs/compute/grasshopper';\nimport { UI_SCHEMA_VERSION, type UISchema } from '@selvajs/schemas';\nimport type {\n\tComputeServerConfig,\n\tDefinitionRecord,\n\tDefinitionVersion,\n\tIDefinitionStore,\n\tIProjectStore,\n\tIStorageProvider,\n\tRequestContext\n} from '@selvajs/platform';\nimport { NoopLogger, type ILogger } from '@selvajs/platform';\nimport {\n\tcompareSchemaVersion,\n\tfetchSchemaFromCompute,\n\tisOlderMinorSchemaVersion\n} from './schema-extraction.js';\nimport {\n\tapplySavedValues,\n\tsavedValuesFrom,\n\tsavedValuesFromRecord,\n\tsavedValuesToRecord,\n\ttype SavedValues\n} from './saved-values.js';\nimport { withTimeout } from './with-timeout.js';\n\nexport type DefinitionChannel = 'live' | 'draft';\n\nexport interface LoadedDefinition {\n\tversion: DefinitionVersion;\n\tdefinitionSource: Uint8Array;\n\tcomputeServer: ComputeServerConfig;\n\tschema: UISchema;\n\t/**\n\t * True when `schema` holds the stored defaults because the file's saved values are not read\n\t * yet. A later load carries them once the read behind this one lands.\n\t */\n\tdefaultsPending: boolean;\n\t/**\n\t * While `defaultsPending`: a Compute read of the saved values is running, so a later load can\n\t * carry them. False means the last read failed and the next is not due yet.\n\t */\n\tdefaultsReading: boolean;\n}\n\n/**\n * Classified failure modes so callers can map to appropriate HTTP status:\n * - 'data': record references a version/blob that isn't there. (400)\n * - 'missing-config': no compute server resolvable for this org/definition. (503)\n * - 'connect': compute server is unreachable, or too slow to answer. (503)\n * - 'schema': compute responded but IO/schema phase failed. (500)\n */\nexport type DefinitionLoadErrorKind = 'data' | 'missing-config' | 'connect' | 'schema';\n\nexport class DefinitionLoadError extends Error {\n\tconstructor(\n\t\tpublic readonly kind: DefinitionLoadErrorKind,\n\t\tmessage: string,\n\t\tpublic readonly cause?: unknown\n\t) {\n\t\tsuper(message);\n\t\tthis.name = 'DefinitionLoadError';\n\t}\n}\n\nexport interface DefinitionLoaderDeps {\n\tstorage: Pick<IStorageProvider, 'get'>;\n\tdefinitions: Pick<IDefinitionStore, 'getVersion' | 'setVersionSchema' | 'setVersionSavedValues'>;\n\tprojects: Pick<IProjectStore, 'getProject'>;\n\t/** Resolution order: definition pin → org default override → global default. */\n\tresolveServer: (\n\t\tctx: RequestContext,\n\t\torgId: string | null,\n\t\topts: { definitionPin: string | null }\n\t) => Promise<ComputeServerConfig>;\n\t/** Shared warm-client cache, keyed by server id. */\n\tgetClient: (server: ComputeServerConfig) => Promise<{ client: GrasshopperClient }>;\n\t/** Schema extraction; defaults to `fetchSchemaFromCompute`. Injectable for tests. */\n\tfetchSchema?: (bytes: Uint8Array, server: ComputeServerConfig) => Promise<UISchema>;\n\t/**\n\t * Longest a load waits on Compute for a version with no renderable stored schema, before it\n\t * fails as 'connect'. Keep it under the reverse proxy's timeout, or the proxy answers 504\n\t * first. Default `DEFAULT_RENDER_WAIT_MS`.\n\t */\n\trenderWaitMs?: number;\n\t/**\n\t * When set, an unhealthy IO result also dumps the raw /io wire shape, making\n\t * casing/serialization mismatches visible.\n\t */\n\tcomputeDebug?: boolean;\n\t/** Legacy diagnostic sink. When set it takes the warnings below instead of `logger`. */\n\tonWarn?: (message: string, detail?: string) => void;\n\t/**\n\t * Defaults to `NoopLogger`, so a consumer that wires nothing gets silence\n\t * rather than unsolicited stdout.\n\t */\n\tlogger?: ILogger;\n}\n\nexport interface DefinitionLoadOptions {\n\t/**\n\t * For callers that read only schema STRUCTURE (input ids, `source.key`,\n\t * widget types — anything persisted at upload). A fresh stored schema is then\n\t * returned as stored, and Compute is not read for it, not even in the\n\t * background: a page resolving several definitions would otherwise send each\n\t * file to Compute.\n\t */\n\tskipComputeDefaults?: boolean;\n}\n\nexport type DefinitionLoader = (\n\tctx: RequestContext,\n\trecord: DefinitionRecord,\n\tchannel: DefinitionChannel,\n\texplicitVersionId?: string | null,\n\toptions?: DefinitionLoadOptions\n) => Promise<LoadedDefinition>;\n\ninterface ComputeRead {\n\tctx: RequestContext;\n\trecord: DefinitionRecord;\n\tversion: DefinitionVersion;\n\tsource: Uint8Array;\n\tserver: ComputeServerConfig;\n}\n\n/**\n * The returned loader resolves the `channel` pointer (live/draft) by default.\n * `explicitVersionId` renders an arbitrary historical version instead — the\n * caller MUST gate that behind edit permission, as with the draft channel.\n */\nexport function createDefinitionLoader(deps: DefinitionLoaderDeps): DefinitionLoader {\n\tconst {\n\t\tstorage,\n\t\tdefinitions,\n\t\tprojects,\n\t\tresolveServer,\n\t\tgetClient,\n\t\tfetchSchema = fetchSchemaFromCompute,\n\t\trenderWaitMs = DEFAULT_RENDER_WAIT_MS,\n\t\tcomputeDebug = false,\n\t\tonWarn,\n\t\tlogger = new NoopLogger()\n\t} = deps;\n\n\t// Schemas extracted because the row had none usable, keyed by version id. The row write may\n\t// never land: a viewer or share-link context may not be able to write it (Supabase RLS turns\n\t// the UPDATE into a silent 0-row success), and then every load would call Compute. An older\n\t// format expires after `OLDER_SCHEMA_RECHECK_MS`.\n\tconst extracts = new Map<string, { schema: UISchema; extractedAt: string }>();\n\t// Read from Compute for a version stored without them, once per process: a context that\n\t// cannot write the row still needs them.\n\tconst savedValues = new Map<string, SavedValues>();\n\t// One Compute read per version at a time; loads arriving meanwhile share it.\n\tconst reads = new Map<string, Promise<UISchema>>();\n\t// When a version's last read failed, so a broken Compute isn't sent the file on every load.\n\tconst failedAt = new Map<string, number>();\n\n\tfunction warn(message: string, title: string, fields: Record<string, unknown>) {\n\t\tif (onWarn) onWarn(message);\n\t\telse logger.warn(title, { component: 'loadForRender', ...fields });\n\t}\n\n\tfunction cachedSchemaFor(version: DefinitionVersion): UISchema | null {\n\t\tconst row = version.schema as UISchema | undefined;\n\t\tif (row && isUsableCachedSchema(row, version.schemaExtractedAt)) return row;\n\t\tconst memo = extracts.get(version.id);\n\t\tif (!memo) return null;\n\t\tif (isUsableCachedSchema(memo.schema, memo.extractedAt)) return memo.schema;\n\t\textracts.delete(version.id);\n\t\treturn null;\n\t}\n\n\tasync function readFromCompute({\n\t\tctx,\n\t\trecord,\n\t\tversion,\n\t\tsource,\n\t\tserver\n\t}: ComputeRead): Promise<UISchema> {\n\t\tlet client: GrasshopperClient;\n\t\ttry {\n\t\t\tclient = (await getClient(server)).client;\n\t\t} catch (err) {\n\t\t\tthrow new DefinitionLoadError(\n\t\t\t\t'connect',\n\t\t\t\t`Failed to connect to Rhino Compute server: ${messageOf(err)}`,\n\t\t\t\terr\n\t\t\t);\n\t\t}\n\n\t\ttry {\n\t\t\t// The stored schema is a disposable cache (`isUsableCachedSchema`). Past it\n\t\t\t// (or on a pre-caching row with no schema) re-extract from compute, whose C#\n\t\t\t// SchemaMigrator emits its plugin's format — the web side never migrates\n\t\t\t// schemas itself.\n\t\t\tconst fresh = cachedSchemaFor(version);\n\t\t\tconst [io, extracted] = await Promise.all([\n\t\t\t\tclient.getIO(source),\n\t\t\t\tfresh ? Promise.resolve(fresh) : fetchSchema(source, server)\n\t\t\t]);\n\t\t\tif (!io) throw new Error(`Failed to get definition IO — server returned undefined`);\n\t\t\tassertHasInputs(extracted);\n\t\t\tawait reportUnhealthyIO(record, io, () => client.getRawIO(source));\n\n\t\t\tconst values = savedValuesFrom(io.inputs);\n\t\t\tsetBounded(savedValues, version.id, values);\n\t\t\t// Not an empty read: Compute may be missing a plugin, and a stored `{}` is never re-read.\n\t\t\tif (!version.savedValues && values.size > 0) persistSavedValues(ctx, version.id, values);\n\t\t\tconst schema = applySavedValues(extracted, values);\n\n\t\t\t// An older format (compute plugin behind the app) is warned about once per window, so\n\t\t\t// it costs one Compute call per instance per window.\n\t\t\tconst extractedAt = new Date().toISOString();\n\t\t\tif (!fresh) setBounded(extracts, version.id, { schema: extracted, extractedAt });\n\t\t\tif (!fresh && compareSchemaVersion(extracted.schemaVersion) === -1) {\n\t\t\t\twarn(\n\t\t\t\t\t`[loadForRender] compute's plugin emits schema format ${extracted.schemaVersion ?? '(none)'} ` +\n\t\t\t\t\t\t`for version ${version.id}, behind this app's ${UI_SCHEMA_VERSION}; serving it for ` +\n\t\t\t\t\t\t`${OLDER_SCHEMA_RECHECK_MS / 3_600_000} h before asking again. Update the plugin.`,\n\t\t\t\t\t'Compute plugin behind the app schema format',\n\t\t\t\t\t{ versionId: version.id, emitted: extracted.schemaVersion, expected: UI_SCHEMA_VERSION }\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst row = version.schema as UISchema | undefined;\n\t\t\tconst rowCurrent = fresh !== null && row !== undefined && sameDefaults(row, schema);\n\t\t\tif (!rowCurrent && isUsableCachedSchema(schema, extractedAt))\n\t\t\t\tpersist(ctx, version.id, schema);\n\t\t\treturn schema;\n\t\t} catch (err) {\n\t\t\tif (err instanceof DefinitionLoadError) throw err;\n\t\t\tthrow new DefinitionLoadError('schema', messageOf(err), err);\n\t\t}\n\t}\n\n\t// Best-effort — a viewer context may lack write access, and the next editor render or the\n\t// solve-time backfill will land it. Stores exactly what a read right after the write would\n\t// serve, so the two rules cannot drift.\n\tfunction persist(ctx: RequestContext, versionId: string, schema: UISchema) {\n\t\tdefinitions.setVersionSchema(ctx, versionId, schema).catch((err) => {\n\t\t\twarn(\n\t\t\t\t`[loadForRender] schema cache refresh failed for version ${versionId}: ${messageOf(err)}`,\n\t\t\t\t'Schema cache refresh failed',\n\t\t\t\t{ versionId, err: err instanceof Error ? (err.stack ?? err.message) : String(err) }\n\t\t\t);\n\t\t});\n\t}\n\n\t// Best-effort, like `persist`: the next load reads them from Compute again.\n\tfunction persistSavedValues(ctx: RequestContext, versionId: string, values: SavedValues) {\n\t\tdefinitions.setVersionSavedValues(ctx, versionId, savedValuesToRecord(values)).catch((err) => {\n\t\t\twarn(\n\t\t\t\t`[loadForRender] saved values write failed for version ${versionId}: ${messageOf(err)}`,\n\t\t\t\t'Saved values write failed',\n\t\t\t\t{ versionId, err: err instanceof Error ? (err.stack ?? err.message) : String(err) }\n\t\t\t);\n\t\t});\n\t}\n\n\t// Zero inputs or reported parse/load problems mean a definition that will\n\t// render wrong without saying why: an empty ValueList whose backing GH\n\t// component didn't resolve (\"Missing Definition Objects\"), or a PascalCase\n\t// /io response the parser silently dropped to []. Warning is always on —\n\t// it only fires on the unhappy path — while the raw wire dump costs an\n\t// extra round-trip and stays behind `computeDebug`.\n\tasync function reportUnhealthyIO(\n\t\trecord: DefinitionRecord,\n\t\tio: GrasshopperParsedIO,\n\t\treadRawIO: () => Promise<unknown>\n\t) {\n\t\tconst parseErrors = (io as { parseErrors?: unknown[] }).parseErrors ?? [];\n\t\tconst loadErrors = (io as { loadErrors?: unknown[] }).loadErrors ?? [];\n\t\tif (io.inputs.length > 0 && parseErrors.length === 0 && loadErrors.length === 0) return;\n\n\t\tconst health = {\n\t\t\tinputCount: io.inputs.length,\n\t\t\toutputCount: io.outputs?.length,\n\t\t\tparseErrors,\n\t\t\tloadErrors,\n\t\t\tloadWarnings: (io as { loadWarnings?: unknown }).loadWarnings\n\t\t};\n\t\tif (onWarn) onWarn(`[loadForRender] IO health for '${record.guid}':`, JSON.stringify(health));\n\t\telse\n\t\t\tlogger.warn('Definition IO looks unhealthy', {\n\t\t\t\tcomponent: 'loadForRender',\n\t\t\t\tdefinitionGuid: record.guid,\n\t\t\t\t...health\n\t\t\t});\n\n\t\tif (!computeDebug) return;\n\t\tconst rawIO = await readRawIO().catch((e) => ({ error: String(e) }));\n\t\tconst rendered = JSON.stringify(rawIO).slice(0, 3000);\n\t\tif (onWarn) onWarn('[loadForRender] raw /io:', rendered);\n\t\telse\n\t\t\tlogger.debug('Raw /io wire shape', {\n\t\t\t\tcomponent: 'loadForRender',\n\t\t\t\tdefinitionGuid: record.guid,\n\t\t\t\trawIO: rendered\n\t\t\t});\n\t}\n\n\tfunction read(job: ComputeRead): Promise<UISchema> {\n\t\tconst id = job.version.id;\n\t\tconst running = reads.get(id);\n\t\tif (running) return running;\n\n\t\tconst pending = withTimeout(\n\t\t\treadFromCompute(job),\n\t\t\tCOMPUTE_READ_TIMEOUT_MS,\n\t\t\t() =>\n\t\t\t\tnew DefinitionLoadError(\n\t\t\t\t\t'connect',\n\t\t\t\t\t`Rhino.Compute did not finish reading this definition within ${COMPUTE_READ_TIMEOUT_MS / 1000} s`\n\t\t\t\t)\n\t\t)\n\t\t\t.then(\n\t\t\t\t(schema) => {\n\t\t\t\t\tfailedAt.delete(id);\n\t\t\t\t\treturn schema;\n\t\t\t\t},\n\t\t\t\t(err) => {\n\t\t\t\t\tsetBounded(failedAt, id, Date.now());\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t)\n\t\t\t.finally(() => reads.delete(id));\n\t\treads.set(id, pending);\n\t\treturn pending;\n\t}\n\n\tfunction readInBackground(job: ComputeRead) {\n\t\tconst id = job.version.id;\n\t\tif (reads.has(id)) return;\n\t\tconst failed = failedAt.get(id);\n\t\tif (failed !== undefined && Date.now() - failed < READ_RETRY_MS) return;\n\n\t\tread(job).catch((err) => {\n\t\t\twarn(\n\t\t\t\t`[loadForRender] background read failed for version ${id}: ${messageOf(err)}`,\n\t\t\t\t'Background definition read failed',\n\t\t\t\t{ versionId: id, definitionGuid: job.record.guid, err: messageOf(err) }\n\t\t\t);\n\t\t});\n\t}\n\n\treturn async function loadDefinitionForRender(ctx, record, channel, explicitVersionId, options) {\n\t\tconst versionId =\n\t\t\texplicitVersionId ?? (channel === 'draft' ? record.draftVersionId : record.liveVersionId);\n\t\tif (!versionId)\n\t\t\tthrow new DefinitionLoadError(\n\t\t\t\t'data',\n\t\t\t\t`Definition '${record.guid}' has no ${channel} version`\n\t\t\t);\n\n\t\t// The server needs only the record, so it resolves while the version and file are read.\n\t\t// It is awaited after them, so a definition missing its data still fails as 'data'.\n\t\tconst pendingServer = (async (): Promise<ComputeServerConfig> => {\n\t\t\tconst project = await projects.getProject(ctx, record.projectId);\n\t\t\ttry {\n\t\t\t\treturn await resolveServer(ctx, project?.orgId ?? null, {\n\t\t\t\t\tdefinitionPin: record.computeServerId ?? null\n\t\t\t\t});\n\t\t\t} catch (err) {\n\t\t\t\tthrow new DefinitionLoadError(\n\t\t\t\t\t'missing-config',\n\t\t\t\t\t'No compute server configured for this definition',\n\t\t\t\t\terr\n\t\t\t\t);\n\t\t\t}\n\t\t})();\n\t\tpendingServer.catch(() => {});\n\n\t\tconst version = await definitions.getVersion(ctx, versionId);\n\t\tif (!version) throw new DefinitionLoadError('data', `version missing for '${record.guid}'`);\n\t\t// An explicitly requested version must belong to this definition.\n\t\tif (version.definitionId !== record.guid)\n\t\t\tthrow new DefinitionLoadError('data', `version does not belong to '${record.guid}'`);\n\n\t\tconst definitionSource = await storage.get(version.fileKey);\n\t\tif (!definitionSource)\n\t\t\tthrow new DefinitionLoadError(\n\t\t\t\t'data',\n\t\t\t\t`Definition file for '${record.guid}' not found on disk`\n\t\t\t);\n\n\t\tconst computeServer = await pendingServer;\n\t\tconst loaded = { version, definitionSource, computeServer };\n\t\tconst job: ComputeRead = {\n\t\t\tctx,\n\t\t\trecord,\n\t\t\tversion,\n\t\t\tsource: definitionSource,\n\t\t\tserver: computeServer\n\t\t};\n\n\t\tconst fresh = cachedSchemaFor(version);\n\t\tif (options?.skipComputeDefaults && fresh)\n\t\t\treturn { ...loaded, schema: fresh, defaultsPending: false, defaultsReading: false };\n\n\t\tconst values = version.savedValues\n\t\t\t? savedValuesFromRecord(version.savedValues)\n\t\t\t: savedValues.get(version.id);\n\t\tif (fresh && values)\n\t\t\treturn {\n\t\t\t\t...loaded,\n\t\t\t\tschema: applySavedValues(fresh, values),\n\t\t\t\tdefaultsPending: false,\n\t\t\t\tdefaultsReading: false\n\t\t\t};\n\n\t\t// An older format past its recheck window still renders: serve it while Compute is asked.\n\t\tconst stored = fresh ?? servableStaleSchema(version);\n\t\tif (stored) {\n\t\t\treadInBackground(job);\n\t\t\treturn {\n\t\t\t\t...loaded,\n\t\t\t\tschema: values ? applySavedValues(stored, values) : stored,\n\t\t\t\tdefaultsPending: !values,\n\t\t\t\tdefaultsReading: !values && reads.has(version.id)\n\t\t\t};\n\t\t}\n\n\t\t// The read carries on past the wait, so a retry finds it done.\n\t\tconst schema = await withTimeout(\n\t\t\tread(job),\n\t\t\trenderWaitMs,\n\t\t\t() =>\n\t\t\t\tnew DefinitionLoadError(\n\t\t\t\t\t'connect',\n\t\t\t\t\t'Rhino.Compute is still reading this definition. Retry in a moment.'\n\t\t\t\t)\n\t\t);\n\t\treturn { ...loaded, schema, defaultsPending: false, defaultsReading: false };\n\t};\n}\n\n/**\n * How long a schema in an OLDER format serves from the cache before Compute is asked again. A\n * plugin behind the app re-emits that same format, so asking on every load only buys a Compute\n * round trip (10 s+ while a child starts); the window bounds how long a plugin upgrade waits.\n */\nexport const OLDER_SCHEMA_RECHECK_MS = 24 * 60 * 60 * 1000;\n\n/** Under nginx's default 60 s and the 30 s many load balancers use. */\nexport const DEFAULT_RENDER_WAIT_MS = 20_000;\n\n// Frees the per-version read slot when Compute hangs; the load waiting on it gave up long before.\nconst COMPUTE_READ_TIMEOUT_MS = 120_000;\n\n// After a failed read, background reads of that version pause this long.\nconst READ_RETRY_MS = 60_000;\n\n// Bounds each in-process memo; the oldest entry is evicted first.\nconst MEMO_MAX = 1000;\n\nfunction setBounded<V>(map: Map<string, V>, key: string, value: V) {\n\tif (map.size >= MEMO_MAX && !map.has(key)) map.delete(map.keys().next().value!);\n\tmap.set(key, value);\n}\n\n/**\n * A cached schema is usable when it is structurally sound and either the current format version,\n * an older minor of the current major (`isOlderMinorSchemaVersion`), or an older major (missing\n * counts, see `compareSchemaVersion`) extracted within `OLDER_SCHEMA_RECHECK_MS` of `now`,\n * either side: a future stamp from a skewed clock still expires. Without `extractedAt` an older\n * major never passes. The `inputs` check is the\n * PascalCase guard: a compute server that serialized with the wrong Newtonsoft emits `Inputs`, and\n * such a row must never be served. See `assertCamelCaseSchema`.\n */\nexport function isUsableCachedSchema(\n\tschema: UISchema,\n\textractedAt?: string,\n\tnow: number = Date.now()\n): boolean {\n\tif (!Array.isArray(schema.inputs)) return false;\n\tconst order = compareSchemaVersion(schema.schemaVersion);\n\tif (order === 0 || isOlderMinorSchemaVersion(schema.schemaVersion)) return true;\n\tif (order !== -1 || !extractedAt) return false;\n\tconst at = Date.parse(extractedAt);\n\treturn Number.isFinite(at) && Math.abs(now - at) < OLDER_SCHEMA_RECHECK_MS;\n}\n\n/** A stored older-format schema past its recheck window. Newer and PascalCase rows never render. */\nfunction servableStaleSchema(version: DefinitionVersion): UISchema | null {\n\tconst row = version.schema as UISchema | undefined;\n\tif (!row || !Array.isArray(row.inputs)) return null;\n\treturn compareSchemaVersion(row.schemaVersion) === -1 ? row : null;\n}\n\nfunction assertHasInputs(schema: UISchema) {\n\tif (Array.isArray(schema.inputs)) return;\n\tthrow new DefinitionLoadError(\n\t\t'schema',\n\t\t`Schema has no 'inputs' array (keys: ${Object.keys(schema as object)\n\t\t\t.slice(0, 12)\n\t\t\t.join(', ')}). A PascalCase shape here means compute serialized it with the wrong ` +\n\t\t\t`Newtonsoft — see assertCamelCaseSchema.`\n\t);\n}\n\nfunction sameDefaults(a: UISchema, b: UISchema): boolean {\n\tconst defaults = (schema: UISchema) =>\n\t\tJSON.stringify(schema.inputs.map((input) => input.default));\n\treturn Array.isArray(a.inputs) && defaults(a) === defaults(b);\n}\n\nfunction messageOf(err: unknown): string {\n\treturn err instanceof Error ? err.message : String(err);\n}\n","// A definition page renders before Compute has read the values saved in the file, so its form can\n// start from the stored defaults. The page repeats its load until the saved values are in the\n// schema, then puts them into the inputs the user has not changed.\n\nimport { getDefaultValue, type UISchema } from '@selvajs/schemas';\n\n/** What the definition page's load `depends` on, and the page invalidates to repeat it. */\nexport const SAVED_VALUES_DEPENDENCY = 'selva:saved-values';\n\nconst RECHECK_MS = [2_000, 4_000, 8_000, 15_000, 30_000];\n\n/**\n * The wait before repeated load number `attempt`, which then stays at the longest. There is no\n * last attempt: the page stops once the load says no Compute read is running, so the server's\n * read timeout is what bounds it.\n */\nexport function savedValuesRecheckMs(attempt: number): number {\n\treturn RECHECK_MS[Math.min(attempt, RECHECK_MS.length - 1)];\n}\n\n/**\n * The saved values to load into a form built from `before`, now that `after` carries them: each\n * input whose default changed and whose value is still the one the form started with. An input\n * the user edited keeps its value, and so does a client-sourced input the form left empty.\n */\nexport function lateSavedValues(\n\tbefore: UISchema,\n\tafter: UISchema,\n\tcurrent: Readonly<Record<string, unknown>>\n): Record<string, unknown> {\n\tconst stored = new Map(before.inputs.map((input) => [input.id, input]));\n\tconst late: Record<string, unknown> = {};\n\tfor (const input of after.inputs) {\n\t\tconst old = stored.get(input.id);\n\t\tif (!old || !(input.id in current)) continue;\n\t\tif (input.default === undefined || same(input.default, old.default)) continue;\n\t\t// How the solve session built the value it started with.\n\t\tconst initial = old.default ?? getDefaultValue(old.paramType);\n\t\tif (same(current[input.id], initial)) late[input.id] = input.default;\n\t}\n\treturn late;\n}\n\nfunction same(a: unknown, b: unknown): boolean {\n\treturn JSON.stringify(a) === JSON.stringify(b);\n}\n","// `@selvajs/server/definitions` owns the loading pipeline (version resolution,\n// blob fetch, schema staleness check, default merging); this wires in the\n// app's providers, compute-server resolution, and warm-client cache. Access\n// gating stays with the calling route.\n\nimport {\n\tcreateDefinitionLoader,\n\tDefinitionLoadError,\n\ttype DefinitionChannel,\n\ttype DefinitionLoadErrorKind,\n\ttype LoadedDefinition\n} from '@selvajs/server/definitions';\nimport type { DefinitionRecord, RequestContext } from '@selvajs/platform';\nimport {\n\tgetStorageProvider,\n\tgetDefinitionMeta,\n\tgetProjectProvider,\n\tgetComputeServerConfigStore\n} from '../providers.server';\nimport { serverResolver } from '../compute/serverResolver.server';\nimport { getClient, COMPUTE_DEBUG } from '../compute/engine.server';\n\nexport { DefinitionLoadError };\nexport type { DefinitionChannel, DefinitionLoadErrorKind, LoadedDefinition };\n\n// One loader for the process. It keeps the saved values it read, the Compute read that loads\n// share and the pause after a failed read, so a loader per request sends the file to Compute on\n// every page load and never serves what came back. Providers are looked up per call.\nconst load = createDefinitionLoader({\n\tstorage: { get: (key) => getStorageProvider().get(key) },\n\tdefinitions: {\n\t\tgetVersion: (ctx, versionId) => getDefinitionMeta().getVersion(ctx, versionId),\n\t\tsetVersionSchema: (ctx, versionId, schema) =>\n\t\t\tgetDefinitionMeta().setVersionSchema(ctx, versionId, schema),\n\t\tsetVersionSavedValues: (ctx, versionId, values) =>\n\t\t\tgetDefinitionMeta().setVersionSavedValues(ctx, versionId, values)\n\t},\n\tprojects: { getProject: (ctx, projectId) => getProjectProvider().getProject(ctx, projectId) },\n\tresolveServer: (ctx, orgId, opts) =>\n\t\tserverResolver.resolve(ctx, orgId, getComputeServerConfigStore(), opts),\n\tgetClient,\n\tcomputeDebug: COMPUTE_DEBUG\n});\n\nexport function loadDefinitionForRender(\n\tctx: RequestContext,\n\trecord: DefinitionRecord,\n\tchannel: DefinitionChannel,\n\texplicitVersionId?: string | null\n): Promise<LoadedDefinition> {\n\treturn load(ctx, record, channel, explicitVersionId);\n}\n","import type { PageServerLoad } from './$types';\nimport { error } from '@sveltejs/kit';\nimport type { ILogger, RequestContext } from '@selvajs/platform';\nimport { renderThrown } from '@selvajs/server/logging';\nimport {\n\tgetDefinitionMeta,\n\tgetProjectProvider,\n\tgetOrganizationProvider\n} from '#lib/server/providers.server.js';\nimport { isApiError } from '@selvajs/server/api';\nimport { asHttpError, requireCanSolve, scoped } from '#lib/server/access.server.js';\nimport { readShareToken, tryResolveShareToken } from '#lib/server/shareLinks/resolve.server.js';\nimport { solveDeadlineFor } from '#lib/server/compute/engine.server.js';\nimport { SAVED_VALUES_DEPENDENCY } from '#lib/saved-values.js';\nimport {\n\tloadDefinitionForRender,\n\tDefinitionLoadError\n} from '#lib/server/definitions/loadForRender.server.js';\n\nexport const load = (async ({ params, locals, request, url, depends }) => {\n\tdepends(SAVED_VALUES_DEPENDENCY);\n\tconst meta = getDefinitionMeta();\n\n\tconst guid = params.guid;\n\tconst channel = url.searchParams.get('channel') === 'draft' ? 'draft' : 'live';\n\t// Explicit version pick (versioning tab \"Run\"): render an arbitrary version,\n\t// not just the live/draft pointer. Editor-only, never share-token accessible.\n\tconst explicitVersionId = url.searchParams.get('version');\n\tconst clientDefUrl = `local:${guid}`;\n\t// `shareToken` is forwarded to the page so the client can include it on\n\t// subsequent /api/compute/solve calls. null = user-authenticated session.\n\tlet shareToken: string | null = null;\n\n\ttry {\n\t\t// Draft channel and explicit-version picks are editor-only — share tokens\n\t\t// are always live channel on the pointer. A signed-in viewer who can solve\n\t\t// anyway ignores the token: a share-token solve gets no live events and\n\t\t// counts against the link's solve cap.\n\t\tconst sharedAccess =\n\t\t\tchannel === 'live' &&\n\t\t\t!explicitVersionId &&\n\t\t\treadShareToken(request, url) !== null &&\n\t\t\t!(await sessionCanSolve(locals, guid))\n\t\t\t\t? await tryResolveShareToken(request, url, guid, 'live', { requireSolve: false })\n\t\t\t\t: null;\n\t\tif (sharedAccess) {\n\t\t\tshareToken = url.searchParams.get('token');\n\t\t} else if (!locals.ctx || !locals.user) {\n\t\t\tthrow error(401, 'Unauthorized: You must be logged in to access definitions');\n\t\t}\n\n\t\tconst ctx: RequestContext = sharedAccess?.ctx ?? locals.ctx!;\n\n\t\tconst record = await meta.get(ctx, guid);\n\t\tif (!record) throw new Error(`Definition '${guid}' not found`);\n\n\t\t// User-auth path needs the canSolve gate; token-auth was already gated.\n\t\tif (!sharedAccess) await asHttpError(() => requireCanSolve(scoped(locals), record.projectId));\n\n\t\t// Draft channel and explicit-version picks require edit permission on top\n\t\t// of solve.\n\t\tif (channel === 'draft' || explicitVersionId) {\n\t\t\tconst { requireEditableDefinition } = await import('#lib/server/access.server.js');\n\t\t\tawait asHttpError(() => requireEditableDefinition(scoped(locals), guid));\n\t\t}\n\n\t\t// Owning org's logo, for viewer branding, read beside the definition load. Same\n\t\t// `ctx` already authorized to load this definition (user session or share-token\n\t\t// ctx, which carries actingOrgId). Best-effort: a missing project/org or read\n\t\t// failure just yields no logo — branding is non-essential and must never break a solve.\n\t\tconst [loaded, orgLogoUrl] = await Promise.all([\n\t\t\tloadDefinitionForRender(ctx, record, channel, explicitVersionId),\n\t\t\tresolveOrgLogo(ctx, record.projectId, locals.log)\n\t\t]);\n\n\t\tconst solveDeadlineMs = await solveDeadlineFor(loaded.computeServer);\n\n\t\treturn {\n\t\t\tschema: loaded.schema,\n\t\t\t// The page repeats this load until the file's saved values are in `schema`.\n\t\t\tdefaultsPending: loaded.defaultsPending,\n\t\t\tdefaultsReading: loaded.defaultsReading,\n\t\t\tghDefinition: clientDefUrl,\n\t\t\tcurrentDefinition: guid,\n\t\t\tserverLabel: loaded.computeServer.label,\n\t\t\torgLogoUrl,\n\t\t\tchannel,\n\t\t\t// When rendering an explicit version, forward its id (so solve calls\n\t\t\t// target the same version) and number (for the preview badge).\n\t\t\tversionId: explicitVersionId,\n\t\t\tversionNumber: loaded.version.versionNumber,\n\t\t\t// Forward to the client so /api/compute/solve calls can include it.\n\t\t\t// Null when the request was user-authenticated (session cookie carries auth).\n\t\t\tshareToken,\n\t\t\t// The deadline this definition's compute server sets, so the browser's\n\t\t\t// AbortController doesn't stop a solve the server would still finish.\n\t\t\tsolveDeadlineMs\n\t\t};\n\t} catch (err) {\n\t\t// Let HttpError (from error() calls) bubble up.\n\t\tif (err instanceof Error && 'status' in err) throw err;\n\n\t\t// Translate classified load errors to the same HTTP statuses the route\n\t\t// used pre-extraction:\n\t\t// missing-config | connect → 503 (operator action needed)\n\t\t// schema → 500 (compute responded but IO/schema failed)\n\t\t// data → 400 (definition references missing version/blob)\n\t\tif (err instanceof DefinitionLoadError) {\n\t\t\tif (err.kind === 'missing-config') {\n\t\t\t\tthrow error(\n\t\t\t\t\t503,\n\t\t\t\t\t'No compute server configured. Ask an admin to add one in /admin/compute.'\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (err.kind === 'connect') {\n\t\t\t\tlocals.log.error('Compute server connection failed', {\n\t\t\t\t\tcomponent: 'PageLoad',\n\t\t\t\t\tguid,\n\t\t\t\t\terr: renderThrown(err)\n\t\t\t\t});\n\t\t\t\tthrow error(503, err.message);\n\t\t\t}\n\t\t\tif (err.kind === 'schema') {\n\t\t\t\tlocals.log.error('Definition loading failed', {\n\t\t\t\t\tcomponent: 'PageLoad',\n\t\t\t\t\tguid,\n\t\t\t\t\terr: renderThrown(err)\n\t\t\t\t});\n\n\t\t\t\tif (process.env.NODE_ENV === 'development') {\n\t\t\t\t\tconst hint = `\\n\\nTroubleshooting:\\n1. Check /api/health/compute to diagnose server connectivity\\n2. Check the browser console for more details`;\n\t\t\t\t\tthrow error(500, `Failed to load definition from ${clientDefUrl}: ${err.message}${hint}`);\n\t\t\t\t}\n\t\t\t\tthrow error(500, `Failed to load definition: ${err.message}`);\n\t\t\t}\n\t\t\t// kind === 'data' falls through to the 400 wrap below.\n\t\t}\n\n\t\tif (err instanceof Error) {\n\t\t\tlocals.log.warn('Failed to load definition', {\n\t\t\t\tcomponent: 'App Load',\n\t\t\t\tguid,\n\t\t\t\terr: renderThrown(err)\n\t\t\t});\n\t\t\tthrow error(400, `Failed to load definition '${guid}': ${err.message}`);\n\t\t}\n\t\tthrow err;\n\t}\n}) satisfies PageServerLoad;\n\nasync function sessionCanSolve(locals: App.Locals, guid: string): Promise<boolean> {\n\tif (!locals.ctx || !locals.user) return false;\n\tconst record = await getDefinitionMeta().get(locals.ctx, guid);\n\tif (!record) return false;\n\ttry {\n\t\tawait requireCanSolve(scoped(locals), record.projectId);\n\t\treturn true;\n\t} catch (err) {\n\t\tif (isApiError(err)) return false;\n\t\tthrow err;\n\t}\n}\n\n/**\n * Resolve the owning org's logo URL for viewer branding. definition → project →\n * org. Best-effort and self-contained: any miss or read error returns null so a\n * branding lookup can never fail the render path.\n */\nasync function resolveOrgLogo(\n\tctx: RequestContext,\n\tprojectId: string,\n\tlog: ILogger\n): Promise<string | null> {\n\ttry {\n\t\tconst project = await getProjectProvider().getProject(ctx, projectId);\n\t\tif (!project?.orgId) return null;\n\t\tconst org = await getOrganizationProvider().getOrg(ctx, project.orgId);\n\t\treturn org?.assets?.logo ?? null;\n\t} catch (err) {\n\t\tlog.warn('Failed to resolve org logo', {\n\t\t\tcomponent: 'App Load',\n\t\t\tprojectId,\n\t\t\terr: renderThrown(err)\n\t\t});\n\t\treturn null;\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;AAqEA,IAAa,sBAAb,cAAyC,MAAM;CAE7B;CAEA;CAHjB,YACC,MACA,SACA,OACC;EACD,MAAM,OAAO;EAJG,KAAA,OAAA;EAEA,KAAA,QAAA;EAGhB,KAAK,OAAO;CACb;AACD;;;;;;AAoEA,SAAgB,uBAAuB,MAA8C;CACpF,MAAM,EACL,SACA,aACA,UACA,eACA,WACA,cAAc,wBACd,eAAe,wBACf,eAAe,OACf,QACA,SAAS,IAAI,WAA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;AAEA,eAAe,gBAAgB,QAAoB,MAAgC;CAClF,IAAI,CAAC,OAAO,OAAO,CAAC,OAAO,MAAM,OAAO;CACxC,MAAM,SAAS,MAAM,kBAAkB,CAAC,CAAC,IAAI,OAAO,KAAK,IAAI;CAC7D,IAAI,CAAC,QAAQ,OAAO;CACpB,IAAI;EACH,MAAM,gBAAgB,OAAO,MAAM,GAAG,OAAO,SAAS;EACtD,OAAO;CACR,SAAS,KAAK;EACb,IAAI,WAAW,GAAG,GAAG,OAAO;EAC5B,MAAM;CACP;AACD;;;;;;AAOA,eAAe,eACd,KACA,WACA,KACyB;CACzB,IAAI;EACH,MAAM,UAAU,MAAM,mBAAmB,CAAC,CAAC,WAAW,KAAK,SAAS;EACpE,IAAI,CAAC,SAAS,OAAO,OAAO;EAE5B,QAAO,MADW,wBAAwB,CAAC,CAAC,OAAO,KAAK,QAAQ,KAAK,EAAA,EACzD,QAAQ,QAAQ;CAC7B,SAAS,KAAK;EACb,IAAI,KAAK,8BAA8B;GACtC,WAAW;GACX;GACA,KAAK,aAAa,GAAG;EACtB,CAAC;EACD,OAAO;CACR;AACD"}
|
|
@@ -15113,33 +15113,39 @@ var BINARY_ACCEPT_HEADER = typeof DecompressionStream === "undefined" ? null : `
|
|
|
15113
15113
|
function isBinarySolveResponse(res) {
|
|
15114
15114
|
return (res.headers.get("Content-Type") ?? "").startsWith(BINARY_SOLVE_MEDIA_TYPE);
|
|
15115
15115
|
}
|
|
15116
|
-
/**
|
|
15117
|
-
* The response JSON with each display item's `data` parsed into its batch object, its
|
|
15118
|
-
* `compressedData` the blob's bytes. The blobs are views over `bytes`, so they keep it alive.
|
|
15119
|
-
*/
|
|
15116
|
+
/** The response JSON with each display item's `data` parsed into its batch, the mesh as bytes. */
|
|
15120
15117
|
async function decodeBinarySolveResponse(bytes) {
|
|
15121
15118
|
const { flags, json, blobs } = readFrame(bytes);
|
|
15122
15119
|
const jsonBytes = flags & 1 ? await gunzip(json) : json;
|
|
15123
|
-
const
|
|
15124
|
-
const
|
|
15125
|
-
|
|
15126
|
-
for (const value of values) for (const tree of [value?.InnerTree, value?.innerTree]) {
|
|
15120
|
+
const response = JSON.parse(new TextDecoder().decode(jsonBytes));
|
|
15121
|
+
const batches = [];
|
|
15122
|
+
const values = response?.values;
|
|
15123
|
+
if (Array.isArray(values)) for (const value of values) for (const tree of [value?.InnerTree, value?.innerTree]) {
|
|
15127
15124
|
if (!tree || typeof tree !== "object") continue;
|
|
15128
|
-
for (const branch of Object.values(tree))
|
|
15125
|
+
for (const branch of Object.values(tree)) {
|
|
15126
|
+
if (!Array.isArray(branch)) continue;
|
|
15127
|
+
for (const item of branch) {
|
|
15128
|
+
const batch = attachBlob(item, blobs);
|
|
15129
|
+
if (batch) batches.push(batch);
|
|
15130
|
+
}
|
|
15131
|
+
}
|
|
15129
15132
|
}
|
|
15130
|
-
return
|
|
15133
|
+
return {
|
|
15134
|
+
response,
|
|
15135
|
+
releaseBlobs: () => batches.forEach((batch) => batch.compressedData = "")
|
|
15136
|
+
};
|
|
15131
15137
|
}
|
|
15132
15138
|
function attachBlob(item, blobs) {
|
|
15133
15139
|
const display = item;
|
|
15134
|
-
if (typeof display?.type !== "string" || typeof display.data !== "string") return;
|
|
15135
|
-
if (!isDisplayItemType$1(display.type)) return;
|
|
15140
|
+
if (typeof display?.type !== "string" || typeof display.data !== "string") return null;
|
|
15141
|
+
if (!isDisplayItemType$1(display.type)) return null;
|
|
15136
15142
|
const batch = JSON.parse(display.data);
|
|
15137
|
-
if (isBlobRef(batch.compressedData)) {
|
|
15138
|
-
const blob = blobs[batch.compressedData.$blob];
|
|
15139
|
-
if (!blob) throw new Error("Malformed binary solve response: a batch names a missing blob");
|
|
15140
|
-
batch.compressedData = blob;
|
|
15141
|
-
}
|
|
15142
15143
|
display.data = batch;
|
|
15144
|
+
if (!isBlobRef(batch.compressedData)) return null;
|
|
15145
|
+
const blob = blobs[batch.compressedData.$blob];
|
|
15146
|
+
if (!blob) throw new Error("Malformed binary solve response: a batch names a missing blob");
|
|
15147
|
+
batch.compressedData = blob;
|
|
15148
|
+
return batch;
|
|
15143
15149
|
}
|
|
15144
15150
|
async function gunzip(bytes) {
|
|
15145
15151
|
const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("gzip"));
|
|
@@ -15246,14 +15252,14 @@ function createComputeFetchSolveFn(opts) {
|
|
|
15246
15252
|
const remainingMs = cooldownUntil - Date.now();
|
|
15247
15253
|
if (remainingMs > 0) throw rateLimited(remainingMs / 1e3);
|
|
15248
15254
|
const solveStart = performance.now();
|
|
15249
|
-
const inputs = opts.inputs();
|
|
15255
|
+
const inputs = opts.inputs?.();
|
|
15250
15256
|
const outputs = opts.outputs();
|
|
15251
15257
|
const channel = opts.channel?.();
|
|
15252
15258
|
const versionId = opts.versionId?.();
|
|
15253
15259
|
const streamId = call.liveEvents === false ? null : opts.streamId?.();
|
|
15254
15260
|
const bearerToken = opts.bearerToken?.();
|
|
15255
15261
|
const payload = JSON.stringify({
|
|
15256
|
-
inputs,
|
|
15262
|
+
...inputs ? { inputs } : {},
|
|
15257
15263
|
values,
|
|
15258
15264
|
definitionUrl: opts.definitionUrl(),
|
|
15259
15265
|
...versionId ? { versionId } : channel === "draft" ? { channel: "draft" } : {},
|
|
@@ -15349,8 +15355,10 @@ function createComputeFetchSolveFn(opts) {
|
|
|
15349
15355
|
const invalidResponse = (cause) => new Error("Received an invalid response from the server. Reload the page and try again.", { cause });
|
|
15350
15356
|
const parseStart = performance.now();
|
|
15351
15357
|
let parsed;
|
|
15358
|
+
let releaseBlobs = () => {};
|
|
15352
15359
|
try {
|
|
15353
|
-
|
|
15360
|
+
if (typeof body === "string") parsed = JSON.parse(body);
|
|
15361
|
+
else ({response: parsed, releaseBlobs} = await decodeBinarySolveResponse(body));
|
|
15354
15362
|
} catch (err) {
|
|
15355
15363
|
throw invalidResponse(err);
|
|
15356
15364
|
}
|
|
@@ -15366,6 +15374,7 @@ function createComputeFetchSolveFn(opts) {
|
|
|
15366
15374
|
signal
|
|
15367
15375
|
}) : [];
|
|
15368
15376
|
const meshesMs = performance.now() - meshesStart;
|
|
15377
|
+
releaseBlobs();
|
|
15369
15378
|
const resultOutputs = {};
|
|
15370
15379
|
for (const o of rejected ? [] : outputs) {
|
|
15371
15380
|
const byId = processor.getValue({ byId: o.id }, { parseValues: true });
|
|
@@ -19132,6 +19141,7 @@ function createCurveLayer(options) {
|
|
|
19132
19141
|
let previewLabel = null;
|
|
19133
19142
|
let editing = false;
|
|
19134
19143
|
const renderLabels = () => {
|
|
19144
|
+
if (disposed) return;
|
|
19135
19145
|
shown.forEach((label) => label.remove());
|
|
19136
19146
|
shown = wanted.map((label) => {
|
|
19137
19147
|
const handle = viewer.labelLayer.addLabel(label.text, toScene(label.at));
|
|
@@ -24006,7 +24016,6 @@ function _page($$renderer, $$props) {
|
|
|
24006
24016
|
const onSolve = createComputeFetchSolveFn({
|
|
24007
24017
|
endpoint: "/api/v1/compute",
|
|
24008
24018
|
definitionUrl: () => data.ghDefinition,
|
|
24009
|
-
inputs: () => data.schema.inputs,
|
|
24010
24019
|
outputs: () => data.schema.outputs,
|
|
24011
24020
|
channel: () => data.channel === "draft" ? "draft" : void 0,
|
|
24012
24021
|
versionId: () => data.versionId,
|