@selvajs/server 0.2.0-beta.1
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/LICENSE +21 -0
- package/dist/compute/__tests__/client-cache.test.d.ts +11 -0
- package/dist/compute/__tests__/client-cache.test.d.ts.map +1 -0
- package/dist/compute/__tests__/client-cache.test.js +149 -0
- package/dist/compute/__tests__/client-cache.test.js.map +1 -0
- package/dist/compute/__tests__/rate-limit.test.d.ts +2 -0
- package/dist/compute/__tests__/rate-limit.test.d.ts.map +1 -0
- package/dist/compute/__tests__/rate-limit.test.js +62 -0
- package/dist/compute/__tests__/rate-limit.test.js.map +1 -0
- package/dist/compute/__tests__/remote-definition.test.d.ts +11 -0
- package/dist/compute/__tests__/remote-definition.test.d.ts.map +1 -0
- package/dist/compute/__tests__/remote-definition.test.js +114 -0
- package/dist/compute/__tests__/remote-definition.test.js.map +1 -0
- package/dist/compute/__tests__/safe-url.test.d.ts +2 -0
- package/dist/compute/__tests__/safe-url.test.d.ts.map +1 -0
- package/dist/compute/__tests__/safe-url.test.js +71 -0
- package/dist/compute/__tests__/safe-url.test.js.map +1 -0
- package/dist/compute/__tests__/solve-pipeline.test.d.ts +11 -0
- package/dist/compute/__tests__/solve-pipeline.test.d.ts.map +1 -0
- package/dist/compute/__tests__/solve-pipeline.test.js +245 -0
- package/dist/compute/__tests__/solve-pipeline.test.js.map +1 -0
- package/dist/compute/__tests__/transform-input.test.d.ts +14 -0
- package/dist/compute/__tests__/transform-input.test.d.ts.map +1 -0
- package/dist/compute/__tests__/transform-input.test.js +114 -0
- package/dist/compute/__tests__/transform-input.test.js.map +1 -0
- package/dist/compute/client-cache.d.ts +104 -0
- package/dist/compute/client-cache.d.ts.map +1 -0
- package/dist/compute/client-cache.js +147 -0
- package/dist/compute/client-cache.js.map +1 -0
- package/dist/compute/index.d.ts +8 -0
- package/dist/compute/index.d.ts.map +1 -0
- package/dist/compute/index.js +9 -0
- package/dist/compute/index.js.map +1 -0
- package/dist/compute/limits.d.ts +102 -0
- package/dist/compute/limits.d.ts.map +1 -0
- package/dist/compute/limits.js +76 -0
- package/dist/compute/limits.js.map +1 -0
- package/dist/compute/rate-limit.d.ts +49 -0
- package/dist/compute/rate-limit.d.ts.map +1 -0
- package/dist/compute/rate-limit.js +49 -0
- package/dist/compute/rate-limit.js.map +1 -0
- package/dist/compute/remote-definition.d.ts +53 -0
- package/dist/compute/remote-definition.d.ts.map +1 -0
- package/dist/compute/remote-definition.js +110 -0
- package/dist/compute/remote-definition.js.map +1 -0
- package/dist/compute/safe-url.d.ts +15 -0
- package/dist/compute/safe-url.d.ts.map +1 -0
- package/dist/compute/safe-url.js +195 -0
- package/dist/compute/safe-url.js.map +1 -0
- package/dist/compute/solve-pipeline.d.ts +127 -0
- package/dist/compute/solve-pipeline.d.ts.map +1 -0
- package/dist/compute/solve-pipeline.js +195 -0
- package/dist/compute/solve-pipeline.js.map +1 -0
- package/dist/compute/transform-input.d.ts +20 -0
- package/dist/compute/transform-input.d.ts.map +1 -0
- package/dist/compute/transform-input.js +47 -0
- package/dist/compute/transform-input.js.map +1 -0
- package/dist/definitions/__tests__/load-for-render.test.d.ts +8 -0
- package/dist/definitions/__tests__/load-for-render.test.d.ts.map +1 -0
- package/dist/definitions/__tests__/load-for-render.test.js +196 -0
- package/dist/definitions/__tests__/load-for-render.test.js.map +1 -0
- package/dist/definitions/__tests__/schema-extraction.test.d.ts +11 -0
- package/dist/definitions/__tests__/schema-extraction.test.d.ts.map +1 -0
- package/dist/definitions/__tests__/schema-extraction.test.js +115 -0
- package/dist/definitions/__tests__/schema-extraction.test.js.map +1 -0
- package/dist/definitions/definition-service.d.ts +77 -0
- package/dist/definitions/definition-service.d.ts.map +1 -0
- package/dist/definitions/definition-service.js +184 -0
- package/dist/definitions/definition-service.js.map +1 -0
- package/dist/definitions/index.d.ts +4 -0
- package/dist/definitions/index.d.ts.map +1 -0
- package/dist/definitions/index.js +8 -0
- package/dist/definitions/index.js.map +1 -0
- package/dist/definitions/load-for-render.d.ts +61 -0
- package/dist/definitions/load-for-render.d.ts.map +1 -0
- package/dist/definitions/load-for-render.js +165 -0
- package/dist/definitions/load-for-render.js.map +1 -0
- package/dist/definitions/schema-extraction.d.ts +22 -0
- package/dist/definitions/schema-extraction.d.ts.map +1 -0
- package/dist/definitions/schema-extraction.js +89 -0
- package/dist/definitions/schema-extraction.js.map +1 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +18 -0
- package/dist/index.js.map +1 -0
- package/dist/providers/__tests__/create-selva-providers.test.d.ts +7 -0
- package/dist/providers/__tests__/create-selva-providers.test.d.ts.map +1 -0
- package/dist/providers/__tests__/create-selva-providers.test.js +135 -0
- package/dist/providers/__tests__/create-selva-providers.test.js.map +1 -0
- package/dist/providers/create-selva-providers.d.ts +53 -0
- package/dist/providers/create-selva-providers.d.ts.map +1 -0
- package/dist/providers/create-selva-providers.js +152 -0
- package/dist/providers/create-selva-providers.js.map +1 -0
- package/dist/providers/index.d.ts +2 -0
- package/dist/providers/index.d.ts.map +1 -0
- package/dist/providers/index.js +6 -0
- package/dist/providers/index.js.map +1 -0
- package/package.json +60 -0
- package/src/compute/__tests__/client-cache.test.ts +164 -0
- package/src/compute/__tests__/rate-limit.test.ts +69 -0
- package/src/compute/__tests__/remote-definition.test.ts +140 -0
- package/src/compute/__tests__/safe-url.test.ts +72 -0
- package/src/compute/__tests__/solve-pipeline.test.ts +294 -0
- package/src/compute/__tests__/transform-input.test.ts +155 -0
- package/src/compute/client-cache.ts +278 -0
- package/src/compute/index.ts +48 -0
- package/src/compute/limits.ts +147 -0
- package/src/compute/rate-limit.ts +83 -0
- package/src/compute/remote-definition.ts +149 -0
- package/src/compute/safe-url.ts +186 -0
- package/src/compute/solve-pipeline.ts +324 -0
- package/src/compute/transform-input.ts +52 -0
- package/src/definitions/__tests__/load-for-render.test.ts +244 -0
- package/src/definitions/__tests__/schema-extraction.test.ts +137 -0
- package/src/definitions/definition-service.ts +243 -0
- package/src/definitions/index.ts +22 -0
- package/src/definitions/load-for-render.ts +272 -0
- package/src/definitions/schema-extraction.ts +117 -0
- package/src/index.ts +18 -0
- package/src/providers/__tests__/create-selva-providers.test.ts +172 -0
- package/src/providers/__tests__/fixtures/override-config.mjs +8 -0
- package/src/providers/create-selva-providers.ts +241 -0
- package/src/providers/index.ts +12 -0
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// Definitions server slice — the write orchestration (DefinitionService), the
|
|
2
|
+
// compute-schema extraction/validation gate, and the render loader. All
|
|
3
|
+
// composition-root wiring (stores, warm-client cache, server resolution) is
|
|
4
|
+
// injected; access gating stays with the calling app.
|
|
5
|
+
|
|
6
|
+
export { DefinitionService, type CreateDefinitionRecord } from './definition-service.js';
|
|
7
|
+
|
|
8
|
+
export {
|
|
9
|
+
fetchSchemaFromCompute,
|
|
10
|
+
assertSupportedSchemaVersion,
|
|
11
|
+
SchemaExtractionError
|
|
12
|
+
} from './schema-extraction.js';
|
|
13
|
+
|
|
14
|
+
export {
|
|
15
|
+
createDefinitionLoader,
|
|
16
|
+
DefinitionLoadError,
|
|
17
|
+
type DefinitionChannel,
|
|
18
|
+
type DefinitionLoader,
|
|
19
|
+
type DefinitionLoaderDeps,
|
|
20
|
+
type DefinitionLoadErrorKind,
|
|
21
|
+
type LoadedDefinition
|
|
22
|
+
} from './load-for-render.js';
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
// Loader for "given a definition record, produce everything the client needs to
|
|
2
|
+
// render its form and solve it": version resolution, blob fetch, compute-server
|
|
3
|
+
// resolution, schema fetch (with the ADR 0005 staleness check), default merging.
|
|
4
|
+
//
|
|
5
|
+
// Access gating is intentionally NOT done here — the calling route decides
|
|
6
|
+
// whether `ctx` is allowed to load this definition, since gates differ across
|
|
7
|
+
// routes (project membership, segment ownership, share-token, admin override).
|
|
8
|
+
//
|
|
9
|
+
// Everything stateful is injected (`DefinitionLoaderDeps`): stores, server
|
|
10
|
+
// resolution, the warm-client cache, and the schema fetcher — so any app built
|
|
11
|
+
// on the engine can wire its own composition root.
|
|
12
|
+
|
|
13
|
+
import type { GrasshopperClient } from '@selvajs/compute/grasshopper';
|
|
14
|
+
import { UI_SCHEMA_VERSION, type UISchema } from '@selvajs/schemas';
|
|
15
|
+
import type {
|
|
16
|
+
ComputeServerConfig,
|
|
17
|
+
DefinitionRecord,
|
|
18
|
+
DefinitionVersion,
|
|
19
|
+
IDefinitionStore,
|
|
20
|
+
IProjectStore,
|
|
21
|
+
IStorageProvider,
|
|
22
|
+
RequestContext
|
|
23
|
+
} from '@selvajs/platform';
|
|
24
|
+
import { fetchSchemaFromCompute } from './schema-extraction.js';
|
|
25
|
+
|
|
26
|
+
export type DefinitionChannel = 'live' | 'draft';
|
|
27
|
+
|
|
28
|
+
export interface LoadedDefinition {
|
|
29
|
+
version: DefinitionVersion;
|
|
30
|
+
definitionSource: Uint8Array;
|
|
31
|
+
computeServer: ComputeServerConfig;
|
|
32
|
+
schema: UISchema;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Classified failure modes so callers can map to appropriate HTTP status:
|
|
37
|
+
* - 'data': record references a version/blob that isn't there. (400)
|
|
38
|
+
* - 'missing-config': no compute server resolvable for this org/definition. (503)
|
|
39
|
+
* - 'connect': compute server is configured but unreachable. (503)
|
|
40
|
+
* - 'schema': compute responded but IO/schema phase failed. (500)
|
|
41
|
+
*/
|
|
42
|
+
export type DefinitionLoadErrorKind = 'data' | 'missing-config' | 'connect' | 'schema';
|
|
43
|
+
|
|
44
|
+
export class DefinitionLoadError extends Error {
|
|
45
|
+
constructor(
|
|
46
|
+
public readonly kind: DefinitionLoadErrorKind,
|
|
47
|
+
message: string,
|
|
48
|
+
public readonly cause?: unknown
|
|
49
|
+
) {
|
|
50
|
+
super(message);
|
|
51
|
+
this.name = 'DefinitionLoadError';
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface DefinitionLoaderDeps {
|
|
56
|
+
storage: Pick<IStorageProvider, 'get'>;
|
|
57
|
+
definitions: Pick<IDefinitionStore, 'getVersion' | 'setVersionSchema'>;
|
|
58
|
+
projects: Pick<IProjectStore, 'getProject'>;
|
|
59
|
+
/** §3 resolution order: definition pin → org default override → global default. */
|
|
60
|
+
resolveServer: (
|
|
61
|
+
ctx: RequestContext,
|
|
62
|
+
orgId: string | null,
|
|
63
|
+
opts: { definitionPin: string | null }
|
|
64
|
+
) => Promise<ComputeServerConfig>;
|
|
65
|
+
/** Shared warm-client cache (ADR 0004: keyed by server id, definition-guid affinity header). */
|
|
66
|
+
getClient: (
|
|
67
|
+
server: ComputeServerConfig,
|
|
68
|
+
opts: { definitionGuid: string }
|
|
69
|
+
) => Promise<{ client: GrasshopperClient }>;
|
|
70
|
+
/** Schema extraction; defaults to `fetchSchemaFromCompute`. Injectable for tests. */
|
|
71
|
+
fetchSchema?: (bytes: Uint8Array, server: ComputeServerConfig) => Promise<UISchema>;
|
|
72
|
+
/**
|
|
73
|
+
* Verbose IO diagnostics — when set, an unhealthy IO result (empty inputs /
|
|
74
|
+
* parse / load errors) also dumps the raw /io wire shape so
|
|
75
|
+
* casing/serialization mismatches are visible.
|
|
76
|
+
*/
|
|
77
|
+
computeDebug?: boolean;
|
|
78
|
+
/** Diagnostic sink; defaults to `console.warn`. */
|
|
79
|
+
onWarn?: (message: string, detail?: string) => void;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export type DefinitionLoader = (
|
|
83
|
+
ctx: RequestContext,
|
|
84
|
+
record: DefinitionRecord,
|
|
85
|
+
channel: DefinitionChannel,
|
|
86
|
+
explicitVersionId?: string | null
|
|
87
|
+
) => Promise<LoadedDefinition>;
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Build a definition loader over the injected stores/compute wiring.
|
|
91
|
+
*
|
|
92
|
+
* The returned function loads a definition's version blob + schema (with
|
|
93
|
+
* merged compute defaults). By default it resolves the `channel` pointer
|
|
94
|
+
* (live/draft); pass `explicitVersionId` to render an arbitrary historical
|
|
95
|
+
* version instead — the caller must gate that behind edit permission
|
|
96
|
+
* (editor-only, like the draft channel). Throws `DefinitionLoadError` for
|
|
97
|
+
* classified failures so the caller can translate to HTTP status codes.
|
|
98
|
+
*/
|
|
99
|
+
export function createDefinitionLoader(deps: DefinitionLoaderDeps): DefinitionLoader {
|
|
100
|
+
const {
|
|
101
|
+
storage,
|
|
102
|
+
definitions,
|
|
103
|
+
projects,
|
|
104
|
+
resolveServer,
|
|
105
|
+
getClient,
|
|
106
|
+
fetchSchema = fetchSchemaFromCompute,
|
|
107
|
+
computeDebug = false,
|
|
108
|
+
onWarn = (message, detail) => (detail ? console.warn(message, detail) : console.warn(message))
|
|
109
|
+
} = deps;
|
|
110
|
+
|
|
111
|
+
return async function loadDefinitionForRender(ctx, record, channel, explicitVersionId) {
|
|
112
|
+
const versionId =
|
|
113
|
+
explicitVersionId ?? (channel === 'draft' ? record.draftVersionId : record.liveVersionId);
|
|
114
|
+
if (!versionId)
|
|
115
|
+
throw new DefinitionLoadError(
|
|
116
|
+
'data',
|
|
117
|
+
`Definition '${record.guid}' has no ${channel} version`
|
|
118
|
+
);
|
|
119
|
+
|
|
120
|
+
const version = await definitions.getVersion(ctx, versionId);
|
|
121
|
+
if (!version) throw new DefinitionLoadError('data', `version missing for '${record.guid}'`);
|
|
122
|
+
// An explicitly requested version must belong to this definition.
|
|
123
|
+
if (version.definitionId !== record.guid)
|
|
124
|
+
throw new DefinitionLoadError('data', `version does not belong to '${record.guid}'`);
|
|
125
|
+
|
|
126
|
+
const definitionSource = await storage.get(version.fileKey);
|
|
127
|
+
if (!definitionSource)
|
|
128
|
+
throw new DefinitionLoadError(
|
|
129
|
+
'data',
|
|
130
|
+
`Definition file for '${record.guid}' not found on disk`
|
|
131
|
+
);
|
|
132
|
+
|
|
133
|
+
const project = await projects.getProject(ctx, record.projectId);
|
|
134
|
+
let computeServer: ComputeServerConfig;
|
|
135
|
+
try {
|
|
136
|
+
computeServer = await resolveServer(ctx, project?.orgId ?? null, {
|
|
137
|
+
definitionPin: record.computeServerId ?? null
|
|
138
|
+
});
|
|
139
|
+
} catch (err) {
|
|
140
|
+
throw new DefinitionLoadError(
|
|
141
|
+
'missing-config',
|
|
142
|
+
'No compute server configured for this definition',
|
|
143
|
+
err
|
|
144
|
+
);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// Only the client is used here (getIO); the entry's solve scheduler rides
|
|
148
|
+
// along unused.
|
|
149
|
+
let client: GrasshopperClient;
|
|
150
|
+
try {
|
|
151
|
+
client = (await getClient(computeServer, { definitionGuid: record.guid })).client;
|
|
152
|
+
} catch (err) {
|
|
153
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
154
|
+
throw new DefinitionLoadError(
|
|
155
|
+
'connect',
|
|
156
|
+
`Failed to connect to Rhino Compute server: ${message}`,
|
|
157
|
+
err
|
|
158
|
+
);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
try {
|
|
162
|
+
// Prefer the schema cached on the version row (extracted + validated at
|
|
163
|
+
// upload) — but ONLY when its format version matches the app's. The
|
|
164
|
+
// stored schema is a disposable cache (ADR 0005): on a version mismatch
|
|
165
|
+
// (or a pre-caching row with no schema at all) re-extract from compute,
|
|
166
|
+
// whose C# SchemaMigrator emits the current format — the web side never
|
|
167
|
+
// migrates schemas itself. `getIO` is always needed to merge compute
|
|
168
|
+
// default values into the schema, cached or not.
|
|
169
|
+
const cachedSchema = version.schema as UISchema | undefined;
|
|
170
|
+
const freshCache =
|
|
171
|
+
cachedSchema && cachedSchema.schemaVersion === UI_SCHEMA_VERSION ? cachedSchema : null;
|
|
172
|
+
const [definition, fetchedSchema] = await Promise.all([
|
|
173
|
+
client.getIO(definitionSource),
|
|
174
|
+
freshCache ? Promise.resolve(freshCache) : fetchSchema(definitionSource, computeServer)
|
|
175
|
+
]);
|
|
176
|
+
|
|
177
|
+
// Persist the refreshed schema back onto the version row (best-effort —
|
|
178
|
+
// a viewer context may lack write access; the next editor render or the
|
|
179
|
+
// solve-time backfill will land it). Only when the re-extracted schema
|
|
180
|
+
// is at the app's current version: persisting an older format (compute
|
|
181
|
+
// plugin behind the app) would just go stale again next render.
|
|
182
|
+
if (!freshCache && fetchedSchema.schemaVersion === UI_SCHEMA_VERSION) {
|
|
183
|
+
definitions.setVersionSchema(ctx, version.id, fetchedSchema).catch((err) => {
|
|
184
|
+
onWarn(
|
|
185
|
+
`[loadForRender] schema cache refresh failed for version ${version.id}: ` +
|
|
186
|
+
`${err instanceof Error ? err.message : String(err)}`
|
|
187
|
+
);
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
if (!definition) {
|
|
192
|
+
throw new Error(`Failed to get definition IO — server returned undefined`);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// Surface IO health when something looks off: zero inputs, or the compute
|
|
196
|
+
// layer reported parse/load problems (e.g. an empty ValueList because its
|
|
197
|
+
// backing GH component didn't resolve → "Missing Definition Objects", or a
|
|
198
|
+
// PascalCase /io response the parser silently dropped to []). On a problem
|
|
199
|
+
// we also fetch the raw IO so the un-parsed wire shape is in the logs.
|
|
200
|
+
// Always-on warn (cheap, only fires on the unhappy path); the verbose raw
|
|
201
|
+
// dump is gated on `computeDebug`.
|
|
202
|
+
const ioParseErrors = (definition as { parseErrors?: unknown[] }).parseErrors ?? [];
|
|
203
|
+
const ioLoadErrors = (definition as { loadErrors?: unknown[] }).loadErrors ?? [];
|
|
204
|
+
const ioLooksBroken =
|
|
205
|
+
definition.inputs.length === 0 || ioParseErrors.length > 0 || ioLoadErrors.length > 0;
|
|
206
|
+
if (ioLooksBroken) {
|
|
207
|
+
onWarn(
|
|
208
|
+
`[loadForRender] IO health for '${record.guid}':`,
|
|
209
|
+
JSON.stringify({
|
|
210
|
+
inputCount: definition.inputs.length,
|
|
211
|
+
outputCount: definition.outputs?.length,
|
|
212
|
+
parseErrors: ioParseErrors,
|
|
213
|
+
loadErrors: ioLoadErrors,
|
|
214
|
+
loadWarnings: (definition as { loadWarnings?: unknown }).loadWarnings
|
|
215
|
+
})
|
|
216
|
+
);
|
|
217
|
+
if (computeDebug) {
|
|
218
|
+
const rawIO = await client
|
|
219
|
+
.getRawIO(definitionSource)
|
|
220
|
+
.catch((e) => ({ error: String(e) }));
|
|
221
|
+
onWarn('[loadForRender] raw /io:', JSON.stringify(rawIO).slice(0, 3000));
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
return {
|
|
226
|
+
version,
|
|
227
|
+
definitionSource,
|
|
228
|
+
computeServer,
|
|
229
|
+
schema: mergeComputeDefaults(fetchedSchema, definition.inputs)
|
|
230
|
+
};
|
|
231
|
+
} catch (err) {
|
|
232
|
+
if (err instanceof DefinitionLoadError) throw err;
|
|
233
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
234
|
+
throw new DefinitionLoadError('schema', message, err);
|
|
235
|
+
}
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// Merge default values from Compute definition into schema inputs.
|
|
240
|
+
// Colors come back as "r,g,b" or "a,r,g,b" strings — convert to hex so the
|
|
241
|
+
// color picker can consume them directly.
|
|
242
|
+
function mergeComputeDefaults(
|
|
243
|
+
schema: UISchema,
|
|
244
|
+
computeInputs: Array<{ id?: string; paramType?: string; default?: unknown }>
|
|
245
|
+
): UISchema {
|
|
246
|
+
const byParamId = new Map(computeInputs.map((input) => [input.id, input]));
|
|
247
|
+
|
|
248
|
+
return {
|
|
249
|
+
...schema,
|
|
250
|
+
inputs: schema.inputs.map((schemaInput) => {
|
|
251
|
+
const computeInput = byParamId.get(schemaInput.id);
|
|
252
|
+
|
|
253
|
+
if (computeInput?.paramType === 'Color' && computeInput.default !== undefined) {
|
|
254
|
+
const toHex = (value: number) => value.toString(16).padStart(2, '0');
|
|
255
|
+
const parts = String(computeInput.default)
|
|
256
|
+
.split(',')
|
|
257
|
+
.map((s) => parseInt(s.trim(), 10));
|
|
258
|
+
|
|
259
|
+
if (parts.length === 3) {
|
|
260
|
+
computeInput.default = `#${toHex(parts[0])}${toHex(parts[1])}${toHex(parts[2])}`;
|
|
261
|
+
} else if (parts.length === 4) {
|
|
262
|
+
computeInput.default = `#${toHex(parts[1])}${toHex(parts[2])}${toHex(parts[3])}`;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
if (computeInput && computeInput.default !== undefined) {
|
|
267
|
+
return { ...schemaInput, default: computeInput.default };
|
|
268
|
+
}
|
|
269
|
+
return schemaInput;
|
|
270
|
+
})
|
|
271
|
+
};
|
|
272
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
// Shared compute-schema extraction. One implementation used by:
|
|
2
|
+
// - upload routes (validate-and-cache gate — no upload without a valid schema)
|
|
3
|
+
// - the render path (falls back to live extraction for un-cached or stale
|
|
4
|
+
// versions; see load-for-render.ts and ADR 0005)
|
|
5
|
+
// - the temporary solve-time backfill bridge (see the app's specs/SchemaCaching.md)
|
|
6
|
+
//
|
|
7
|
+
// Extraction IS validation: a `.gh` with no valid "Schema" output, or an
|
|
8
|
+
// unreachable compute server, throws here and the caller rejects the upload.
|
|
9
|
+
|
|
10
|
+
import { camelcaseKeys } from '@selvajs/compute/core';
|
|
11
|
+
import { UI_SCHEMA_VERSION, type UISchema } from '@selvajs/schemas';
|
|
12
|
+
import type { ComputeServerConfig } from '@selvajs/platform';
|
|
13
|
+
|
|
14
|
+
/** Thrown when compute is reachable but the definition yields no usable schema. */
|
|
15
|
+
export class SchemaExtractionError extends Error {
|
|
16
|
+
constructor(
|
|
17
|
+
public readonly kind: 'unreachable' | 'invalid' | 'unsupported',
|
|
18
|
+
message: string
|
|
19
|
+
) {
|
|
20
|
+
super(message);
|
|
21
|
+
this.name = 'SchemaExtractionError';
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function parseSemver(version: string): [number, number, number] | null {
|
|
26
|
+
const m = /^(\d+)\.(\d+)\.(\d+)$/.exec(version);
|
|
27
|
+
return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Plugin↔app compat gate: reject a schema emitted by a NEWER plugin than this
|
|
32
|
+
* app was built against — its shape may contain constructs the renderer does
|
|
33
|
+
* not know. Older (or missing) versions pass: the compute-side C# migrator
|
|
34
|
+
* always emits its own current version, and an older shape only lacks
|
|
35
|
+
* optional additions.
|
|
36
|
+
*/
|
|
37
|
+
export function assertSupportedSchemaVersion(schema: UISchema): void {
|
|
38
|
+
const version = schema.schemaVersion;
|
|
39
|
+
if (!version) return; // pre-2.12.0 plugin — older than the app, fine
|
|
40
|
+
const extracted = parseSemver(version);
|
|
41
|
+
const supported = parseSemver(UI_SCHEMA_VERSION);
|
|
42
|
+
if (!extracted || !supported) return;
|
|
43
|
+
const newer =
|
|
44
|
+
extracted[0] > supported[0] ||
|
|
45
|
+
(extracted[0] === supported[0] &&
|
|
46
|
+
(extracted[1] > supported[1] ||
|
|
47
|
+
(extracted[1] === supported[1] && extracted[2] > supported[2])));
|
|
48
|
+
if (newer) {
|
|
49
|
+
throw new SchemaExtractionError(
|
|
50
|
+
'unsupported',
|
|
51
|
+
`This definition was authored with a newer Selva plugin (schema format ${version}); ` +
|
|
52
|
+
`this server supports schema format ≤ ${UI_SCHEMA_VERSION}. Update the server, or ` +
|
|
53
|
+
`re-save the definition with a matching plugin version.`
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Fetch the UI schema from Rhino Compute's `/grasshopper/schema` endpoint (no
|
|
60
|
+
* solve required). Throws `SchemaExtractionError` so callers can map to the
|
|
61
|
+
* right HTTP status (503 unreachable / 422 invalid or unsupported).
|
|
62
|
+
*/
|
|
63
|
+
export async function fetchSchemaFromCompute(
|
|
64
|
+
definitionBytes: Uint8Array,
|
|
65
|
+
server: ComputeServerConfig
|
|
66
|
+
): Promise<UISchema> {
|
|
67
|
+
const schemaUrl = new URL('/grasshopper/schema', server.serverUrl).toString();
|
|
68
|
+
|
|
69
|
+
const formData = new FormData();
|
|
70
|
+
const blob = new Blob([new Uint8Array(definitionBytes)], { type: 'application/octet-stream' });
|
|
71
|
+
formData.append('file', blob, 'definition.gh');
|
|
72
|
+
|
|
73
|
+
const headers: Record<string, string> = {};
|
|
74
|
+
if (server.apiKey) {
|
|
75
|
+
headers['RhinoComputeKey'] = server.apiKey;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
let response: Response;
|
|
79
|
+
try {
|
|
80
|
+
response = await fetch(schemaUrl, { method: 'POST', headers, body: formData });
|
|
81
|
+
} catch (err) {
|
|
82
|
+
throw new SchemaExtractionError(
|
|
83
|
+
'unreachable',
|
|
84
|
+
`Compute server is unreachable: ${err instanceof Error ? err.message : String(err)}`
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
if (!response.ok) {
|
|
89
|
+
throw new SchemaExtractionError(
|
|
90
|
+
'unreachable',
|
|
91
|
+
`Schema endpoint returned ${response.status}: ${response.statusText}`
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// Compute returns [{ FileName, Schemas }] with PascalCase wrapper keys only.
|
|
96
|
+
// The schema contents are already camelCase from our C# serializer, so we only
|
|
97
|
+
// need a shallow camelcase per wrapper to normalize FileName→fileName,
|
|
98
|
+
// Schemas→schemas (shallow camelcaseKeys is a no-op on arrays, so each
|
|
99
|
+
// element is normalized individually). deep:true would mangle user-defined
|
|
100
|
+
// option names (e.g. "Display3d" → "display3d").
|
|
101
|
+
const raw = await response.json();
|
|
102
|
+
const results = (Array.isArray(raw) ? raw : [raw]).map((r) => camelcaseKeys(r)) as {
|
|
103
|
+
schemas: UISchema[];
|
|
104
|
+
}[];
|
|
105
|
+
const schemas = results.flatMap((r) => r.schemas ?? []);
|
|
106
|
+
|
|
107
|
+
if (schemas.length === 0) {
|
|
108
|
+
throw new SchemaExtractionError(
|
|
109
|
+
'invalid',
|
|
110
|
+
'No schemas found in definition.\n\n' +
|
|
111
|
+
'In Grasshopper, verify a Context Bake component with the output name "Schema" is present and wired to the solver.'
|
|
112
|
+
);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
assertSupportedSchemaVersion(schemas[0]);
|
|
116
|
+
return schemas[0];
|
|
117
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@selvajs/server` — transport-agnostic compute/solve server building blocks
|
|
3
|
+
* for apps built on the Selva engine.
|
|
4
|
+
*
|
|
5
|
+
* The compute stack (limits, per-key rate limiting, SSRF guard, input
|
|
6
|
+
* transform) that used to live inside the `@selvajs/selva` app, extracted so a
|
|
7
|
+
* consuming app can reuse it instead of copying it. Everything here is
|
|
8
|
+
* env-injected (no ambient `$env` / `process.env`) and framework-agnostic.
|
|
9
|
+
*
|
|
10
|
+
* The full compute subsurface is also available at `@selvajs/server/compute`,
|
|
11
|
+
* the definitions slice (DefinitionService, schema extraction/validation,
|
|
12
|
+
* render loader) at `@selvajs/server/definitions`, and the provider wiring
|
|
13
|
+
* (registry-driven `createSelvaProviders`) at `@selvajs/server/providers`.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
export * from './compute/index.js';
|
|
17
|
+
export * from './definitions/index.js';
|
|
18
|
+
export * from './providers/index.js';
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tests for `createSelvaProviders` (K5) — registry-driven provider selection,
|
|
3
|
+
* lazy memoized instantiation, config parsing (flags/branding/tenancy), the
|
|
4
|
+
* solve-metrics duck-type pick, and the external config-path override.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { describe, it, expect, vi } from 'vitest';
|
|
8
|
+
import { fileURLToPath } from 'node:url';
|
|
9
|
+
import type { IAuthProvider, IDataProvider, IStorageProvider } from '@selvajs/platform';
|
|
10
|
+
import { createSelvaProviders, type ProviderRegistry } from '../create-selva-providers.js';
|
|
11
|
+
|
|
12
|
+
class FakeData {}
|
|
13
|
+
class FakeStorage {}
|
|
14
|
+
|
|
15
|
+
function makeRegistry() {
|
|
16
|
+
const authLocal = vi.fn(() => ({ name: 'local-auth' }) as unknown as IAuthProvider);
|
|
17
|
+
const authSupabase = vi.fn(() => ({ name: 'supabase-auth' }) as unknown as IAuthProvider);
|
|
18
|
+
const dataLocal = vi.fn(() => new FakeData() as unknown as IDataProvider);
|
|
19
|
+
const dataSupabase = vi.fn(() => new FakeData() as unknown as IDataProvider);
|
|
20
|
+
const storageLocal = vi.fn(() => new FakeStorage() as unknown as IStorageProvider);
|
|
21
|
+
const registry: ProviderRegistry = {
|
|
22
|
+
auth: { local: authLocal, supabase: authSupabase },
|
|
23
|
+
data: { local: dataLocal, supabase: dataSupabase },
|
|
24
|
+
storage: { local: storageLocal }
|
|
25
|
+
};
|
|
26
|
+
return { registry, authLocal, authSupabase, dataLocal, dataSupabase, storageLocal };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const noBoot = { onBoot: () => {} };
|
|
30
|
+
|
|
31
|
+
describe('registry selection', () => {
|
|
32
|
+
it('falls back to "local" for every slot when env is empty', async () => {
|
|
33
|
+
const { registry, authLocal, dataLocal, storageLocal } = makeRegistry();
|
|
34
|
+
const runtime = await createSelvaProviders({}, { registry, ...noBoot });
|
|
35
|
+
runtime.resolve();
|
|
36
|
+
expect(authLocal).toHaveBeenCalledTimes(1);
|
|
37
|
+
expect(dataLocal).toHaveBeenCalledTimes(1);
|
|
38
|
+
expect(storageLocal).toHaveBeenCalledTimes(1);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it('honors SELVA_*_PROVIDER env choices, case-insensitively', async () => {
|
|
42
|
+
const { registry, authSupabase, dataSupabase } = makeRegistry();
|
|
43
|
+
const runtime = await createSelvaProviders(
|
|
44
|
+
{ SELVA_AUTH_PROVIDER: 'Supabase', SELVA_DATA_PROVIDER: 'SUPABASE' },
|
|
45
|
+
{ registry, ...noBoot }
|
|
46
|
+
);
|
|
47
|
+
runtime.resolve();
|
|
48
|
+
expect(authSupabase).toHaveBeenCalledTimes(1);
|
|
49
|
+
expect(dataSupabase).toHaveBeenCalledTimes(1);
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
it('honors the defaults option over the built-in "local"', async () => {
|
|
53
|
+
const { registry, authSupabase } = makeRegistry();
|
|
54
|
+
const runtime = await createSelvaProviders(
|
|
55
|
+
{},
|
|
56
|
+
{ registry, defaults: { auth: 'supabase' }, ...noBoot }
|
|
57
|
+
);
|
|
58
|
+
runtime.resolve();
|
|
59
|
+
expect(authSupabase).toHaveBeenCalledTimes(1);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
it('rejects an unknown choice, listing the registered names', async () => {
|
|
63
|
+
const { registry } = makeRegistry();
|
|
64
|
+
const runtime = await createSelvaProviders(
|
|
65
|
+
{ SELVA_AUTH_PROVIDER: 'okta' },
|
|
66
|
+
{ registry, ...noBoot }
|
|
67
|
+
);
|
|
68
|
+
expect(() => runtime.resolve()).toThrow(/SELVA_AUTH_PROVIDER="okta".*local \| supabase/);
|
|
69
|
+
});
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
describe('laziness and memoization', () => {
|
|
73
|
+
it('does not instantiate providers until resolve() is called', async () => {
|
|
74
|
+
const { registry, authLocal } = makeRegistry();
|
|
75
|
+
await createSelvaProviders({}, { registry, ...noBoot });
|
|
76
|
+
expect(authLocal).not.toHaveBeenCalled();
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
it('instantiates once and logs the boot summary once across repeated resolves', async () => {
|
|
80
|
+
const { registry, authLocal } = makeRegistry();
|
|
81
|
+
const onBoot = vi.fn();
|
|
82
|
+
const runtime = await createSelvaProviders({}, { registry, onBoot });
|
|
83
|
+
runtime.resolve();
|
|
84
|
+
runtime.resolve();
|
|
85
|
+
runtime.flag('ENABLE_SHARING');
|
|
86
|
+
expect(authLocal).toHaveBeenCalledTimes(1);
|
|
87
|
+
expect(onBoot).toHaveBeenCalledTimes(1);
|
|
88
|
+
expect(onBoot.mock.calls[0][0]).toContain('auth=local-auth');
|
|
89
|
+
expect(onBoot.mock.calls[0][0]).toContain('data=FakeData');
|
|
90
|
+
expect(onBoot.mock.calls[0][0]).toContain('tenancy=single');
|
|
91
|
+
});
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
describe('config parsing', () => {
|
|
95
|
+
it('parses flags from SELVA_FLAG_* (omitted → false)', async () => {
|
|
96
|
+
const { registry } = makeRegistry();
|
|
97
|
+
const runtime = await createSelvaProviders(
|
|
98
|
+
{ SELVA_FLAG_ENABLE_SHARING: 'true', SELVA_FLAG_ALLOW_ORG_CREATION: 'no' },
|
|
99
|
+
{ registry, ...noBoot }
|
|
100
|
+
);
|
|
101
|
+
expect(runtime.flag('ENABLE_SHARING')).toBe(true);
|
|
102
|
+
expect(runtime.flag('ALLOW_ORG_CREATION')).toBe(false);
|
|
103
|
+
expect(runtime.flag('ALLOW_CROSS_ORG_PUBLIC')).toBe(false);
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
it('parses tenancy and rejects unknown values', async () => {
|
|
107
|
+
const { registry } = makeRegistry();
|
|
108
|
+
const multi = await createSelvaProviders({ SELVA_TENANCY: 'multi' }, { registry, ...noBoot });
|
|
109
|
+
expect(multi.tenancy()).toBe('multi');
|
|
110
|
+
|
|
111
|
+
const bad = await createSelvaProviders({ SELVA_TENANCY: 'galactic' }, { registry, ...noBoot });
|
|
112
|
+
expect(() => bad.tenancy()).toThrow(/SELVA_TENANCY="galactic"/);
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
it('brands with defaults; copyright falls back to the overridden name', async () => {
|
|
116
|
+
const { registry } = makeRegistry();
|
|
117
|
+
const plain = await createSelvaProviders({}, { registry, ...noBoot });
|
|
118
|
+
expect(plain.branding().name).toBe('Selva');
|
|
119
|
+
expect(plain.branding().copyrightName).toBe('Selva');
|
|
120
|
+
expect(plain.branding().tagline).toBeTruthy();
|
|
121
|
+
|
|
122
|
+
const branded = await createSelvaProviders(
|
|
123
|
+
{ SELVA_BRAND_NAME: ' Acme ' },
|
|
124
|
+
{ registry, ...noBoot }
|
|
125
|
+
);
|
|
126
|
+
expect(branded.branding().name).toBe('Acme');
|
|
127
|
+
expect(branded.branding().copyrightName).toBe('Acme');
|
|
128
|
+
expect(branded.branding().description).toContain('Acme');
|
|
129
|
+
});
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
describe('solve metric sink', () => {
|
|
133
|
+
it('falls back to a noop sink when the data provider has no solveMetrics', async () => {
|
|
134
|
+
const { registry } = makeRegistry();
|
|
135
|
+
const runtime = await createSelvaProviders({}, { registry, ...noBoot });
|
|
136
|
+
const sink = runtime.solveMetricSink();
|
|
137
|
+
expect(typeof sink.record).toBe('function');
|
|
138
|
+
expect(runtime.solveMetricSink()).toBe(sink); // memoized
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
it('reuses a duck-typed solveMetrics sink carried by the data provider', async () => {
|
|
142
|
+
const { registry } = makeRegistry();
|
|
143
|
+
const carried = { record: vi.fn() };
|
|
144
|
+
registry.data.local = vi.fn(() => ({ solveMetrics: carried }) as unknown as IDataProvider);
|
|
145
|
+
const runtime = await createSelvaProviders({}, { registry, ...noBoot });
|
|
146
|
+
expect(runtime.solveMetricSink()).toBe(carried);
|
|
147
|
+
});
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
describe('config-path override', () => {
|
|
151
|
+
it('loads the module default export and hands it the env', async () => {
|
|
152
|
+
const { registry, authLocal } = makeRegistry();
|
|
153
|
+
const configPath = fileURLToPath(new URL('./fixtures/override-config.mjs', import.meta.url));
|
|
154
|
+
const runtime = await createSelvaProviders(
|
|
155
|
+
{ OVERRIDE_MARKER: 'hello' },
|
|
156
|
+
{ registry, configPath, ...noBoot }
|
|
157
|
+
);
|
|
158
|
+
const config = runtime.resolve();
|
|
159
|
+
expect(config.auth.name).toBe('override-auth');
|
|
160
|
+
expect((config.data as unknown as { marker: string }).marker).toBe('hello');
|
|
161
|
+
expect(runtime.tenancy()).toBe('multi');
|
|
162
|
+
// The registry is bypassed entirely.
|
|
163
|
+
expect(authLocal).not.toHaveBeenCalled();
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
it('rejects at load time when the path does not exist', async () => {
|
|
167
|
+
const { registry } = makeRegistry();
|
|
168
|
+
await expect(
|
|
169
|
+
createSelvaProviders({}, { registry, configPath: './does-not-exist.js', ...noBoot })
|
|
170
|
+
).rejects.toThrow(/does-not-exist\.js/);
|
|
171
|
+
});
|
|
172
|
+
});
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// Fixture for the SELVA_CONFIG_PATH override test — a minimal selva.config.js
|
|
2
|
+
// whose default export is a config factory, exactly as an operator would write.
|
|
3
|
+
export default (env) => ({
|
|
4
|
+
tenancy: 'multi',
|
|
5
|
+
auth: { name: 'override-auth' },
|
|
6
|
+
data: { marker: env.OVERRIDE_MARKER },
|
|
7
|
+
storage: {}
|
|
8
|
+
});
|