@happyvertical/smrt-core 0.38.6 → 0.38.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/AGENTS.md +4 -1
  2. package/dist/generators/conditional-get.d.ts +23 -1
  3. package/dist/generators/conditional-get.d.ts.map +1 -1
  4. package/dist/generators/conditional-get.js +27 -12
  5. package/dist/generators/conditional-get.js.map +1 -1
  6. package/dist/generators/rest.d.ts +14 -1
  7. package/dist/generators/rest.d.ts.map +1 -1
  8. package/dist/generators/rest.js +4 -2
  9. package/dist/generators/rest.js.map +1 -1
  10. package/dist/generators/tool-schema.d.ts +83 -0
  11. package/dist/generators/tool-schema.d.ts.map +1 -0
  12. package/dist/generators/tool-schema.js +175 -0
  13. package/dist/generators/tool-schema.js.map +1 -0
  14. package/dist/manifest/static-manifest.js +2 -2
  15. package/dist/manifest/static-manifest.js.map +1 -1
  16. package/dist/manifest/store.js +1 -1
  17. package/dist/manifest/test-manifest-stub.js +2 -2
  18. package/dist/manifest/test-manifest-stub.js.map +1 -1
  19. package/dist/manifest.json +2 -2
  20. package/dist/prebuild/index.d.ts.map +1 -1
  21. package/dist/prebuild/index.js +19 -0
  22. package/dist/prebuild/index.js.map +1 -1
  23. package/dist/smrt-knowledge.json +6 -6
  24. package/dist/vite-plugin/index.d.ts.map +1 -1
  25. package/dist/vite-plugin/index.js +34 -13
  26. package/dist/vite-plugin/index.js.map +1 -1
  27. package/dist/vite-plugin/sveltekit-generator.d.ts.map +1 -1
  28. package/dist/vite-plugin/sveltekit-generator.js +7 -2
  29. package/dist/vite-plugin/sveltekit-generator.js.map +1 -1
  30. package/dist/vite-plugin/web-collections.d.ts +68 -3
  31. package/dist/vite-plugin/web-collections.d.ts.map +1 -1
  32. package/dist/vite-plugin/web-collections.js +158 -9
  33. package/dist/vite-plugin/web-collections.js.map +1 -1
  34. package/package.json +4 -4
@@ -1,3 +1,4 @@
1
+ import { ToolDescriptor } from '../generators/tool-schema.js';
1
2
  import { FieldDefinition, SmartObjectDefinition, SmartObjectManifest } from '../scanner/types.js';
2
3
  /** Informational per-column metadata carried by a collection definition. */
