@selvajs/selva 4.21.0-beta.23 → 4.21.0-beta.25
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/A_2RYLH9.js +1 -0
- package/build/client/_app/immutable/chunks/A_2RYLH9.js.br +1 -0
- package/build/client/_app/immutable/chunks/A_2RYLH9.js.gz +0 -0
- package/build/client/_app/immutable/chunks/{DtmN00GS.js → BMp0Pt9F.js} +4 -4
- package/build/client/_app/immutable/chunks/BMp0Pt9F.js.br +0 -0
- package/build/client/_app/immutable/chunks/BMp0Pt9F.js.gz +0 -0
- package/build/client/_app/immutable/entry/{app.Dl3HM1mx.js → app.UvCzfP6E.js} +2 -2
- package/build/client/_app/immutable/entry/app.UvCzfP6E.js.br +0 -0
- package/build/client/_app/immutable/entry/app.UvCzfP6E.js.gz +0 -0
- package/build/client/_app/immutable/nodes/21.BAYqxLPV.js +1 -0
- package/build/client/_app/immutable/nodes/21.BAYqxLPV.js.br +1 -0
- package/build/client/_app/immutable/nodes/21.BAYqxLPV.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/runtime-meta.json +1 -1
- package/build/server/.vite/manifest.json +13 -11
- package/build/server/chunks/compute.js +1 -1
- package/build/server/chunks/engine.server.js +1 -1
- package/build/server/chunks/errors.js +7 -30
- package/build/server/chunks/errors.js.map +1 -1
- package/build/server/chunks/handlers.js +5 -4
- package/build/server/chunks/handlers.js.map +1 -1
- package/build/server/chunks/instance.js +3 -3
- package/build/server/chunks/internal.js +1 -1
- package/build/server/chunks/ops.js +1 -1
- package/build/server/chunks/package.js +1 -1
- package/build/server/chunks/package.js.map +1 -1
- package/build/server/chunks/providers.server.js +48 -15
- package/build/server/chunks/providers.server.js.map +1 -1
- package/build/server/chunks/{limits.js → saved-values.js} +35 -2
- package/build/server/chunks/saved-values.js.map +1 -0
- package/build/server/chunks/server.js +5 -0
- package/build/server/chunks/server.js.map +1 -1
- package/build/server/chunks/types2.js.map +1 -1
- package/build/server/entries/pages/library/_guid_/_page.server.ts.js +14 -3
- package/build/server/entries/pages/library/_guid_/_page.server.ts.js.map +1 -1
- package/build/server/entries/pages/library/_guid_/_page.svelte.js +42 -8
- 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 +9 -9
- package/build/client/_app/immutable/chunks/B58dPMPq.js +0 -1
- package/build/client/_app/immutable/chunks/B58dPMPq.js.br +0 -1
- package/build/client/_app/immutable/chunks/B58dPMPq.js.gz +0 -0
- package/build/client/_app/immutable/chunks/DtmN00GS.js.br +0 -0
- package/build/client/_app/immutable/chunks/DtmN00GS.js.gz +0 -0
- package/build/client/_app/immutable/entry/app.Dl3HM1mx.js.br +0 -0
- package/build/client/_app/immutable/entry/app.Dl3HM1mx.js.gz +0 -0
- package/build/client/_app/immutable/nodes/21.BZJQikE5.js +0 -1
- package/build/client/_app/immutable/nodes/21.BZJQikE5.js.br +0 -0
- package/build/client/_app/immutable/nodes/21.BZJQikE5.js.gz +0 -0
- package/build/server/chunks/limits.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types2.js","names":[],"sources":["../../../../platform/src/definitions/types.ts"],"sourcesContent":["import type { DocumentInventory, InventorySummary, UISchema } from '@selvajs/schemas';\nimport type { z } from 'zod';\nimport type { ListOptions } from '../pagination.js';\nimport type { DefinitionChannelSchema, DefinitionStatusSchema } from './schemas.js';\n\nconst DEFINITION_FILE_EXTS = ['gh', 'ghx'] as const;\n\nexport type DefinitionFileExt = (typeof DEFINITION_FILE_EXTS)[number];\n\nexport const GH_EXTENSIONS: string[] = DEFINITION_FILE_EXTS.map((ext) => `.${ext}`);\n\nexport const COVER_IMAGE_CONTENT_TYPES: Record<string, string> = {\n\t'.jpg': 'image/jpeg',\n\t'.jpeg': 'image/jpeg',\n\t'.png': 'image/png',\n\t'.webp': 'image/webp',\n\t'.gif': 'image/gif'\n};\n\n/**\n * - `pending` — internal: metadata written, blob upload may be in flight.\n * - `draft` — work in progress, not visible to runners.\n * - `published` — live, visible to all with solve access.\n * - `archived` — retired but preserved; restore via `update({ status: 'draft' | 'published' })`.\n *\n * List endpoints filter out `pending` and `archived` by default (opt in via\n * `DefinitionListOptions.includePending`/`includeArchived`, or an explicit `statuses` filter).\n */\nexport type DefinitionStatus = z.infer<typeof DefinitionStatusSchema> | 'pending';\n\n/** Definition-specific filtering on top of `ListOptions`. */\nexport interface DefinitionListOptions extends Omit<ListOptions, 'orderBy'> {\n\torderBy?: 'createdAt' | 'updatedAt' | 'name' | 'solveCount';\n\t/** Include `status='pending'` records. Default false. */\n\tincludePending?: boolean;\n\t/** Include `status='archived'` records. Default false. */\n\tincludeArchived?: boolean;\n\t/**\n\t * Filter to specific editorial statuses. Omit for the default view (all\n\t * non-pending, non-archived). When set, `includePending` / `includeArchived`\n\t * are ignored.\n\t */\n\tstatuses?: DefinitionStatus[];\n\t/**\n\t * Restrict to definitions in these projects. An empty array matches nothing,\n\t * distinct from omitting the filter.\n\t *\n\t * Applying this in the adapter query — rather than filtering a fetched page\n\t * afterwards — is what keeps `limit` and `nextCursor` accurate: filtering\n\t * post-fetch can return a page of 50 with 3 items.\n\t */\n\tprojectIds?: readonly string[];\n\t/** Only definitions whose `sourceDocumentId` equals this lowercase GUID. */\n\tsourceDocumentId?: string;\n}\n\n/**\n * Immutable snapshot of a definition's `.gh` file at a point in time. New\n * uploads create new versions; rollback re-points the parent's\n * `liveVersionId` rather than mutating the version itself.\n */\nexport interface DefinitionVersion {\n\tid: string;\n\tdefinitionId: string;\n\t/** Allocated from `DefinitionRecord.nextVersionNumber`; see that field for the numbering guarantee. */\n\tversionNumber: number;\n\tfileExt: DefinitionFileExt;\n\t/** Full storage key. Opaque to callers. */\n\tfileKey: string;\n\toriginalFilename?: string;\n\tuploadedBy: string;\n\tuploadedAt: string;\n\t/** Free-form note describing what changed in this version. */\n\tchangeNote?: string;\n\t/**\n\t * Compute-extracted UI schema, cached at upload so the render path doesn't\n\t * re-fetch it from Rhino.Compute on every load. Optional only for the\n\t * lazy-backfill bridge on pre-existing versions; new uploads always set it.\n\t */\n\tschema?: UISchema;\n\t/** ISO timestamp of when `schema` was extracted. */\n\tschemaExtractedAt?: string;\n\t/**\n\t * What the file holds beyond its form: plugins, components, values, script fingerprints.\n\t * Left out of list projections like `schema`. Absent on versions uploaded before it existed,\n\t * or through a Compute server whose plugin cannot build it.\n\t */\n\tinventory?: DocumentInventory;\n\t/** The part of `inventory` the version list shows; kept in list projections. */\n\tinventorySummary?: InventorySummary;\n}\n\nexport interface DefinitionRecord {\n\tguid: string;\n\tprojectId: string;\n\t/** Current owner — separate from `createdBy` so ownership can transfer. */\n\townerId: string;\n\tcreatedBy: string;\n\tupdatedBy: string;\n\t/** Falls back to the org default, then the platform default. */\n\tcomputeServerId?: string;\n\t/**\n\t * Per-definition quota for the shared solve-result cache (`ISolveResultCache`):\n\t * `0` = caching off, `N` = keep at most N cached solves, absent = inherit the\n\t * backend default.\n\t */\n\tsolveCacheLimit?: number;\n\tdisplayName: string;\n\tdescription?: string;\n\tcategory?: string;\n\ttags?: string[];\n\t/** Provider-dependent public URL — must be safe to send to clients. */\n\tcoverImage?: string;\n\tstatus: DefinitionStatus;\n\tsolveCount: number;\n\t/**\n\t * Monotonic version-number allocator, never decremented: the next upload\n\t * reserves this value then advances the counter, so a delete-latest-then-reupload\n\t * mints a fresh number and `fileKey` instead of reusing one — otherwise a stale\n\t * storage blob could serve the old version's bytes under the new content's key.\n\t * Starts at 2 after v1 is created.\n\t */\n\tnextVersionNumber: number;\n\t/**\n\t * Both null only during the brief `pending` window between metadata create\n\t * and v1 upload; otherwise both reference live `DefinitionVersion` rows.\n\t */\n\tliveVersionId: string | null;\n\tdraftVersionId: string | null;\n\t/**\n\t * The Grasshopper document GUID (lowercase) from the schema Compute\n\t * extracted at the last upload that carried one. A copied `.gh` keeps its\n\t * GUID, so this suggests a match and never proves one.\n\t */\n\tsourceDocumentId?: string;\n\tcreatedAt: string;\n\tupdatedAt: string;\n\t/** Soft-delete marker, independent of `status`: a store filters this out regardless of `archived`. */\n\tdeletedAt?: string | null;\n}\n\n/**\n * List-row projection of a `DefinitionRecord`; the shape `GET /api/v1/definitions` returns.\n *\n * Deliberately narrower than the full record — `ownerId`, `createdBy`,\n * `updatedBy`, `solveCacheLimit` are internal. v1 is additive-only, so a field\n * published here can only be removed in v2: narrowing later is not an option.\n *\n * `liveVersionId` is the pointer, not a version number — the number isn't a\n * native column, so resolving it would cost a query per row.\n */\nexport interface DefinitionListItem {\n\tguid: string;\n\tprojectId: string;\n\tdisplayName: string;\n\tdescription?: string;\n\tcategory?: string;\n\ttags?: string[];\n\tcoverImage?: string;\n\tstatus: DefinitionStatus;\n\tsolveCount: number;\n\tliveVersionId: string | null;\n\t/** See {@link DefinitionRecord.sourceDocumentId}. */\n\tsourceDocumentId: string | null;\n\tupdatedAt: string;\n}\n\nexport function toDefinitionListItem(r: DefinitionRecord): DefinitionListItem {\n\treturn {\n\t\tguid: r.guid,\n\t\tprojectId: r.projectId,\n\t\tdisplayName: r.displayName,\n\t\tdescription: r.description,\n\t\tcategory: r.category,\n\t\ttags: r.tags,\n\t\tcoverImage: r.coverImage,\n\t\tstatus: r.status,\n\t\tsolveCount: r.solveCount,\n\t\tliveVersionId: r.liveVersionId,\n\t\tsourceDocumentId: r.sourceDocumentId ?? null,\n\t\tupdatedAt: r.updatedAt\n\t};\n}\n\n/**\n * Omits immutable fields and provider-managed ones (use\n * `setLiveVersion`/`setDraftVersion` for channel pointers).\n *\n * - `undefined` — leave unchanged\n * - `null` — clear (only on nullable fields)\n * - value — set\n *\n * Use `incrementSolveCount` for atomic +1 bumps instead of patching `solveCount`.\n */\nexport interface DefinitionRecordPatch {\n\tdisplayName?: string;\n\tdescription?: string | null;\n\tcategory?: string | null;\n\ttags?: string[] | null;\n\tcoverImage?: string | null;\n\tprojectId?: string;\n\tcomputeServerId?: string | null;\n\t/** L2 cache quota (see {@link DefinitionRecord.solveCacheLimit}); `null` clears to inherit. */\n\tsolveCacheLimit?: number | null;\n\tstatus?: DefinitionStatus;\n\townerId?: string;\n\tsourceDocumentId?: string | null;\n}\n\nexport type DefinitionChannel = z.infer<typeof DefinitionChannelSchema>;\n"],"mappings":"AASA,IAAa,gBAA0B,CAJT,MAAM,KAIG,CAAA,CAAqB,KAAK,QAAQ,IAAI,KAAK;AAElF,IAAa,4BAAoD;CAChE,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,SAAS;CACT,QAAQ;AACT;
|
|
1
|
+
{"version":3,"file":"types2.js","names":[],"sources":["../../../../platform/src/definitions/types.ts"],"sourcesContent":["import type { DocumentInventory, InventorySummary, UISchema } from '@selvajs/schemas';\nimport type { z } from 'zod';\nimport type { ListOptions } from '../pagination.js';\nimport type { DefinitionChannelSchema, DefinitionStatusSchema } from './schemas.js';\n\nconst DEFINITION_FILE_EXTS = ['gh', 'ghx'] as const;\n\nexport type DefinitionFileExt = (typeof DEFINITION_FILE_EXTS)[number];\n\nexport const GH_EXTENSIONS: string[] = DEFINITION_FILE_EXTS.map((ext) => `.${ext}`);\n\nexport const COVER_IMAGE_CONTENT_TYPES: Record<string, string> = {\n\t'.jpg': 'image/jpeg',\n\t'.jpeg': 'image/jpeg',\n\t'.png': 'image/png',\n\t'.webp': 'image/webp',\n\t'.gif': 'image/gif'\n};\n\n/**\n * - `pending` — internal: metadata written, blob upload may be in flight.\n * - `draft` — work in progress, not visible to runners.\n * - `published` — live, visible to all with solve access.\n * - `archived` — retired but preserved; restore via `update({ status: 'draft' | 'published' })`.\n *\n * List endpoints filter out `pending` and `archived` by default (opt in via\n * `DefinitionListOptions.includePending`/`includeArchived`, or an explicit `statuses` filter).\n */\nexport type DefinitionStatus = z.infer<typeof DefinitionStatusSchema> | 'pending';\n\n/** Definition-specific filtering on top of `ListOptions`. */\nexport interface DefinitionListOptions extends Omit<ListOptions, 'orderBy'> {\n\torderBy?: 'createdAt' | 'updatedAt' | 'name' | 'solveCount';\n\t/** Include `status='pending'` records. Default false. */\n\tincludePending?: boolean;\n\t/** Include `status='archived'` records. Default false. */\n\tincludeArchived?: boolean;\n\t/**\n\t * Filter to specific editorial statuses. Omit for the default view (all\n\t * non-pending, non-archived). When set, `includePending` / `includeArchived`\n\t * are ignored.\n\t */\n\tstatuses?: DefinitionStatus[];\n\t/**\n\t * Restrict to definitions in these projects. An empty array matches nothing,\n\t * distinct from omitting the filter.\n\t *\n\t * Applying this in the adapter query — rather than filtering a fetched page\n\t * afterwards — is what keeps `limit` and `nextCursor` accurate: filtering\n\t * post-fetch can return a page of 50 with 3 items.\n\t */\n\tprojectIds?: readonly string[];\n\t/** Only definitions whose `sourceDocumentId` equals this lowercase GUID. */\n\tsourceDocumentId?: string;\n}\n\n/**\n * Immutable snapshot of a definition's `.gh` file at a point in time. New\n * uploads create new versions; rollback re-points the parent's\n * `liveVersionId` rather than mutating the version itself.\n */\nexport interface DefinitionVersion {\n\tid: string;\n\tdefinitionId: string;\n\t/** Allocated from `DefinitionRecord.nextVersionNumber`; see that field for the numbering guarantee. */\n\tversionNumber: number;\n\tfileExt: DefinitionFileExt;\n\t/** Full storage key. Opaque to callers. */\n\tfileKey: string;\n\toriginalFilename?: string;\n\tuploadedBy: string;\n\tuploadedAt: string;\n\t/** Free-form note describing what changed in this version. */\n\tchangeNote?: string;\n\t/**\n\t * Compute-extracted UI schema, cached at upload so the render path doesn't\n\t * re-fetch it from Rhino.Compute on every load. Optional only for the\n\t * lazy-backfill bridge on pre-existing versions; new uploads always set it.\n\t */\n\tschema?: UISchema;\n\t/** ISO timestamp of when `schema` was extracted. */\n\tschemaExtractedAt?: string;\n\t/**\n\t * What the file holds beyond its form: plugins, components, values, script fingerprints.\n\t * Left out of list projections like `schema`. Absent on versions uploaded before it existed,\n\t * or through a Compute server whose plugin cannot build it.\n\t */\n\tinventory?: DocumentInventory;\n\t/** The part of `inventory` the version list shows; kept in list projections. */\n\tinventorySummary?: InventorySummary;\n\t/**\n\t * The values saved in the file, by input id, as Compute read them. A page renders them as the\n\t * form's defaults without asking Compute. Absent until read: on versions uploaded before this\n\t * existed, and while an upload's read is still running. Left out of list projections.\n\t */\n\tsavedValues?: Record<string, unknown>;\n}\n\nexport interface DefinitionRecord {\n\tguid: string;\n\tprojectId: string;\n\t/** Current owner — separate from `createdBy` so ownership can transfer. */\n\townerId: string;\n\tcreatedBy: string;\n\tupdatedBy: string;\n\t/** Falls back to the org default, then the platform default. */\n\tcomputeServerId?: string;\n\t/**\n\t * Per-definition quota for the shared solve-result cache (`ISolveResultCache`):\n\t * `0` = caching off, `N` = keep at most N cached solves, absent = inherit the\n\t * backend default.\n\t */\n\tsolveCacheLimit?: number;\n\tdisplayName: string;\n\tdescription?: string;\n\tcategory?: string;\n\ttags?: string[];\n\t/** Provider-dependent public URL — must be safe to send to clients. */\n\tcoverImage?: string;\n\tstatus: DefinitionStatus;\n\tsolveCount: number;\n\t/**\n\t * Monotonic version-number allocator, never decremented: the next upload\n\t * reserves this value then advances the counter, so a delete-latest-then-reupload\n\t * mints a fresh number and `fileKey` instead of reusing one — otherwise a stale\n\t * storage blob could serve the old version's bytes under the new content's key.\n\t * Starts at 2 after v1 is created.\n\t */\n\tnextVersionNumber: number;\n\t/**\n\t * Both null only during the brief `pending` window between metadata create\n\t * and v1 upload; otherwise both reference live `DefinitionVersion` rows.\n\t */\n\tliveVersionId: string | null;\n\tdraftVersionId: string | null;\n\t/**\n\t * The Grasshopper document GUID (lowercase) from the schema Compute\n\t * extracted at the last upload that carried one. A copied `.gh` keeps its\n\t * GUID, so this suggests a match and never proves one.\n\t */\n\tsourceDocumentId?: string;\n\tcreatedAt: string;\n\tupdatedAt: string;\n\t/** Soft-delete marker, independent of `status`: a store filters this out regardless of `archived`. */\n\tdeletedAt?: string | null;\n}\n\n/**\n * List-row projection of a `DefinitionRecord`; the shape `GET /api/v1/definitions` returns.\n *\n * Deliberately narrower than the full record — `ownerId`, `createdBy`,\n * `updatedBy`, `solveCacheLimit` are internal. v1 is additive-only, so a field\n * published here can only be removed in v2: narrowing later is not an option.\n *\n * `liveVersionId` is the pointer, not a version number — the number isn't a\n * native column, so resolving it would cost a query per row.\n */\nexport interface DefinitionListItem {\n\tguid: string;\n\tprojectId: string;\n\tdisplayName: string;\n\tdescription?: string;\n\tcategory?: string;\n\ttags?: string[];\n\tcoverImage?: string;\n\tstatus: DefinitionStatus;\n\tsolveCount: number;\n\tliveVersionId: string | null;\n\t/** See {@link DefinitionRecord.sourceDocumentId}. */\n\tsourceDocumentId: string | null;\n\tupdatedAt: string;\n}\n\nexport function toDefinitionListItem(r: DefinitionRecord): DefinitionListItem {\n\treturn {\n\t\tguid: r.guid,\n\t\tprojectId: r.projectId,\n\t\tdisplayName: r.displayName,\n\t\tdescription: r.description,\n\t\tcategory: r.category,\n\t\ttags: r.tags,\n\t\tcoverImage: r.coverImage,\n\t\tstatus: r.status,\n\t\tsolveCount: r.solveCount,\n\t\tliveVersionId: r.liveVersionId,\n\t\tsourceDocumentId: r.sourceDocumentId ?? null,\n\t\tupdatedAt: r.updatedAt\n\t};\n}\n\n/**\n * Omits immutable fields and provider-managed ones (use\n * `setLiveVersion`/`setDraftVersion` for channel pointers).\n *\n * - `undefined` — leave unchanged\n * - `null` — clear (only on nullable fields)\n * - value — set\n *\n * Use `incrementSolveCount` for atomic +1 bumps instead of patching `solveCount`.\n */\nexport interface DefinitionRecordPatch {\n\tdisplayName?: string;\n\tdescription?: string | null;\n\tcategory?: string | null;\n\ttags?: string[] | null;\n\tcoverImage?: string | null;\n\tprojectId?: string;\n\tcomputeServerId?: string | null;\n\t/** L2 cache quota (see {@link DefinitionRecord.solveCacheLimit}); `null` clears to inherit. */\n\tsolveCacheLimit?: number | null;\n\tstatus?: DefinitionStatus;\n\townerId?: string;\n\tsourceDocumentId?: string | null;\n}\n\nexport type DefinitionChannel = z.infer<typeof DefinitionChannelSchema>;\n"],"mappings":"AASA,IAAa,gBAA0B,CAJT,MAAM,KAIG,CAAA,CAAqB,KAAK,QAAQ,IAAI,KAAK;AAElF,IAAa,4BAAoD;CAChE,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,SAAS;CACT,QAAQ;AACT;AA4JA,SAAgB,qBAAqB,GAAyC;CAC7E,OAAO;EACN,MAAM,EAAE;EACR,WAAW,EAAE;EACb,aAAa,EAAE;EACf,aAAa,EAAE;EACf,UAAU,EAAE;EACZ,MAAM,EAAE;EACR,YAAY,EAAE;EACd,QAAQ,EAAE;EACV,YAAY,EAAE;EACd,eAAe,EAAE;EACjB,kBAAkB,EAAE,oBAAoB;EACxC,WAAW,EAAE;CACd;AACD"}
|
|
@@ -2,8 +2,9 @@ import { E as scoped, V as NoopLogger, h as requireCanSolve, j as isApiError } f
|
|
|
2
2
|
import { a as getComputeServerConfigStore, h as getOrganizationProvider, s as getDefinitionMeta, v as getProjectProvider, x as getStorageProvider } from "../../../../chunks/providers.server.js";
|
|
3
3
|
import "../../../../chunks/api.js";
|
|
4
4
|
import { n as renderThrown } from "../../../../chunks/logging.js";
|
|
5
|
+
import { i as savedValuesToRecord, n as savedValuesFrom, r as savedValuesFromRecord, t as applySavedValues } from "../../../../chunks/saved-values.js";
|
|
5
6
|
import { t as UI_SCHEMA_VERSION } from "../../../../chunks/schema.js";
|
|
6
|
-
import { d as withTimeout,
|
|
7
|
+
import { d as withTimeout, i as compareSchemaVersion, l as isOlderMinorSchemaVersion, s as fetchSchemaFromCompute } from "../../../../chunks/errors.js";
|
|
7
8
|
import { t as asHttpError } from "../../../../chunks/access2.server.js";
|
|
8
9
|
import { d as solveDeadlineFor, l as getClient, t as COMPUTE_DEBUG } from "../../../../chunks/engine.server.js";
|
|
9
10
|
import { t as serverResolver } from "../../../../chunks/serverResolver.server.js";
|
|
@@ -62,6 +63,7 @@ function createDefinitionLoader(deps) {
|
|
|
62
63
|
await reportUnhealthyIO(record, io, () => client.getRawIO(source));
|
|
63
64
|
const values = savedValuesFrom(io.inputs);
|
|
64
65
|
setBounded(savedValues, version.id, values);
|
|
66
|
+
if (!version.savedValues && values.size > 0) persistSavedValues(ctx, version.id, values);
|
|
65
67
|
const schema = applySavedValues(extracted, values);
|
|
66
68
|
const extractedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
67
69
|
if (!fresh) setBounded(extracts, version.id, {
|
|
@@ -89,6 +91,14 @@ function createDefinitionLoader(deps) {
|
|
|
89
91
|
});
|
|
90
92
|
});
|
|
91
93
|
}
|
|
94
|
+
function persistSavedValues(ctx, versionId, values) {
|
|
95
|
+
definitions.setVersionSavedValues(ctx, versionId, savedValuesToRecord(values)).catch((err) => {
|
|
96
|
+
warn(`[loadForRender] saved values write failed for version ${versionId}: ${messageOf(err)}`, "Saved values write failed", {
|
|
97
|
+
versionId,
|
|
98
|
+
err: err instanceof Error ? err.stack ?? err.message : String(err)
|
|
99
|
+
});
|
|
100
|
+
});
|
|
101
|
+
}
|
|
92
102
|
async function reportUnhealthyIO(record, io, readRawIO) {
|
|
93
103
|
const parseErrors = io.parseErrors ?? [];
|
|
94
104
|
const loadErrors = io.loadErrors ?? [];
|
|
@@ -179,7 +189,7 @@ function createDefinitionLoader(deps) {
|
|
|
179
189
|
schema: fresh,
|
|
180
190
|
defaultsPending: false
|
|
181
191
|
};
|
|
182
|
-
const values = savedValues.get(version.id);
|
|
192
|
+
const values = version.savedValues ? savedValuesFromRecord(version.savedValues) : savedValues.get(version.id);
|
|
183
193
|
if (fresh && values) return {
|
|
184
194
|
...loaded,
|
|
185
195
|
schema: applySavedValues(fresh, values),
|
|
@@ -259,7 +269,8 @@ var load$1 = createDefinitionLoader({
|
|
|
259
269
|
storage: { get: (key) => getStorageProvider().get(key) },
|
|
260
270
|
definitions: {
|
|
261
271
|
getVersion: (ctx, versionId) => getDefinitionMeta().getVersion(ctx, versionId),
|
|
262
|
-
setVersionSchema: (ctx, versionId, schema) => getDefinitionMeta().setVersionSchema(ctx, versionId, schema)
|
|
272
|
+
setVersionSchema: (ctx, versionId, schema) => getDefinitionMeta().setVersionSchema(ctx, versionId, schema),
|
|
273
|
+
setVersionSavedValues: (ctx, versionId, values) => getDefinitionMeta().setVersionSavedValues(ctx, versionId, values)
|
|
263
274
|
},
|
|
264
275
|
projects: { getProject: (ctx, projectId) => getProjectProvider().getProject(ctx, projectId) },
|
|
265
276
|
resolveServer: (ctx, orgId, opts) => serverResolver.resolve(ctx, orgId, getComputeServerConfigStore(), opts),
|
|
@@ -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 { applySavedValues, savedValuesFrom, type SavedValues } 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'>;\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 once per version per process. The stored row may already hold them, but nothing on the\n\t// row says so, and a context that 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\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// 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 = 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},\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":";;;;;;;;;;;;AA0DA,IAAa,sBAA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C5B,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}\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,QAAQ,OAAO,OAAO;OACrB,OAAO,KAAK,OAAO;GAAE,WAAW;GAAiB,GAAG;EAAO,CAAC;CAClE;CAEA,SAAS,gBAAgB,SAA6C;EACrE,MAAM,MAAM,QAAQ;EACpB,IAAI,OAAO,qBAAqB,KA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O,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"}
|
|
@@ -5831,29 +5831,34 @@ function CalculateButton($$renderer, $$props) {
|
|
|
5831
5831
|
$$renderer.component(($$renderer) => {
|
|
5832
5832
|
const locale = getLocaleContext();
|
|
5833
5833
|
const t = derived(() => locale.messages);
|
|
5834
|
+
/** While set, the button is disabled and shows this instead: the app is not ready to solve. */
|
|
5834
5835
|
/** Beside the button, sharing its row: the panel footer's actions menu. */
|
|
5835
|
-
let { hasPendingChanges, hasNeverSolved = false, isSolving, oncalculate, trailing } = $$props;
|
|
5836
|
+
let { hasPendingChanges, hasNeverSolved = false, isSolving, hold, oncalculate, trailing } = $$props;
|
|
5836
5837
|
$$renderer.push(`<div class="bottom-0 mt-3 pb-3 pt-2 backdrop-blur-sm px-2 sticky border-t border-border"><span class="sr-only" role="status" aria-live="polite">${escape_html("")}</span> <div class="gap-2 flex">`);
|
|
5837
5838
|
Button($$renderer, {
|
|
5838
5839
|
variant: hasPendingChanges ? "default" : "ghost",
|
|
5839
5840
|
size: "lg",
|
|
5840
|
-
onclick: () => !isSolving && oncalculate(),
|
|
5841
|
-
disabled: !hasPendingChanges && !isSolving,
|
|
5841
|
+
onclick: () => !isSolving && !hold && oncalculate(),
|
|
5842
|
+
disabled: !!hold || !hasPendingChanges && !isSolving,
|
|
5842
5843
|
"aria-busy": isSolving,
|
|
5843
5844
|
class: `gap-2 font-medium min-w-0 flex-1 transition-all duration-200
|
|
5844
5845
|
${hasPendingChanges && !isSolving ? "shadow-md" : ""}
|
|
5845
5846
|
${!hasPendingChanges && !isSolving ? "text-muted-foreground" : ""}`,
|
|
5846
5847
|
children: ($$renderer) => {
|
|
5847
|
-
if (isSolving) {
|
|
5848
|
+
if (hold && !isSolving) {
|
|
5848
5849
|
$$renderer.push("<!--[0-->");
|
|
5849
5850
|
Loader_circle($$renderer, { class: "h-4 w-4 animate-spin" });
|
|
5851
|
+
$$renderer.push(`<!----> ${escape_html(hold)}`);
|
|
5852
|
+
} else if (isSolving) {
|
|
5853
|
+
$$renderer.push("<!--[1-->");
|
|
5854
|
+
Loader_circle($$renderer, { class: "h-4 w-4 animate-spin" });
|
|
5850
5855
|
$$renderer.push(`<!----> ${escape_html(t().solvingEllipsis)} <kbd class="px-1 rounded-sm border border-current/30 font-sans text-2xs opacity-70"${attr("title", t().solveMessagesEscHint)}>Esc</kbd>`);
|
|
5851
5856
|
} else if (hasNeverSolved) {
|
|
5852
|
-
$$renderer.push("<!--[
|
|
5857
|
+
$$renderer.push("<!--[2-->");
|
|
5853
5858
|
Play($$renderer, { class: "h-4 w-4" });
|
|
5854
5859
|
$$renderer.push(`<!----> ${escape_html(t().pressToCalculate)}`);
|
|
5855
5860
|
} else if (hasPendingChanges) {
|
|
5856
|
-
$$renderer.push("<!--[
|
|
5861
|
+
$$renderer.push("<!--[3-->");
|
|
5857
5862
|
Zap($$renderer, { class: "h-4 w-4" });
|
|
5858
5863
|
$$renderer.push(`<!----> ${escape_html(t().calculate)}`);
|
|
5859
5864
|
} else $$renderer.push(`<!--[-1--><span class="size-1.5 shrink-0 rounded-full bg-success" aria-hidden="true"></span> ${escape_html(t().upToDate)}`);
|
|
@@ -14426,6 +14431,8 @@ function createSolveSession(args) {
|
|
|
14426
14431
|
let lastDispatched = null;
|
|
14427
14432
|
const state = createInitialState(currentSchema, args.scopeKey, readExternalValue);
|
|
14428
14433
|
let disposed = false;
|
|
14434
|
+
let held = false;
|
|
14435
|
+
let dispatchHeld = false;
|
|
14429
14436
|
const listeners = /* @__PURE__ */ new Set();
|
|
14430
14437
|
const emit = () => notifyAll(listeners, void 0);
|
|
14431
14438
|
const driverSolveFiles = args.driver.solveFiles;
|
|
@@ -14503,6 +14510,10 @@ function createSolveSession(args) {
|
|
|
14503
14510
|
}
|
|
14504
14511
|
function dispatch() {
|
|
14505
14512
|
if (disposed) return;
|
|
14513
|
+
if (held) {
|
|
14514
|
+
dispatchHeld = true;
|
|
14515
|
+
return emit();
|
|
14516
|
+
}
|
|
14506
14517
|
dropHeld();
|
|
14507
14518
|
lastSent = { ...pickInputValues(currentSchema, state.values) };
|
|
14508
14519
|
lastDispatched = lastSent;
|
|
@@ -14589,6 +14600,10 @@ function createSolveSession(args) {
|
|
|
14589
14600
|
},
|
|
14590
14601
|
solve,
|
|
14591
14602
|
ensureSolved() {
|
|
14603
|
+
if (held) {
|
|
14604
|
+
dispatchHeld = true;
|
|
14605
|
+
return nextSettlement();
|
|
14606
|
+
}
|
|
14592
14607
|
const busy = args.driver.isSolving || args.driver.hasQueued === true;
|
|
14593
14608
|
const step = ensureSolvedStep(state, busy);
|
|
14594
14609
|
if (step === "wait") return nextSettlement();
|
|
@@ -14603,6 +14618,13 @@ function createSolveSession(args) {
|
|
|
14603
14618
|
diagnostics: state.diagnostics
|
|
14604
14619
|
});
|
|
14605
14620
|
},
|
|
14621
|
+
hold(on) {
|
|
14622
|
+
if (held === on) return;
|
|
14623
|
+
held = on;
|
|
14624
|
+
if (on || !dispatchHeld) return;
|
|
14625
|
+
dispatchHeld = false;
|
|
14626
|
+
dispatch();
|
|
14627
|
+
},
|
|
14606
14628
|
onSettled(listener) {
|
|
14607
14629
|
settledListeners.add(listener);
|
|
14608
14630
|
return () => settledListeners.delete(listener);
|
|
@@ -14615,6 +14637,7 @@ function createSolveSession(args) {
|
|
|
14615
14637
|
if (disposed) return;
|
|
14616
14638
|
abandon();
|
|
14617
14639
|
currentSchema = schema;
|
|
14640
|
+
dispatchHeld = false;
|
|
14618
14641
|
lastSent = null;
|
|
14619
14642
|
lastDispatched = null;
|
|
14620
14643
|
args.driver.reset?.();
|
|
@@ -22056,12 +22079,13 @@ function AppLayout($$renderer, $$props) {
|
|
|
22056
22079
|
/** As passed to `createSolvingIndicator`. */
|
|
22057
22080
|
/** @deprecated Ignored: the solving status always sits in the action row. */
|
|
22058
22081
|
/** Rendered above the action row, for a host that keeps the solve's messages in the flow. */
|
|
22082
|
+
/** See `ComputeApp`'s `solveHold`. */
|
|
22059
22083
|
/**
|
|
22060
22084
|
* The result for the current inputs, solving if it must (`session.ensureSolved`). Needed
|
|
22061
22085
|
* by `solvesFirst` actions; without it they run straight away.
|
|
22062
22086
|
*/
|
|
22063
22087
|
/** A visible button beside Calculate, for the host's one main commit action. */
|
|
22064
|
-
let { schema, showViewer: hasViewer, meshes = [], isSolving, showSolvingIndicator = false, solveIsSlow = false, live, onabort, freezesDuringSolve = false, solveMessages, hasPendingChanges = false, hasNeverSolved = false, isViewerFullscreen = false, oncalculate = () => {}, ensureSolved, values, onValueChange, onLoadValues, panelActions = [], primaryAction, showSaveButton = true, showLoadButton = true, onSaveState, onListStates, presetLabels, viewerConfig = {}, logoUrl, onViewerReady } = $$props;
|
|
22088
|
+
let { schema, showViewer: hasViewer, meshes = [], isSolving, showSolvingIndicator = false, solveIsSlow = false, live, onabort, freezesDuringSolve = false, solveMessages, hasPendingChanges = false, hasNeverSolved = false, solveHold, isViewerFullscreen = false, oncalculate = () => {}, ensureSolved, values, onValueChange, onLoadValues, panelActions = [], primaryAction, showSaveButton = true, showLoadButton = true, onSaveState, onListStates, presetLabels, viewerConfig = {}, logoUrl, onViewerReady } = $$props;
|
|
22065
22089
|
const presetText = derived(() => ({
|
|
22066
22090
|
...DEFAULT_PRESET_LABELS,
|
|
22067
22091
|
...presetLabels
|
|
@@ -22296,6 +22320,7 @@ function AppLayout($$renderer, $$props) {
|
|
|
22296
22320
|
hasPendingChanges,
|
|
22297
22321
|
hasNeverSolved,
|
|
22298
22322
|
isSolving,
|
|
22323
|
+
hold: solveHold,
|
|
22299
22324
|
oncalculate,
|
|
22300
22325
|
trailing: hasMenu() || primaryAction ? footerActions : void 0
|
|
22301
22326
|
});
|
|
@@ -22870,6 +22895,7 @@ function useSolveSession(args) {
|
|
|
22870
22895
|
setValue: (id, value, forceSolve) => session.setValue(id, value, forceSolve),
|
|
22871
22896
|
solve: () => session.solve(),
|
|
22872
22897
|
ensureSolved: () => session.ensureSolved(),
|
|
22898
|
+
hold: (on) => session.hold(on),
|
|
22873
22899
|
onSettled: (listener) => session.onSettled(listener),
|
|
22874
22900
|
loadValues: (incoming) => session.loadValues(incoming),
|
|
22875
22901
|
rebuild: (schema, scopeKey) => session.rebuild(schema, scopeKey),
|
|
@@ -23634,6 +23660,10 @@ function ComputeApp($$renderer, $$props) {
|
|
|
23634
23660
|
* have finished.
|
|
23635
23661
|
*/
|
|
23636
23662
|
/**
|
|
23663
|
+
* While set, the app is not ready to solve: the calculate button is disabled and shows this
|
|
23664
|
+
* text, and every solve waits until it clears (`SolveSession.hold`).
|
|
23665
|
+
*/
|
|
23666
|
+
/**
|
|
23637
23667
|
* Live events for the solves this app runs (`createSolveEventStream`). Pair it with
|
|
23638
23668
|
* `streamId` on the `createComputeFetchSolveFn` that backs `onSolve`, or the server has
|
|
23639
23669
|
* no stream to route to. Without it the app works as before, just with no mid-solve news.
|
|
@@ -23668,7 +23698,7 @@ function ComputeApp($$renderer, $$props) {
|
|
|
23668
23698
|
* placeholder in the default is filled the same way in an override. The preset manager's
|
|
23669
23699
|
* strings come from `presetLabels` instead.
|
|
23670
23700
|
*/
|
|
23671
|
-
let { schema, onSolve, definitionKey = "", title, logo, isEmbedded, primaryColor, showModeToggle = false, panelActions = [], primaryAction, showSaveButton = true, showLoadButton = true, onSaveState, onListStates, presetLabels, copyrightName, footerText, solveDeadlineMs, events, footerComponent, footerComponentProps, footerItemId = "footer-item", footerItemPriority = 0, headerRight, navItems, homeUrl, brandName, header, onReady, onSolved, onViewerReady, loadRhino, viewerConfig = {}, externalScopeKey, clientSlot, lang, messages } = $$props;
|
|
23701
|
+
let { schema, onSolve, definitionKey = "", title, logo, isEmbedded, primaryColor, showModeToggle = false, panelActions = [], primaryAction, showSaveButton = true, showLoadButton = true, onSaveState, onListStates, presetLabels, copyrightName, footerText, solveDeadlineMs, solveHold, events, footerComponent, footerComponentProps, footerItemId = "footer-item", footerItemPriority = 0, headerRight, navItems, homeUrl, brandName, header, onReady, onSolved, onViewerReady, loadRhino, viewerConfig = {}, externalScopeKey, clientSlot, lang, messages } = $$props;
|
|
23672
23702
|
setClientSlot(clientSlot);
|
|
23673
23703
|
const locale = layerLocaleContext(() => lang, () => messages);
|
|
23674
23704
|
const t = derived(() => locale.messages);
|
|
@@ -23684,6 +23714,7 @@ function ComputeApp($$renderer, $$props) {
|
|
|
23684
23714
|
scopeKey: externalScopeKey || definitionKey || schema?.id || "",
|
|
23685
23715
|
driver
|
|
23686
23716
|
});
|
|
23717
|
+
session.hold(!!solveHold);
|
|
23687
23718
|
setDeferredFilesContext({
|
|
23688
23719
|
get files() {
|
|
23689
23720
|
return session.files;
|
|
@@ -23795,6 +23826,7 @@ function ComputeApp($$renderer, $$props) {
|
|
|
23795
23826
|
onabort: () => session.abort(),
|
|
23796
23827
|
hasPendingChanges: session.hasPendingChanges,
|
|
23797
23828
|
hasNeverSolved: session.hasNeverSolved,
|
|
23829
|
+
solveHold,
|
|
23798
23830
|
values: session.values,
|
|
23799
23831
|
logoUrl: logo,
|
|
23800
23832
|
onViewerReady: handleViewerReady,
|
|
@@ -23902,6 +23934,7 @@ function _page($$renderer, $$props) {
|
|
|
23902
23934
|
return held.schema;
|
|
23903
23935
|
});
|
|
23904
23936
|
function handleReady(api) {}
|
|
23937
|
+
let readingSavedValues = run(() => data.defaultsPending);
|
|
23905
23938
|
{
|
|
23906
23939
|
function navItems($$renderer) {
|
|
23907
23940
|
if (isAuthed()) {
|
|
@@ -23939,6 +23972,7 @@ function _page($$renderer, $$props) {
|
|
|
23939
23972
|
brandName: pageData().branding?.name,
|
|
23940
23973
|
homeUrl: "/",
|
|
23941
23974
|
solveDeadlineMs: data.solveDeadlineMs,
|
|
23975
|
+
solveHold: readingSavedValues ? "Reading saved values…" : void 0,
|
|
23942
23976
|
events: liveEvents ?? void 0,
|
|
23943
23977
|
loadRhino,
|
|
23944
23978
|
footerComponent: ServerFooter,
|