@happyvertical/smrt-core 0.40.2 → 0.40.4

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.
@@ -39,9 +39,57 @@ var RELATIONSHIP_EDGE_TYPES = /* @__PURE__ */ new Set([
39
39
  "oneToMany",
40
40
  "manyToMany"
41
41
  ]);
42
- /** Resolve a manifest object by qualified name or simple class name. */
43
- function findByName(manifest, name) {
44
- return Object.values(manifest.objects).find((candidate) => candidate.qualifiedName === name || candidate.className === name);
42
+ function compareText(left, right) {
43
+ if (left < right) return -1;
44
+ if (left > right) return 1;
45
+ return 0;
46
+ }
47
+ function manifestObjectPackage(manifestKey, obj) {
48
+ if (obj.packageName) return obj.packageName;
49
+ const qualifiedName = obj.qualifiedName || manifestKey;
50
+ const separator = qualifiedName?.lastIndexOf(":") ?? -1;
51
+ return separator > 0 ? qualifiedName?.slice(0, separator) : void 0;
52
+ }
53
+ var manifestObjectIndexes = /* @__PURE__ */ new WeakMap();
54
+ function packageAndClassKey(packageName, className) {
55
+ return `${packageName}\0${className}`;
56
+ }
57
+ function getManifestObjectIndex(manifest) {
58
+ const cached = manifestObjectIndexes.get(manifest.objects);
59
+ if (cached) return cached;
60
+ const entries = Object.entries(manifest.objects).sort(([leftKey, left], [rightKey, right]) => compareText(left.qualifiedName || leftKey, right.qualifiedName || rightKey) || compareText(leftKey, rightKey));
61
+ const index = {
62
+ byExactName: /* @__PURE__ */ new Map(),
63
+ byPackageAndClass: /* @__PURE__ */ new Map(),
64
+ bySimpleName: /* @__PURE__ */ new Map()
65
+ };
66
+ for (const [manifestKey, candidate] of entries) {
67
+ if (!index.byExactName.has(manifestKey)) index.byExactName.set(manifestKey, candidate);
68
+ if (candidate.qualifiedName && !index.byExactName.has(candidate.qualifiedName)) index.byExactName.set(candidate.qualifiedName, candidate);
69
+ if (!index.bySimpleName.has(candidate.className)) index.bySimpleName.set(candidate.className, candidate);
70
+ const packageName = manifestObjectPackage(manifestKey, candidate);
71
+ if (packageName) {
72
+ const packageKey = packageAndClassKey(packageName, candidate.className);
73
+ if (!index.byPackageAndClass.has(packageKey)) index.byPackageAndClass.set(packageKey, candidate);
74
+ }
75
+ }
76
+ manifestObjectIndexes.set(manifest.objects, index);
77
+ return index;
78
+ }
79
+ /**
80
+ * Resolve a manifest object deterministically across aggregated packages.
81
+ *
82
+ * Qualified references win exactly. Simple references prefer the referencing
83
+ * object's package, then fall back to a stable qualified/key identity. This is
84
+ * important because aggregated manifests can contain duplicate class names and
85
+ * their object insertion order reflects package discovery order.
86
+ */
87
+ function findManifestObjectByName(manifest, name, owner) {
88
+ const index = getManifestObjectIndex(manifest);
89
+ const exact = name.includes(":") ? index.byExactName.get(name) : void 0;
90
+ if (exact) return exact;
91
+ const ownerPackage = owner ? manifestObjectPackage(void 0, owner) : void 0;
92
+ return (ownerPackage ? index.byPackageAndClass.get(packageAndClassKey(ownerPackage, name)) : void 0) || index.bySimpleName.get(name);
45
93
  }
46
94
  /**
47
95
  * Normalize a relationship field's `related` value to a resolvable class name.
@@ -55,7 +103,8 @@ function findByName(manifest, name) {
55
103
  * untouched — the qualified `:` separator is preserved.
56
104
  *
57
105
  * Kept local to the relationship-edge path on purpose: extends-chain resolution
58
- * never sees a thunk, so `findByName` and the scanner stay unchanged.
106
+ * never sees a thunk, so `findManifestObjectByName` and the scanner stay
107
+ * unchanged.
59
108
  */
60
109
  function normalizeRelatedName(related) {
61
110
  const thunk = related.match(/=>\s*([A-Za-z_$][\w$]*)/);
@@ -77,7 +126,7 @@ function isCollectionManifestClass(manifest, obj, seen = /* @__PURE__ */ new Set
77
126
  const parentName = obj.extendsQualified || obj.extends;
78
127
  if (!parentName || seen.has(parentName)) return false;
79
128
  seen.add(parentName);
80
- const parent = findByName(manifest, parentName);
129
+ const parent = findManifestObjectByName(manifest, parentName, obj);
81
130
  return parent ? isCollectionManifestClass(manifest, parent, seen) : false;
82
131
  }
83
132
  /**
@@ -86,12 +135,14 @@ function isCollectionManifestClass(manifest, obj, seen = /* @__PURE__ */ new Set
86
135
  */
87
136
  function isStiChildModel(manifest, obj) {
88
137
  const seen = /* @__PURE__ */ new Set();
89
- let parentName = obj.extendsQualified || obj.extends;
138
+ let child = obj;
139
+ let parentName = child.extendsQualified || child.extends;
90
140
  while (parentName && !seen.has(parentName)) {
91
141
  seen.add(parentName);
92
- const parent = findByName(manifest, parentName);
142
+ const parent = findManifestObjectByName(manifest, parentName, child);
93
143
  if (!parent) return false;
94
144
  if (parent.collection === obj.collection) return true;
145
+ child = parent;
95
146
  parentName = parent.extendsQualified || parent.extends;
96
147
  }
97
148
  return false;
@@ -219,7 +270,7 @@ function buildWebRelationships(obj, manifest) {
219
270
  for (const [fieldName, field] of Object.entries(obj.fields ?? {})) {
220
271
  if (!RELATIONSHIP_EDGE_TYPES.has(field.type)) continue;
221
272
  if (!field.related) continue;
222
- const target = findByName(manifest, normalizeRelatedName(field.related));
273
+ const target = findManifestObjectByName(manifest, normalizeRelatedName(field.related), obj);
223
274
  if (!target) continue;
224
275
  if (!exposedCollections.has(target.collection)) continue;
225
276
  const dedupeKey = `${fieldName}:${target.collection}`;
@@ -318,6 +369,6 @@ function computeWebManifestHash(manifest) {
318
369
  return createHash("sha256").update(canonicalJson).digest("base64url").slice(0, 16);
319
370
  }
320
371
  //#endregion
321
- export { buildWebCollectionDefinition, buildWebFieldDefinitions, buildWebRelationships, buildWebToolDescriptors, computeWebManifestHash, isCollectionManifestClass, selectWebCollectionEntries };
372
+ export { buildWebCollectionDefinition, buildWebFieldDefinitions, buildWebRelationships, buildWebToolDescriptors, computeWebManifestHash, findManifestObjectByName, isCollectionManifestClass, selectWebCollectionEntries };
322
373
 
323
374
  //# 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. 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 */\nexport function isCollectionManifestClass(\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 ? isCollectionManifestClass(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 (isCollectionManifestClass(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,SAAgB,0BACd,UACA,KACA,uBAAoB,IAAI,IAAI,GACnB;CAIT,IAAI,IAAI,YAAY,oBAAoB,IAAI,gBAC1C,OAAO;CAET,MAAM,aAAa,IAAI,oBAAoB,IAAI;CAC/C,IAAI,CAAC,cAAc,KAAK,IAAI,UAAU,GAAG,OAAO;CAChD,KAAK,IAAI,UAAU;CACnB,MA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WAAW,CAAC,CACnB,MAAM,GAAG,EAAE;AAChB"}
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\nfunction compareText(left: string, right: string): number {\n if (left < right) return -1;\n if (left > right) return 1;\n return 0;\n}\n\nfunction manifestObjectPackage(\n manifestKey: string | undefined,\n obj: SmartObjectDefinition,\n): string | undefined {\n if (obj.packageName) return obj.packageName;\n const qualifiedName = obj.qualifiedName || manifestKey;\n const separator = qualifiedName?.lastIndexOf(':') ?? -1;\n return separator > 0 ? qualifiedName?.slice(0, separator) : undefined;\n}\n\ninterface ManifestObjectIndex {\n byExactName: Map<string, SmartObjectDefinition>;\n byPackageAndClass: Map<string, SmartObjectDefinition>;\n bySimpleName: Map<string, SmartObjectDefinition>;\n}\n\nconst manifestObjectIndexes = new WeakMap<\n SmartObjectManifest['objects'],\n ManifestObjectIndex\n>();\n\nfunction packageAndClassKey(packageName: string, className: string): string {\n return `${packageName}\\0${className}`;\n}\n\nfunction getManifestObjectIndex(\n manifest: SmartObjectManifest,\n): ManifestObjectIndex {\n const cached = manifestObjectIndexes.get(manifest.objects);\n if (cached) return cached;\n\n const entries = Object.entries(manifest.objects).sort(\n ([leftKey, left], [rightKey, right]) =>\n compareText(\n left.qualifiedName || leftKey,\n right.qualifiedName || rightKey,\n ) || compareText(leftKey, rightKey),\n );\n const index: ManifestObjectIndex = {\n byExactName: new Map(),\n byPackageAndClass: new Map(),\n bySimpleName: new Map(),\n };\n\n for (const [manifestKey, candidate] of entries) {\n if (!index.byExactName.has(manifestKey)) {\n index.byExactName.set(manifestKey, candidate);\n }\n if (\n candidate.qualifiedName &&\n !index.byExactName.has(candidate.qualifiedName)\n ) {\n index.byExactName.set(candidate.qualifiedName, candidate);\n }\n if (!index.bySimpleName.has(candidate.className)) {\n index.bySimpleName.set(candidate.className, candidate);\n }\n\n const packageName = manifestObjectPackage(manifestKey, candidate);\n if (packageName) {\n const packageKey = packageAndClassKey(packageName, candidate.className);\n if (!index.byPackageAndClass.has(packageKey)) {\n index.byPackageAndClass.set(packageKey, candidate);\n }\n }\n }\n\n manifestObjectIndexes.set(manifest.objects, index);\n return index;\n}\n\n/**\n * Resolve a manifest object deterministically across aggregated packages.\n *\n * Qualified references win exactly. Simple references prefer the referencing\n * object's package, then fall back to a stable qualified/key identity. This is\n * important because aggregated manifests can contain duplicate class names and\n * their object insertion order reflects package discovery order.\n */\nexport function findManifestObjectByName(\n manifest: SmartObjectManifest,\n name: string,\n owner?: SmartObjectDefinition,\n): SmartObjectDefinition | undefined {\n const index = getManifestObjectIndex(manifest);\n const exact = name.includes(':') ? index.byExactName.get(name) : undefined;\n if (exact) return exact;\n\n const ownerPackage = owner\n ? manifestObjectPackage(undefined, owner)\n : undefined;\n const packageLocal = ownerPackage\n ? index.byPackageAndClass.get(packageAndClassKey(ownerPackage, name))\n : undefined;\n\n return packageLocal || index.bySimpleName.get(name);\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 `findManifestObjectByName` and the scanner stay\n * 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 */\nexport function isCollectionManifestClass(\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 = findManifestObjectByName(manifest, parentName, obj);\n return parent ? isCollectionManifestClass(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 child = obj;\n let parentName = child.extendsQualified || child.extends;\n while (parentName && !seen.has(parentName)) {\n seen.add(parentName);\n const parent = findManifestObjectByName(manifest, parentName, child);\n if (!parent) return false;\n if (parent.collection === obj.collection) return true;\n child = parent;\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 (isCollectionManifestClass(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 findManifestObjectByName cannot match on its\n // own.\n const target = findManifestObjectByName(\n manifest,\n normalizeRelatedName(field.related),\n obj,\n );\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;;;;;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,wBACd,OACkB;CAClB,MAAM,YAAY,yBAAyB,MAAM,GAAG;CACpD,MAAM,SAA0B,OAAO,QAAQ,SAAS,CAAC,CAAC,KACvD,CAAC,MAAM,UAAU;EAChB;EACA,MAAM,IAAI;EACV,GAAI,IAAI,aAAa,KAAA,IAAY,EAAE,UAAU,IAAI,SAAS,IAAI,CAAC;EAC/D,GAAI,IAAI,YAAY,KAAA,IAAY,EAAE,SAAS,IAAI,QAAQ,IAAI,CAAC;CAC9D,EACF;CACA,OAAO,qBAAqB;EAC1B,WAAW,MAAM,IAAI;EACrB;EACA,SAAS,MAAM;CACjB,CAAC;AACH;;;;;;;;;;AAWA,SAAS,aAAa,OAAyB;CAC7C,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO,MAAM,KAAK,UAAU,aAAa,KAAK,CAAC;CAEjD,IAAI,SAAS,OAAO,UAAU,UAAU;EACtC,MAAM,SAAkC,CAAC;EACzC,KAAK,MAAM,OAAO,OAAO,KAAK,KAAgC,CAAC,CAAC,KAAK,GACnE,OAAO,OAAO,aAAc,MAAkC,IAAI;EAEpE,OAAO;CACT;CACA,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,SAAgB,uBAAuB,UAAuC;CAC5E,MAAM,cAAuC,CAAC;CAC9C,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.40.2",
3
+ "version": "0.40.4",
4
4
  "description": "Core AI agent framework with standardized collections, object-relational mapping, and code generators",
5
5
  "author": "HappyVertical",
6
6
  "type": "module",
@@ -157,11 +157,11 @@
157
157
  "minimatch": "10.2.5",
158
158
  "pluralize": "^8.0.0",
159
159
  "tsx": "^4.23.0",
160
- "typescript": "^5.9.3",
160
+ "typescript": "5.9.3",
161
161
  "yaml": "^2.9.0",
162
- "@happyvertical/smrt-config": "0.40.2",
163
- "@happyvertical/smrt-types": "0.40.2",
164
- "@happyvertical/smrt-scanner": "0.40.2"
162
+ "@happyvertical/smrt-scanner": "0.40.4",
163
+ "@happyvertical/smrt-config": "0.40.4",
164
+ "@happyvertical/smrt-types": "0.40.4"
165
165
  },
166
166
  "peerDependencies": {
167
167
  "@huggingface/transformers": ">=3.0.0 <4.0.0",
@@ -181,9 +181,9 @@
181
181
  "@types/node": "24.13.2",
182
182
  "@types/pluralize": "^0.0.33",
183
183
  "@xenova/transformers": "^2.17.2",
184
- "vite": "8.1.3",
184
+ "vite": "8.1.4",
185
185
  "vite-plugin-dts": "4.5.4",
186
- "vitest": "^4.1.9"
186
+ "vitest": "4.1.10"
187
187
  },
188
188
  "publishConfig": {
189
189
  "registry": "https://registry.npmjs.org",