3
4
  export interface WebFieldDefinition {
@@ -35,11 +36,27 @@ export interface WebCollectionEntry {
35
36
  * Select the manifest entries that become web collection definitions: one per
36
37
  * REST collection, STI children folding into their base model, collection
37
38
  * classes excluded, and only models that expose `list` (a read surface is
38
- * required to materialize a collection). Uses the canonical
39
- * {@link resolveApiActionSet} so the exposed-action set matches exactly what
40
- * the REST/SvelteKit generators actually emit.
39
+ * required to MATERIALIZE a client collection that is what persists).
41
40
  */
42
41
  export declare function selectWebCollectionEntries(manifest: SmartObjectManifest): WebCollectionEntry[];
42
+ /**
43
+ * Build the per-collection web-collection definition literal — the SINGLE
44
+ * source of truth for the shape emitted by {@link generateWebModule} and hashed
45
+ * by {@link computeWebManifestHash}. Building it in ONE place is a
46
+ * cache-coherency requirement: if the emitted shape and the hashed shape were
47
+ * built independently, adding a field to one and not the other would let the
48
+ * hash silently UNDER-cover a shape change, so persisted caches would not drop
49
+ * and stale rows would hydrate into new code.
50
+ */
51
+ export declare function buildWebCollectionDefinition(entry: WebCollectionEntry, manifest: SmartObjectManifest): {
52
+ name: string;
53
+ className: string;
54
+ endpoint: string;
55
+ idField: string;
56
+ actions: string[];
57
+ fields: Record<string, WebFieldDefinition>;
58
+ relationships: WebRelationship[];
59
+ };
43
60
  /**
44
61
  * Build the informational per-field metadata for a web collection definition:
45
62
  * the persisted public-DTO columns only. Relationship pseudo-fields, STI meta
@@ -70,4 +87,52 @@ export declare function buildWebFieldDefinitions(obj: SmartObjectDefinition): Re
70
87
  * and keeping it avoids a special case.
71
88
  */
72
89
  export declare function buildWebRelationships(obj: SmartObjectDefinition, manifest: SmartObjectManifest): WebRelationship[];
90
+ /**
91
+ * Build the WebMCP / MCP tool descriptors for a web collection (#1812): one
92
+ * descriptor per exposed action, over the SAME public-DTO fields the definition
93
+ * already exposes (`buildWebFieldDefinitions`). The tool ids match the Node MCP
94
+ * surface (`<class>_<action>`), so a page's WebMCP tools and its MCP-server
95
+ * tools share one vocabulary.
96
+ *
97
+ * Deliberately NOT part of {@link buildWebCollectionDefinition}: descriptors are
98
+ * layered onto the emitted value by {@link generateWebModule} instead, so the
99
+ * #1764 {@link computeWebManifestHash} shape digest keeps hashing ONLY the row
100
+ * shape. That is safe because a descriptor is a pure function of
101
+ * className/actions/fields — all already in the hash — so excluding it never
102
+ * lets the digest under-cover a real shape change.
103
+ */
104
+ export declare function buildWebToolDescriptors(entry: WebCollectionEntry): ToolDescriptor[];
105
+ /**
106
+ * A deterministic, replica-stable digest of the web-collection SHAPE (#1764).
107
+ *
108
+ * The hash covers exactly the thing whose change means either old persisted
109
+ * client rows may mis-hydrate OR a stale read ETag would still 304: the same
110
+ * per-collection definition shape {@link generateWebModule} emits — name,
111
+ * className, endpoint, idField, actions, fields, relationships — built via the
112
+ * SHARED {@link buildWebCollectionDefinition} so the hash can never disagree
113
+ * with what is actually shipped. The shape is CANONICALIZED (keys recursively
114
+ * sorted; see {@link canonicalize}) before hashing, so the same schema always
115
+ * yields the same digest across builds and replicas regardless of manifest
116
+ * iteration order.
117
+ *
118
+ * SCOPE — get-OR-list (broader than materializable collections). Covered by
119
+ * {@link selectWebEtagSaltEntries}, so it includes GET-ONLY models too: those do
120
+ * not persist (no materializable collection), but their generated GET route IS
121
+ * salted with this hash, so a shape-only change to a get-only model must change
122
+ * it or a client holding the old concrete ETag gets a zero-query 304 after a
123
+ * shape-only deploy (the #1765 gap the salt closes). The two consumers both use
124
+ * this one value, so it stays identical between them:
125
+ * - `@happyvertical/smrt-web` persistence (#1764) folds it into the durable
126
+ * namespace, so a contract-changing deploy lands on a fresh namespace and old
127
+ * rows are never found (dropped, not mis-hydrated). Including get-only models
128
+ * here is harmless over-invalidation — only list-materializable collections
129
+ * ever hold a persisted snapshot.
130
+ * - the generated read ETag (#1765 salt, #1764) folds it in so a shape-only
131
+ * deploy (no table write) busts every read validator, get-only routes too.
132
+ *
133
+ * Truncated to the first 16 base64url chars: 96 bits is far more than enough to
134
+ * make an accidental shape collision negligible, and a short constant keeps the
135
+ * emitted module and every persistence key compact.
136
+ */
137
+ export declare function computeWebManifestHash(manifest: SmartObjectManifest): string;
73
138
  //# sourceMappingURL=web-collections.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"web-collections.d.ts","sourceRoot":"","sources":["../../src/vite-plugin/web-collections.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,KAAK,EACV,eAAe,EACf,qBAAqB,EACrB,mBAAmB,EACpB,MAAM,qBAAqB,CAAC;AAyB7B,4EAA4E;AAC5E,MAAM,WAAW,kBAAkB;IACjC,IAAI,EAAE,eAAe,CAAC,MAAM,CAAC,CAAC;IAC9B,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAED,iEAAiE;AACjE,MAAM,MAAM,mBAAmB,GAC3B,YAAY,GACZ,iBAAiB,GACjB,WAAW,GACX,YAAY,CAAC;AAEjB;;;;;;GAMG;AACH,MAAM,WAAW,eAAe;IAC9B,+EAA+E;IAC/E,KAAK,EAAE,MAAM,CAAC;IACd,gEAAgE;IAChE,IAAI,EAAE,mBAAmB,CAAC;IAC1B,oEAAoE;IACpE,iBAAiB,EAAE,MAAM,CAAC;CAC3B;AAED,2EAA2E;AAC3E,MAAM,WAAW,kBAAkB;IACjC,0DAA0D;IAC1D,UAAU,EAAE,MAAM,CAAC;IACnB,kEAAkE;IAClE,GAAG,EAAE,qBAAqB,CAAC;IAC3B,mDAAmD;IACnD,OAAO,EAAE,MAAM,EAAE,CAAC;CACnB;AAiFD;;;;;;;GAOG;AACH,wBAAgB,0BAA0B,CACxC,QAAQ,EAAE,mBAAmB,GAC5B,kBAAkB,EAAE,CAgCtB;AAED;;;;;GAKG;AACH,wBAAgB,wBAAwB,CACtC,GAAG,EAAE,qBAAqB,GACzB,MAAM,CAA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C,KAAK,EAAE,kBAAkB,EACzB,QAAQ,EAAE,mBAAmB,GAC5B;IACD,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,kBAAkB,CAAC,CAAC;IAC3C,aAAa,EAAE,eAAe,EAAE,CAAC;CAClC,CAUA;AAED;;;;;GAKG;AACH,wBAAgB,wBAAwB,CACtC,GAAG,EAAE,qBAAqB,GACzB,MAAM,CAAC,MAAM,EAAE,kBAAkB,CAAC,CAcpC;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,qBAAqB,CACnC,GAAG,EAAE,qBAAqB,EAC1B,QAAQ,EAAE,mBAAmB,GAC5B,eAAe,EAAE,CAiCnB;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,uBAAuB,CACrC,KAAK,EAAE,kBAAkB,GACxB,cAAc,EAAE,CAelB;AAyBD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,wBAAgB,sBAAsB,CAAC,QAAQ,EAAE,mBAAmB,GAAG,MAAM,CAa5E"}
@@ -1,6 +1,28 @@
1
+ import { buildToolDescriptors } from "../generators/tool-schema.js";
1
2
  import { resolveApiActionSet } from "./sveltekit-generator.js";
3
+ import { createHash } from "node:crypto";
2
4
  //#region src/vite-plugin/web-collections.ts
3
5
  /**
6
+ * Manifest → web collection selection (single source of truth).
7
+ *
8
+ * The browser client data runtime (`@happyvertical/smrt-web`, #1761) consumes
9
+ * one typed collection definition per API-exposed REST collection. Three
10
+ * emission sites need the SAME selection and field rules, or the emitted
11
+ * runtime values and their declared types drift apart:
12
+ *
13
+ * - the `\0smrt:web` runtime virtual module (JSON literal — {@link generateWebModule})
14
+ * - the `@happyvertical/smrt-virt-web` ambient d.ts (vite-plugin)
15
+ * - the physical `@smrt/web` d.ts (prebuild, for `tsc`-only consumers)
16
+ *
17
+ * All three import {@link selectWebCollectionEntries} from here so the value
18
+ * emission and the type emission can never disagree. The per-collection SHAPE
19
+ * (name/className/endpoint/idField/actions/fields/relationships) is built by the
20
+ * ONE {@link buildWebCollectionDefinition}, shared by the runtime emission AND
21
+ * the #1764 {@link computeWebManifestHash} shape digest — so the emitted shape
22
+ * and the hashed shape can never drift (a drift would let the hash under-cover a
23
+ * change → stale client caches).
24
+ */
25
+ /**
4
26
  * Field types that are relationship pseudo-columns rather than persisted
5
27
  * public-DTO columns — they never appear on the wire as scalar values.
6
28
  */
@@ -75,19 +97,20 @@ function isStiChildModel(manifest, obj) {
75
97
  return false;
76
98
  }
77
99
  /**
78
- * Select the manifest entries that become web collection definitions: one per
79
- * REST collection, STI children folding into their base model, collection
80
- * classes excluded, and only models that expose `list` (a read surface is
81
- * required to materialize a collection). Uses the canonical
82
- * {@link resolveApiActionSet} so the exposed-action set matches exactly what
83
- * the REST/SvelteKit generators actually emit.
100
+ * Select one entry per REST collection whose exposed action set satisfies
101
+ * `qualifies` STI children folding into their base model, collection classes
102
+ * excluded. Uses the canonical {@link resolveApiActionSet} so the exposed-action
103
+ * set matches exactly what the REST/SvelteKit generators actually emit. Shared
104
+ * by {@link selectWebCollectionEntries} (list-qualified materializable
105
+ * collections) and {@link selectWebEtagSaltEntries} (get-OR-list — every model
106
+ * with a read route the ETag salt must cover).
84
107
  */
85
- function selectWebCollectionEntries(manifest) {
108
+ function selectEntriesQualifiedBy(manifest, qualifies) {
86
109
  const byCollection = /* @__PURE__ */ new Map();
87
110
  for (const obj of Object.values(manifest.objects)) {
88
111
  if (isWebCollectionClass(manifest, obj)) continue;
89
112
  const exposedActions = resolveApiActionSet(obj);
90
- if (!exposedActions.has("list")) continue;
113
+ if (!qualifies(exposedActions)) continue;
91
114
  const isStiChild = isStiChildModel(manifest, obj);
92
115
  const existing = byCollection.get(obj.collection);
93
116
  if (existing && !(existing.isStiChild && !isStiChild)) continue;
@@ -105,6 +128,48 @@ function selectWebCollectionEntries(manifest) {
105
128
  }));
106
129
  }
107
130
  /**
131
+ * Select the manifest entries that become web collection definitions: one per
132
+ * REST collection, STI children folding into their base model, collection
133
+ * classes excluded, and only models that expose `list` (a read surface is
134
+ * required to MATERIALIZE a client collection — that is what persists).
135
+ */
136
+ function selectWebCollectionEntries(manifest) {
137
+ return selectEntriesQualifiedBy(manifest, (actions) => actions.has("list"));
138
+ }
139
+ /**
140
+ * Select the entries the ETag salt (#1764) must cover: every api-exposed model
141
+ * with a GENERATED READ ROUTE — `list` OR `get`. Broader than
142
+ * {@link selectWebCollectionEntries} on purpose: a get-only model
143
+ * (`api: { include: ['get'] }`) has no materializable client collection (so it
144
+ * never persists), but its generated GET route IS salted, so a shape-only change
145
+ * to it must still change the salt — otherwise a client holding the old concrete
146
+ * ETag would get a zero-query 304 after a shape-only deploy (the #1765 gap the
147
+ * salt closes). Not exported: only {@link computeWebManifestHash} consumes it.
148
+ */
149
+ function selectWebEtagSaltEntries(manifest) {
150
+ return selectEntriesQualifiedBy(manifest, (actions) => actions.has("list") || actions.has("get"));
151
+ }
152
+ /**
153
+ * Build the per-collection web-collection definition literal — the SINGLE
154
+ * source of truth for the shape emitted by {@link generateWebModule} and hashed
155
+ * by {@link computeWebManifestHash}. Building it in ONE place is a
156
+ * cache-coherency requirement: if the emitted shape and the hashed shape were
157
+ * built independently, adding a field to one and not the other would let the
158
+ * hash silently UNDER-cover a shape change, so persisted caches would not drop
159
+ * and stale rows would hydrate into new code.
160
+ */
161
+ function buildWebCollectionDefinition(entry, manifest) {
162
+ return {
163
+ name: entry.collection,
164
+ className: entry.obj.className,
165
+ endpoint: `/${entry.collection}`,
166
+ idField: "id",
167
+ actions: entry.actions,
168
+ fields: buildWebFieldDefinitions(entry.obj),
169
+ relationships: buildWebRelationships(entry.obj, manifest)
170
+ };
171
+ }
172
+ /**
108
173
  * Build the informational per-field metadata for a web collection definition:
109
174
  * the persisted public-DTO columns only. Relationship pseudo-fields, STI meta
110
175
  * internals, transient (unpersisted) and sensitive (wire-stripped) fields are
@@ -168,7 +233,91 @@ function buildWebRelationships(obj, manifest) {
168
233
  }
169
234
  return relationships;
170
235
  }
236
+ /**
237
+ * Build the WebMCP / MCP tool descriptors for a web collection (#1812): one
238
+ * descriptor per exposed action, over the SAME public-DTO fields the definition
239
+ * already exposes (`buildWebFieldDefinitions`). The tool ids match the Node MCP
240
+ * surface (`<class>_<action>`), so a page's WebMCP tools and its MCP-server
241
+ * tools share one vocabulary.
242
+ *
243
+ * Deliberately NOT part of {@link buildWebCollectionDefinition}: descriptors are
244
+ * layered onto the emitted value by {@link generateWebModule} instead, so the
245
+ * #1764 {@link computeWebManifestHash} shape digest keeps hashing ONLY the row
246
+ * shape. That is safe because a descriptor is a pure function of
247
+ * className/actions/fields — all already in the hash — so excluding it never
248
+ * lets the digest under-cover a real shape change.
249
+ */
250
+ function buildWebToolDescriptors(entry) {
251
+ const webFields = buildWebFieldDefinitions(entry.obj);
252
+ const fields = Object.entries(webFields).map(([name, def]) => ({
253
+ name,
254
+ type: def.type,
255
+ ...def.required !== void 0 ? { required: def.required } : {},
256
+ ...def.default !== void 0 ? { default: def.default } : {}
257
+ }));
258
+ return buildToolDescriptors({
259
+ className: entry.obj.className,
260
+ fields,
261
+ actions: entry.actions
262
+ });
263
+ }
264
+ /**
265
+ * Recursively sort object keys so structurally-equal values serialize to the
266
+ * SAME JSON regardless of insertion order. Arrays keep their order (order is
267
+ * semantic for `actions`/`relationships`); objects are rebuilt with keys sorted.
268
+ * Required for {@link computeWebManifestHash} to be replica-stable: two builds
269
+ * that produce the same schema but visit the manifest in a different order (map
270
+ * insertion, scan order) must still hash identically, which a plain
271
+ * `JSON.stringify` of insertion-ordered objects would NOT guarantee.
272
+ */
273
+ function canonicalize(value) {
274
+ if (Array.isArray(value)) return value.map((entry) => canonicalize(entry));
275
+ if (value && typeof value === "object") {
276
+ const sorted = {};
277
+ for (const key of Object.keys(value).sort()) sorted[key] = canonicalize(value[key]);
278
+ return sorted;
279
+ }
280
+ return value;
281
+ }
282
+ /**
283
+ * A deterministic, replica-stable digest of the web-collection SHAPE (#1764).
284
+ *
285
+ * The hash covers exactly the thing whose change means either old persisted
286
+ * client rows may mis-hydrate OR a stale read ETag would still 304: the same
287
+ * per-collection definition shape {@link generateWebModule} emits — name,
288
+ * className, endpoint, idField, actions, fields, relationships — built via the
289
+ * SHARED {@link buildWebCollectionDefinition} so the hash can never disagree
290
+ * with what is actually shipped. The shape is CANONICALIZED (keys recursively
291
+ * sorted; see {@link canonicalize}) before hashing, so the same schema always
292
+ * yields the same digest across builds and replicas regardless of manifest
293
+ * iteration order.
294
+ *
295
+ * SCOPE — get-OR-list (broader than materializable collections). Covered by
296
+ * {@link selectWebEtagSaltEntries}, so it includes GET-ONLY models too: those do
297
+ * not persist (no materializable collection), but their generated GET route IS
298
+ * salted with this hash, so a shape-only change to a get-only model must change
299
+ * it or a client holding the old concrete ETag gets a zero-query 304 after a
300
+ * shape-only deploy (the #1765 gap the salt closes). The two consumers both use
301
+ * this one value, so it stays identical between them:
302
+ * - `@happyvertical/smrt-web` persistence (#1764) folds it into the durable
303
+ * namespace, so a contract-changing deploy lands on a fresh namespace and old
304
+ * rows are never found (dropped, not mis-hydrated). Including get-only models
305
+ * here is harmless over-invalidation — only list-materializable collections
306
+ * ever hold a persisted snapshot.
307
+ * - the generated read ETag (#1765 salt, #1764) folds it in so a shape-only
308
+ * deploy (no table write) busts every read validator, get-only routes too.
309
+ *
310
+ * Truncated to the first 16 base64url chars: 96 bits is far more than enough to
311
+ * make an accidental shape collision negligible, and a short constant keeps the
312
+ * emitted module and every persistence key compact.
313
+ */
314
+ function computeWebManifestHash(manifest) {
315
+ const definitions = {};
316
+ for (const entry of selectWebEtagSaltEntries(manifest)) definitions[entry.collection] = buildWebCollectionDefinition(entry, manifest);
317
+ const canonicalJson = JSON.stringify(canonicalize(definitions));
318
+ return createHash("sha256").update(canonicalJson).digest("base64url").slice(0, 16);
319
+ }
171
320
  //#endregion
172
- export { buildWebFieldDefinitions, buildWebRelationships, selectWebCollectionEntries };
321
+ export { buildWebCollectionDefinition, buildWebFieldDefinitions, buildWebRelationships, buildWebToolDescriptors, computeWebManifestHash, selectWebCollectionEntries };
173
322
 
174
323
  //# sourceMappingURL=web-collections.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"web-collections.js","names":[],"sources":["../../src/vite-plugin/web-collections.ts"],"sourcesContent":["/**\n * Manifest → web collection selection (single source of truth).\n *\n * The browser client data runtime (`@happyvertical/smrt-web`, #1761) consumes\n * one typed collection definition per API-exposed REST collection. Three\n * emission sites need the SAME selection and field rules, or the emitted\n * runtime values and their declared types drift apart:\n *\n * - the `\\0smrt:web` runtime virtual module (JSON literal — {@link generateWebModule})\n * - the `@happyvertical/smrt-virt-web` ambient d.ts (vite-plugin)\n * - the physical `@smrt/web` d.ts (prebuild, for `tsc`-only consumers)\n *\n * All three import {@link selectWebCollectionEntries} from here so the value\n * emission and the type emission can never disagree.\n */\n\nimport type {\n FieldDefinition,\n SmartObjectDefinition,\n SmartObjectManifest,\n} from '../scanner/types.js';\nimport { resolveApiActionSet } from './sveltekit-generator.js';\n\n/**\n * Field types that are relationship pseudo-columns rather than persisted\n * public-DTO columns — they never appear on the wire as scalar values.\n */\nconst RELATIONSHIP_FIELD_TYPES: ReadonlySet<FieldDefinition['type']> = new Set([\n 'oneToMany',\n 'manyToMany',\n]);\n\n/**\n * Field types that describe a relationship to another model. A superset of\n * {@link RELATIONSHIP_FIELD_TYPES}: `foreignKey`/`crossPackageRef` are persisted\n * scalar id columns (they DO appear on the wire), while `oneToMany`/`manyToMany`\n * are pseudo-columns — but all four carry a `related` edge to a sibling model.\n */\nconst RELATIONSHIP_EDGE_TYPES: ReadonlySet<FieldDefinition['type']> = new Set([\n 'foreignKey',\n 'crossPackageRef',\n 'oneToMany',\n 'manyToMany',\n]);\n\n/** Informational per-column metadata carried by a collection definition. */\nexport interface WebFieldDefinition {\n type: FieldDefinition['type'];\n required?: boolean;\n default?: unknown;\n}\n\n/** The relationship kinds a web collection edge can describe. */\nexport type WebRelationshipKind =\n | 'foreignKey'\n | 'crossPackageRef'\n | 'oneToMany'\n | 'manyToMany';\n\n/**\n * One manifest-derived relationship edge from a collection to a sibling REST\n * collection. Consumed by the browser client-data runtime to invalidate\n * dependent collection caches when this collection is mutated (#1761) — the\n * cache-invalidation graph is derived entirely from these edges, never\n * hand-wired. SMRT-owned data: no client-engine type appears here.\n */\nexport interface WebRelationship {\n /** The declaring field carrying the relationship (e.g. `groupId`, `items`). */\n field: string;\n /** The relationship kind, mirroring the manifest field type. */\n kind: WebRelationshipKind;\n /** REST collection name the edge resolves to (e.g. `ad_groups`). */\n relatedCollection: string;\n}\n\n/** One selected REST collection and the model that owns its definition. */\nexport interface WebCollectionEntry {\n /** REST collection name (pluralized), e.g. `products`. */\n collection: string;\n /** The manifest object that owns this collection's definition. */\n obj: SmartObjectDefinition;\n /** Sorted set of exposed CRUD + custom actions. */\n actions: string[];\n}\n\n/** Resolve a manifest object by qualified name or simple class name. */\nfunction findByName(\n manifest: SmartObjectManifest,\n name: string,\n): SmartObjectDefinition | undefined {\n return Object.values(manifest.objects).find(\n (candidate) =>\n candidate.qualifiedName === name || candidate.className === name,\n );\n}\n\n/**\n * Normalize a relationship field's `related` value to a resolvable class name.\n *\n * Thunk forward-ref decorators — `@foreignKey(() => Scene)`, used heavily in\n * video/voice for models that reference a class declared later — serialize as\n * the RAW arrow-function source string `\"() => Scene\"` in the manifest, which\n * neither `className` nor `qualifiedName` matches. Extract the target class\n * name from the thunk so the edge resolves. Plain (`\"Scene\"`) and qualified\n * (`\"@happyvertical/smrt-assets:Asset\"`) forms contain no `=>` and pass through\n * untouched — the qualified `:` separator is preserved.\n *\n * Kept local to the relationship-edge path on purpose: extends-chain resolution\n * never sees a thunk, so `findByName` and the scanner stay unchanged.\n */\nfunction normalizeRelatedName(related: string): string {\n const thunk = related.match(/=>\\s*([A-Za-z_$][\\w$]*)/);\n return thunk ? thunk[1] : related.trim();\n}\n\n/**\n * True when `obj` is (transitively) a SmrtCollection subclass. Collection\n * classes describe access, not row shapes, so they never become web\n * collection definitions.\n *\n * NOTE: deliberately stronger than sveltekit-generator's private\n * `isCollectionClass`, which only inspects the direct base / a type argument.\n * A deeper subclass (`SpecialWidgetCollection extends WidgetCollection`)\n * carries no type argument of its own; without walking the extends chain it\n * would be mistaken for a model and claim its base model's REST collection.\n */\nfunction isWebCollectionClass(\n manifest: SmartObjectManifest,\n obj: SmartObjectDefinition,\n seen: Set<string> = new Set(),\n): boolean {\n // Truthy check (not `!== undefined`) mirrors the scanner's own\n // manifest-generator: a scanner that emits `extendsTypeArg: null` for a\n // non-generic base must not be misread as a collection.\n if (obj.extends === 'SmrtCollection' || obj.extendsTypeArg) {\n return true;\n }\n const parentName = obj.extendsQualified || obj.extends;\n if (!parentName || seen.has(parentName)) return false;\n seen.add(parentName);\n const parent = findByName(manifest, parentName);\n return parent ? isWebCollectionClass(manifest, parent, seen) : false;\n}\n\n/**\n * True when some ancestor model maps to the SAME REST collection (a shared STI\n * table). The STI base model owns the shared table's single definition.\n */\nfunction isStiChildModel(\n manifest: SmartObjectManifest,\n obj: SmartObjectDefinition,\n): boolean {\n const seen = new Set<string>();\n let parentName = obj.extendsQualified || obj.extends;\n while (parentName && !seen.has(parentName)) {\n seen.add(parentName);\n const parent = findByName(manifest, parentName);\n if (!parent) return false;\n if (parent.collection === obj.collection) return true;\n parentName = parent.extendsQualified || parent.extends;\n }\n return false;\n}\n\n/**\n * Select the manifest entries that become web collection definitions: one per\n * REST collection, STI children folding into their base model, collection\n * classes excluded, and only models that expose `list` (a read surface is\n * required to materialize a collection). Uses the canonical\n * {@link resolveApiActionSet} so the exposed-action set matches exactly what\n * the REST/SvelteKit generators actually emit.\n */\nexport function selectWebCollectionEntries(\n manifest: SmartObjectManifest,\n): WebCollectionEntry[] {\n const byCollection = new Map<\n string,\n WebCollectionEntry & { isStiChild: boolean }\n >();\n\n for (const obj of Object.values(manifest.objects)) {\n if (isWebCollectionClass(manifest, obj)) continue;\n\n const exposedActions = resolveApiActionSet(obj);\n if (!exposedActions.has('list')) continue;\n\n const isStiChild = isStiChildModel(manifest, obj);\n const existing = byCollection.get(obj.collection);\n // One definition per REST collection. The STI BASE model owns it: a child\n // only wins while no base has been recorded yet, so the result is\n // independent of declaration / scan order.\n if (existing && !(existing.isStiChild && !isStiChild)) continue;\n\n byCollection.set(obj.collection, {\n collection: obj.collection,\n obj,\n actions: [...exposedActions].sort(),\n isStiChild,\n });\n }\n\n return [...byCollection.values()].map(({ collection, obj, actions }) => ({\n collection,\n obj,\n actions,\n }));\n}\n\n/**\n * Build the informational per-field metadata for a web collection definition:\n * the persisted public-DTO columns only. Relationship pseudo-fields, STI meta\n * internals, transient (unpersisted) and sensitive (wire-stripped) fields are\n * excluded — they are not columns a client reads back over the REST surface.\n */\nexport function buildWebFieldDefinitions(\n obj: SmartObjectDefinition,\n): Record<string, WebFieldDefinition> {\n const fields: Record<string, WebFieldDefinition> = {};\n for (const [fieldName, field] of Object.entries(obj.fields ?? {})) {\n if (RELATIONSHIP_FIELD_TYPES.has(field.type)) continue;\n if (field.type === 'meta') continue;\n if (field.transient) continue;\n if (field.sensitive) continue;\n fields[fieldName] = {\n type: field.type,\n ...(field.required !== undefined ? { required: field.required } : {}),\n ...(field.default !== undefined ? { default: field.default } : {}),\n };\n }\n return fields;\n}\n\n/**\n * Build the manifest-derived relationship edges for a web collection\n * definition (#1761): one entry per relationship field (`foreignKey`,\n * `crossPackageRef`, `oneToMany`, `manyToMany`) whose `related` target resolves\n * to another API-exposed REST collection.\n *\n * These edges drive relationship-derived cache invalidation in the browser\n * client-data runtime: mutating this collection invalidates the caches of the\n * collections named here. The invalidation graph is thus derived entirely from\n * the manifest — no hand-wired cache keys.\n *\n * An edge is SKIPPED (not emitted) when:\n * - `related` is missing, or\n * - `related` cannot be resolved to a manifest object (e.g. a cross-package\n * target not present in this package's manifest), or\n * - the resolved target is not itself an API-exposed web collection (no read\n * surface to invalidate — it never appears in {@link selectWebCollectionEntries}).\n *\n * Self-referential edges (a collection related to itself) are kept: the runtime\n * always invalidates the mutated collection anyway, so a self edge is harmless\n * and keeping it avoids a special case.\n */\nexport function buildWebRelationships(\n obj: SmartObjectDefinition,\n manifest: SmartObjectManifest,\n): WebRelationship[] {\n // The set of REST collections that are actually materialized as web\n // collections. An edge to a model outside this set has no client cache to\n // invalidate, so it is dropped.\n const exposedCollections = new Set(\n selectWebCollectionEntries(manifest).map((entry) => entry.collection),\n );\n\n const relationships: WebRelationship[] = [];\n const seen = new Set<string>();\n for (const [fieldName, field] of Object.entries(obj.fields ?? {})) {\n if (!RELATIONSHIP_EDGE_TYPES.has(field.type)) continue;\n if (!field.related) continue;\n\n // Normalize first: `@foreignKey(() => Scene)` thunks serialize as the raw\n // \"() => Scene\" source, which findByName cannot match on its own.\n const target = findByName(manifest, normalizeRelatedName(field.related));\n if (!target) continue;\n if (!exposedCollections.has(target.collection)) continue;\n\n // De-dupe on (field, relatedCollection): a model never declares the same\n // field twice, but guard anyway so the emitted edge list is stable.\n const dedupeKey = `${fieldName}:${target.collection}`;\n if (seen.has(dedupeKey)) continue;\n seen.add(dedupeKey);\n\n relationships.push({\n field: fieldName,\n kind: field.type as WebRelationshipKind,\n relatedCollection: target.collection,\n });\n }\n return relationships;\n}\n"],"mappings":";;;;;;AA2BA,IAAM,2CAAiE,IAAI,IAAI,CAC7E,aACA,YACF,CAAC;;;;;;;AAQD,IAAM,0CAAgE,IAAI,IAAI;CAC5E;CACA;CACA;CACA;AACF,CAAC;;AA2CD,SAAS,WACP,UACA,MACmC;CACnC,OAAO,OAAO,OAAO,SAAS,OAAO,CAAC,CAAC,MACpC,cACC,UAAU,kBAAkB,QAAQ,UAAU,cAAc,IAChE;AACF;;;;;;;;;;;;;;;AAgBA,SAAS,qBAAqB,SAAyB;CACrD,MAAM,QAAQ,QAAQ,MAAM,yBAAyB;CACr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mBAAmB,OAAO;EAC5B,CAAC;CACH;CACA,OAAO;AACT"}
1
+ {"version":3,"file":"web-collections.js","names":[],"sources":["../../src/vite-plugin/web-collections.ts"],"sourcesContent":["/**\n * Manifest → web collection selection (single source of truth).\n *\n * The browser client data runtime (`@happyvertical/smrt-web`, #1761) consumes\n * one typed collection definition per API-exposed REST collection. Three\n * emission sites need the SAME selection and field rules, or the emitted\n * runtime values and their declared types drift apart:\n *\n * - the `\\0smrt:web` runtime virtual module (JSON literal — {@link generateWebModule})\n * - the `@happyvertical/smrt-virt-web` ambient d.ts (vite-plugin)\n * - the physical `@smrt/web` d.ts (prebuild, for `tsc`-only consumers)\n *\n * All three import {@link selectWebCollectionEntries} from here so the value\n * emission and the type emission can never disagree. The per-collection SHAPE\n * (name/className/endpoint/idField/actions/fields/relationships) is built by the\n * ONE {@link buildWebCollectionDefinition}, shared by the runtime emission AND\n * the #1764 {@link computeWebManifestHash} shape digest — so the emitted shape\n * and the hashed shape can never drift (a drift would let the hash under-cover a\n * change → stale client caches).\n */\n\nimport { createHash } from 'node:crypto';\nimport {\n buildToolDescriptors,\n type ToolDescriptor,\n type ToolFieldMeta,\n} from '../generators/tool-schema.js';\nimport type {\n FieldDefinition,\n SmartObjectDefinition,\n SmartObjectManifest,\n} from '../scanner/types.js';\nimport { resolveApiActionSet } from './sveltekit-generator.js';\n\n/**\n * Field types that are relationship pseudo-columns rather than persisted\n * public-DTO columns — they never appear on the wire as scalar values.\n */\nconst RELATIONSHIP_FIELD_TYPES: ReadonlySet<FieldDefinition['type']> = new Set([\n 'oneToMany',\n 'manyToMany',\n]);\n\n/**\n * Field types that describe a relationship to another model. A superset of\n * {@link RELATIONSHIP_FIELD_TYPES}: `foreignKey`/`crossPackageRef` are persisted\n * scalar id columns (they DO appear on the wire), while `oneToMany`/`manyToMany`\n * are pseudo-columns — but all four carry a `related` edge to a sibling model.\n */\nconst RELATIONSHIP_EDGE_TYPES: ReadonlySet<FieldDefinition['type']> = new Set([\n 'foreignKey',\n 'crossPackageRef',\n 'oneToMany',\n 'manyToMany',\n]);\n\n/** Informational per-column metadata carried by a collection definition. */\nexport interface WebFieldDefinition {\n type: FieldDefinition['type'];\n required?: boolean;\n default?: unknown;\n}\n\n/** The relationship kinds a web collection edge can describe. */\nexport type WebRelationshipKind =\n | 'foreignKey'\n | 'crossPackageRef'\n | 'oneToMany'\n | 'manyToMany';\n\n/**\n * One manifest-derived relationship edge from a collection to a sibling REST\n * collection. Consumed by the browser client-data runtime to invalidate\n * dependent collection caches when this collection is mutated (#1761) — the\n * cache-invalidation graph is derived entirely from these edges, never\n * hand-wired. SMRT-owned data: no client-engine type appears here.\n */\nexport interface WebRelationship {\n /** The declaring field carrying the relationship (e.g. `groupId`, `items`). */\n field: string;\n /** The relationship kind, mirroring the manifest field type. */\n kind: WebRelationshipKind;\n /** REST collection name the edge resolves to (e.g. `ad_groups`). */\n relatedCollection: string;\n}\n\n/** One selected REST collection and the model that owns its definition. */\nexport interface WebCollectionEntry {\n /** REST collection name (pluralized), e.g. `products`. */\n collection: string;\n /** The manifest object that owns this collection's definition. */\n obj: SmartObjectDefinition;\n /** Sorted set of exposed CRUD + custom actions. */\n actions: string[];\n}\n\n/** Resolve a manifest object by qualified name or simple class name. */\nfunction findByName(\n manifest: SmartObjectManifest,\n name: string,\n): SmartObjectDefinition | undefined {\n return Object.values(manifest.objects).find(\n (candidate) =>\n candidate.qualifiedName === name || candidate.className === name,\n );\n}\n\n/**\n * Normalize a relationship field's `related` value to a resolvable class name.\n *\n * Thunk forward-ref decorators — `@foreignKey(() => Scene)`, used heavily in\n * video/voice for models that reference a class declared later — serialize as\n * the RAW arrow-function source string `\"() => Scene\"` in the manifest, which\n * neither `className` nor `qualifiedName` matches. Extract the target class\n * name from the thunk so the edge resolves. Plain (`\"Scene\"`) and qualified\n * (`\"@happyvertical/smrt-assets:Asset\"`) forms contain no `=>` and pass through\n * untouched — the qualified `:` separator is preserved.\n *\n * Kept local to the relationship-edge path on purpose: extends-chain resolution\n * never sees a thunk, so `findByName` and the scanner stay unchanged.\n */\nfunction normalizeRelatedName(related: string): string {\n const thunk = related.match(/=>\\s*([A-Za-z_$][\\w$]*)/);\n return thunk ? thunk[1] : related.trim();\n}\n\n/**\n * True when `obj` is (transitively) a SmrtCollection subclass. Collection\n * classes describe access, not row shapes, so they never become web\n * collection definitions.\n *\n * NOTE: deliberately stronger than sveltekit-generator's private\n * `isCollectionClass`, which only inspects the direct base / a type argument.\n * A deeper subclass (`SpecialWidgetCollection extends WidgetCollection`)\n * carries no type argument of its own; without walking the extends chain it\n * would be mistaken for a model and claim its base model's REST collection.\n */\nfunction isWebCollectionClass(\n manifest: SmartObjectManifest,\n obj: SmartObjectDefinition,\n seen: Set<string> = new Set(),\n): boolean {\n // Truthy check (not `!== undefined`) mirrors the scanner's own\n // manifest-generator: a scanner that emits `extendsTypeArg: null` for a\n // non-generic base must not be misread as a collection.\n if (obj.extends === 'SmrtCollection' || obj.extendsTypeArg) {\n return true;\n }\n const parentName = obj.extendsQualified || obj.extends;\n if (!parentName || seen.has(parentName)) return false;\n seen.add(parentName);\n const parent = findByName(manifest, parentName);\n return parent ? isWebCollectionClass(manifest, parent, seen) : false;\n}\n\n/**\n * True when some ancestor model maps to the SAME REST collection (a shared STI\n * table). The STI base model owns the shared table's single definition.\n */\nfunction isStiChildModel(\n manifest: SmartObjectManifest,\n obj: SmartObjectDefinition,\n): boolean {\n const seen = new Set<string>();\n let parentName = obj.extendsQualified || obj.extends;\n while (parentName && !seen.has(parentName)) {\n seen.add(parentName);\n const parent = findByName(manifest, parentName);\n if (!parent) return false;\n if (parent.collection === obj.collection) return true;\n parentName = parent.extendsQualified || parent.extends;\n }\n return false;\n}\n\n/**\n * Select one entry per REST collection whose exposed action set satisfies\n * `qualifies` — STI children folding into their base model, collection classes\n * excluded. Uses the canonical {@link resolveApiActionSet} so the exposed-action\n * set matches exactly what the REST/SvelteKit generators actually emit. Shared\n * by {@link selectWebCollectionEntries} (list-qualified — materializable\n * collections) and {@link selectWebEtagSaltEntries} (get-OR-list — every model\n * with a read route the ETag salt must cover).\n */\nfunction selectEntriesQualifiedBy(\n manifest: SmartObjectManifest,\n qualifies: (actions: ReadonlySet<string>) => boolean,\n): WebCollectionEntry[] {\n const byCollection = new Map<\n string,\n WebCollectionEntry & { isStiChild: boolean }\n >();\n\n for (const obj of Object.values(manifest.objects)) {\n if (isWebCollectionClass(manifest, obj)) continue;\n\n const exposedActions = resolveApiActionSet(obj);\n if (!qualifies(exposedActions)) continue;\n\n const isStiChild = isStiChildModel(manifest, obj);\n const existing = byCollection.get(obj.collection);\n // One definition per REST collection. The STI BASE model owns it: a child\n // only wins while no base has been recorded yet, so the result is\n // independent of declaration / scan order.\n if (existing && !(existing.isStiChild && !isStiChild)) continue;\n\n byCollection.set(obj.collection, {\n collection: obj.collection,\n obj,\n actions: [...exposedActions].sort(),\n isStiChild,\n });\n }\n\n return [...byCollection.values()].map(({ collection, obj, actions }) => ({\n collection,\n obj,\n actions,\n }));\n}\n\n/**\n * Select the manifest entries that become web collection definitions: one per\n * REST collection, STI children folding into their base model, collection\n * classes excluded, and only models that expose `list` (a read surface is\n * required to MATERIALIZE a client collection — that is what persists).\n */\nexport function selectWebCollectionEntries(\n manifest: SmartObjectManifest,\n): WebCollectionEntry[] {\n return selectEntriesQualifiedBy(manifest, (actions) => actions.has('list'));\n}\n\n/**\n * Select the entries the ETag salt (#1764) must cover: every api-exposed model\n * with a GENERATED READ ROUTE — `list` OR `get`. Broader than\n * {@link selectWebCollectionEntries} on purpose: a get-only model\n * (`api: { include: ['get'] }`) has no materializable client collection (so it\n * never persists), but its generated GET route IS salted, so a shape-only change\n * to it must still change the salt — otherwise a client holding the old concrete\n * ETag would get a zero-query 304 after a shape-only deploy (the #1765 gap the\n * salt closes). Not exported: only {@link computeWebManifestHash} consumes it.\n */\nfunction selectWebEtagSaltEntries(\n manifest: SmartObjectManifest,\n): WebCollectionEntry[] {\n return selectEntriesQualifiedBy(\n manifest,\n (actions) => actions.has('list') || actions.has('get'),\n );\n}\n\n/**\n * Build the per-collection web-collection definition literal — the SINGLE\n * source of truth for the shape emitted by {@link generateWebModule} and hashed\n * by {@link computeWebManifestHash}. Building it in ONE place is a\n * cache-coherency requirement: if the emitted shape and the hashed shape were\n * built independently, adding a field to one and not the other would let the\n * hash silently UNDER-cover a shape change, so persisted caches would not drop\n * and stale rows would hydrate into new code.\n */\nexport function buildWebCollectionDefinition(\n entry: WebCollectionEntry,\n manifest: SmartObjectManifest,\n): {\n name: string;\n className: string;\n endpoint: string;\n idField: string;\n actions: string[];\n fields: Record<string, WebFieldDefinition>;\n relationships: WebRelationship[];\n} {\n return {\n name: entry.collection,\n className: entry.obj.className,\n endpoint: `/${entry.collection}`,\n idField: 'id',\n actions: entry.actions,\n fields: buildWebFieldDefinitions(entry.obj),\n relationships: buildWebRelationships(entry.obj, manifest),\n };\n}\n\n/**\n * Build the informational per-field metadata for a web collection definition:\n * the persisted public-DTO columns only. Relationship pseudo-fields, STI meta\n * internals, transient (unpersisted) and sensitive (wire-stripped) fields are\n * excluded — they are not columns a client reads back over the REST surface.\n */\nexport function buildWebFieldDefinitions(\n obj: SmartObjectDefinition,\n): Record<string, WebFieldDefinition> {\n const fields: Record<string, WebFieldDefinition> = {};\n for (const [fieldName, field] of Object.entries(obj.fields ?? {})) {\n if (RELATIONSHIP_FIELD_TYPES.has(field.type)) continue;\n if (field.type === 'meta') continue;\n if (field.transient) continue;\n if (field.sensitive) continue;\n fields[fieldName] = {\n type: field.type,\n ...(field.required !== undefined ? { required: field.required } : {}),\n ...(field.default !== undefined ? { default: field.default } : {}),\n };\n }\n return fields;\n}\n\n/**\n * Build the manifest-derived relationship edges for a web collection\n * definition (#1761): one entry per relationship field (`foreignKey`,\n * `crossPackageRef`, `oneToMany`, `manyToMany`) whose `related` target resolves\n * to another API-exposed REST collection.\n *\n * These edges drive relationship-derived cache invalidation in the browser\n * client-data runtime: mutating this collection invalidates the caches of the\n * collections named here. The invalidation graph is thus derived entirely from\n * the manifest — no hand-wired cache keys.\n *\n * An edge is SKIPPED (not emitted) when:\n * - `related` is missing, or\n * - `related` cannot be resolved to a manifest object (e.g. a cross-package\n * target not present in this package's manifest), or\n * - the resolved target is not itself an API-exposed web collection (no read\n * surface to invalidate — it never appears in {@link selectWebCollectionEntries}).\n *\n * Self-referential edges (a collection related to itself) are kept: the runtime\n * always invalidates the mutated collection anyway, so a self edge is harmless\n * and keeping it avoids a special case.\n */\nexport function buildWebRelationships(\n obj: SmartObjectDefinition,\n manifest: SmartObjectManifest,\n): WebRelationship[] {\n // The set of REST collections that are actually materialized as web\n // collections. An edge to a model outside this set has no client cache to\n // invalidate, so it is dropped.\n const exposedCollections = new Set(\n selectWebCollectionEntries(manifest).map((entry) => entry.collection),\n );\n\n const relationships: WebRelationship[] = [];\n const seen = new Set<string>();\n for (const [fieldName, field] of Object.entries(obj.fields ?? {})) {\n if (!RELATIONSHIP_EDGE_TYPES.has(field.type)) continue;\n if (!field.related) continue;\n\n // Normalize first: `@foreignKey(() => Scene)` thunks serialize as the raw\n // \"() => Scene\" source, which findByName cannot match on its own.\n const target = findByName(manifest, normalizeRelatedName(field.related));\n if (!target) continue;\n if (!exposedCollections.has(target.collection)) continue;\n\n // De-dupe on (field, relatedCollection): a model never declares the same\n // field twice, but guard anyway so the emitted edge list is stable.\n const dedupeKey = `${fieldName}:${target.collection}`;\n if (seen.has(dedupeKey)) continue;\n seen.add(dedupeKey);\n\n relationships.push({\n field: fieldName,\n kind: field.type as WebRelationshipKind,\n relatedCollection: target.collection,\n });\n }\n return relationships;\n}\n\n/**\n * Build the WebMCP / MCP tool descriptors for a web collection (#1812): one\n * descriptor per exposed action, over the SAME public-DTO fields the definition\n * already exposes (`buildWebFieldDefinitions`). The tool ids match the Node MCP\n * surface (`<class>_<action>`), so a page's WebMCP tools and its MCP-server\n * tools share one vocabulary.\n *\n * Deliberately NOT part of {@link buildWebCollectionDefinition}: descriptors are\n * layered onto the emitted value by {@link generateWebModule} instead, so the\n * #1764 {@link computeWebManifestHash} shape digest keeps hashing ONLY the row\n * shape. That is safe because a descriptor is a pure function of\n * className/actions/fields — all already in the hash — so excluding it never\n * lets the digest under-cover a real shape change.\n */\nexport function buildWebToolDescriptors(\n entry: WebCollectionEntry,\n): ToolDescriptor[] {\n const webFields = buildWebFieldDefinitions(entry.obj);\n const fields: ToolFieldMeta[] = Object.entries(webFields).map(\n ([name, def]) => ({\n name,\n type: def.type,\n ...(def.required !== undefined ? { required: def.required } : {}),\n ...(def.default !== undefined ? { default: def.default } : {}),\n }),\n );\n return buildToolDescriptors({\n className: entry.obj.className,\n fields,\n actions: entry.actions,\n });\n}\n\n/**\n * Recursively sort object keys so structurally-equal values serialize to the\n * SAME JSON regardless of insertion order. Arrays keep their order (order is\n * semantic for `actions`/`relationships`); objects are rebuilt with keys sorted.\n * Required for {@link computeWebManifestHash} to be replica-stable: two builds\n * that produce the same schema but visit the manifest in a different order (map\n * insertion, scan order) must still hash identically, which a plain\n * `JSON.stringify` of insertion-ordered objects would NOT guarantee.\n */\nfunction canonicalize(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map((entry) => canonicalize(entry));\n }\n if (value && typeof value === 'object') {\n const sorted: Record<string, unknown> = {};\n for (const key of Object.keys(value as Record<string, unknown>).sort()) {\n sorted[key] = canonicalize((value as Record<string, unknown>)[key]);\n }\n return sorted;\n }\n return value;\n}\n\n/**\n * A deterministic, replica-stable digest of the web-collection SHAPE (#1764).\n *\n * The hash covers exactly the thing whose change means either old persisted\n * client rows may mis-hydrate OR a stale read ETag would still 304: the same\n * per-collection definition shape {@link generateWebModule} emits — name,\n * className, endpoint, idField, actions, fields, relationships — built via the\n * SHARED {@link buildWebCollectionDefinition} so the hash can never disagree\n * with what is actually shipped. The shape is CANONICALIZED (keys recursively\n * sorted; see {@link canonicalize}) before hashing, so the same schema always\n * yields the same digest across builds and replicas regardless of manifest\n * iteration order.\n *\n * SCOPE — get-OR-list (broader than materializable collections). Covered by\n * {@link selectWebEtagSaltEntries}, so it includes GET-ONLY models too: those do\n * not persist (no materializable collection), but their generated GET route IS\n * salted with this hash, so a shape-only change to a get-only model must change\n * it or a client holding the old concrete ETag gets a zero-query 304 after a\n * shape-only deploy (the #1765 gap the salt closes). The two consumers both use\n * this one value, so it stays identical between them:\n * - `@happyvertical/smrt-web` persistence (#1764) folds it into the durable\n * namespace, so a contract-changing deploy lands on a fresh namespace and old\n * rows are never found (dropped, not mis-hydrated). Including get-only models\n * here is harmless over-invalidation — only list-materializable collections\n * ever hold a persisted snapshot.\n * - the generated read ETag (#1765 salt, #1764) folds it in so a shape-only\n * deploy (no table write) busts every read validator, get-only routes too.\n *\n * Truncated to the first 16 base64url chars: 96 bits is far more than enough to\n * make an accidental shape collision negligible, and a short constant keeps the\n * emitted module and every persistence key compact.\n */\nexport function computeWebManifestHash(manifest: SmartObjectManifest): string {\n const definitions: Record<string, unknown> = {};\n for (const entry of selectWebEtagSaltEntries(manifest)) {\n definitions[entry.collection] = buildWebCollectionDefinition(\n entry,\n manifest,\n );\n }\n const canonicalJson = JSON.stringify(canonicalize(definitions));\n return createHash('sha256')\n .update(canonicalJson)\n .digest('base64url')\n .slice(0, 16);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,IAAM,2CAAiE,IAAI,IAAI,CAC7E,aACA,YACF,CAAC;;;;;;;AAQD,IAAM,0CAAgE,IAAI,IAAI;CAC5E;CACA;CACA;CACA;AACF,CAAC;;AA2CD,SAAS,WACP,UACA,MACmC;CACnC,OAAO,OAAO,OAAO,SAAS,OAAO,CAAC,CAAC,MACpC,cACC,UAAU,kBAAkB,QAAQ,UAAU,cAAc,IAChE;AACF;;;;;;;;;;;;;;;AAgBA,SAAS,qBAAqB,SAAyB;CACrD,MAAM,QAAQ,QAAQ,MAAM,yBAAyB;CACrD,OAAO,QAAQ,MAAM,KAAK,QAAQ,KAAK;AACzC;;;;;;;;;;;;AAaA,SAAS,qBACP,UACA,KACA,uBAAoB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C,KAAK,MAAM,SAAS,yBAAyB,QAAQ,GACnD,YAAY,MAAM,cAAc,6BAC9B,OACA,QACF;CAEF,MAAM,gBAAgB,KAAK,UAAU,aAAa,WAAW,CAAC;CAC9D,OAAO,WAAW,QAAQ,CAAC,CACxB,OAAO,aAAa,CAAC,CACrB,OAAO,WAAW,CAAC,CACnB,MAAM,GAAG,EAAE;AAChB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@happyvertical/smrt-core",
3
- "version": "0.38.6",
3
+ "version": "0.38.8",
4
4
  "description": "Core AI agent framework with standardized collections, object-relational mapping, and code generators",
5
5
  "author": "HappyVertical",
6
6
  "type": "module",
@@ -154,9 +154,9 @@
154
154
  "tsx": "^4.23.0",
155
155
  "typescript": "^5.9.3",
156
156
  "yaml": "^2.9.0",
157
- "@happyvertical/smrt-config": "0.38.6",
158
- "@happyvertical/smrt-scanner": "0.38.6",
159
- "@happyvertical/smrt-types": "0.38.6"
157
+ "@happyvertical/smrt-config": "0.38.8",
158
+ "@happyvertical/smrt-scanner": "0.38.8",
159
+ "@happyvertical/smrt-types": "0.38.8"
160
160
  },
161
161
  "peerDependencies": {
162
162
  "@huggingface/transformers": ">=3.0.0 <4.0.0",