@happyvertical/smrt-core 0.55.20 → 0.55.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/agents/cookbook-engine.md +7 -0
- package/agents/cookbook.md +15 -0
- package/dist/cookbook/engine/document.d.ts +3 -0
- package/dist/cookbook/engine/document.d.ts.map +1 -1
- package/dist/cookbook/engine/document.js +6 -0
- package/dist/cookbook/engine/document.js.map +1 -1
- package/dist/cookbook/engine/engine.d.ts.map +1 -1
- package/dist/cookbook/engine/engine.js +4 -1
- package/dist/cookbook/engine/engine.js.map +1 -1
- package/dist/cookbook/engine/schemas.d.ts.map +1 -1
- package/dist/cookbook/engine/schemas.js +23 -0
- package/dist/cookbook/engine/schemas.js.map +1 -1
- package/dist/cookbook/engine/types.d.ts +6 -0
- package/dist/cookbook/engine/types.d.ts.map +1 -1
- package/dist/cookbook/engine/types.js.map +1 -1
- package/dist/cookbook/v1.schema.json +3 -0
- package/dist/cookbook/validate.d.ts.map +1 -1
- package/dist/cookbook/validate.js +25 -0
- package/dist/cookbook/validate.js.map +1 -1
- package/dist/manifest/static-manifest.js +1 -1
- package/dist/manifest/static-manifest.js.map +1 -1
- package/dist/manifest/store.js +1 -1
- package/dist/manifest.json +1 -1
- package/dist/smrt-knowledge.json +7 -7
- package/package.json +4 -4
|
@@ -31,6 +31,13 @@ engine.tools / engine.batchTool // JSON Schema tool definit
|
|
|
31
31
|
`set_policy`, `set_theme`, `reset_theme`, `set_name`, `rename_section`,
|
|
32
32
|
`rename_item`, `hide`, `show`, `validate`, `export_cookbook`, `undo`. Navigation
|
|
33
33
|
and focus are not commands: they are an adapter concern.
|
|
34
|
+
- **`set_theme`** takes `preset`, `primary` (a brand colour that replaces the
|
|
35
|
+
preset, see cookbook.md), `colorScheme`, `fontFamily` (`null` restores the
|
|
36
|
+
preset font), and `borderRadius` (`none|sm|md|lg|xl|full`), `density`
|
|
37
|
+
(`comfortable|touch`), `contrast` (`auto|standard|more`). Each is optional and
|
|
38
|
+
only the fields given change; repeating the same input is an unchanged
|
|
39
|
+
receipt. Values outside the enums are `invalid_input`. `snapshot().theme`
|
|
40
|
+
reports the three new fields (`null` when unset); `reset_theme` clears them.
|
|
34
41
|
- **Errors** are typed (`CommandError`: `code`, `message`, `path?`, `details?`):
|
|
35
42
|
`unknown_command`, `invalid_input`, `not_found`, `confirmation_required`,
|
|
36
43
|
`conflict`, `id_reuse`, `batch_failed`, `failed`.
|
package/agents/cookbook.md
CHANGED
|
@@ -28,6 +28,21 @@ stylesheet after review.
|
|
|
28
28
|
brand colour. A host that knows the key applies it; unknown keys are retained
|
|
29
29
|
in the portable document. Older `theme.custom.fontFamily` values still read.
|
|
30
30
|
|
|
31
|
+
`theme.borderRadius` (`none|sm|md|lg|xl|full`), `theme.density`
|
|
32
|
+
(`comfortable|touch`) and `theme.contrast` (`auto|standard|more`) are optional
|
|
33
|
+
and mirror the `ThemeProvider` props of the same names. Absent means the
|
|
34
|
+
preset's own value (`contrast` absent is `auto`, which follows the OS). They are
|
|
35
|
+
additive: a document without them validates and reads unchanged, so there is no
|
|
36
|
+
version bump. Anything outside the enums is an `invalid_value` diagnostic at
|
|
37
|
+
`theme.<field>`.
|
|
38
|
+
|
|
39
|
+
`theme.custom.primary` and `ThemeProvider`'s `primaryColor` are different
|
|
40
|
+
controls. The cookbook sets `custom.primary`: the shell builds a whole theme
|
|
41
|
+
from it (`createThemeFromColor`) that REPLACES the preset, so `preset` is
|
|
42
|
+
ignored while it is present. `primaryColor` instead TINTS the current preset by
|
|
43
|
+
overriding only the derived primary colours (`derivePrimaryOverrides`). The
|
|
44
|
+
cookbook has no `primaryColor` field and the shell never passes one.
|
|
45
|
+
|
|
31
46
|
## Rules
|
|
32
47
|
|
|
33
48
|
- Versioning: add optional fields within `version: 1`; readers keep and ignore
|
|
@@ -55,6 +55,9 @@ export declare function withThemePatch(doc: Cookbook, patch: {
|
|
|
55
55
|
primary?: string;
|
|
56
56
|
colorScheme?: CookbookTheme['colorScheme'];
|
|
57
57
|
fontFamily?: string | null;
|
|
58
|
+
borderRadius?: CookbookTheme['borderRadius'];
|
|
59
|
+
density?: CookbookTheme['density'];
|
|
60
|
+
contrast?: CookbookTheme['contrast'];
|
|
58
61
|
}): Cookbook;
|
|
59
62
|
/**
|
|
60
63
|
* Check a document against the catalog. Structural errors come from
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"document.d.ts","sourceRoot":"","sources":["../../../src/cookbook/engine/document.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,QAAQ,EAER,aAAa,EACd,MAAM,2BAA2B,CAAC;AAanC,OAAO,KAAK,EACV,UAAU,EACV,aAAa,EACb,YAAY,EACZ,aAAa,EACb,cAAc,EACf,MAAM,YAAY,CAAC;AAOpB,eAAO,MAAM,KAAK,GAAI,CAAC,EAAE,OAAO,CAAC,KAAG,CACkB,CAAC;AAEvD,eAAO,MAAM,IAAI,GAAI,GAAG,OAAO,EAAE,GAAG,OAAO,KAAG,OACW,CAAC;AAE1D,eAAO,MAAM,aAAa,QAAO,QAM/B,CAAC;AAEH,4EAA4E;AAC5E,wBAAgB,eAAe,CAAC,GAAG,EAAE,QAAQ,GAAG,OAAO,CAUtD;AAID;;;;GAIG;AACH,wBAAgB,SAAS,CAAC,GAAG,EAAE,QAAQ,GAAG,QAAQ,CAsDjD;AAOD,wEAAwE;AACxE,wBAAgB,gBAAgB,CAC9B,GAAG,EAAE,QAAQ,CAAC,MAAM,CAAC,EACrB,OAAO,EAAE,WAAW,CAAC,MAAM,EAAE,YAAY,CAAC,GACzC,MAAM,EAAE,CAwBV;AAED,mDAAmD;AACnD,wBAAgB,aAAa,CAC3B,OAAO,EAAE,aAAa,EACtB,GAAG,EAAE,QAAQ,GACZ,GAAG,CAAC,MAAM,CAAC,CAMb;AAED,wBAAgB,cAAc,CAAC,OAAO,EAAE,aAAa,GAAG,cAAc,CAErE;AAQD,4EAA4E;AAC5E,wBAAgB,KAAK,CAAC,O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AC,EAAE,MAAM,CAAC;IACjB,WAAW,CAAC,EAAE,aAAa,CAAC,aAAa,CAAC,CAAC;IAC3C,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,YAAY,CAAC,EAAE,aAAa,CAAC,cAAc,CAAC,CAAC;IAC7C,OAAO,CAAC,EAAE,aAAa,CAAC,SAAS,CAAC,CAAC;IACnC,QAAQ,CAAC,EAAE,aAAa,CAAC,UAAU,CAAC,CAAC;CACtC,GACA,QAAQ,CA4BV;AAID;;;;;;GAMG;AACH,wBAAgB,QAAQ,CACtB,OAAO,EAAE,aAAa,EACtB,KAAK,EAAE,QAAQ,GACd,UAAU,EAAE,CA2Id"}
|
|
@@ -264,6 +264,9 @@ function compactTheme(theme) {
|
|
|
264
264
|
const out = {};
|
|
265
265
|
if (theme.preset) out.preset = theme.preset;
|
|
266
266
|
if (theme.colorScheme) out.colorScheme = theme.colorScheme;
|
|
267
|
+
if (theme.borderRadius) out.borderRadius = theme.borderRadius;
|
|
268
|
+
if (theme.density) out.density = theme.density;
|
|
269
|
+
if (theme.contrast) out.contrast = theme.contrast;
|
|
267
270
|
if (theme.fontFamily) out.fontFamily = theme.fontFamily;
|
|
268
271
|
if (theme.custom) out.custom = { ...theme.custom };
|
|
269
272
|
if (theme.customCss) out.customCss = theme.customCss;
|
|
@@ -286,6 +289,9 @@ function withThemePatch(doc, patch) {
|
|
|
286
289
|
...doc.theme?.custom?.fontFamily ? { fontFamily: doc.theme.custom.fontFamily } : {}
|
|
287
290
|
};
|
|
288
291
|
if (patch.colorScheme) next.colorScheme = patch.colorScheme;
|
|
292
|
+
if (patch.borderRadius) next.borderRadius = patch.borderRadius;
|
|
293
|
+
if (patch.density) next.density = patch.density;
|
|
294
|
+
if (patch.contrast) next.contrast = patch.contrast;
|
|
289
295
|
if (patch.fontFamily === null) {
|
|
290
296
|
delete next.fontFamily;
|
|
291
297
|
if (next.custom?.fontFamily) next.custom = { primary: next.custom.primary };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"document.js","names":[],"sources":["../../../src/cookbook/engine/document.ts"],"sourcesContent":["import type {\n Cookbook,\n CookbookPolicyRow,\n CookbookTheme,\n} from '@happyvertical/smrt-types';\nimport {\n COOKBOOK_SCHEMA_URL,\n COOKBOOK_VERSION,\n validateCookbook,\n} from '../validate.js';\nimport {\n COMMERCE_SETTING_TARGETS,\n DEFAULT_COLOR_SCHEME,\n DEFAULT_PRESET,\n DEFAULT_THEME_PRESETS,\n} from './defaults.js';\nimport { buildNav, findModel } from './nav.js';\nimport type {\n Diagnostic,\n EngineCatalog,\n EngineRecipe,\n RecipeChanges,\n SettingTargets,\n} from './types.js';\n\n/*\n * Pure document rules: every function takes a cookbook and returns a new one.\n * The engine holds a document and calls these; nothing here keeps state.\n */\n\nexport const clone = <T>(value: T): T =>\n value === undefined ? value : structuredClone(value);\n\nexport const same = (a: unknown, b: unknown): boolean =>\n JSON.stringify(a ?? null) === JSON.stringify(b ?? null);\n\nexport const emptyCookbook = (): Cookbook => ({\n $schema: COOKBOOK_SCHEMA_URL,\n version: COOKBOOK_VERSION,\n recipes: [],\n features: [],\n policies: [],\n});\n\n/** Does the document hold nothing yet (so replacing it needs no say-so)? */\nexport function isEmptyCookbook(doc: Cookbook): boolean {\n return (\n !doc.recipes.length &&\n !doc.features.length &&\n !doc.policies.length &&\n !Object.keys(doc.exposure ?? {}).length &&\n !doc.layout &&\n !doc.theme &&\n !Object.keys(doc.overviews ?? {}).length\n );\n}\n\nconst sortedUnique = (ids: Iterable<string>) => [...new Set(ids)].sort();\n\n/**\n * The document in its stable shape: sorted ids, sorted policies, empty optional\n * sections absent, key order fixed. Unknown top-level keys are kept (additive\n * fields in v1). Two engines given the same commands export identical text.\n */\nexport function canonical(doc: Cookbook): Cookbook {\n const known = new Set([\n '$schema',\n 'version',\n 'name',\n 'description',\n 'recipes',\n 'features',\n 'policies',\n 'exposure',\n 'layout',\n 'theme',\n 'overviews',\n ]);\n const out: Cookbook = {\n $schema: COOKBOOK_SCHEMA_URL,\n version: COOKBOOK_VERSION,\n ...(doc.name ? { name: doc.name } : {}),\n ...(doc.description ? { description: doc.description } : {}),\n recipes: sortedUnique(doc.recipes),\n features: sortedUnique(doc.features),\n policies: [...doc.policies]\n .sort(\n (a, b) =>\n a.objectRef.localeCompare(b.objectRef) ||\n a.fieldName.localeCompare(b.fieldName),\n )\n .map((row) => ({ ...row })),\n };\n const exposure = Object.fromEntries(\n Object.keys(doc.exposure ?? {})\n .sort()\n .filter((ref) => doc.exposure?.[ref]?.length)\n .map((ref) => [ref, [...(doc.exposure?.[ref] ?? [])].sort()]),\n );\n if (Object.keys(exposure).length) {\n out.exposure = exposure as NonNullable<Cookbook['exposure']>;\n }\n if (doc.layout) out.layout = clone(doc.layout);\n const theme = compactTheme(doc.theme);\n if (theme) out.theme = theme;\n const overviews = Object.entries(doc.overviews ?? {}).sort(([a], [b]) =>\n a < b ? -1 : a > b ? 1 : 0,\n );\n if (overviews.length) {\n out.overviews = Object.fromEntries(\n overviews.map(([id, value]) => [id, clone(value)]),\n );\n }\n for (const [key, value] of Object.entries(doc)) {\n if (!known.has(key))\n (out as unknown as Record<string, unknown>)[key] = clone(value);\n }\n return out;\n}\n\n// ---- recipes ---------------------------------------------------------------\n\nconst recipeMap = (catalog: EngineCatalog) =>\n new Map(catalog.recipes.map((r) => [r.id, r]));\n\n/** `ids` plus everything they transitively require, as a sorted set. */\nexport function withRequirements(\n ids: Iterable<string>,\n recipes: ReadonlyMap<string, EngineRecipe>,\n): string[] {\n const result = new Set<string>();\n const visit = (id: string) => {\n const recipe = recipes.get(id);\n if (!recipe || result.has(id)) return;\n result.add(id);\n for (const required of recipe.requires) visit(required);\n };\n for (const id of ids) visit(id);\n let changed = true;\n while (changed) {\n changed = false;\n for (const id of [...result]) {\n for (const alternatives of recipes.get(id)?.requiresAny ?? []) {\n if (alternatives.some((alt) => result.has(alt))) continue;\n const first = alternatives.find((alt) => recipes.has(alt));\n if (first) {\n visit(first);\n changed = true;\n }\n }\n }\n }\n return sortedUnique(result);\n}\n\n/** Models the added recipes and features cover. */\nexport function coveredModels(\n catalog: EngineCatalog,\n doc: Cookbook,\n): Set<string> {\n const byId = recipeMap(catalog);\n return new Set([\n ...doc.recipes.flatMap((id) => byId.get(id)?.models ?? []),\n ...doc.features,\n ]);\n}\n\nexport function settingTargets(catalog: EngineCatalog): SettingTargets {\n return catalog.settingTargets ?? COMMERCE_SETTING_TARGETS;\n}\n\nfunction isSettingRow(catalog: EngineCatalog, row: CookbookPolicyRow): boolean {\n return Object.values(settingTargets(catalog)).some((targets) =>\n targets.some((t) => t.model === row.objectRef && t.field === row.fieldName),\n );\n}\n\n/** Drop options for models nothing covers any more (settings rows stay). */\nexport function prune(catalog: EngineCatalog, doc: Cookbook): Cookbook {\n const covered = coveredModels(catalog, doc);\n const next: Cookbook = {\n ...doc,\n policies: doc.policies.filter(\n (r) => covered.has(r.objectRef) || isSettingRow(catalog, r),\n ),\n };\n if (doc.exposure) {\n const exposure = Object.fromEntries(\n Object.entries(doc.exposure).filter(([ref]) => covered.has(ref)),\n );\n if (Object.keys(exposure).length) next.exposure = exposure;\n else delete next.exposure;\n }\n return next;\n}\n\nconst knownRecipeIds = (catalog: EngineCatalog, doc: Cookbook) => {\n const byId = recipeMap(catalog);\n return doc.recipes.filter((id) => byId.has(id));\n};\n\nconst unknownRecipeIds = (catalog: EngineCatalog, doc: Cookbook) => {\n const byId = recipeMap(catalog);\n return doc.recipes.filter((id) => !byId.has(id));\n};\n\nfunction diff(\n before: string[],\n after: string[],\n): Pick<RecipeChanges, 'added' | 'removed'> {\n const b = new Set(before);\n const a = new Set(after);\n return {\n added: after.filter((id) => !b.has(id)),\n removed: before.filter((id) => !a.has(id)),\n };\n}\n\nexport function withRecipesAdded(\n catalog: EngineCatalog,\n doc: Cookbook,\n ids: readonly string[],\n): { doc: Cookbook; changes: RecipeChanges } {\n const byId = recipeMap(catalog);\n const before = knownRecipeIds(catalog, doc);\n const known = withRequirements([...before, ...ids], byId);\n const next = {\n ...doc,\n recipes: sortedUnique([...known, ...unknownRecipeIds(catalog, doc)]),\n };\n return { doc: next, changes: { ...diff(before, known), kept: [] } };\n}\n\nexport function withRecipesRemoved(\n catalog: EngineCatalog,\n doc: Cookbook,\n ids: readonly string[],\n): { doc: Cookbook; changes: RecipeChanges } {\n const byId = recipeMap(catalog);\n const before = knownRecipeIds(catalog, doc);\n const removing = new Set(ids);\n const known = withRequirements(\n before.filter((id) => !removing.has(id)),\n byId,\n );\n const next = prune(catalog, {\n ...doc,\n recipes: sortedUnique([...known, ...unknownRecipeIds(catalog, doc)]),\n });\n const { added, removed } = diff(before, known);\n return {\n doc: next,\n changes: {\n added,\n removed,\n kept: ids.filter((id) => known.includes(id) && before.includes(id)),\n },\n };\n}\n\nexport function withFeaturesChanged(\n catalog: EngineCatalog,\n doc: Cookbook,\n ids: readonly string[],\n on: boolean,\n): { doc: Cookbook; changes: RecipeChanges } {\n const set = new Set(doc.features);\n for (const id of ids) {\n if (on) set.add(id);\n else set.delete(id);\n }\n const features = [...set].sort();\n let next: Cookbook = { ...doc, features };\n if (!on) next = prune(catalog, next);\n return {\n doc: next,\n changes: { ...diff(doc.features, features), kept: [] },\n };\n}\n\nexport const mergeChanges = (\n a: RecipeChanges,\n b: RecipeChanges,\n): RecipeChanges => ({\n added: [...a.added, ...b.added],\n removed: [...a.removed, ...b.removed],\n kept: [...a.kept, ...b.kept],\n});\n\n// ---- settings --------------------------------------------------------------\n\nexport interface AppSettings {\n currency: string;\n /** A fraction: 0.0825 is 8.25%. */\n taxRate: number;\n paymentTerms: string;\n}\n\nexport const DEFAULT_SETTINGS: Readonly<AppSettings> = {\n currency: 'USD',\n taxRate: 0,\n paymentTerms: '',\n};\n\nconst SETTING_KEYS = ['currency', 'taxRate', 'paymentTerms'] as const;\n\nfunction rowValue(row: CookbookPolicyRow | undefined): unknown {\n if (row?.defaultValue === undefined || row.defaultValue === null)\n return undefined;\n try {\n return JSON.parse(row.defaultValue);\n } catch {\n return undefined;\n }\n}\n\nconst findRow = (\n policies: readonly CookbookPolicyRow[],\n model: string,\n field: string,\n) =>\n policies.find(\n (r) =>\n r.scopeType === 'app' && r.objectRef === model && r.fieldName === field,\n );\n\n/** The app's settings: the first stored row of each, else the defaults. */\nexport function readSettings(\n catalog: EngineCatalog,\n doc: Cookbook,\n): AppSettings {\n const targets = settingTargets(catalog);\n const out: AppSettings = { ...DEFAULT_SETTINGS };\n const first = (key: keyof AppSettings, type: 'number' | 'string') => {\n for (const { model, field } of targets[key]) {\n const value = rowValue(findRow(doc.policies, model, field));\n if (typeof value === type) return value;\n }\n return undefined;\n };\n const currency = first('currency', 'string');\n const taxRate = first('taxRate', 'number');\n const paymentTerms = first('paymentTerms', 'string');\n if (typeof currency === 'string') out.currency = currency;\n if (typeof taxRate === 'number') out.taxRate = taxRate;\n if (typeof paymentTerms === 'string') out.paymentTerms = paymentTerms;\n return out;\n}\n\nconst isUnset = (v: unknown) => v === undefined || v === null || v === '';\n\nfunction seedDefault(\n catalog: EngineCatalog,\n doc: Cookbook,\n modelId: string,\n field: string,\n): unknown {\n const byId = recipeMap(catalog);\n for (const id of doc.recipes) {\n const hint = byId.get(id)?.options?.[modelId]?.fields?.[field];\n if (hint && 'default' in hint) return hint.default;\n }\n return findModel(catalog, modelId)?.fields?.find((f) => f.name === field)\n ?.default;\n}\n\n/**\n * The document with the settings written as app-scope policy rows. A row is\n * written for every model a setting covers (covered or not, so a recipe added\n * later picks it up) and only where the value differs from what the model\n * starts as; otherwise the row's default is removed. Other row keys are kept.\n */\nexport function writeSettings(\n catalog: EngineCatalog,\n doc: Cookbook,\n settings: AppSettings,\n): Cookbook {\n const targets = settingTargets(catalog);\n let policies = doc.policies.map((row) => ({ ...row }));\n for (const key of SETTING_KEYS) {\n const raw = settings[key];\n const value =\n key === 'paymentTerms'\n ? String(raw).trim()\n : key === 'currency'\n ? String(raw).trim().toUpperCase()\n : raw;\n for (const { model, field } of targets[key]) {\n const seed = seedDefault(catalog, doc, model, field);\n const wanted =\n !isUnset(value) &&\n !(!isUnset(seed) && seed === value) &&\n !(isUnset(seed) && key === 'taxRate' && value === 0);\n const existing = findRow(policies, model, field);\n if (wanted) {\n const encoded = JSON.stringify(value);\n if (existing) existing.defaultValue = encoded;\n else\n policies.push({\n objectRef: model,\n fieldName: field,\n scopeType: 'app',\n defaultValue: encoded,\n });\n } else if (existing) {\n delete existing.defaultValue;\n if (Object.keys(existing).length <= 3) {\n policies = policies.filter((r) => r !== existing);\n }\n }\n }\n }\n return { ...doc, policies };\n}\n\n// ---- theme -----------------------------------------------------------------\n\nexport function compactTheme(\n theme: CookbookTheme | undefined,\n): CookbookTheme | undefined {\n if (!theme) return undefined;\n const out: CookbookTheme = {};\n if (theme.preset) out.preset = theme.preset;\n if (theme.colorScheme) out.colorScheme = theme.colorScheme;\n if (theme.fontFamily) out.fontFamily = theme.fontFamily;\n if (theme.custom) out.custom = { ...theme.custom };\n if (theme.customCss) out.customCss = theme.customCss;\n return Object.keys(out).length ? out : undefined;\n}\n\nexport function describeTheme(theme: CookbookTheme | undefined): string {\n const scheme = theme?.colorScheme ?? DEFAULT_COLOR_SCHEME;\n const base = theme?.custom\n ? `brand colour ${theme.custom.primary}`\n : (theme?.preset ?? DEFAULT_PRESET);\n return scheme === 'system' ? base : `${base}, ${scheme}`;\n}\n\n/** A preset replaces a brand colour; a brand colour sits on the preset; the scheme is kept. */\nexport function withThemePatch(\n doc: Cookbook,\n patch: {\n preset?: string;\n primary?: string;\n colorScheme?: CookbookTheme['colorScheme'];\n fontFamily?: string | null;\n },\n): Cookbook {\n const next: CookbookTheme = { ...(doc.theme ?? {}) };\n if (patch.preset) {\n next.preset = patch.preset;\n delete next.custom;\n }\n if (patch.primary) {\n next.custom = {\n primary: patch.primary.toLowerCase(),\n ...(doc.theme?.custom?.fontFamily\n ? { fontFamily: doc.theme.custom.fontFamily }\n : {}),\n };\n }\n if (patch.colorScheme) next.colorScheme = patch.colorScheme;\n if (patch.fontFamily === null) {\n // Null restores the preset font, so a legacy brand font goes too.\n delete next.fontFamily;\n if (next.custom?.fontFamily) next.custom = { primary: next.custom.primary };\n } else if (patch.fontFamily !== undefined) next.fontFamily = patch.fontFamily;\n const theme = compactTheme(next);\n const out = { ...doc };\n if (theme) out.theme = theme;\n else delete out.theme;\n return out;\n}\n\n// ---- validation ------------------------------------------------------------\n\n/**\n * Check a document against the catalog. Structural errors come from\n * `validateCookbook`; the rest need the catalog: unknown ids, unmet `requires`,\n * policy targets nothing covers, layout ids the menu does not have, theme\n * values. Errors mean the app would not build as written; warnings mean\n * something is carried but unused.\n */\nexport function diagnose(\n catalog: EngineCatalog,\n input: Cookbook,\n): Diagnostic[] {\n const out: Diagnostic[] = [];\n const add = (\n severity: Diagnostic['severity'],\n code: string,\n path: string,\n message: string,\n ) => out.push({ severity, code, path, message });\n\n const structural = validateCookbook(input);\n if (!structural.ok) {\n for (const issue of structural.diagnostics.filter(\n (diagnostic) => diagnostic.severity === 'error',\n )) {\n add('error', 'invalid_document', issue.path, issue.message);\n }\n return out;\n }\n for (const issue of structural.diagnostics) {\n add(\n issue.severity,\n issue.code === 'migrated_schema' ? 'migrated' : issue.code,\n issue.path,\n issue.message,\n );\n }\n const doc = structural.cookbook;\n const byId = recipeMap(catalog);\n\n const nav = buildNav(catalog, { ...doc, layout: undefined });\n const checked = validateCookbook(doc, {\n themePresets: catalog.themePresets ?? DEFAULT_THEME_PRESETS,\n layout: {\n sections: nav.map((section) => section.id),\n items: nav.flatMap((section) => section.items.map((item) => item.id)),\n ...(catalog.placementItems\n ? { placementItems: catalog.placementItems }\n : {}),\n },\n overviewIds: [\n ...nav.map((section) => section.id),\n ...(doc.layout?.customSections ?? []).map((section) => section.id),\n ],\n });\n for (const issue of checked.diagnostics) {\n if (\n issue.code === 'unknown_theme_preset' ||\n issue.code === 'unknown_layout_id' ||\n issue.code === 'unknown_overview'\n ) {\n add(\n issue.code === 'unknown_layout_id' &&\n !issue.path.startsWith('layout.placements.')\n ? 'warning'\n : issue.severity,\n issue.code === 'unknown_theme_preset' ? 'unknown_preset' : issue.code,\n issue.path,\n issue.message,\n );\n }\n }\n\n for (const [i, id] of doc.recipes.entries()) {\n if (!byId.has(id))\n add(\n 'error',\n 'unknown_recipe',\n `recipes[${i}]`,\n `Unknown recipe \"${id}\".`,\n );\n }\n const closure = new Set(withRequirements(doc.recipes, byId));\n for (const id of closure) {\n if (!doc.recipes.includes(id)) {\n add(\n 'error',\n 'missing_requirement',\n 'recipes',\n `A recipe needs \"${id}\", which is not listed.`,\n );\n }\n }\n for (const [i, id] of doc.features.entries()) {\n const model = findModel(catalog, id);\n if (!model)\n add('error', 'unknown_model', `features[${i}]`, `Unknown model \"${id}\".`);\n else if (model.exposed === false) {\n add(\n 'error',\n 'model_not_exposed',\n `features[${i}]`,\n `${id} cannot be added as a feature.`,\n );\n }\n }\n const covered = coveredModels(catalog, doc);\n for (const [i, row] of doc.policies.entries()) {\n const at = `policies[${i}]`;\n const model = findModel(catalog, row.objectRef);\n if (!model) {\n add(\n 'error',\n 'unknown_model',\n `${at}.objectRef`,\n `Unknown model \"${row.objectRef}\".`,\n );\n continue;\n }\n if (\n model.fields &&\n !model.fields.some((f) => f.name === row.fieldName && !f.system)\n ) {\n add(\n 'error',\n 'unknown_field',\n `${at}.fieldName`,\n `${model.name} has no field \"${row.fieldName}\".`,\n );\n }\n if (!covered.has(row.objectRef) && !isSettingRow(catalog, row)) {\n add(\n 'warning',\n 'policy_not_covered',\n at,\n `${model.name} is not in the app, so this row has no effect.`,\n );\n }\n }\n for (const ref of Object.keys(doc.exposure ?? {})) {\n if (!findModel(catalog, ref)) {\n add(\n 'error',\n 'unknown_model',\n `exposure.${ref}`,\n `Unknown model \"${ref}\".`,\n );\n }\n }\n return out;\n}\n"],"mappings":";;;;AA8BA,IAAa,SAAY,UACvB,UAAU,KAAA,IAAY,QAAQ,gBAAgB,KAAK;AAErD,IAAa,QAAQ,GAAY,MAC/B,KAAK,UAAU,KAA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MAAM,QAAQ,UAAU,SAAS,IAAI,SAAS;EAC9C,IAAI,CAAC,OAAO;GACV,IACE,SACA,iBACA,GAAG,GAAG,aACN,kBAAkB,IAAI,UAAU,GAClC;GACA;EACF;EACA,IACE,MAAM,UACN,CAAC,MAAM,OAAO,MAAM,MAAM,EAAE,SAAS,IAAI,aAAa,CAAC,EAAE,MAAM,GAE/D,IACE,SACA,iBACA,GAAG,GAAG,aACN,GAAG,MAAM,KAAK,iBAAiB,IAAI,UAAU,GAC/C;EAEF,IAAI,CAAC,QAAQ,IAAI,IAAI,SAAS,KAAK,CAAC,aAAa,SAAS,GAAG,GAC3D,IACE,WACA,sBACA,IACA,GAAG,MAAM,KAAK,+CAChB;CAEJ;CACA,KAAK,MAAM,OAAO,OAAO,KAAK,IAAI,YAAY,CAAC,CAAC,GAC9C,IAAI,CAAC,UAAU,SAAS,GAAG,GACzB,IACE,SACA,iBACA,YAAY,OACZ,kBAAkB,IAAI,GACxB;CAGJ,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"document.js","names":[],"sources":["../../../src/cookbook/engine/document.ts"],"sourcesContent":["import type {\n Cookbook,\n CookbookPolicyRow,\n CookbookTheme,\n} from '@happyvertical/smrt-types';\nimport {\n COOKBOOK_SCHEMA_URL,\n COOKBOOK_VERSION,\n validateCookbook,\n} from '../validate.js';\nimport {\n COMMERCE_SETTING_TARGETS,\n DEFAULT_COLOR_SCHEME,\n DEFAULT_PRESET,\n DEFAULT_THEME_PRESETS,\n} from './defaults.js';\nimport { buildNav, findModel } from './nav.js';\nimport type {\n Diagnostic,\n EngineCatalog,\n EngineRecipe,\n RecipeChanges,\n SettingTargets,\n} from './types.js';\n\n/*\n * Pure document rules: every function takes a cookbook and returns a new one.\n * The engine holds a document and calls these; nothing here keeps state.\n */\n\nexport const clone = <T>(value: T): T =>\n value === undefined ? value : structuredClone(value);\n\nexport const same = (a: unknown, b: unknown): boolean =>\n JSON.stringify(a ?? null) === JSON.stringify(b ?? null);\n\nexport const emptyCookbook = (): Cookbook => ({\n $schema: COOKBOOK_SCHEMA_URL,\n version: COOKBOOK_VERSION,\n recipes: [],\n features: [],\n policies: [],\n});\n\n/** Does the document hold nothing yet (so replacing it needs no say-so)? */\nexport function isEmptyCookbook(doc: Cookbook): boolean {\n return (\n !doc.recipes.length &&\n !doc.features.length &&\n !doc.policies.length &&\n !Object.keys(doc.exposure ?? {}).length &&\n !doc.layout &&\n !doc.theme &&\n !Object.keys(doc.overviews ?? {}).length\n );\n}\n\nconst sortedUnique = (ids: Iterable<string>) => [...new Set(ids)].sort();\n\n/**\n * The document in its stable shape: sorted ids, sorted policies, empty optional\n * sections absent, key order fixed. Unknown top-level keys are kept (additive\n * fields in v1). Two engines given the same commands export identical text.\n */\nexport function canonical(doc: Cookbook): Cookbook {\n const known = new Set([\n '$schema',\n 'version',\n 'name',\n 'description',\n 'recipes',\n 'features',\n 'policies',\n 'exposure',\n 'layout',\n 'theme',\n 'overviews',\n ]);\n const out: Cookbook = {\n $schema: COOKBOOK_SCHEMA_URL,\n version: COOKBOOK_VERSION,\n ...(doc.name ? { name: doc.name } : {}),\n ...(doc.description ? { description: doc.description } : {}),\n recipes: sortedUnique(doc.recipes),\n features: sortedUnique(doc.features),\n policies: [...doc.policies]\n .sort(\n (a, b) =>\n a.objectRef.localeCompare(b.objectRef) ||\n a.fieldName.localeCompare(b.fieldName),\n )\n .map((row) => ({ ...row })),\n };\n const exposure = Object.fromEntries(\n Object.keys(doc.exposure ?? {})\n .sort()\n .filter((ref) => doc.exposure?.[ref]?.length)\n .map((ref) => [ref, [...(doc.exposure?.[ref] ?? [])].sort()]),\n );\n if (Object.keys(exposure).length) {\n out.exposure = exposure as NonNullable<Cookbook['exposure']>;\n }\n if (doc.layout) out.layout = clone(doc.layout);\n const theme = compactTheme(doc.theme);\n if (theme) out.theme = theme;\n const overviews = Object.entries(doc.overviews ?? {}).sort(([a], [b]) =>\n a < b ? -1 : a > b ? 1 : 0,\n );\n if (overviews.length) {\n out.overviews = Object.fromEntries(\n overviews.map(([id, value]) => [id, clone(value)]),\n );\n }\n for (const [key, value] of Object.entries(doc)) {\n if (!known.has(key))\n (out as unknown as Record<string, unknown>)[key] = clone(value);\n }\n return out;\n}\n\n// ---- recipes ---------------------------------------------------------------\n\nconst recipeMap = (catalog: EngineCatalog) =>\n new Map(catalog.recipes.map((r) => [r.id, r]));\n\n/** `ids` plus everything they transitively require, as a sorted set. */\nexport function withRequirements(\n ids: Iterable<string>,\n recipes: ReadonlyMap<string, EngineRecipe>,\n): string[] {\n const result = new Set<string>();\n const visit = (id: string) => {\n const recipe = recipes.get(id);\n if (!recipe || result.has(id)) return;\n result.add(id);\n for (const required of recipe.requires) visit(required);\n };\n for (const id of ids) visit(id);\n let changed = true;\n while (changed) {\n changed = false;\n for (const id of [...result]) {\n for (const alternatives of recipes.get(id)?.requiresAny ?? []) {\n if (alternatives.some((alt) => result.has(alt))) continue;\n const first = alternatives.find((alt) => recipes.has(alt));\n if (first) {\n visit(first);\n changed = true;\n }\n }\n }\n }\n return sortedUnique(result);\n}\n\n/** Models the added recipes and features cover. */\nexport function coveredModels(\n catalog: EngineCatalog,\n doc: Cookbook,\n): Set<string> {\n const byId = recipeMap(catalog);\n return new Set([\n ...doc.recipes.flatMap((id) => byId.get(id)?.models ?? []),\n ...doc.features,\n ]);\n}\n\nexport function settingTargets(catalog: EngineCatalog): SettingTargets {\n return catalog.settingTargets ?? COMMERCE_SETTING_TARGETS;\n}\n\nfunction isSettingRow(catalog: EngineCatalog, row: CookbookPolicyRow): boolean {\n return Object.values(settingTargets(catalog)).some((targets) =>\n targets.some((t) => t.model === row.objectRef && t.field === row.fieldName),\n );\n}\n\n/** Drop options for models nothing covers any more (settings rows stay). */\nexport function prune(catalog: EngineCatalog, doc: Cookbook): Cookbook {\n const covered = coveredModels(catalog, doc);\n const next: Cookbook = {\n ...doc,\n policies: doc.policies.filter(\n (r) => covered.has(r.objectRef) || isSettingRow(catalog, r),\n ),\n };\n if (doc.exposure) {\n const exposure = Object.fromEntries(\n Object.entries(doc.exposure).filter(([ref]) => covered.has(ref)),\n );\n if (Object.keys(exposure).length) next.exposure = exposure;\n else delete next.exposure;\n }\n return next;\n}\n\nconst knownRecipeIds = (catalog: EngineCatalog, doc: Cookbook) => {\n const byId = recipeMap(catalog);\n return doc.recipes.filter((id) => byId.has(id));\n};\n\nconst unknownRecipeIds = (catalog: EngineCatalog, doc: Cookbook) => {\n const byId = recipeMap(catalog);\n return doc.recipes.filter((id) => !byId.has(id));\n};\n\nfunction diff(\n before: string[],\n after: string[],\n): Pick<RecipeChanges, 'added' | 'removed'> {\n const b = new Set(before);\n const a = new Set(after);\n return {\n added: after.filter((id) => !b.has(id)),\n removed: before.filter((id) => !a.has(id)),\n };\n}\n\nexport function withRecipesAdded(\n catalog: EngineCatalog,\n doc: Cookbook,\n ids: readonly string[],\n): { doc: Cookbook; changes: RecipeChanges } {\n const byId = recipeMap(catalog);\n const before = knownRecipeIds(catalog, doc);\n const known = withRequirements([...before, ...ids], byId);\n const next = {\n ...doc,\n recipes: sortedUnique([...known, ...unknownRecipeIds(catalog, doc)]),\n };\n return { doc: next, changes: { ...diff(before, known), kept: [] } };\n}\n\nexport function withRecipesRemoved(\n catalog: EngineCatalog,\n doc: Cookbook,\n ids: readonly string[],\n): { doc: Cookbook; changes: RecipeChanges } {\n const byId = recipeMap(catalog);\n const before = knownRecipeIds(catalog, doc);\n const removing = new Set(ids);\n const known = withRequirements(\n before.filter((id) => !removing.has(id)),\n byId,\n );\n const next = prune(catalog, {\n ...doc,\n recipes: sortedUnique([...known, ...unknownRecipeIds(catalog, doc)]),\n });\n const { added, removed } = diff(before, known);\n return {\n doc: next,\n changes: {\n added,\n removed,\n kept: ids.filter((id) => known.includes(id) && before.includes(id)),\n },\n };\n}\n\nexport function withFeaturesChanged(\n catalog: EngineCatalog,\n doc: Cookbook,\n ids: readonly string[],\n on: boolean,\n): { doc: Cookbook; changes: RecipeChanges } {\n const set = new Set(doc.features);\n for (const id of ids) {\n if (on) set.add(id);\n else set.delete(id);\n }\n const features = [...set].sort();\n let next: Cookbook = { ...doc, features };\n if (!on) next = prune(catalog, next);\n return {\n doc: next,\n changes: { ...diff(doc.features, features), kept: [] },\n };\n}\n\nexport const mergeChanges = (\n a: RecipeChanges,\n b: RecipeChanges,\n): RecipeChanges => ({\n added: [...a.added, ...b.added],\n removed: [...a.removed, ...b.removed],\n kept: [...a.kept, ...b.kept],\n});\n\n// ---- settings --------------------------------------------------------------\n\nexport interface AppSettings {\n currency: string;\n /** A fraction: 0.0825 is 8.25%. */\n taxRate: number;\n paymentTerms: string;\n}\n\nexport const DEFAULT_SETTINGS: Readonly<AppSettings> = {\n currency: 'USD',\n taxRate: 0,\n paymentTerms: '',\n};\n\nconst SETTING_KEYS = ['currency', 'taxRate', 'paymentTerms'] as const;\n\nfunction rowValue(row: CookbookPolicyRow | undefined): unknown {\n if (row?.defaultValue === undefined || row.defaultValue === null)\n return undefined;\n try {\n return JSON.parse(row.defaultValue);\n } catch {\n return undefined;\n }\n}\n\nconst findRow = (\n policies: readonly CookbookPolicyRow[],\n model: string,\n field: string,\n) =>\n policies.find(\n (r) =>\n r.scopeType === 'app' && r.objectRef === model && r.fieldName === field,\n );\n\n/** The app's settings: the first stored row of each, else the defaults. */\nexport function readSettings(\n catalog: EngineCatalog,\n doc: Cookbook,\n): AppSettings {\n const targets = settingTargets(catalog);\n const out: AppSettings = { ...DEFAULT_SETTINGS };\n const first = (key: keyof AppSettings, type: 'number' | 'string') => {\n for (const { model, field } of targets[key]) {\n const value = rowValue(findRow(doc.policies, model, field));\n if (typeof value === type) return value;\n }\n return undefined;\n };\n const currency = first('currency', 'string');\n const taxRate = first('taxRate', 'number');\n const paymentTerms = first('paymentTerms', 'string');\n if (typeof currency === 'string') out.currency = currency;\n if (typeof taxRate === 'number') out.taxRate = taxRate;\n if (typeof paymentTerms === 'string') out.paymentTerms = paymentTerms;\n return out;\n}\n\nconst isUnset = (v: unknown) => v === undefined || v === null || v === '';\n\nfunction seedDefault(\n catalog: EngineCatalog,\n doc: Cookbook,\n modelId: string,\n field: string,\n): unknown {\n const byId = recipeMap(catalog);\n for (const id of doc.recipes) {\n const hint = byId.get(id)?.options?.[modelId]?.fields?.[field];\n if (hint && 'default' in hint) return hint.default;\n }\n return findModel(catalog, modelId)?.fields?.find((f) => f.name === field)\n ?.default;\n}\n\n/**\n * The document with the settings written as app-scope policy rows. A row is\n * written for every model a setting covers (covered or not, so a recipe added\n * later picks it up) and only where the value differs from what the model\n * starts as; otherwise the row's default is removed. Other row keys are kept.\n */\nexport function writeSettings(\n catalog: EngineCatalog,\n doc: Cookbook,\n settings: AppSettings,\n): Cookbook {\n const targets = settingTargets(catalog);\n let policies = doc.policies.map((row) => ({ ...row }));\n for (const key of SETTING_KEYS) {\n const raw = settings[key];\n const value =\n key === 'paymentTerms'\n ? String(raw).trim()\n : key === 'currency'\n ? String(raw).trim().toUpperCase()\n : raw;\n for (const { model, field } of targets[key]) {\n const seed = seedDefault(catalog, doc, model, field);\n const wanted =\n !isUnset(value) &&\n !(!isUnset(seed) && seed === value) &&\n !(isUnset(seed) && key === 'taxRate' && value === 0);\n const existing = findRow(policies, model, field);\n if (wanted) {\n const encoded = JSON.stringify(value);\n if (existing) existing.defaultValue = encoded;\n else\n policies.push({\n objectRef: model,\n fieldName: field,\n scopeType: 'app',\n defaultValue: encoded,\n });\n } else if (existing) {\n delete existing.defaultValue;\n if (Object.keys(existing).length <= 3) {\n policies = policies.filter((r) => r !== existing);\n }\n }\n }\n }\n return { ...doc, policies };\n}\n\n// ---- theme -----------------------------------------------------------------\n\nexport function compactTheme(\n theme: CookbookTheme | undefined,\n): CookbookTheme | undefined {\n if (!theme) return undefined;\n const out: CookbookTheme = {};\n if (theme.preset) out.preset = theme.preset;\n if (theme.colorScheme) out.colorScheme = theme.colorScheme;\n if (theme.borderRadius) out.borderRadius = theme.borderRadius;\n if (theme.density) out.density = theme.density;\n if (theme.contrast) out.contrast = theme.contrast;\n if (theme.fontFamily) out.fontFamily = theme.fontFamily;\n if (theme.custom) out.custom = { ...theme.custom };\n if (theme.customCss) out.customCss = theme.customCss;\n return Object.keys(out).length ? out : undefined;\n}\n\nexport function describeTheme(theme: CookbookTheme | undefined): string {\n const scheme = theme?.colorScheme ?? DEFAULT_COLOR_SCHEME;\n const base = theme?.custom\n ? `brand colour ${theme.custom.primary}`\n : (theme?.preset ?? DEFAULT_PRESET);\n return scheme === 'system' ? base : `${base}, ${scheme}`;\n}\n\n/** A preset replaces a brand colour; a brand colour sits on the preset; the scheme is kept. */\nexport function withThemePatch(\n doc: Cookbook,\n patch: {\n preset?: string;\n primary?: string;\n colorScheme?: CookbookTheme['colorScheme'];\n fontFamily?: string | null;\n borderRadius?: CookbookTheme['borderRadius'];\n density?: CookbookTheme['density'];\n contrast?: CookbookTheme['contrast'];\n },\n): Cookbook {\n const next: CookbookTheme = { ...(doc.theme ?? {}) };\n if (patch.preset) {\n next.preset = patch.preset;\n delete next.custom;\n }\n if (patch.primary) {\n next.custom = {\n primary: patch.primary.toLowerCase(),\n ...(doc.theme?.custom?.fontFamily\n ? { fontFamily: doc.theme.custom.fontFamily }\n : {}),\n };\n }\n if (patch.colorScheme) next.colorScheme = patch.colorScheme;\n if (patch.borderRadius) next.borderRadius = patch.borderRadius;\n if (patch.density) next.density = patch.density;\n if (patch.contrast) next.contrast = patch.contrast;\n if (patch.fontFamily === null) {\n // Null restores the preset font, so a legacy brand font goes too.\n delete next.fontFamily;\n if (next.custom?.fontFamily) next.custom = { primary: next.custom.primary };\n } else if (patch.fontFamily !== undefined) next.fontFamily = patch.fontFamily;\n const theme = compactTheme(next);\n const out = { ...doc };\n if (theme) out.theme = theme;\n else delete out.theme;\n return out;\n}\n\n// ---- validation ------------------------------------------------------------\n\n/**\n * Check a document against the catalog. Structural errors come from\n * `validateCookbook`; the rest need the catalog: unknown ids, unmet `requires`,\n * policy targets nothing covers, layout ids the menu does not have, theme\n * values. Errors mean the app would not build as written; warnings mean\n * something is carried but unused.\n */\nexport function diagnose(\n catalog: EngineCatalog,\n input: Cookbook,\n): Diagnostic[] {\n const out: Diagnostic[] = [];\n const add = (\n severity: Diagnostic['severity'],\n code: string,\n path: string,\n message: string,\n ) => out.push({ severity, code, path, message });\n\n const structural = validateCookbook(input);\n if (!structural.ok) {\n for (const issue of structural.diagnostics.filter(\n (diagnostic) => diagnostic.severity === 'error',\n )) {\n add('error', 'invalid_document', issue.path, issue.message);\n }\n return out;\n }\n for (const issue of structural.diagnostics) {\n add(\n issue.severity,\n issue.code === 'migrated_schema' ? 'migrated' : issue.code,\n issue.path,\n issue.message,\n );\n }\n const doc = structural.cookbook;\n const byId = recipeMap(catalog);\n\n const nav = buildNav(catalog, { ...doc, layout: undefined });\n const checked = validateCookbook(doc, {\n themePresets: catalog.themePresets ?? DEFAULT_THEME_PRESETS,\n layout: {\n sections: nav.map((section) => section.id),\n items: nav.flatMap((section) => section.items.map((item) => item.id)),\n ...(catalog.placementItems\n ? { placementItems: catalog.placementItems }\n : {}),\n },\n overviewIds: [\n ...nav.map((section) => section.id),\n ...(doc.layout?.customSections ?? []).map((section) => section.id),\n ],\n });\n for (const issue of checked.diagnostics) {\n if (\n issue.code === 'unknown_theme_preset' ||\n issue.code === 'unknown_layout_id' ||\n issue.code === 'unknown_overview'\n ) {\n add(\n issue.code === 'unknown_layout_id' &&\n !issue.path.startsWith('layout.placements.')\n ? 'warning'\n : issue.severity,\n issue.code === 'unknown_theme_preset' ? 'unknown_preset' : issue.code,\n issue.path,\n issue.message,\n );\n }\n }\n\n for (const [i, id] of doc.recipes.entries()) {\n if (!byId.has(id))\n add(\n 'error',\n 'unknown_recipe',\n `recipes[${i}]`,\n `Unknown recipe \"${id}\".`,\n );\n }\n const closure = new Set(withRequirements(doc.recipes, byId));\n for (const id of closure) {\n if (!doc.recipes.includes(id)) {\n add(\n 'error',\n 'missing_requirement',\n 'recipes',\n `A recipe needs \"${id}\", which is not listed.`,\n );\n }\n }\n for (const [i, id] of doc.features.entries()) {\n const model = findModel(catalog, id);\n if (!model)\n add('error', 'unknown_model', `features[${i}]`, `Unknown model \"${id}\".`);\n else if (model.exposed === false) {\n add(\n 'error',\n 'model_not_exposed',\n `features[${i}]`,\n `${id} cannot be added as a feature.`,\n );\n }\n }\n const covered = coveredModels(catalog, doc);\n for (const [i, row] of doc.policies.entries()) {\n const at = `policies[${i}]`;\n const model = findModel(catalog, row.objectRef);\n if (!model) {\n add(\n 'error',\n 'unknown_model',\n `${at}.objectRef`,\n `Unknown model \"${row.objectRef}\".`,\n );\n continue;\n }\n if (\n model.fields &&\n !model.fields.some((f) => f.name === row.fieldName && !f.system)\n ) {\n add(\n 'error',\n 'unknown_field',\n `${at}.fieldName`,\n `${model.name} has no field \"${row.fieldName}\".`,\n );\n }\n if (!covered.has(row.objectRef) && !isSettingRow(catalog, row)) {\n add(\n 'warning',\n 'policy_not_covered',\n at,\n `${model.name} is not in the app, so this row has no effect.`,\n );\n }\n }\n for (const ref of Object.keys(doc.exposure ?? {})) {\n if (!findModel(catalog, ref)) {\n add(\n 'error',\n 'unknown_model',\n `exposure.${ref}`,\n `Unknown model \"${ref}\".`,\n );\n }\n }\n return out;\n}\n"],"mappings":";;;;AA8BA,IAAa,SAAY,UACvB,UAAU,KAAA,IAAY,QAAQ,gBAAgB,KAAK;AAErD,IAAa,QAAQ,GAAY,MAC/B,KAAK,UAAU,KAAK,IAAI,MAAM,KAAK,UAAU,KAAK,IAAI;AAExD,IAAa,uBAAiC;CAC5C,SAAS;CACT,SAAA;CACA,SAAS,CAAC;CACV,UAAU,CAAC;CACX,UAAU,CAAC;AACb;;AAGA,SAAgB,gBAAgB,KAAwB;CACtD,OACE,CAAC,IAAI,QAAQ,UACb,CAAC,IAAI,SAAS,UACd,CAAC,IAAI,SAAS,UACd,CAAC,OAAO,KAAK,IAAI,YAAY,CAAC,CAAC,CAAC,CAAC,UACjC,CAAC,IAAI,UACL,CAAC,IAAI,SACL,CAAC,OAAO,KAAK,IAAI,aAAa,C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AClC;GACA;EACF;EACA,IACE,MAAM,UACN,CAAC,MAAM,OAAO,MAAM,MAAM,EAAE,SAAS,IAAI,aAAa,CAAC,EAAE,MAAM,GAE/D,IACE,SACA,iBACA,GAAG,GAAG,aACN,GAAG,MAAM,KAAK,iBAAiB,IAAI,UAAU,GAC/C;EAEF,IAAI,CAAC,QAAQ,IAAI,IAAI,SAAS,KAAK,CAAC,aAAa,SAAS,GAAG,GAC3D,IACE,WACA,sBACA,IACA,GAAG,MAAM,KAAK,+CAChB;CAEJ;CACA,KAAK,MAAM,OAAO,OAAO,KAAK,IAAI,YAAY,CAAC,CAAC,GAC9C,IAAI,CAAC,UAAU,SAAS,GAAG,GACzB,IACE,SACA,iBACA,YAAY,OACZ,kBAAkB,IAAI,GACxB;CAGJ,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"engine.d.ts","sourceRoot":"","sources":["../../../src/cookbook/engine/engine.ts"],"names":[],"mappings":"AACA,OAAO,EAKL,KAAK,SAAS,EACf,MAAM,eAAe,CAAC;AAEvB,OAAO,EACL,KAAK,EAKN,MAAM,eAAe,CAAC;AASvB,OAAO,EACL,KAAK,WAAW,EAEhB,KAAK,YAAY,EAGjB,KAAK,aAAa,EAClB,KAAK,WAAW,EAChB,KAAK,aAAa,EAClB,KAAK,WAAW,EAEhB,KAAK,UAAU,EACf,KAAK,YAAY,EACjB,KAAK,UAAU,EAChB,MAAM,YAAY,CAAC;AAEpB,MAAM,WAAW,qBAAqB;IACpC,OAAO,EAAE,aAAa,CAAC;IACvB,+EAA+E;IAC/E,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,sEAAsE;IACtE,KAAK,CAAC,EAAE,WAAW,CAAC;IACpB,oEAAoE;IACpE,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,kDAAkD;IAClD,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,yEAAyE;IACzE,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED;;;;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,aAAa,CAAC;IACvB,+EAA+E;IAC/E,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,sEAAsE;IACtE,KAAK,CAAC,EAAE,WAAW,CAAC;IACpB,oEAAoE;IACpE,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,kDAAkD;IAClD,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,yEAAyE;IACzE,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED;;;;GAIG;AACH,MAAM,WAAW,cAAc;IAC7B;;;OAGG;IACH,GAAG,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,UAAU,GAAG,aAAa,CAAC;IAC3D;;;OAGG;IACH,KAAK,CAAC,KAAK,EAAE,YAAY,GAAG,OAAO,GAAG,WAAW,CAAC;IAClD,+DAA+D;IAC/D,QAAQ,IAAI,YAAY,CAAC;IACzB,6BAA6B;IAC7B,QAAQ,IAAI,UAAU,CAAC,OAAO,KAAK,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IACvD,uEAAuE;IACvE,KAAK,IAAI,WAAW,CAAC;IACrB,oEAAoE;IACpE,SAAS,CAAC,QAAQ,EAAE,CAAC,QAAQ,EAAE,YAAY,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC;IAClE,oFAAoF;IACpF,QAAQ,CAAC,KAAK,EAAE,SAAS,WAAW,EAAE,CAAC;IACvC,wCAAwC;IACxC,QAAQ,CAAC,SAAS,EAAE;QAClB,IAAI,EAAE,WAAW,CAAC;QAClB,WAAW,EAAE,MAAM,CAAC;QACpB,WAAW,EAAE,UAAU,CAAC;KACzB,CAAC;CACH;AAsGD,wBAAgB,oBAAoB,CAClC,OAAO,EAAE,qBAAqB,GAC7B,cAAc,CAigBhB"}
|
|
@@ -119,7 +119,10 @@ function createCookbookEngine(options) {
|
|
|
119
119
|
text: describeTheme(doc.theme),
|
|
120
120
|
preset: doc.theme?.preset ?? null,
|
|
121
121
|
primary: doc.theme?.custom?.primary ?? null,
|
|
122
|
-
colorScheme: doc.theme?.colorScheme ?? "system"
|
|
122
|
+
colorScheme: doc.theme?.colorScheme ?? "system",
|
|
123
|
+
borderRadius: doc.theme?.borderRadius ?? null,
|
|
124
|
+
density: doc.theme?.density ?? null,
|
|
125
|
+
contrast: doc.theme?.contrast ?? null
|
|
123
126
|
},
|
|
124
127
|
sections: buildNav(catalog, doc).map((s) => ({
|
|
125
128
|
id: s.id,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"engine.js","names":[],"sources":["../../../src/cookbook/engine/engine.ts"],"sourcesContent":["import { validateCookbook } from '../validate.js';\nimport {\n adopt,\n execute,\n libraryName,\n type Outcome,\n type PlanState,\n} from './commands.js';\nimport { DEFAULT_APP_NAME, DEFAULT_COLOR_SCHEME } from './defaults.js';\nimport {\n clone,\n describeTheme,\n emptyCookbook,\n readSettings,\n same,\n} from './document.js';\nimport { buildNav } from './nav.js';\nimport {\n buildBatchTool,\n buildCommandTools,\n type CommandSchemas,\n checkSchema,\n commandSchemas,\n} from './schemas.js';\nimport {\n type BatchResult,\n COOKBOOK_COMMANDS_VERSION,\n type CommandBatch,\n type CommandError,\n type CommandName,\n type CommandResult,\n type CommandTool,\n type EngineCatalog,\n type EngineState,\n type JournalEntry,\n type JsonSchema,\n type PlanSnapshot,\n type RunOptions,\n} from './types.js';\n\nexport interface CookbookEngineOptions {\n catalog: EngineCatalog;\n /** Start from this document (strictly checked; the call throws if invalid). */\n cookbook?: unknown;\n /** Resume from a saved {@link EngineState} (wins over `cookbook`). */\n state?: EngineState;\n /** How many command ids are remembered for retries; default 500. */\n maxJournal?: number;\n /** How many undo entries are kept; default 20. */\n maxUndo?: number;\n /** Optional namespace for process-local undo handles; default `undo`. */\n undoPrefix?: string;\n}\n\n/**\n * The cookbook command engine: typed, versioned commands over one cookbook\n * document, held in plain objects. Never throws from `run`/`batch`; every\n * refusal is a typed error and leaves the document untouched.\n */\nexport interface CookbookEngine {\n /**\n * Run one command (`{ name, input, id?, expectedRevision? }`). A repeated\n * `id` returns the first result with `replayed: true` and applies nothing.\n */\n run(command: unknown, options?: RunOptions): CommandResult;\n /**\n * Run several commands all-or-nothing. On any failure the state is exactly\n * as before and the error names the failing command.\n */\n batch(batch: CommandBatch | unknown): BatchResult;\n /** The compact plan state, cheap enough for a model prompt. */\n snapshot(): PlanSnapshot;\n /** The document (a copy). */\n cookbook(): ReturnType<typeof clone<PlanState['doc']>>;\n /** Serializable state to persist and resume from, retries included. */\n state(): EngineState;\n /** Call `listener` with the snapshot now and after every change. */\n subscribe(listener: (snapshot: PlanSnapshot) => void): () => void;\n /** Command tool definitions (JSON Schema inputs), enums narrowed to the catalog. */\n readonly tools: readonly CommandTool[];\n /** The atomic-batch tool definition. */\n readonly batchTool: {\n name: 'run_batch';\n description: string;\n inputSchema: JsonSchema;\n };\n}\n\ninterface UndoEntry {\n before: PlanState;\n /** What the change left; undo is a conflict while the plan differs from it. */\n after: PlanState;\n}\n\nconst err = (\n code: CommandError['code'],\n message: string,\n extra: Pick<CommandError, 'path' | 'details'> = {},\n): CommandError => ({ code, message, ...extra });\n\n/** Key order never changes a payload's identity: `{a, b}` and `{b, a}` match. */\nconst canonical = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(canonical);\n if (value && typeof value === 'object') {\n return Object.fromEntries(\n Object.keys(value)\n .sort()\n .map((key) => [\n key,\n canonical((value as Record<string, unknown>)[key]),\n ]),\n );\n }\n return value;\n};\n\nconst fingerprint = (value: unknown): string => {\n try {\n return JSON.stringify(canonical(value)) ?? 'undefined';\n } catch {\n return 'unserializable';\n }\n};\n\ntype Parsed =\n | { ok: true; name: CommandName; input: Record<string, unknown> }\n | { ok: false; error: CommandError };\n\nfunction readCommand(\n value: unknown,\n schemas: CommandSchemas,\n extraKeys: readonly string[],\n): Parsed {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return {\n ok: false,\n error: err('unknown_command', 'A command is an object: { name, input }.'),\n };\n }\n const record = value as Record<string, unknown>;\n const { name, input = {} } = record;\n if (typeof name !== 'string' || !Object.hasOwn(schemas, name)) {\n return {\n ok: false,\n error: err('unknown_command', `Unknown command ${JSON.stringify(name)}.`),\n };\n }\n for (const key of Object.keys(record)) {\n if (key !== 'name' && key !== 'input' && !extraKeys.includes(key)) {\n return {\n ok: false,\n error: err('invalid_input', `${key} is not part of a command.`, {\n path: key,\n }),\n };\n }\n }\n const problem = checkSchema(schemas[name as CommandName], input);\n if (problem) {\n return {\n ok: false,\n error: err('invalid_input', problem.message, { path: problem.path }),\n };\n }\n return {\n ok: true,\n name: name as CommandName,\n input: input as Record<string, unknown>,\n };\n}\n\nconst checkId = (id: unknown): CommandError | null =>\n id === undefined ||\n (typeof id === 'string' && id.length > 0 && id.length <= 200)\n ? null\n : err(\n 'invalid_input',\n 'id must be a non-empty string of at most 200 characters.',\n { path: 'id' },\n );\n\nconst checkRevision = (value: unknown): CommandError | null =>\n value === undefined || (Number.isInteger(value) && (value as number) >= 0)\n ? null\n : err('invalid_input', 'expectedRevision must be a whole number.', {\n path: 'expectedRevision',\n });\n\nexport function createCookbookEngine(\n options: CookbookEngineOptions,\n): CookbookEngine {\n const { catalog } = options;\n const schemas = commandSchemas(catalog);\n const tools = buildCommandTools(catalog);\n const batchTool = buildBatchTool(catalog);\n const maxJournal = options.maxJournal ?? 500;\n const maxUndo = options.maxUndo ?? 20;\n\n let current: PlanState;\n let revision = 0;\n const journal = new Map<string, JournalEntry>();\n\n if (options.state) {\n const saved = options.state;\n const checked = validateCookbook(saved.cookbook);\n if (!checked.ok)\n throw new Error(`Invalid saved cookbook: ${checked.errors.join('; ')}`);\n if (!Number.isInteger(saved.revision) || saved.revision < 0) {\n throw new Error('Invalid saved revision.');\n }\n current = {\n doc: adopt(catalog, checked.cookbook),\n applied: saved.applied ?? null,\n };\n revision = saved.revision;\n for (const entry of saved.journal ?? [])\n journal.set(entry.id, clone(entry));\n } else if (options.cookbook !== undefined) {\n const checked = validateCookbook(options.cookbook);\n if (!checked.ok)\n throw new Error(`Invalid cookbook: ${checked.errors.join('; ')}`);\n current = { doc: adopt(catalog, checked.cookbook), applied: null };\n } else {\n current = { doc: adopt(catalog, emptyCookbook()), applied: null };\n }\n\n const undos = new Map<string, UndoEntry>();\n let undoIds: string[] = [];\n let undoCounter = 0;\n const listeners = new Map<(s: PlanSnapshot) => void, number>();\n\n function snapshotOf(state: PlanState, rev: number): PlanSnapshot {\n const { doc } = state;\n const byId = new Map(catalog.recipes.map((r) => [r.id, r]));\n const settings = readSettings(catalog, doc);\n const exposed = new Set(\n catalog.models.filter((m) => m.exposed !== false).map((m) => m.id),\n );\n return {\n version: COOKBOOK_COMMANDS_VERSION,\n revision: rev,\n app: {\n name:\n doc.name ?? libraryName(catalog, state.applied) ?? DEFAULT_APP_NAME,\n description: doc.description ?? null,\n cookbook: state.applied,\n },\n recipes: doc.recipes.flatMap((id) => {\n const recipe = byId.get(id);\n return recipe ? [{ id, label: recipe.label }] : [];\n }),\n features: doc.features.filter((id) => exposed.has(id)),\n unavailable: [\n ...doc.recipes.filter((id) => !byId.has(id)),\n ...doc.features.filter((id) => !exposed.has(id)),\n ],\n settings: {\n currency: settings.currency,\n taxRate: Number((settings.taxRate * 100).toFixed(4)),\n paymentTerms: settings.paymentTerms,\n },\n theme: {\n text: describeTheme(doc.theme),\n preset: doc.theme?.preset ?? null,\n primary: doc.theme?.custom?.primary ?? null,\n colorScheme: doc.theme?.colorScheme ?? DEFAULT_COLOR_SCHEME,\n },\n sections: buildNav(catalog, doc).map((s) => ({\n id: s.id,\n label: s.label,\n hidden: s.hidden,\n items: s.items.map((i) => ({\n id: i.id,\n label: i.label,\n hidden: i.hidden,\n })),\n })),\n policies: doc.policies.length,\n undo: [...undoIds],\n };\n }\n\n const snapshot = () => snapshotOf(current, revision);\n\n function notify(): void {\n for (const [listener, last] of listeners) {\n if (last === revision) continue;\n listeners.set(listener, revision);\n listener(snapshot());\n }\n }\n\n function remember(\n id: string | undefined,\n print: string,\n result: CommandResult | BatchResult,\n ) {\n if (id === undefined) return;\n journal.set(id, { id, fingerprint: print, result: clone(result) });\n while (journal.size > maxJournal) {\n const oldest = journal.keys().next().value;\n if (oldest === undefined) break;\n journal.delete(oldest);\n }\n }\n\n function replay<R extends CommandResult | BatchResult>(\n id: string | undefined,\n print: string,\n ): R | CommandResult | null {\n if (id === undefined) return null;\n const hit = journal.get(id);\n if (!hit) return null;\n if (hit.fingerprint !== print) {\n return {\n ok: false,\n id,\n error: err(\n 'id_reuse',\n `The id \"${id}\" was already used for a different command.`,\n {\n path: 'id',\n },\n ),\n };\n }\n return { ...(clone(hit.result) as R), replayed: true };\n }\n\n function recordUndo(before: PlanState, after: PlanState): string {\n const undoId = `${options.undoPrefix ?? 'undo'}-${++undoCounter}`;\n undos.set(undoId, { before: clone(before), after: clone(after) });\n undoIds = [...undoIds, undoId].slice(-maxUndo);\n for (const key of [...undos.keys()])\n if (!undoIds.includes(key)) undos.delete(key);\n return undoId;\n }\n\n const changedBetween = (a: PlanState, b: PlanState) =>\n a.applied !== b.applied || !same(a.doc, b.doc);\n\n function toSuccess(\n id: string | undefined,\n name: CommandName,\n outcome: Extract<Outcome, { ok: true }>,\n revisionBefore: number,\n revisionAfter: number,\n snap: PlanSnapshot,\n undoId?: string,\n ): Extract<CommandResult, { ok: true }> {\n return {\n ok: true,\n ...(id !== undefined ? { id } : {}),\n snapshot: snap,\n receipt: {\n name,\n ...(id !== undefined ? { id } : {}),\n summary: revisionAfter !== revisionBefore ? outcome.summary : '',\n changed: revisionAfter !== revisionBefore,\n revisionBefore,\n revisionAfter,\n ...(undoId ? { undoId } : {}),\n ...(outcome.changes ? { changes: outcome.changes } : {}),\n ...(outcome.warnings ? { warnings: outcome.warnings } : {}),\n },\n ...(outcome.data !== undefined ? { data: outcome.data } : {}),\n };\n }\n\n function runUndo(\n id: string | undefined,\n input: { undoId: string; force?: boolean },\n ): CommandResult {\n const entry = undos.get(input.undoId);\n if (!entry) {\n return {\n ok: false,\n ...(id !== undefined ? { id } : {}),\n error: err('not_found', `Nothing to undo for \"${input.undoId}\".`, {\n path: 'input.undoId',\n }),\n };\n }\n if (!input.force && changedBetween(current, entry.after)) {\n return {\n ok: false,\n ...(id !== undefined ? { id } : {}),\n error: err(\n 'conflict',\n 'The plan changed since; send force: true to undo anyway.',\n {\n details: { currentRevision: revision },\n },\n ),\n };\n }\n const before = revision;\n const restored = clone(entry.before);\n const changed = changedBetween(current, restored);\n current = restored;\n if (changed) revision += 1;\n undos.delete(input.undoId);\n undoIds = undoIds.filter((u) => u !== input.undoId);\n const result = toSuccess(\n id,\n 'undo',\n { ok: true, state: current, summary: 'Undone.' },\n before,\n revision,\n snapshot(),\n );\n notify();\n return result;\n }\n\n function run(command: unknown, runOptions: RunOptions = {}): CommandResult {\n try {\n const raw =\n command && typeof command === 'object' && !Array.isArray(command)\n ? (command as Record<string, unknown>)\n : undefined;\n const id = raw?.id as string | undefined;\n const idProblem = checkId(id);\n if (idProblem) return { ok: false, error: idProblem };\n const expected = (raw?.expectedRevision ?? runOptions.expectedRevision) as\n | number\n | undefined;\n const revProblem = checkRevision(expected);\n if (revProblem)\n return {\n ok: false,\n ...(id !== undefined ? { id } : {}),\n error: revProblem,\n };\n\n const print = fingerprint({\n name: raw?.name,\n input: raw?.input ?? {},\n expectedRevision: expected,\n });\n const replayed = replay<CommandResult>(id, print);\n if (replayed) return replayed as CommandResult;\n\n const finish = (result: CommandResult) => {\n remember(id, print, result);\n return result;\n };\n const withId = (error: CommandError): CommandResult => ({\n ok: false,\n ...(id !== undefined ? { id } : {}),\n error,\n });\n\n const parsed = readCommand(command, schemas, ['id', 'expectedRevision']);\n if (!parsed.ok) return finish(withId(parsed.error));\n if (expected !== undefined && expected !== revision) {\n return finish(\n withId(\n err(\n 'conflict',\n `The plan is at revision ${revision}, not ${expected}. Read the snapshot and try again.`,\n {\n details: {\n expectedRevision: expected,\n currentRevision: revision,\n },\n },\n ),\n ),\n );\n }\n if (parsed.name === 'undo') {\n return finish(\n runUndo(id, parsed.input as { undoId: string; force?: boolean }),\n );\n }\n const before = current;\n const outcome = execute(\n catalog,\n before,\n parsed.name,\n parsed.input as never,\n );\n if (!outcome.ok) return finish(withId(outcome.error));\n const revisionBefore = revision;\n const changed = changedBetween(before, outcome.state);\n let undoId: string | undefined;\n if (changed) {\n current = outcome.state;\n revision += 1;\n undoId = recordUndo(before, outcome.state);\n }\n const result = finish(\n toSuccess(\n id,\n parsed.name,\n outcome,\n revisionBefore,\n revision,\n snapshot(),\n undoId,\n ),\n );\n notify();\n return result;\n } catch (cause) {\n return {\n ok: false,\n error: err(\n 'failed',\n cause instanceof Error ? cause.message : String(cause),\n ),\n };\n }\n }\n\n function batch(input: CommandBatch | unknown): BatchResult {\n const unchanged = (error: CommandError, id?: string): BatchResult => ({\n ok: false,\n ...(id !== undefined ? { id } : {}),\n error,\n snapshot: snapshot(),\n });\n try {\n if (!input || typeof input !== 'object' || Array.isArray(input)) {\n return unchanged(\n err('invalid_input', 'A batch is an object: { commands }.'),\n );\n }\n const raw = input as Record<string, unknown>;\n const id = raw.id as string | undefined;\n const idProblem = checkId(id);\n if (idProblem) return unchanged(idProblem);\n const revProblem = checkRevision(raw.expectedRevision);\n if (revProblem) return unchanged(revProblem, id);\n const print = fingerprint({\n commands: raw.commands,\n expectedRevision: raw.expectedRevision,\n });\n const replayed = replay<BatchResult>(id, print);\n if (replayed) {\n return 'results' in replayed || 'snapshot' in replayed\n ? (replayed as BatchResult)\n : unchanged(\n (replayed as Extract<CommandResult, { ok: false }>).error,\n id,\n );\n }\n const finish = (result: BatchResult) => {\n remember(id, print, result);\n return result;\n };\n\n const commands = raw.commands;\n if (\n !Array.isArray(commands) ||\n commands.length === 0 ||\n commands.length > 50\n ) {\n return finish(\n unchanged(\n err(\n 'invalid_input',\n 'commands must be a list of 1 to 50 commands.',\n { path: 'commands' },\n ),\n id,\n ),\n );\n }\n const expected = raw.expectedRevision as number | undefined;\n if (expected !== undefined && expected !== revision) {\n return finish(\n unchanged(\n err(\n 'conflict',\n `The plan is at revision ${revision}, not ${expected}. Read the snapshot and try again.`,\n {\n details: {\n expectedRevision: expected,\n currentRevision: revision,\n },\n },\n ),\n id,\n ),\n );\n }\n\n const failAt = (index: number, name: unknown, cause: CommandError) =>\n finish(\n unchanged(\n err(\n 'batch_failed',\n `Command ${index + 1} (${String(name)}) failed: ${cause.message}`,\n {\n path: `commands[${index}]`,\n details: { index, cause },\n },\n ),\n id,\n ),\n );\n\n // Everything runs on a working copy; the live state is replaced once, at the end.\n const base = current;\n const baseRevision = revision;\n let working = base;\n let rev = baseRevision;\n const results: Extract<CommandResult, { ok: true }>[] = [];\n for (const [index, command] of commands.entries()) {\n const parsed = readCommand(command, schemas, []);\n if (!parsed.ok)\n return failAt(\n index,\n (command as { name?: unknown })?.name,\n parsed.error,\n );\n if (parsed.name === 'undo') {\n return failAt(\n index,\n 'undo',\n err('invalid_input', 'undo cannot run inside a batch.'),\n );\n }\n const outcome = execute(\n catalog,\n working,\n parsed.name,\n parsed.input as never,\n );\n if (!outcome.ok) return failAt(index, parsed.name, outcome.error);\n const before = rev;\n if (changedBetween(working, outcome.state)) rev += 1;\n working = outcome.state;\n results.push(\n toSuccess(\n undefined,\n parsed.name,\n outcome,\n before,\n rev,\n snapshotOf(working, rev),\n ),\n );\n }\n const changed = rev !== baseRevision;\n let undoId: string | undefined;\n if (changed) {\n current = working;\n revision = rev;\n undoId = recordUndo(base, working);\n // The batch's one undo restores the state before all of it.\n for (const r of results) if (r.receipt.changed) delete r.receipt.undoId;\n }\n const result = finish({\n ok: true,\n ...(id !== undefined ? { id } : {}),\n snapshot: snapshot(),\n receipt: {\n ...(id !== undefined ? { id } : {}),\n count: results.length,\n changed,\n revisionBefore: baseRevision,\n revisionAfter: rev,\n ...(undoId ? { undoId } : {}),\n },\n results,\n });\n notify();\n return result;\n } catch (cause) {\n return unchanged(\n err('failed', cause instanceof Error ? cause.message : String(cause)),\n );\n }\n }\n\n return {\n run: run as CookbookEngine['run'],\n batch,\n snapshot,\n cookbook: () => clone(current.doc),\n state: () => ({\n version: COOKBOOK_COMMANDS_VERSION,\n revision,\n applied: current.applied,\n cookbook: clone(current.doc),\n journal: [...journal.values()].map((entry) => clone(entry)),\n }),\n subscribe(listener) {\n listeners.set(listener, revision);\n listener(snapshot());\n return () => {\n listeners.delete(listener);\n };\n },\n tools,\n batchTool,\n };\n}\n"],"mappings":";;;;;;;;AA8FA,IAAM,OACJ,MACA,SACA,QAAgD,CAAC,OAC/B;CAAE;CAAM;CAAS,GAAG;AAAM;;AAG9C,IAAM,aAAa,UAA4B;CAC7C,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,MAAM,IAAI,SAAS;CACpD,IAAI,SAAS,OAAO,UAAU,UAC5B,OAAO,OAAO,YACZ,OAAO,KAAK,KAAK,CAAC,CACf,KAAK,CAAC,CACN,KAAK,QAAQ,CACZ,KACA,UAAW,MAAkC,IAAI,CACnD,CAAC,CACL;CAEF,OAAO;AACT;AAEA,IAAM,eAAe,UAA2B;CAC9C,IAAI;EACF,OAAO,KAAK,UAAU,UAAU,KAAK,CAAC,KAAK;CAC7C,QAAQ;EACN,OAAO;CACT;AACF;AAMA,SAAS,YACP,OACA,SACA,WACQ;CACR,IAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAC5D,OAAO;EACL,IAAI;EACJ,OAAO,IAAI,mBAAmB,0CAA0C;CAC1E;CAEF,MAAM,SAAS;CACf,MAAM,EAAE,MAAM,QAAQ,CAAC,MAAM;CAC7B,IAAI,OAAO,SAAS,YAAY,CAAC,OAAO,OAAO,SAAS,IAAI,GAC1D,OAAO;EACL,IAAI;EACJ,OAAO,IAAI,mBAAmB,mBAAmB,KAAK,UAAU,IAAI,EAAE,EAAE;CAC1E;CAEF,KAAK,MAAM,OAAO,OAAO,KAAK,MAAM,GAClC,IAAI,QAAQ,UAAU,QAAQ,WAAW,CAAC,UAAU,SAAS,GAAG,GAC9D,OAAO;EACL,IAAI;EACJ,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AK,CAAC,CACtE;EACF;CACF;CAEA,OAAO;EACA;EACL;EACA;EACA,gBAAgB,MAAM,QAAQ,GAAG;EACjC,cAAc;GACZ,SAAA;GACA;GACA,SAAS,QAAQ;GACjB,UAAU,MAAM,QAAQ,GAAG;GAC3B,SAAS,CAAC,GAAG,QAAQ,OAAO,CAAC,CAAC,CAAC,KAAK,UAAU,MAAM,KAAK,CAAC;EAC5D;EACA,UAAU,UAAU;GAClB,UAAU,IAAI,UAAU,QAAQ;GAChC,SAAS,SAAS,CAAC;GACnB,aAAa;IACX,UAAU,OAAO,QAAQ;GAC3B;EACF;EACA;EACA;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"engine.js","names":[],"sources":["../../../src/cookbook/engine/engine.ts"],"sourcesContent":["import { validateCookbook } from '../validate.js';\nimport {\n adopt,\n execute,\n libraryName,\n type Outcome,\n type PlanState,\n} from './commands.js';\nimport { DEFAULT_APP_NAME, DEFAULT_COLOR_SCHEME } from './defaults.js';\nimport {\n clone,\n describeTheme,\n emptyCookbook,\n readSettings,\n same,\n} from './document.js';\nimport { buildNav } from './nav.js';\nimport {\n buildBatchTool,\n buildCommandTools,\n type CommandSchemas,\n checkSchema,\n commandSchemas,\n} from './schemas.js';\nimport {\n type BatchResult,\n COOKBOOK_COMMANDS_VERSION,\n type CommandBatch,\n type CommandError,\n type CommandName,\n type CommandResult,\n type CommandTool,\n type EngineCatalog,\n type EngineState,\n type JournalEntry,\n type JsonSchema,\n type PlanSnapshot,\n type RunOptions,\n} from './types.js';\n\nexport interface CookbookEngineOptions {\n catalog: EngineCatalog;\n /** Start from this document (strictly checked; the call throws if invalid). */\n cookbook?: unknown;\n /** Resume from a saved {@link EngineState} (wins over `cookbook`). */\n state?: EngineState;\n /** How many command ids are remembered for retries; default 500. */\n maxJournal?: number;\n /** How many undo entries are kept; default 20. */\n maxUndo?: number;\n /** Optional namespace for process-local undo handles; default `undo`. */\n undoPrefix?: string;\n}\n\n/**\n * The cookbook command engine: typed, versioned commands over one cookbook\n * document, held in plain objects. Never throws from `run`/`batch`; every\n * refusal is a typed error and leaves the document untouched.\n */\nexport interface CookbookEngine {\n /**\n * Run one command (`{ name, input, id?, expectedRevision? }`). A repeated\n * `id` returns the first result with `replayed: true` and applies nothing.\n */\n run(command: unknown, options?: RunOptions): CommandResult;\n /**\n * Run several commands all-or-nothing. On any failure the state is exactly\n * as before and the error names the failing command.\n */\n batch(batch: CommandBatch | unknown): BatchResult;\n /** The compact plan state, cheap enough for a model prompt. */\n snapshot(): PlanSnapshot;\n /** The document (a copy). */\n cookbook(): ReturnType<typeof clone<PlanState['doc']>>;\n /** Serializable state to persist and resume from, retries included. */\n state(): EngineState;\n /** Call `listener` with the snapshot now and after every change. */\n subscribe(listener: (snapshot: PlanSnapshot) => void): () => void;\n /** Command tool definitions (JSON Schema inputs), enums narrowed to the catalog. */\n readonly tools: readonly CommandTool[];\n /** The atomic-batch tool definition. */\n readonly batchTool: {\n name: 'run_batch';\n description: string;\n inputSchema: JsonSchema;\n };\n}\n\ninterface UndoEntry {\n before: PlanState;\n /** What the change left; undo is a conflict while the plan differs from it. */\n after: PlanState;\n}\n\nconst err = (\n code: CommandError['code'],\n message: string,\n extra: Pick<CommandError, 'path' | 'details'> = {},\n): CommandError => ({ code, message, ...extra });\n\n/** Key order never changes a payload's identity: `{a, b}` and `{b, a}` match. */\nconst canonical = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(canonical);\n if (value && typeof value === 'object') {\n return Object.fromEntries(\n Object.keys(value)\n .sort()\n .map((key) => [\n key,\n canonical((value as Record<string, unknown>)[key]),\n ]),\n );\n }\n return value;\n};\n\nconst fingerprint = (value: unknown): string => {\n try {\n return JSON.stringify(canonical(value)) ?? 'undefined';\n } catch {\n return 'unserializable';\n }\n};\n\ntype Parsed =\n | { ok: true; name: CommandName; input: Record<string, unknown> }\n | { ok: false; error: CommandError };\n\nfunction readCommand(\n value: unknown,\n schemas: CommandSchemas,\n extraKeys: readonly string[],\n): Parsed {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return {\n ok: false,\n error: err('unknown_command', 'A command is an object: { name, input }.'),\n };\n }\n const record = value as Record<string, unknown>;\n const { name, input = {} } = record;\n if (typeof name !== 'string' || !Object.hasOwn(schemas, name)) {\n return {\n ok: false,\n error: err('unknown_command', `Unknown command ${JSON.stringify(name)}.`),\n };\n }\n for (const key of Object.keys(record)) {\n if (key !== 'name' && key !== 'input' && !extraKeys.includes(key)) {\n return {\n ok: false,\n error: err('invalid_input', `${key} is not part of a command.`, {\n path: key,\n }),\n };\n }\n }\n const problem = checkSchema(schemas[name as CommandName], input);\n if (problem) {\n return {\n ok: false,\n error: err('invalid_input', problem.message, { path: problem.path }),\n };\n }\n return {\n ok: true,\n name: name as CommandName,\n input: input as Record<string, unknown>,\n };\n}\n\nconst checkId = (id: unknown): CommandError | null =>\n id === undefined ||\n (typeof id === 'string' && id.length > 0 && id.length <= 200)\n ? null\n : err(\n 'invalid_input',\n 'id must be a non-empty string of at most 200 characters.',\n { path: 'id' },\n );\n\nconst checkRevision = (value: unknown): CommandError | null =>\n value === undefined || (Number.isInteger(value) && (value as number) >= 0)\n ? null\n : err('invalid_input', 'expectedRevision must be a whole number.', {\n path: 'expectedRevision',\n });\n\nexport function createCookbookEngine(\n options: CookbookEngineOptions,\n): CookbookEngine {\n const { catalog } = options;\n const schemas = commandSchemas(catalog);\n const tools = buildCommandTools(catalog);\n const batchTool = buildBatchTool(catalog);\n const maxJournal = options.maxJournal ?? 500;\n const maxUndo = options.maxUndo ?? 20;\n\n let current: PlanState;\n let revision = 0;\n const journal = new Map<string, JournalEntry>();\n\n if (options.state) {\n const saved = options.state;\n const checked = validateCookbook(saved.cookbook);\n if (!checked.ok)\n throw new Error(`Invalid saved cookbook: ${checked.errors.join('; ')}`);\n if (!Number.isInteger(saved.revision) || saved.revision < 0) {\n throw new Error('Invalid saved revision.');\n }\n current = {\n doc: adopt(catalog, checked.cookbook),\n applied: saved.applied ?? null,\n };\n revision = saved.revision;\n for (const entry of saved.journal ?? [])\n journal.set(entry.id, clone(entry));\n } else if (options.cookbook !== undefined) {\n const checked = validateCookbook(options.cookbook);\n if (!checked.ok)\n throw new Error(`Invalid cookbook: ${checked.errors.join('; ')}`);\n current = { doc: adopt(catalog, checked.cookbook), applied: null };\n } else {\n current = { doc: adopt(catalog, emptyCookbook()), applied: null };\n }\n\n const undos = new Map<string, UndoEntry>();\n let undoIds: string[] = [];\n let undoCounter = 0;\n const listeners = new Map<(s: PlanSnapshot) => void, number>();\n\n function snapshotOf(state: PlanState, rev: number): PlanSnapshot {\n const { doc } = state;\n const byId = new Map(catalog.recipes.map((r) => [r.id, r]));\n const settings = readSettings(catalog, doc);\n const exposed = new Set(\n catalog.models.filter((m) => m.exposed !== false).map((m) => m.id),\n );\n return {\n version: COOKBOOK_COMMANDS_VERSION,\n revision: rev,\n app: {\n name:\n doc.name ?? libraryName(catalog, state.applied) ?? DEFAULT_APP_NAME,\n description: doc.description ?? null,\n cookbook: state.applied,\n },\n recipes: doc.recipes.flatMap((id) => {\n const recipe = byId.get(id);\n return recipe ? [{ id, label: recipe.label }] : [];\n }),\n features: doc.features.filter((id) => exposed.has(id)),\n unavailable: [\n ...doc.recipes.filter((id) => !byId.has(id)),\n ...doc.features.filter((id) => !exposed.has(id)),\n ],\n settings: {\n currency: settings.currency,\n taxRate: Number((settings.taxRate * 100).toFixed(4)),\n paymentTerms: settings.paymentTerms,\n },\n theme: {\n text: describeTheme(doc.theme),\n preset: doc.theme?.preset ?? null,\n primary: doc.theme?.custom?.primary ?? null,\n colorScheme: doc.theme?.colorScheme ?? DEFAULT_COLOR_SCHEME,\n borderRadius: doc.theme?.borderRadius ?? null,\n density: doc.theme?.density ?? null,\n contrast: doc.theme?.contrast ?? null,\n },\n sections: buildNav(catalog, doc).map((s) => ({\n id: s.id,\n label: s.label,\n hidden: s.hidden,\n items: s.items.map((i) => ({\n id: i.id,\n label: i.label,\n hidden: i.hidden,\n })),\n })),\n policies: doc.policies.length,\n undo: [...undoIds],\n };\n }\n\n const snapshot = () => snapshotOf(current, revision);\n\n function notify(): void {\n for (const [listener, last] of listeners) {\n if (last === revision) continue;\n listeners.set(listener, revision);\n listener(snapshot());\n }\n }\n\n function remember(\n id: string | undefined,\n print: string,\n result: CommandResult | BatchResult,\n ) {\n if (id === undefined) return;\n journal.set(id, { id, fingerprint: print, result: clone(result) });\n while (journal.size > maxJournal) {\n const oldest = journal.keys().next().value;\n if (oldest === undefined) break;\n journal.delete(oldest);\n }\n }\n\n function replay<R extends CommandResult | BatchResult>(\n id: string | undefined,\n print: string,\n ): R | CommandResult | null {\n if (id === undefined) return null;\n const hit = journal.get(id);\n if (!hit) return null;\n if (hit.fingerprint !== print) {\n return {\n ok: false,\n id,\n error: err(\n 'id_reuse',\n `The id \"${id}\" was already used for a different command.`,\n {\n path: 'id',\n },\n ),\n };\n }\n return { ...(clone(hit.result) as R), replayed: true };\n }\n\n function recordUndo(before: PlanState, after: PlanState): string {\n const undoId = `${options.undoPrefix ?? 'undo'}-${++undoCounter}`;\n undos.set(undoId, { before: clone(before), after: clone(after) });\n undoIds = [...undoIds, undoId].slice(-maxUndo);\n for (const key of [...undos.keys()])\n if (!undoIds.includes(key)) undos.delete(key);\n return undoId;\n }\n\n const changedBetween = (a: PlanState, b: PlanState) =>\n a.applied !== b.applied || !same(a.doc, b.doc);\n\n function toSuccess(\n id: string | undefined,\n name: CommandName,\n outcome: Extract<Outcome, { ok: true }>,\n revisionBefore: number,\n revisionAfter: number,\n snap: PlanSnapshot,\n undoId?: string,\n ): Extract<CommandResult, { ok: true }> {\n return {\n ok: true,\n ...(id !== undefined ? { id } : {}),\n snapshot: snap,\n receipt: {\n name,\n ...(id !== undefined ? { id } : {}),\n summary: revisionAfter !== revisionBefore ? outcome.summary : '',\n changed: revisionAfter !== revisionBefore,\n revisionBefore,\n revisionAfter,\n ...(undoId ? { undoId } : {}),\n ...(outcome.changes ? { changes: outcome.changes } : {}),\n ...(outcome.warnings ? { warnings: outcome.warnings } : {}),\n },\n ...(outcome.data !== undefined ? { data: outcome.data } : {}),\n };\n }\n\n function runUndo(\n id: string | undefined,\n input: { undoId: string; force?: boolean },\n ): CommandResult {\n const entry = undos.get(input.undoId);\n if (!entry) {\n return {\n ok: false,\n ...(id !== undefined ? { id } : {}),\n error: err('not_found', `Nothing to undo for \"${input.undoId}\".`, {\n path: 'input.undoId',\n }),\n };\n }\n if (!input.force && changedBetween(current, entry.after)) {\n return {\n ok: false,\n ...(id !== undefined ? { id } : {}),\n error: err(\n 'conflict',\n 'The plan changed since; send force: true to undo anyway.',\n {\n details: { currentRevision: revision },\n },\n ),\n };\n }\n const before = revision;\n const restored = clone(entry.before);\n const changed = changedBetween(current, restored);\n current = restored;\n if (changed) revision += 1;\n undos.delete(input.undoId);\n undoIds = undoIds.filter((u) => u !== input.undoId);\n const result = toSuccess(\n id,\n 'undo',\n { ok: true, state: current, summary: 'Undone.' },\n before,\n revision,\n snapshot(),\n );\n notify();\n return result;\n }\n\n function run(command: unknown, runOptions: RunOptions = {}): CommandResult {\n try {\n const raw =\n command && typeof command === 'object' && !Array.isArray(command)\n ? (command as Record<string, unknown>)\n : undefined;\n const id = raw?.id as string | undefined;\n const idProblem = checkId(id);\n if (idProblem) return { ok: false, error: idProblem };\n const expected = (raw?.expectedRevision ?? runOptions.expectedRevision) as\n | number\n | undefined;\n const revProblem = checkRevision(expected);\n if (revProblem)\n return {\n ok: false,\n ...(id !== undefined ? { id } : {}),\n error: revProblem,\n };\n\n const print = fingerprint({\n name: raw?.name,\n input: raw?.input ?? {},\n expectedRevision: expected,\n });\n const replayed = replay<CommandResult>(id, print);\n if (replayed) return replayed as CommandResult;\n\n const finish = (result: CommandResult) => {\n remember(id, print, result);\n return result;\n };\n const withId = (error: CommandError): CommandResult => ({\n ok: false,\n ...(id !== undefined ? { id } : {}),\n error,\n });\n\n const parsed = readCommand(command, schemas, ['id', 'expectedRevision']);\n if (!parsed.ok) return finish(withId(parsed.error));\n if (expected !== undefined && expected !== revision) {\n return finish(\n withId(\n err(\n 'conflict',\n `The plan is at revision ${revision}, not ${expected}. Read the snapshot and try again.`,\n {\n details: {\n expectedRevision: expected,\n currentRevision: revision,\n },\n },\n ),\n ),\n );\n }\n if (parsed.name === 'undo') {\n return finish(\n runUndo(id, parsed.input as { undoId: string; force?: boolean }),\n );\n }\n const before = current;\n const outcome = execute(\n catalog,\n before,\n parsed.name,\n parsed.input as never,\n );\n if (!outcome.ok) return finish(withId(outcome.error));\n const revisionBefore = revision;\n const changed = changedBetween(before, outcome.state);\n let undoId: string | undefined;\n if (changed) {\n current = outcome.state;\n revision += 1;\n undoId = recordUndo(before, outcome.state);\n }\n const result = finish(\n toSuccess(\n id,\n parsed.name,\n outcome,\n revisionBefore,\n revision,\n snapshot(),\n undoId,\n ),\n );\n notify();\n return result;\n } catch (cause) {\n return {\n ok: false,\n error: err(\n 'failed',\n cause instanceof Error ? cause.message : String(cause),\n ),\n };\n }\n }\n\n function batch(input: CommandBatch | unknown): BatchResult {\n const unchanged = (error: CommandError, id?: string): BatchResult => ({\n ok: false,\n ...(id !== undefined ? { id } : {}),\n error,\n snapshot: snapshot(),\n });\n try {\n if (!input || typeof input !== 'object' || Array.isArray(input)) {\n return unchanged(\n err('invalid_input', 'A batch is an object: { commands }.'),\n );\n }\n const raw = input as Record<string, unknown>;\n const id = raw.id as string | undefined;\n const idProblem = checkId(id);\n if (idProblem) return unchanged(idProblem);\n const revProblem = checkRevision(raw.expectedRevision);\n if (revProblem) return unchanged(revProblem, id);\n const print = fingerprint({\n commands: raw.commands,\n expectedRevision: raw.expectedRevision,\n });\n const replayed = replay<BatchResult>(id, print);\n if (replayed) {\n return 'results' in replayed || 'snapshot' in replayed\n ? (replayed as BatchResult)\n : unchanged(\n (replayed as Extract<CommandResult, { ok: false }>).error,\n id,\n );\n }\n const finish = (result: BatchResult) => {\n remember(id, print, result);\n return result;\n };\n\n const commands = raw.commands;\n if (\n !Array.isArray(commands) ||\n commands.length === 0 ||\n commands.length > 50\n ) {\n return finish(\n unchanged(\n err(\n 'invalid_input',\n 'commands must be a list of 1 to 50 commands.',\n { path: 'commands' },\n ),\n id,\n ),\n );\n }\n const expected = raw.expectedRevision as number | undefined;\n if (expected !== undefined && expected !== revision) {\n return finish(\n unchanged(\n err(\n 'conflict',\n `The plan is at revision ${revision}, not ${expected}. Read the snapshot and try again.`,\n {\n details: {\n expectedRevision: expected,\n currentRevision: revision,\n },\n },\n ),\n id,\n ),\n );\n }\n\n const failAt = (index: number, name: unknown, cause: CommandError) =>\n finish(\n unchanged(\n err(\n 'batch_failed',\n `Command ${index + 1} (${String(name)}) failed: ${cause.message}`,\n {\n path: `commands[${index}]`,\n details: { index, cause },\n },\n ),\n id,\n ),\n );\n\n // Everything runs on a working copy; the live state is replaced once, at the end.\n const base = current;\n const baseRevision = revision;\n let working = base;\n let rev = baseRevision;\n const results: Extract<CommandResult, { ok: true }>[] = [];\n for (const [index, command] of commands.entries()) {\n const parsed = readCommand(command, schemas, []);\n if (!parsed.ok)\n return failAt(\n index,\n (command as { name?: unknown })?.name,\n parsed.error,\n );\n if (parsed.name === 'undo') {\n return failAt(\n index,\n 'undo',\n err('invalid_input', 'undo cannot run inside a batch.'),\n );\n }\n const outcome = execute(\n catalog,\n working,\n parsed.name,\n parsed.input as never,\n );\n if (!outcome.ok) return failAt(index, parsed.name, outcome.error);\n const before = rev;\n if (changedBetween(working, outcome.state)) rev += 1;\n working = outcome.state;\n results.push(\n toSuccess(\n undefined,\n parsed.name,\n outcome,\n before,\n rev,\n snapshotOf(working, rev),\n ),\n );\n }\n const changed = rev !== baseRevision;\n let undoId: string | undefined;\n if (changed) {\n current = working;\n revision = rev;\n undoId = recordUndo(base, working);\n // The batch's one undo restores the state before all of it.\n for (const r of results) if (r.receipt.changed) delete r.receipt.undoId;\n }\n const result = finish({\n ok: true,\n ...(id !== undefined ? { id } : {}),\n snapshot: snapshot(),\n receipt: {\n ...(id !== undefined ? { id } : {}),\n count: results.length,\n changed,\n revisionBefore: baseRevision,\n revisionAfter: rev,\n ...(undoId ? { undoId } : {}),\n },\n results,\n });\n notify();\n return result;\n } catch (cause) {\n return unchanged(\n err('failed', cause instanceof Error ? cause.message : String(cause)),\n );\n }\n }\n\n return {\n run: run as CookbookEngine['run'],\n batch,\n snapshot,\n cookbook: () => clone(current.doc),\n state: () => ({\n version: COOKBOOK_COMMANDS_VERSION,\n revision,\n applied: current.applied,\n cookbook: clone(current.doc),\n journal: [...journal.values()].map((entry) => clone(entry)),\n }),\n subscribe(listener) {\n listeners.set(listener, revision);\n listener(snapshot());\n return () => {\n listeners.delete(listener);\n };\n },\n tools,\n batchTool,\n };\n}\n"],"mappings":";;;;;;;;AA8FA,IAAM,OACJ,MACA,SACA,QAAgD,CAAC,OAC/B;CAAE;CAAM;CAAS,GAAG;AAAM;;AAG9C,IAAM,aAAa,UAA4B;CAC7C,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,MAAM,IAAI,SAAS;CACpD,IAAI,SAAS,OAAO,UAAU,UAC5B,OAAO,OAAO,YACZ,OAAO,KAAK,KAAK,CAAC,CACf,KAAK,CAAC,CACN,KAAK,QAAQ,CACZ,KACA,UAAW,MAAkC,IAAI,CACnD,CAAC,CACL;CAEF,OAAO;AACT;AAEA,IAAM,eAAe,UAA2B;CAC9C,IAAI;EACF,OAAO,KAAK,UAAU,UAAU,KAAK,CAAC,KAAK;CAC7C,QAAQ;EACN,OAAO;CACT;AACF;AAMA,SAAS,YACP,OACA,SACA,WACQ;CACR,IAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAC5D,OAAO;EACL,IAAI;EACJ,OAAO,IAAI,mBAAmB,0CAA0C;CAC1E;CAEF,MAAM,SAAS;CACf,MAAM,EAAE,MAAM,QAAQ,CAAC,MAAM;CAC7B,IAAI,OAAO,SAAS,YAAY,CAAC,OAAO,OAAO,SAAS,IAAI,GAC1D,OAAO;EACL,IAAI;EACJ,OAAO,IAAI,mBAAmB,m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AS;KACP,GAAI,OAAO,KAAA,IAAY,EAAE,GAAG,IAAI,CAAC;KACjC,OAAO,QAAQ;KACf;KACA,gBAAgB;KAChB,eAAe;KACf,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;IAC7B;IACA;GACF,CAAC;GACD,OAAO;GACP,OAAO;EACT,SAAS,OAAO;GACd,OAAO,UACL,IAAI,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC,CACtE;EACF;CACF;CAEA,OAAO;EACA;EACL;EACA;EACA,gBAAgB,MAAM,QAAQ,GAAG;EACjC,cAAc;GACZ,SAAA;GACA;GACA,SAAS,QAAQ;GACjB,UAAU,MAAM,QAAQ,GAAG;GAC3B,SAAS,CAAC,GAAG,QAAQ,OAAO,CAAC,CAAC,CAAC,KAAK,UAAU,MAAM,KAAK,CAAC;EAC5D;EACA,UAAU,UAAU;GAClB,UAAU,IAAI,UAAU,QAAQ;GAChC,SAAS,SAAS,CAAC;GACnB,aAAa;IACX,UAAU,OAAO,QAAQ;GAC3B;EACF;EACA;EACA;CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schemas.d.ts","sourceRoot":"","sources":["../../../src/cookbook/engine/schemas.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,WAAW,EACX,WAAW,EACX,aAAa,EACb,UAAU,EACX,MAAM,YAAY,CAAC;AA8BpB;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,aAAa,GAAG,WAAW,EAAE,
|
|
1
|
+
{"version":3,"file":"schemas.d.ts","sourceRoot":"","sources":["../../../src/cookbook/engine/schemas.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,WAAW,EACX,WAAW,EACX,aAAa,EACb,UAAU,EACX,MAAM,YAAY,CAAC;AA8BpB;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,aAAa,GAAG,WAAW,EAAE,CAqQvE;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,aAAa,GAAG;IACtD,IAAI,EAAE,WAAW,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;IACpB,WAAW,EAAE,UAAU,CAAC;CACzB,CA+BA;AAgBD;;;;GAIG;AACH,wBAAgB,WAAW,CACzB,MAAM,EAAE,UAAU,EAClB,KAAK,EAAE,OAAO,EACd,IAAI,SAAU,GACb;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAiG1C;AAED,MAAM,MAAM,cAAc,GAAG,QAAQ,CAAC,MAAM,CAAC,WAAW,EAAE,UAAU,CAAC,CAAC,CAAC;AAEvE,yCAAyC;AACzC,wBAAgB,cAAc,CAAC,OAAO,EAAE,aAAa,GAAG,cAAc,CAIrE"}
|
|
@@ -175,6 +175,29 @@ function buildCommandTools(catalog) {
|
|
|
175
175
|
type: ["string", "null"],
|
|
176
176
|
minLength: 1,
|
|
177
177
|
description: "Font key. Null restores the preset font."
|
|
178
|
+
},
|
|
179
|
+
borderRadius: {
|
|
180
|
+
enum: [
|
|
181
|
+
"none",
|
|
182
|
+
"sm",
|
|
183
|
+
"md",
|
|
184
|
+
"lg",
|
|
185
|
+
"xl",
|
|
186
|
+
"full"
|
|
187
|
+
],
|
|
188
|
+
description: "Corner roundness."
|
|
189
|
+
},
|
|
190
|
+
density: {
|
|
191
|
+
enum: ["comfortable", "touch"],
|
|
192
|
+
description: "Control size: comfortable, or larger touch targets."
|
|
193
|
+
},
|
|
194
|
+
contrast: {
|
|
195
|
+
enum: [
|
|
196
|
+
"auto",
|
|
197
|
+
"standard",
|
|
198
|
+
"more"
|
|
199
|
+
],
|
|
200
|
+
description: "Contrast: auto follows the device, or force standard or more."
|
|
178
201
|
}
|
|
179
202
|
})
|
|
180
203
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schemas.js","names":[],"sources":["../../../src/cookbook/engine/schemas.ts"],"sourcesContent":["import { DEFAULT_THEME_PRESETS, MAX_TERMS_LENGTH } from './defaults.js';\nimport type {\n CommandName,\n CommandTool,\n EngineCatalog,\n JsonSchema,\n} from './types.js';\n\nconst ids = (description: string, values?: readonly string[]): JsonSchema => ({\n type: 'array',\n description,\n minItems: 1,\n maxItems: 50,\n items: values?.length\n ? { type: 'string', enum: [...values] }\n : { type: 'string', minLength: 1 },\n});\n\nconst text = (description: string, extra: JsonSchema = {}): JsonSchema => ({\n type: 'string',\n description,\n minLength: 1,\n maxLength: 200,\n ...extra,\n});\n\nconst object = (\n properties: Record<string, JsonSchema>,\n required: string[] = [],\n): JsonSchema => ({\n type: 'object',\n properties,\n ...(required.length ? { required } : {}),\n additionalProperties: false,\n});\n\n/**\n * Every command as an MCP/LLM tool definition (`inputSchema` is JSON Schema\n * 2020-12). Recipe and cookbook ids become enums from the catalog, so\n * grammar-constrained decoding cannot name one that does not exist.\n */\nexport function buildCommandTools(catalog: EngineCatalog): CommandTool[] {\n const recipeIds = catalog.recipes.map((r) => r.id);\n const cookbookIds = (catalog.cookbooks ?? []).map((c) => c.id);\n const presets = catalog.themePresets ?? DEFAULT_THEME_PRESETS;\n const cookbookId = (description: string): JsonSchema => ({\n type: 'string',\n description,\n ...(cookbookIds.length ? { enum: [...cookbookIds] } : { minLength: 1 }),\n });\n const entryId = (what: string): JsonSchema =>\n text(`The id of ${what}, as the plan snapshot's \"sections\" lists it.`);\n const replace: JsonSchema = {\n type: 'boolean',\n description: 'Confirm replacing what is there.',\n };\n return [\n {\n name: 'add_recipes',\n description:\n 'Switch recipes on. Recipes they require come along. Returns what was added.',\n inputSchema: object({ ids: ids('Recipe ids to add.', recipeIds) }, [\n 'ids',\n ]),\n },\n {\n name: 'remove_recipes',\n description:\n 'Switch recipes off. A recipe another one needs is kept and reported.',\n inputSchema: object({ ids: ids('Recipe ids to remove.', recipeIds) }, [\n 'ids',\n ]),\n },\n {\n name: 'add_features',\n description:\n 'Add single models no recipe covers, by qualified name (`@scope/pkg:Class`).',\n inputSchema: object({ ids: ids('Qualified model names to add.') }, [\n 'ids',\n ]),\n },\n {\n name: 'remove_features',\n description: 'Remove single models added with add_features.',\n inputSchema: object({ ids: ids('Qualified model names to remove.') }, [\n 'ids',\n ]),\n },\n {\n name: 'add_cookbook',\n description:\n 'Add the recipes and features of a ready-made cookbook to the current app. Nothing is replaced.',\n inputSchema: object({ id: cookbookId('The cookbook to add.') }, ['id']),\n },\n {\n name: 'remove_cookbook',\n description:\n 'Remove the recipes and features a ready-made cookbook adds. Ones another recipe needs are kept.',\n inputSchema: object({ id: cookbookId('The cookbook to remove.') }, [\n 'id',\n ]),\n },\n {\n name: 'apply_cookbook',\n description:\n 'Select a ready-made cookbook: replace the whole app (recipes, options, menu, theme) with it. When the app has anything in it, replace must be true.',\n inputSchema: object(\n { id: cookbookId('The cookbook to set up.'), replace },\n ['id'],\n ),\n },\n {\n name: 'import_cookbook',\n description:\n 'Replace the whole app with a cookbook document (version 1). Checked strictly; nothing is applied if it is invalid. When the app has anything in it, replace must be true.',\n inputSchema: object(\n {\n document: {\n type: 'object',\n description: 'A cookbook document, version 1.',\n },\n replace,\n },\n ['document'],\n ),\n },\n {\n name: 'set_settings',\n description:\n 'Change app settings: currency, default tax rate (percent), default payment terms. Applies to new records only.',\n inputSchema: object({\n currency: catalog.currencies?.length\n ? {\n type: 'string',\n description: 'ISO 4217 code, e.g. CAD.',\n enum: [...catalog.currencies],\n }\n : {\n type: 'string',\n description: 'ISO 4217 code, e.g. CAD.',\n pattern: '^[A-Z]{3}$',\n },\n taxRate: {\n type: 'number',\n description: 'Default tax rate in percent, 0 to 100.',\n minimum: 0,\n maximum: 100,\n },\n paymentTerms: {\n type: 'string',\n description: 'Default payment terms, e.g. \"Net 30\".',\n minLength: 1,\n maxLength: MAX_TERMS_LENGTH,\n },\n }),\n },\n {\n name: 'set_policy',\n description:\n \"Set one field's policy: default value, visibility, label or help. The model must be covered by a recipe or feature that is on. null clears a part.\",\n inputSchema: object(\n {\n model: text(\n 'Qualified model name, e.g. @happyvertical/smrt-commerce:Order.',\n ),\n field: text('The model field name.'),\n defaultValue: {\n description:\n 'The default as a JSON value (a string, number or boolean). null clears it.',\n },\n visibility: {\n enum: ['basic', 'advanced', 'hidden', null],\n description: 'Whether the field shows in forms and lists.',\n },\n label: {\n type: ['string', 'null'],\n description: 'A different label.',\n maxLength: 120,\n },\n help: {\n type: ['string', 'null'],\n description: 'Help text under the field.',\n maxLength: 400,\n },\n },\n ['model', 'field'],\n ),\n },\n {\n name: 'set_theme',\n description:\n 'Change the look: a preset, a brand colour, light or dark. A preset replaces a brand colour.',\n inputSchema: object({\n preset: { enum: [...presets], description: 'A built-in theme.' },\n primary: {\n type: 'string',\n description: 'Brand colour as #rrggbb.',\n pattern: '^#[0-9a-fA-F]{6}$',\n },\n colorScheme: {\n enum: ['light', 'dark', 'system'],\n description: 'Light, dark or follow the device.',\n },\n fontFamily: {\n type: ['string', 'null'],\n minLength: 1,\n description: 'Font key. Null restores the preset font.',\n },\n }),\n },\n {\n name: 'reset_theme',\n description: 'Go back to the default look.',\n inputSchema: object({}),\n },\n {\n name: 'set_name',\n description: 'Name and describe the app. null clears a part.',\n inputSchema: object({\n name: { type: ['string', 'null'], minLength: 1, maxLength: 60 },\n description: {\n type: ['string', 'null'],\n minLength: 1,\n maxLength: 400,\n },\n }),\n },\n {\n name: 'rename_section',\n description: 'Rename a menu section.',\n inputSchema: object(\n {\n id: entryId('the section'),\n label: text('The new name.', { maxLength: 60 }),\n },\n ['id', 'label'],\n ),\n },\n {\n name: 'rename_item',\n description: 'Rename a menu entry. A null label restores its own name.',\n inputSchema: object(\n {\n id: entryId('the entry'),\n label: { type: ['string', 'null'], minLength: 1, maxLength: 60 },\n },\n ['id', 'label'],\n ),\n },\n {\n name: 'hide',\n description: 'Hide a menu section or entry. Nothing is deleted.',\n inputSchema: object({ id: entryId('the section or entry') }, ['id']),\n },\n {\n name: 'show',\n description: 'Show a hidden menu section or entry again.',\n inputSchema: object({ id: entryId('the section or entry') }, ['id']),\n },\n {\n name: 'validate',\n description:\n 'Check the current cookbook against the catalog and report typed diagnostics. Changes nothing.',\n inputSchema: object({}),\n },\n {\n name: 'export_cookbook',\n description:\n 'The cookbook as a <name>.cookbook.json file (text in the result). Changes nothing.',\n inputSchema: object({\n name: text('A name for the file.', { maxLength: 60 }),\n }),\n },\n {\n name: 'undo',\n description:\n 'Undo an earlier change by the undoId its receipt carried. Refused with a conflict when the plan changed since, unless force is true.',\n inputSchema: object(\n {\n undoId: text('The undoId from a receipt.'),\n force: {\n type: 'boolean',\n description: 'Undo even after later edits.',\n },\n },\n ['undoId'],\n ),\n },\n ];\n}\n\n/**\n * The batch envelope as a tool definition: several commands, applied\n * all-or-nothing. Commands inside are validated against their own schemas.\n */\nexport function buildBatchTool(catalog: EngineCatalog): {\n name: 'run_batch';\n description: string;\n inputSchema: JsonSchema;\n} {\n return {\n name: 'run_batch',\n description:\n 'Run several commands as one atomic batch: all apply or none does. A failure names the command and leaves the plan unchanged.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', minLength: 1, maxLength: 200 },\n expectedRevision: { type: 'integer', minimum: 0 },\n commands: {\n type: 'array',\n minItems: 1,\n maxItems: 50,\n items: {\n oneOf: buildCommandTools(catalog).map((tool) => ({\n type: 'object',\n properties: {\n name: { const: tool.name },\n input: tool.inputSchema,\n },\n required: ['name'],\n additionalProperties: false,\n })),\n },\n },\n },\n required: ['commands'],\n additionalProperties: false,\n },\n };\n}\n\nconst typeOf = (value: unknown): string =>\n value === null\n ? 'null'\n : Array.isArray(value)\n ? 'array'\n : Number.isInteger(value)\n ? 'integer'\n : typeof value;\n\nfunction typeMatches(wanted: string, value: unknown): boolean {\n const actual = typeOf(value);\n return actual === wanted || (wanted === 'number' && actual === 'integer');\n}\n\n/**\n * Check a value against a command schema (the subset the commands use). One\n * validator for runtime and exported schemas, so they cannot drift. Returns\n * the first problem as `{ path, message }`, or null.\n */\nexport function checkSchema(\n schema: JsonSchema,\n value: unknown,\n path = 'input',\n): { path: string; message: string } | null {\n const bad = (message: string) => ({ path, message: `${path} ${message}` });\n const type = schema.type as string | string[] | undefined;\n if (type) {\n const wanted = Array.isArray(type) ? type : [type];\n if (!wanted.some((t) => typeMatches(t, value))) {\n return bad(`must be ${wanted.join(' or ')}`);\n }\n }\n const choices = schema.enum as unknown[] | undefined;\n if (choices && !choices.includes(value)) {\n return bad(\n choices.length > 12\n ? 'is not a known value'\n : `must be one of ${choices.map((c) => JSON.stringify(c)).join(', ')}`,\n );\n }\n if (typeof value === 'string') {\n const { minLength, maxLength, pattern } = schema as {\n minLength?: number;\n maxLength?: number;\n pattern?: string;\n };\n if (minLength !== undefined && value.length < minLength) {\n return bad('must not be empty');\n }\n if (maxLength !== undefined && value.length > maxLength) {\n return bad(`must be at most ${maxLength} characters`);\n }\n if (pattern && !new RegExp(pattern).test(value)) {\n return bad('has the wrong format');\n }\n }\n if (typeof value === 'number') {\n const { minimum, maximum } = schema as {\n minimum?: number;\n maximum?: number;\n };\n if (!Number.isFinite(value)) return bad('must be a finite number');\n if (minimum !== undefined && value < minimum) {\n return bad(`must be at least ${minimum}`);\n }\n if (maximum !== undefined && value > maximum) {\n return bad(`must be at most ${maximum}`);\n }\n }\n if (Array.isArray(value)) {\n const { minItems, maxItems, items } = schema as {\n minItems?: number;\n maxItems?: number;\n items?: JsonSchema;\n };\n if (minItems !== undefined && value.length < minItems) {\n return bad(`needs at least ${minItems} item${minItems === 1 ? '' : 's'}`);\n }\n if (maxItems !== undefined && value.length > maxItems) {\n return bad(`takes at most ${maxItems} items`);\n }\n if (items) {\n for (const [index, item] of value.entries()) {\n const problem = checkSchema(items, item, `${path}[${index}]`);\n if (problem) return problem;\n }\n }\n }\n if (typeOf(value) === 'object') {\n const object = value as Record<string, unknown>;\n const { properties, required, additionalProperties } = schema as {\n properties?: Record<string, JsonSchema>;\n required?: string[];\n additionalProperties?: boolean;\n };\n for (const key of required ?? []) {\n if (object[key] === undefined) {\n return {\n path: `${path}.${key}`,\n message: `${path}.${key} is required`,\n };\n }\n }\n for (const [key, entry] of Object.entries(object)) {\n const child = properties?.[key];\n if (!child) {\n if (additionalProperties === false) {\n return {\n path: `${path}.${key}`,\n message: `${path}.${key} is not an option of this command`,\n };\n }\n continue;\n }\n if (entry === undefined) continue;\n const problem = checkSchema(child, entry, `${path}.${key}`);\n if (problem) return problem;\n }\n }\n return null;\n}\n\nexport type CommandSchemas = Readonly<Record<CommandName, JsonSchema>>;\n\n/** The input schemas by command name. */\nexport function commandSchemas(catalog: EngineCatalog): CommandSchemas {\n return Object.fromEntries(\n buildCommandTools(catalog).map((tool) => [tool.name, tool.inputSchema]),\n ) as CommandSchemas;\n}\n"],"mappings":";;AAQA,IAAM,OAAO,aAAqB,YAA4C;CAC5E,MAAM;CACN;CACA,UAAU;CACV,UAAU;CACV,OAAO,QAAQ,SACX;EAAE,MAAM;EAAU,MAAM,CAAC,GAAG,MAAM;CAAE,IACpC;EAAE,MAAM;EAAU,WAAW;CAAE;AACrC;AAEA,IAAM,QAAQ,aAAqB,QAAoB,CAAC,OAAmB;CACzE,MAAM;CACN;CACA,WAAW;CACX,WAAW;CACX,GAAG;AACL;AAEA,IAAM,UACJ,YACA,WAAqB,CAAC,OACN;CAChB,MAAM;CACN;CACA,GAAI,SAAS,SAAS,EAAE,SAAS,IAAI,CAAC;CACtC,sBAAsB;AACxB;;;;;;AAOA,SAAgB,kBAAkB,SAAuC;CACvE,MAAM,YAAY,QAAQ,QAAQ,KAAK,MAAM,EAAE,EAAE;CACjD,MAAM,eAAe,QAAQ,aAAa,CAAC,EAAA,CAAG,KAAK,MAAM,EAAE,EAAE;CAC7D,MAAM,UAAU,QAAQ,gBAAgB;CACxC,MAAM,cAAc,iBAAqC;EACvD,MAAM;EACN;EACA,GAAI,YAAY,SAAS,EAAE,MAAM,CAAC,GAAG,WAAW,EAAE,IAAI,EAAE,WAAW,EAAE;CACvE;CACA,MAAM,WAAW,SACf,KAAK,aAAa,KAAK,8CAA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GTH } from './defaults.js';\nimport type {\n CommandName,\n CommandTool,\n EngineCatalog,\n JsonSchema,\n} from './types.js';\n\nconst ids = (description: string, values?: readonly string[]): JsonSchema => ({\n type: 'array',\n description,\n minItems: 1,\n maxItems: 50,\n items: values?.length\n ? { type: 'string', enum: [...values] }\n : { type: 'string', minLength: 1 },\n});\n\nconst text = (description: string, extra: JsonSchema = {}): JsonSchema => ({\n type: 'string',\n description,\n minLength: 1,\n maxLength: 200,\n ...extra,\n});\n\nconst object = (\n properties: Record<string, JsonSchema>,\n required: string[] = [],\n): JsonSchema => ({\n type: 'object',\n properties,\n ...(required.length ? { required } : {}),\n additionalProperties: false,\n});\n\n/**\n * Every command as an MCP/LLM tool definition (`inputSchema` is JSON Schema\n * 2020-12). Recipe and cookbook ids become enums from the catalog, so\n * grammar-constrained decoding cannot name one that does not exist.\n */\nexport function buildCommandTools(catalog: EngineCatalog): CommandTool[] {\n const recipeIds = catalog.recipes.map((r) => r.id);\n const cookbookIds = (catalog.cookbooks ?? []).map((c) => c.id);\n const presets = catalog.themePresets ?? DEFAULT_THEME_PRESETS;\n const cookbookId = (description: string): JsonSchema => ({\n type: 'string',\n description,\n ...(cookbookIds.length ? { enum: [...cookbookIds] } : { minLength: 1 }),\n });\n const entryId = (what: string): JsonSchema =>\n text(`The id of ${what}, as the plan snapshot's \"sections\" lists it.`);\n const replace: JsonSchema = {\n type: 'boolean',\n description: 'Confirm replacing what is there.',\n };\n return [\n {\n name: 'add_recipes',\n description:\n 'Switch recipes on. Recipes they require come along. Returns what was added.',\n inputSchema: object({ ids: ids('Recipe ids to add.', recipeIds) }, [\n 'ids',\n ]),\n },\n {\n name: 'remove_recipes',\n description:\n 'Switch recipes off. A recipe another one needs is kept and reported.',\n inputSchema: object({ ids: ids('Recipe ids to remove.', recipeIds) }, [\n 'ids',\n ]),\n },\n {\n name: 'add_features',\n description:\n 'Add single models no recipe covers, by qualified name (`@scope/pkg:Class`).',\n inputSchema: object({ ids: ids('Qualified model names to add.') }, [\n 'ids',\n ]),\n },\n {\n name: 'remove_features',\n description: 'Remove single models added with add_features.',\n inputSchema: object({ ids: ids('Qualified model names to remove.') }, [\n 'ids',\n ]),\n },\n {\n name: 'add_cookbook',\n description:\n 'Add the recipes and features of a ready-made cookbook to the current app. Nothing is replaced.',\n inputSchema: object({ id: cookbookId('The cookbook to add.') }, ['id']),\n },\n {\n name: 'remove_cookbook',\n description:\n 'Remove the recipes and features a ready-made cookbook adds. Ones another recipe needs are kept.',\n inputSchema: object({ id: cookbookId('The cookbook to remove.') }, [\n 'id',\n ]),\n },\n {\n name: 'apply_cookbook',\n description:\n 'Select a ready-made cookbook: replace the whole app (recipes, options, menu, theme) with it. When the app has anything in it, replace must be true.',\n inputSchema: object(\n { id: cookbookId('The cookbook to set up.'), replace },\n ['id'],\n ),\n },\n {\n name: 'import_cookbook',\n description:\n 'Replace the whole app with a cookbook document (version 1). Checked strictly; nothing is applied if it is invalid. When the app has anything in it, replace must be true.',\n inputSchema: object(\n {\n document: {\n type: 'object',\n description: 'A cookbook document, version 1.',\n },\n replace,\n },\n ['document'],\n ),\n },\n {\n name: 'set_settings',\n description:\n 'Change app settings: currency, default tax rate (percent), default payment terms. Applies to new records only.',\n inputSchema: object({\n currency: catalog.currencies?.length\n ? {\n type: 'string',\n description: 'ISO 4217 code, e.g. CAD.',\n enum: [...catalog.currencies],\n }\n : {\n type: 'string',\n description: 'ISO 4217 code, e.g. CAD.',\n pattern: '^[A-Z]{3}$',\n },\n taxRate: {\n type: 'number',\n description: 'Default tax rate in percent, 0 to 100.',\n minimum: 0,\n maximum: 100,\n },\n paymentTerms: {\n type: 'string',\n description: 'Default payment terms, e.g. \"Net 30\".',\n minLength: 1,\n maxLength: MAX_TERMS_LENGTH,\n },\n }),\n },\n {\n name: 'set_policy',\n description:\n \"Set one field's policy: default value, visibility, label or help. The model must be covered by a recipe or feature that is on. null clears a part.\",\n inputSchema: object(\n {\n model: text(\n 'Qualified model name, e.g. @happyvertical/smrt-commerce:Order.',\n ),\n field: text('The model field name.'),\n defaultValue: {\n description:\n 'The default as a JSON value (a string, number or boolean). null clears it.',\n },\n visibility: {\n enum: ['basic', 'advanced', 'hidden', null],\n description: 'Whether the field shows in forms and lists.',\n },\n label: {\n type: ['string', 'null'],\n description: 'A different label.',\n maxLength: 120,\n },\n help: {\n type: ['string', 'null'],\n description: 'Help text under the field.',\n maxLength: 400,\n },\n },\n ['model', 'field'],\n ),\n },\n {\n name: 'set_theme',\n description:\n 'Change the look: a preset, a brand colour, light or dark. A preset replaces a brand colour.',\n inputSchema: object({\n preset: { enum: [...presets], description: 'A built-in theme.' },\n primary: {\n type: 'string',\n description: 'Brand colour as #rrggbb.',\n pattern: '^#[0-9a-fA-F]{6}$',\n },\n colorScheme: {\n enum: ['light', 'dark', 'system'],\n description: 'Light, dark or follow the device.',\n },\n fontFamily: {\n type: ['string', 'null'],\n minLength: 1,\n description: 'Font key. Null restores the preset font.',\n },\n borderRadius: {\n enum: ['none', 'sm', 'md', 'lg', 'xl', 'full'],\n description: 'Corner roundness.',\n },\n density: {\n enum: ['comfortable', 'touch'],\n description: 'Control size: comfortable, or larger touch targets.',\n },\n contrast: {\n enum: ['auto', 'standard', 'more'],\n description:\n 'Contrast: auto follows the device, or force standard or more.',\n },\n }),\n },\n {\n name: 'reset_theme',\n description: 'Go back to the default look.',\n inputSchema: object({}),\n },\n {\n name: 'set_name',\n description: 'Name and describe the app. null clears a part.',\n inputSchema: object({\n name: { type: ['string', 'null'], minLength: 1, maxLength: 60 },\n description: {\n type: ['string', 'null'],\n minLength: 1,\n maxLength: 400,\n },\n }),\n },\n {\n name: 'rename_section',\n description: 'Rename a menu section.',\n inputSchema: object(\n {\n id: entryId('the section'),\n label: text('The new name.', { maxLength: 60 }),\n },\n ['id', 'label'],\n ),\n },\n {\n name: 'rename_item',\n description: 'Rename a menu entry. A null label restores its own name.',\n inputSchema: object(\n {\n id: entryId('the entry'),\n label: { type: ['string', 'null'], minLength: 1, maxLength: 60 },\n },\n ['id', 'label'],\n ),\n },\n {\n name: 'hide',\n description: 'Hide a menu section or entry. Nothing is deleted.',\n inputSchema: object({ id: entryId('the section or entry') }, ['id']),\n },\n {\n name: 'show',\n description: 'Show a hidden menu section or entry again.',\n inputSchema: object({ id: entryId('the section or entry') }, ['id']),\n },\n {\n name: 'validate',\n description:\n 'Check the current cookbook against the catalog and report typed diagnostics. Changes nothing.',\n inputSchema: object({}),\n },\n {\n name: 'export_cookbook',\n description:\n 'The cookbook as a <name>.cookbook.json file (text in the result). Changes nothing.',\n inputSchema: object({\n name: text('A name for the file.', { maxLength: 60 }),\n }),\n },\n {\n name: 'undo',\n description:\n 'Undo an earlier change by the undoId its receipt carried. Refused with a conflict when the plan changed since, unless force is true.',\n inputSchema: object(\n {\n undoId: text('The undoId from a receipt.'),\n force: {\n type: 'boolean',\n description: 'Undo even after later edits.',\n },\n },\n ['undoId'],\n ),\n },\n ];\n}\n\n/**\n * The batch envelope as a tool definition: several commands, applied\n * all-or-nothing. Commands inside are validated against their own schemas.\n */\nexport function buildBatchTool(catalog: EngineCatalog): {\n name: 'run_batch';\n description: string;\n inputSchema: JsonSchema;\n} {\n return {\n name: 'run_batch',\n description:\n 'Run several commands as one atomic batch: all apply or none does. A failure names the command and leaves the plan unchanged.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', minLength: 1, maxLength: 200 },\n expectedRevision: { type: 'integer', minimum: 0 },\n commands: {\n type: 'array',\n minItems: 1,\n maxItems: 50,\n items: {\n oneOf: buildCommandTools(catalog).map((tool) => ({\n type: 'object',\n properties: {\n name: { const: tool.name },\n input: tool.inputSchema,\n },\n required: ['name'],\n additionalProperties: false,\n })),\n },\n },\n },\n required: ['commands'],\n additionalProperties: false,\n },\n };\n}\n\nconst typeOf = (value: unknown): string =>\n value === null\n ? 'null'\n : Array.isArray(value)\n ? 'array'\n : Number.isInteger(value)\n ? 'integer'\n : typeof value;\n\nfunction typeMatches(wanted: string, value: unknown): boolean {\n const actual = typeOf(value);\n return actual === wanted || (wanted === 'number' && actual === 'integer');\n}\n\n/**\n * Check a value against a command schema (the subset the commands use). One\n * validator for runtime and exported schemas, so they cannot drift. Returns\n * the first problem as `{ path, message }`, or null.\n */\nexport function checkSchema(\n schema: JsonSchema,\n value: unknown,\n path = 'input',\n): { path: string; message: string } | null {\n const bad = (message: string) => ({ path, message: `${path} ${message}` });\n const type = schema.type as string | string[] | undefined;\n if (type) {\n const wanted = Array.isArray(type) ? type : [type];\n if (!wanted.some((t) => typeMatches(t, value))) {\n return bad(`must be ${wanted.join(' or ')}`);\n }\n }\n const choices = schema.enum as unknown[] | undefined;\n if (choices && !choices.includes(value)) {\n return bad(\n choices.length > 12\n ? 'is not a known value'\n : `must be one of ${choices.map((c) => JSON.stringify(c)).join(', ')}`,\n );\n }\n if (typeof value === 'string') {\n const { minLength, maxLength, pattern } = schema as {\n minLength?: number;\n maxLength?: number;\n pattern?: string;\n };\n if (minLength !== undefined && value.length < minLength) {\n return bad('must not be empty');\n }\n if (maxLength !== undefined && value.length > maxLength) {\n return bad(`must be at most ${maxLength} characters`);\n }\n if (pattern && !new RegExp(pattern).test(value)) {\n return bad('has the wrong format');\n }\n }\n if (typeof value === 'number') {\n const { minimum, maximum } = schema as {\n minimum?: number;\n maximum?: number;\n };\n if (!Number.isFinite(value)) return bad('must be a finite number');\n if (minimum !== undefined && value < minimum) {\n return bad(`must be at least ${minimum}`);\n }\n if (maximum !== undefined && value > maximum) {\n return bad(`must be at most ${maximum}`);\n }\n }\n if (Array.isArray(value)) {\n const { minItems, maxItems, items } = schema as {\n minItems?: number;\n maxItems?: number;\n items?: JsonSchema;\n };\n if (minItems !== undefined && value.length < minItems) {\n return bad(`needs at least ${minItems} item${minItems === 1 ? '' : 's'}`);\n }\n if (maxItems !== undefined && value.length > maxItems) {\n return bad(`takes at most ${maxItems} items`);\n }\n if (items) {\n for (const [index, item] of value.entries()) {\n const problem = checkSchema(items, item, `${path}[${index}]`);\n if (problem) return problem;\n }\n }\n }\n if (typeOf(value) === 'object') {\n const object = value as Record<string, unknown>;\n const { properties, required, additionalProperties } = schema as {\n properties?: Record<string, JsonSchema>;\n required?: string[];\n additionalProperties?: boolean;\n };\n for (const key of required ?? []) {\n if (object[key] === undefined) {\n return {\n path: `${path}.${key}`,\n message: `${path}.${key} is required`,\n };\n }\n }\n for (const [key, entry] of Object.entries(object)) {\n const child = properties?.[key];\n if (!child) {\n if (additionalProperties === false) {\n return {\n path: `${path}.${key}`,\n message: `${path}.${key} is not an option of this command`,\n };\n }\n continue;\n }\n if (entry === undefined) continue;\n const problem = checkSchema(child, entry, `${path}.${key}`);\n if (problem) return problem;\n }\n }\n return null;\n}\n\nexport type CommandSchemas = Readonly<Record<CommandName, JsonSchema>>;\n\n/** The input schemas by command name. */\nexport function commandSchemas(catalog: EngineCatalog): CommandSchemas {\n return Object.fromEntries(\n buildCommandTools(catalog).map((tool) => [tool.name, tool.inputSchema]),\n ) as CommandSchemas;\n}\n"],"mappings":";;AAQA,IAAM,OAAO,aAAqB,YAA4C;CAC5E,MAAM;CACN;CACA,UAAU;CACV,UAAU;CACV,OAAO,QAAQ,SACX;EAAE,MAAM;EAAU,MAAM,CAAC,GAAG,MAAM;CAAE,IACpC;EAAE,MAAM;EAAU,WAAW;CAAE;AACrC;AAEA,IAAM,QAAQ,aAAqB,QAAoB,CAAC,OAAmB;CACzE,MAAM;CACN;CACA,WAAW;CACX,WAAW;CACX,GAAG;AACL;AAEA,IAAM,UACJ,YACA,WAAqB,CAAC,OACN;CAChB,MAAM;CACN;CACA,GAAI,SAAS,SAAS,EAAE,SAAS,IAAI,CAAC;CACtC,sBAAsB;AACxB;;;;;;AAOA,SAAgB,kBAAkB,SAAuC;CACvE,MAAM,YAAY,QAAQ,QAAQ,KAAK,MAAM,EAAE,EAAE;CACjD,MAAM,eAAe,QAAQ,aAAa,CAAC,EAAA,CAAG,KAAK,MAAM,EAAE,EAAE;CAC7D,MAAM,UAAU,QAAQ,gBAAgB;CACxC,MAAM,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AAW;GACzB,MAAM,UAAU,YAAY,OAAO,OAAO,GAAG,KAAK,GAAG,KAAK;GAC1D,IAAI,SAAS,OAAO;EACtB;CACF;CACA,OAAO;AACT;;AAKA,SAAgB,eAAe,SAAwC;CACrE,OAAO,OAAO,YACZ,kBAAkB,OAAO,CAAC,CAAC,KAAK,SAAS,CAAC,KAAK,MAAM,KAAK,WAAW,CAAC,CACxE;AACF"}
|
|
@@ -119,6 +119,9 @@ export interface CommandInputs {
|
|
|
119
119
|
primary?: string;
|
|
120
120
|
colorScheme?: 'light' | 'dark' | 'system';
|
|
121
121
|
fontFamily?: string | null;
|
|
122
|
+
borderRadius?: 'none' | 'sm' | 'md' | 'lg' | 'xl' | 'full';
|
|
123
|
+
density?: 'comfortable' | 'touch';
|
|
124
|
+
contrast?: 'auto' | 'standard' | 'more';
|
|
122
125
|
};
|
|
123
126
|
reset_theme: Record<string, never>;
|
|
124
127
|
/** Name (and describe) the app; null clears. */
|
|
@@ -215,6 +218,9 @@ export interface PlanSnapshot {
|
|
|
215
218
|
preset: string | null;
|
|
216
219
|
primary: string | null;
|
|
217
220
|
colorScheme: string;
|
|
221
|
+
borderRadius: string | null;
|
|
222
|
+
density: string | null;
|
|
223
|
+
contrast: string | null;
|
|
218
224
|
};
|
|
219
225
|
sections: {
|
|
220
226
|
id: string;
|