@schema-engine/layout 0.5.1 → 0.5.2
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/README.md +10 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +4 -4
- package/dist/index.js.map +4 -4
- package/dist/lib/grid-placement.d.ts +51 -4
- package/dist/lib/grid-placement.js +1 -1
- package/dist/lib/grid-placement.js.map +3 -3
- package/dist/lib/grid-styles.d.ts +79 -5
- package/dist/lib/grid-styles.js +2 -2
- package/dist/lib/grid-styles.js.map +3 -3
- package/dist/lib/layout-theme.js +4 -4
- package/dist/lib/layout-theme.js.map +3 -3
- package/dist/recipes/bind-recipe.d.ts +3 -3
- package/dist/recipes/bind-recipe.js +1 -1
- package/dist/recipes/bind-recipe.js.map +2 -2
- package/dist/recipes/define-recipe-spec.d.ts +37 -13
- package/dist/recipes/define-recipe-spec.js +1 -1
- package/dist/recipes/define-recipe-spec.js.map +4 -4
- package/dist/recipes/protocol.d.ts +5 -2
- package/dist/recipes/protocol.js +1 -1
- package/dist/recipes/protocol.js.map +3 -3
- package/dist/recipes/resolve-recipe-view.d.ts +2 -0
- package/dist/recipes/resolve-recipe-view.js +1 -1
- package/dist/recipes/resolve-recipe-view.js.map +4 -4
- package/dist/recipes/types.d.ts +21 -6
- package/dist/recipes/view-model.d.ts +2 -2
- package/dist/recipes/view-model.js +1 -1
- package/dist/recipes/view-model.js.map +2 -2
- package/dist/schemas/grid.d.ts +28 -15
- package/dist/schemas/grid.js +1 -1
- package/dist/schemas/grid.js.map +2 -2
- package/package.json +5 -2
- package/skill/SKILL.md +26 -25
- package/skill/reference/layout.md +61 -2
|
@@ -1,20 +1,37 @@
|
|
|
1
|
-
import
|
|
2
|
-
import type {
|
|
1
|
+
import type { StandardSchemaV1 } from '@standard-schema/spec';
|
|
2
|
+
import type { AppearanceAxisList } from '../lib/appearance';
|
|
3
3
|
import { type RecipeProtocol } from './protocol';
|
|
4
4
|
import type { RecipeMetadata, RecipeSlotDefaults, ProtocolRecipeSlotSchemas, ProtocolRecipeSpec } from './types';
|
|
5
|
+
type Flat<T> = {
|
|
6
|
+
[K in keyof T]: T[K];
|
|
7
|
+
};
|
|
8
|
+
/** What an author writes for a view: the literal `$type`, every declared slot optional. */
|
|
9
|
+
type RecipeViewSchemaInput<TType extends string, TSlots extends ProtocolRecipeSlotSchemas> = Flat<{
|
|
10
|
+
$type: TType;
|
|
11
|
+
} & {
|
|
12
|
+
-readonly [K in keyof TSlots]?: StandardSchemaV1.InferInput<NonNullable<TSlots[K]>>;
|
|
13
|
+
}>;
|
|
14
|
+
/** A parsed view: every declared slot present, as its schema outputs it. */
|
|
15
|
+
type RecipeViewSchemaOutput<TType extends string, TSlots extends ProtocolRecipeSlotSchemas> = Flat<{
|
|
16
|
+
$type: TType;
|
|
17
|
+
} & {
|
|
18
|
+
-readonly [K in keyof TSlots]-?: StandardSchemaV1.InferOutput<NonNullable<TSlots[K]>>;
|
|
19
|
+
}>;
|
|
5
20
|
/**
|
|
6
|
-
* Strict view schema of a spec: the literal `$type` plus each declared slot, which
|
|
21
|
+
* Strict view schema of a spec: the literal `$type` plus each declared slot, which parses from `{}` when omitted.
|
|
7
22
|
*
|
|
8
23
|
* @remarks
|
|
9
|
-
* A
|
|
10
|
-
*
|
|
11
|
-
*
|
|
24
|
+
* A Standard Schema, not a schema of any one library, so slot schemas can come from any library. It validates
|
|
25
|
+
* synchronously and so needs synchronous slot schemas: a slot that validates asynchronously throws where the view is
|
|
26
|
+
* parsed. A slot is an optional key on input and always present on output, so each slot schema's own defaults fill
|
|
27
|
+
* it. A key outside `$type` and the declared slots is an issue at `[key]`. The input and output types let the engine
|
|
28
|
+
* infer the authoring type of `view` from a registration.
|
|
12
29
|
*/
|
|
13
|
-
export type RecipeViewSchema<TType extends string, TSlots extends ProtocolRecipeSlotSchemas> =
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
[K in keyof TSlots]
|
|
17
|
-
}
|
|
30
|
+
export type RecipeViewSchema<TType extends string, TSlots extends ProtocolRecipeSlotSchemas> = StandardSchemaV1<RecipeViewSchemaInput<TType, TSlots>, RecipeViewSchemaOutput<TType, TSlots>>;
|
|
31
|
+
/** The axes a spec may declare per slot: a slot whose schema input has no `appearance` key takes none. */
|
|
32
|
+
type SlotAppearanceAxesOf<TSlots extends ProtocolRecipeSlotSchemas> = {
|
|
33
|
+
[K in keyof TSlots]?: 'appearance' extends keyof StandardSchemaV1.InferInput<NonNullable<TSlots[K]>> ? AppearanceAxisList : never;
|
|
34
|
+
};
|
|
18
35
|
/**
|
|
19
36
|
* What a domain passes to `defineProtocolRecipeSpec`; the slot and kind names come from its protocol.
|
|
20
37
|
*
|
|
@@ -25,6 +42,9 @@ export type RecipeViewSchema<TType extends string, TSlots extends ProtocolRecipe
|
|
|
25
42
|
*
|
|
26
43
|
* `slotSchemas` also maps every key outside the protocol's slots to `never`. The `TSlots` constraint
|
|
27
44
|
* alone accepts extra properties, so without it a slot the protocol does not declare would compile.
|
|
45
|
+
*
|
|
46
|
+
* `appearanceAxes` accepts only slots whose schema input has an `appearance` key, so a slot that cannot
|
|
47
|
+
* be given a pick does not declare axes.
|
|
28
48
|
*/
|
|
29
49
|
export interface ProtocolRecipeSpecDefinition<TSlot extends string, TKind extends string, TType extends string, TSlots extends ProtocolRecipeSlotSchemas<TSlot>> {
|
|
30
50
|
$type: TType;
|
|
@@ -34,7 +54,7 @@ export interface ProtocolRecipeSpecDefinition<TSlot extends string, TKind extend
|
|
|
34
54
|
[K in Exclude<keyof TSlots, TSlot>]: never;
|
|
35
55
|
};
|
|
36
56
|
slotDefaults?: RecipeSlotDefaults<NoInfer<TSlots>>;
|
|
37
|
-
appearanceAxes?:
|
|
57
|
+
appearanceAxes?: SlotAppearanceAxesOf<NoInfer<TSlots>>;
|
|
38
58
|
}
|
|
39
59
|
/**
|
|
40
60
|
* Declares a recipe's `$type`, kind, slot schemas, and metadata against a domain's protocol.
|
|
@@ -45,5 +65,9 @@ export interface ProtocolRecipeSpecDefinition<TSlot extends string, TKind extend
|
|
|
45
65
|
*
|
|
46
66
|
* The rules run before the slots are listed, because listing filters the protocol's slots and would
|
|
47
67
|
* otherwise drop a slot the protocol does not declare without a word.
|
|
68
|
+
*
|
|
69
|
+
* A slot schema is any Standard Schema that validates synchronously. A spec that leaves out `slotSchemas` declares
|
|
70
|
+
* no slots, so `TSlots` defaults to the empty object type.
|
|
48
71
|
*/
|
|
49
|
-
export declare function defineProtocolRecipeSpec<TSlot extends string, TKind extends string, const TType extends string, const TSlots extends ProtocolRecipeSlotSchemas<TSlot> =
|
|
72
|
+
export declare function defineProtocolRecipeSpec<TSlot extends string, TKind extends string, const TType extends string, const TSlots extends ProtocolRecipeSlotSchemas<TSlot> = {}>(protocol: RecipeProtocol<TSlot, TKind>, definition: ProtocolRecipeSpecDefinition<TSlot, TKind, TType, TSlots>): ProtocolRecipeSpec<TSlot, TKind, TType, RecipeViewSchema<TType, TSlots>, TSlots>;
|
|
73
|
+
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import{formatIssuePath as y,safeParseStandardSchema as S,standardSchema as f}from"@schema-engine/registry";import{assertStandardSchema as x,createRegistry as w}from"@schema-engine/registry";function d(t,e){let s=t.kinds,n=t.slots;if(!s.includes(e.kind))throw new Error(`Recipe '${e.$type}' has kind '${e.kind}', which the protocol does not declare (kinds: ${t.kinds.join(", ")}).`);for(let o of e.slots)if(!n.includes(o))throw new Error(`Recipe '${e.$type}' declares slot '${o}', which the protocol does not declare (slots: ${t.slots.join(", ")}).`);for(let o of t.rules){let r=o.check(e);if(r!==void 0)throw new Error(`Recipe '${e.$type}' breaks rule '${o.name}': ${r}.`)}}import{safeParseStandardSchema as A}from"@schema-engine/registry";function u(t,e,s){return`Recipe '${t}' does not accept view key '${e}'. Allowed: ${s.join(", ")||"(none)"}.`}function T(t,e,s){return f(n=>{if(typeof n!="object"||n===null||Array.isArray(n))return{issues:[{message:"Expected a view object.",path:[]}]};let o=n,r=[];o.$type!==t&&r.push({message:`Expected $type '${t}'.`,path:["$type"]});for(let a of Object.keys(o))a!=="$type"&&!e.includes(a)&&r.push({message:u(t,a,e),path:[a]});let c={$type:t};for(let a of e){let l=s[a];if(!l)continue;let i=S(l,o[a]===void 0?{}:o[a]);i.success?c[a]=i.data:r.push(...i.error.issues.map(p=>({...p,path:[a,...p.path??[]]})))}return r.length>0?{issues:r}:{value:c}})}function h(t){let e=t.keys,s=Array.isArray(e)?e.filter(o=>typeof o=="string"||typeof o=="number"):[];return(s.length>0?s.map(o=>[...t.path??[],o]):[t.path]).map(o=>`${y(o)||"(value)"}: ${t.message}`)}function m(t,e,s){for(let[n,o]of Object.entries(s??{})){let r=e[n];if(!r)throw new Error(`Recipe '${t}' slotDefaults.${n}: the recipe does not declare a '${n}' slot.`);let c=S(r,o);if(!c.success){let a=c.error.issues.flatMap(h);throw new Error(`Recipe '${t}' slotDefaults.${n} is invalid: ${a.join("; ")}`)}}}function R(t,e,s){for(let[n,o]of Object.entries(s??{}))if(o&&!e[n])throw new Error(`Recipe '${t}' appearanceAxes.${n}: the recipe does not declare a '${n}' slot.`)}function I(t,e){let s=e.slotSchemas??{},n=Object.keys(s).filter(c=>s[c]);d(t,{$type:e.$type,kind:e.kind,slots:n});let o=t.slots.filter(c=>s[c]);m(e.$type,s,e.slotDefaults),R(e.$type,s,e.appearanceAxes);let r=T(e.$type,o,s);return{$type:e.$type,kind:e.kind,slots:o,slotSchemas:s,slotDefaults:e.slotDefaults,appearanceAxes:e.appearanceAxes,metadata:e.metadata,schema:r}}export{I as defineProtocolRecipeSpec};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../../src/recipes/define-recipe-spec.ts", "../../src/recipes/protocol.ts"],
|
|
4
|
-
"sourcesContent": ["import * as z from 'zod/mini';\nimport type { SlotAppearanceAxes } from '../lib/appearance';\nimport { assertRecipeRules, type RecipeProtocol } from './protocol';\nimport type { RecipeMetadata, RecipeSlotDefaults, ProtocolRecipeSlotSchemas, ProtocolRecipeSpec } from './types';\n\n/**\n * Strict view schema of a spec: the literal `$type` plus each declared slot, which defaults to `{}`.\n *\n * @remarks\n * A slot is an optional key on input and always present on output, parsed from `{}` when the author\n * omits it, so each slot schema's own defaults fill it. Keeping the concrete object type, rather than `z.ZodMiniType`, lets the engine infer the\n * authoring type of `view` from a registration.\n */\nexport type RecipeViewSchema<TType extends string, TSlots extends ProtocolRecipeSlotSchemas> = z.ZodMiniObject<\n\t{ $type: z.ZodMiniLiteral<TType> } & {\n\t\t[K in keyof TSlots]: TSlots[K] extends z.ZodMiniType ? z.ZodMiniPrefault<TSlots[K]> : never;\n\t},\n\tz.core.$strict\n>;\n\n/**\n * What a domain passes to `defineProtocolRecipeSpec`; the slot and kind names come from its protocol.\n *\n * @remarks\n * The slots come from `slotSchemas` alone: `slotDefaults` and `appearanceAxes` are checked\n * against them but take no part in inference, so a spec can add a slot to another spec's schemas\n * while reusing that spec's defaults.\n *\n * `slotSchemas` also maps every key outside the protocol's slots to `never`. The `TSlots` constraint\n * alone accepts extra properties, so without it a slot the protocol does not declare would compile.\n */\nexport interface ProtocolRecipeSpecDefinition<\n\tTSlot extends string,\n\tTKind extends string,\n\tTType extends string,\n\tTSlots extends ProtocolRecipeSlotSchemas<TSlot>,\n> {\n\t$type: TType;\n\tkind: NoInfer<TKind>;\n\tmetadata: RecipeMetadata;\n\tslotSchemas?: TSlots & { [K in Exclude<keyof TSlots, TSlot>]: never };\n\tslotDefaults?: RecipeSlotDefaults<NoInfer<TSlots>>;\n\tappearanceAxes?: SlotAppearanceAxes<keyof NoInfer<TSlots>>;\n}\n\n/**\n * @remarks\n * The shape is assembled dynamically from the same slot schemas that `RecipeViewSchema` maps over,\n * so the cast only restores the static type TypeScript cannot derive from a loop.\n */\nfunction mergeRecipeSlotSchemas<const TType extends string, const TSlots extends ProtocolRecipeSlotSchemas>(\n\t$type: TType,\n\tslotSchemas: TSlots,\n): RecipeViewSchema<TType, TSlots> {\n\tconst shape: Record<string, z.ZodMiniType> = {\n\t\t$type: z.literal($type),\n\t};\n\n\tfor (const [slot, schema] of Object.entries(slotSchemas)) {\n\t\tif (schema) {\n\t\t\tshape[slot] = z.prefault(schema, {});\n\t\t}\n\t}\n\n\treturn z.strictObject(shape) as unknown as RecipeViewSchema<TType, TSlots>;\n}\n\n/**\n * @remarks\n * Validation only: the parsed output is discarded. The defaults are merged under the author's\n * slot config before the view schema parses, so schema defaults still fill what they leave unset.\n */\nfunction assertSlotDefaults(\n\t$type: string,\n\tslotSchemas: ProtocolRecipeSlotSchemas,\n\tslotDefaults: Record<string, unknown> | undefined,\n): void {\n\tfor (const [slot, value] of Object.entries(slotDefaults ?? {})) {\n\t\tconst schema = slotSchemas[slot];\n\t\tif (!schema) {\n\t\t\tthrow new Error(`Recipe '${$type}' slotDefaults.${slot}: the recipe does not declare a '${slot}' slot.`);\n\t\t}\n\t\tconst result = z.safeParse(schema, value);\n\t\tif (!result.success) {\n\t\t\tconst problems = result.error.issues.map((issue) => {\n\t\t\t\tconst keys = [...issue.path, ...('keys' in issue && Array.isArray(issue.keys) ? issue.keys : [])];\n\t\t\t\treturn `${keys.join('.') || '(value)'}: ${issue.message}`;\n\t\t\t});\n\t\t\tthrow new Error(`Recipe '${$type}' slotDefaults.${slot} is invalid: ${problems.join('; ')}`);\n\t\t}\n\t}\n}\n\n/**\n * Validation only: a slot that declares appearance axes must exist and must accept the `appearance` key.\n */\nfunction assertAppearanceAxes(\n\t$type: string,\n\tslotSchemas: ProtocolRecipeSlotSchemas,\n\tappearanceAxes: SlotAppearanceAxes | undefined,\n): void {\n\tfor (const [slot, axes] of Object.entries(appearanceAxes ?? {})) {\n\t\tif (!axes) continue;\n\t\tconst schema = slotSchemas[slot];\n\t\tif (!schema) {\n\t\t\tthrow new Error(`Recipe '${$type}' appearanceAxes.${slot}: the recipe does not declare a '${slot}' slot.`);\n\t\t}\n\t\tconst result = z.safeParse(schema, { appearance: {} });\n\t\tconst rejectsKey = result.error?.issues.some(\n\t\t\t(issue) => issue.code === 'unrecognized_keys' && issue.keys.includes('appearance'),\n\t\t);\n\t\tif (rejectsKey) {\n\t\t\tthrow new Error(\n\t\t\t\t`Recipe '${$type}' appearanceAxes.${slot}: the '${slot}' slot schema must accept an 'appearance' key (z.optional(AppearanceConfigSchema)).`,\n\t\t\t);\n\t\t}\n\t}\n}\n\n/**\n * Declares a recipe's `$type`, kind, slot schemas, and metadata against a domain's protocol.\n *\n * @remarks\n * The protocol decides which slots and kinds exist, in the types and at runtime, and its rules run\n * here for an early failure. The spec lists its declared slots in the protocol's order.\n *\n * The rules run before the slots are listed, because listing filters the protocol's slots and would\n * otherwise drop a slot the protocol does not declare without a word.\n */\nexport function defineProtocolRecipeSpec<\n\tTSlot extends string,\n\tTKind extends string,\n\tconst TType extends string,\n\tconst TSlots extends ProtocolRecipeSlotSchemas<TSlot> = Record<never, never>,\n>(\n\tprotocol: RecipeProtocol<TSlot, TKind>,\n\tdefinition: ProtocolRecipeSpecDefinition<TSlot, TKind, TType, TSlots>,\n): ProtocolRecipeSpec<TSlot, TKind, TType, RecipeViewSchema<TType, TSlots>, TSlots> {\n\tconst slotSchemas = (definition.slotSchemas ?? {}) as TSlots;\n\tconst declared = Object.keys(slotSchemas).filter((slot) => slotSchemas[slot as TSlot]);\n\tassertRecipeRules(protocol, { $type: definition.$type, kind: definition.kind, slots: declared });\n\tconst slots = protocol.slots.filter((slot) => slotSchemas[slot]);\n\tassertSlotDefaults(definition.$type, slotSchemas, definition.slotDefaults);\n\tassertAppearanceAxes(definition.$type, slotSchemas, definition.appearanceAxes as SlotAppearanceAxes | undefined);\n\tconst schema = mergeRecipeSlotSchemas(definition.$type, slotSchemas);\n\treturn {\n\t\t$type: definition.$type,\n\t\tkind: definition.kind,\n\t\tslots,\n\t\tslotSchemas,\n\t\tslotDefaults: definition.slotDefaults,\n\t\tappearanceAxes: definition.appearanceAxes,\n\t\tmetadata: definition.metadata,\n\t\tschema,\n\t};\n}\n", "import { createRegistry, type BaseRegistration, type ReadOnlyRegistry } from '@schema-engine/registry';\n\n/** The part of a recipe that a protocol reads: its `$type`, kind and the slots it declares. */\nexport interface RecipeShape<TSlot extends string = string, TKind extends string = string> {\n\treadonly $type: string;\n\treadonly kind: TKind;\n\treadonly slots: readonly TSlot[];\n}\n\n/**\n * A named check a domain runs on every recipe of its protocol.\n *\n * @remarks\n * `check` returns the problem as a phrase that continues \"Recipe 'x' breaks rule 'name': \", or\n * `undefined` when the recipe passes. Rules read the declared kind and slots only. The slot and\n * kind vocabulary is checked before rules run, so a rule never sees a name outside the protocol.\n */\nexport interface RecipeRule<TSlot extends string = string, TKind extends string = string> {\n\treadonly name: string;\n\tcheck(recipe: RecipeShape<TSlot, TKind>): string | undefined;\n}\n\n/**\n * The slots, kinds and rules one domain gives its recipes.\n *\n * @remarks\n * `slots` is ordered: it is the order a spec lists its declared slots in, and the order a renderer\n * can compose them in.\n */\nexport interface RecipeProtocol<TSlot extends string = string, TKind extends string = string> {\n\treadonly slots: readonly TSlot[];\n\treadonly kinds: readonly TKind[];\n\treadonly rules: readonly RecipeRule<TSlot, TKind>[];\n}\n\nexport type SlotOf<TProtocol extends RecipeProtocol> = TProtocol extends RecipeProtocol<infer TSlot> ? TSlot : never;\n\nexport type KindOf<TProtocol extends RecipeProtocol> =\n\tTProtocol extends RecipeProtocol<string, infer TKind> ? TKind : never;\n\nfunction assertUnique(values: readonly string[], noun: 'slot' | 'kind'): void {\n\tif (values.length === 0) {\n\t\tthrow new Error(`A recipe protocol must declare at least one ${noun}.`);\n\t}\n\tconst seen = new Set<string>();\n\tfor (const value of values) {\n\t\tif (seen.has(value)) {\n\t\t\tthrow new Error(`A recipe protocol's ${noun} '${value}' is declared twice.`);\n\t\t}\n\t\tseen.add(value);\n\t}\n}\n\n/**\n * Declares the slots, kinds and rules of one domain's recipes, once.\n *\n * @param definition.slots - Slot names in composition order\n * @param definition.kinds - Kind names a recipe can take\n * @param definition.rules - Checks run on each recipe when a spec is defined and when a registry is built\n * @throws {Error} When no slot or kind is declared, or a name repeats\n */\nexport function defineRecipeProtocol<const TSlot extends string, const TKind extends string>(definition: {\n\tslots: readonly TSlot[];\n\tkinds: readonly TKind[];\n\trules?: readonly RecipeRule<NoInfer<TSlot>, NoInfer<TKind>>[];\n}): RecipeProtocol<TSlot, TKind> {\n\tassertUnique(definition.slots, 'slot');\n\tassertUnique(definition.kinds, 'kind');\n\treturn Object.freeze({\n\t\tslots: Object.freeze([...definition.slots]),\n\t\tkinds: Object.freeze([...definition.kinds]),\n\t\trules: Object.freeze([...(definition.rules ?? [])]),\n\t});\n}\n\n/**\n * Checks a recipe against its protocol: the kind and every slot must be declared, then each rule runs.\n *\n * @throws {Error} Naming the recipe, and the rule when one fails\n *\n * @remarks\n * Runs in `defineProtocolRecipeSpec` for an early failure and in {@link createRecipeRegistry} for each winning\n * registration, which also covers hand-written recipes whose schema is not a Zod schema.\n *\n * The vocabulary is checked before any rule runs, so the narrowing of the recipe to the protocol's\n * own slot and kind names, which the rules receive, holds.\n */\nexport function assertRecipeRules<TSlot extends string, TKind extends string>(\n\tprotocol: RecipeProtocol<TSlot, TKind>,\n\trecipe: RecipeShape,\n): void {\n\tconst kinds: readonly string[] = protocol.kinds;\n\tconst slots: readonly string[] = protocol.slots;\n\tif (!kinds.includes(recipe.kind)) {\n\t\tthrow new Error(\n\t\t\t`Recipe '${recipe.$type}' has kind '${recipe.kind}', which the protocol does not declare (kinds: ${protocol.kinds.join(', ')}).`,\n\t\t);\n\t}\n\tfor (const slot of recipe.slots) {\n\t\tif (!slots.includes(slot)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Recipe '${recipe.$type}' declares slot '${slot}', which the protocol does not declare (slots: ${protocol.slots.join(', ')}).`,\n\t\t\t);\n\t\t}\n\t}\n\tfor (const rule of protocol.rules) {\n\t\tconst problem = rule.check(recipe as RecipeShape<TSlot, TKind>);\n\t\tif (problem !== undefined) {\n\t\t\tthrow new Error(`Recipe '${recipe.$type}' breaks rule '${rule.name}': ${problem}.`);\n\t\t}\n\t}\n}\n\n/**\n * Builds the read-only `Recipe` registry of a domain, with its protocol rules run at build.\n *\n * @throws {Error} Naming the recipe when a winning registration breaks the protocol or has no Standard Schema\n *\n * @remarks\n * Only the winning registration of each `$type` is checked, the same as the registry's schema check: a\n * recipe overridden later in the list is skipped.\n */\nexport function createRecipeRegistry<\n\tTSlot extends string,\n\tTKind extends string,\n\tTRecipe extends BaseRegistration & RecipeShape<TSlot, TKind>,\n>(protocol: RecipeProtocol<TSlot, TKind>, recipes: readonly TRecipe[]): ReadOnlyRegistry<TRecipe> {\n\tconst registry = createRegistry('Recipe', recipes);\n\tfor (const recipe of registry.all()) {\n\t\tassertRecipeRules(protocol, recipe);\n\t}\n\treturn registry;\n}\n"],
|
|
5
|
-
"mappings": "
|
|
6
|
-
"names": ["
|
|
3
|
+
"sources": ["../../src/recipes/define-recipe-spec.ts", "../../src/recipes/protocol.ts", "../../src/recipes/resolve-recipe-view.ts"],
|
|
4
|
+
"sourcesContent": ["import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { formatIssuePath, safeParseStandardSchema, standardSchema } from '@schema-engine/registry';\nimport type { AppearanceAxisList, SlotAppearanceAxes } from '../lib/appearance';\nimport { assertRecipeRules, type RecipeProtocol } from './protocol';\nimport { unknownViewKeyMessage } from './resolve-recipe-view';\nimport type { RecipeMetadata, RecipeSlotDefaults, ProtocolRecipeSlotSchemas, ProtocolRecipeSpec } from './types';\n\ntype Flat<T> = { [K in keyof T]: T[K] };\n\n/** What an author writes for a view: the literal `$type`, every declared slot optional. */\ntype RecipeViewSchemaInput<TType extends string, TSlots extends ProtocolRecipeSlotSchemas> = Flat<\n\t{ $type: TType } & { -readonly [K in keyof TSlots]?: StandardSchemaV1.InferInput<NonNullable<TSlots[K]>> }\n>;\n\n/** A parsed view: every declared slot present, as its schema outputs it. */\ntype RecipeViewSchemaOutput<TType extends string, TSlots extends ProtocolRecipeSlotSchemas> = Flat<\n\t{ $type: TType } & { -readonly [K in keyof TSlots]-?: StandardSchemaV1.InferOutput<NonNullable<TSlots[K]>> }\n>;\n\n/**\n * Strict view schema of a spec: the literal `$type` plus each declared slot, which parses from `{}` when omitted.\n *\n * @remarks\n * A Standard Schema, not a schema of any one library, so slot schemas can come from any library. It validates\n * synchronously and so needs synchronous slot schemas: a slot that validates asynchronously throws where the view is\n * parsed. A slot is an optional key on input and always present on output, so each slot schema's own defaults fill\n * it. A key outside `$type` and the declared slots is an issue at `[key]`. The input and output types let the engine\n * infer the authoring type of `view` from a registration.\n */\nexport type RecipeViewSchema<TType extends string, TSlots extends ProtocolRecipeSlotSchemas> = StandardSchemaV1<\n\tRecipeViewSchemaInput<TType, TSlots>,\n\tRecipeViewSchemaOutput<TType, TSlots>\n>;\n\n/** The axes a spec may declare per slot: a slot whose schema input has no `appearance` key takes none. */\ntype SlotAppearanceAxesOf<TSlots extends ProtocolRecipeSlotSchemas> = {\n\t[K in keyof TSlots]?: 'appearance' extends keyof StandardSchemaV1.InferInput<NonNullable<TSlots[K]>>\n\t\t? AppearanceAxisList\n\t\t: never;\n};\n\n/**\n * What a domain passes to `defineProtocolRecipeSpec`; the slot and kind names come from its protocol.\n *\n * @remarks\n * The slots come from `slotSchemas` alone: `slotDefaults` and `appearanceAxes` are checked\n * against them but take no part in inference, so a spec can add a slot to another spec's schemas\n * while reusing that spec's defaults.\n *\n * `slotSchemas` also maps every key outside the protocol's slots to `never`. The `TSlots` constraint\n * alone accepts extra properties, so without it a slot the protocol does not declare would compile.\n *\n * `appearanceAxes` accepts only slots whose schema input has an `appearance` key, so a slot that cannot\n * be given a pick does not declare axes.\n */\nexport interface ProtocolRecipeSpecDefinition<\n\tTSlot extends string,\n\tTKind extends string,\n\tTType extends string,\n\tTSlots extends ProtocolRecipeSlotSchemas<TSlot>,\n> {\n\t$type: TType;\n\tkind: NoInfer<TKind>;\n\tmetadata: RecipeMetadata;\n\tslotSchemas?: TSlots & { [K in Exclude<keyof TSlots, TSlot>]: never };\n\tslotDefaults?: RecipeSlotDefaults<NoInfer<TSlots>>;\n\tappearanceAxes?: SlotAppearanceAxesOf<NoInfer<TSlots>>;\n}\n\n/**\n * @remarks\n * The output is assembled dynamically from the same slot schemas that `RecipeViewSchema` maps over,\n * so the cast only restores the static type TypeScript cannot derive from a loop. A slot an author omits\n * is validated as `{}`, as an object's own defaults would fill it.\n */\nfunction createRecipeViewSchema<const TType extends string, const TSlots extends ProtocolRecipeSlotSchemas>(\n\t$type: TType,\n\tslots: readonly string[],\n\tslotSchemas: TSlots,\n): RecipeViewSchema<TType, TSlots> {\n\treturn standardSchema<RecipeViewSchemaOutput<TType, TSlots>, RecipeViewSchemaInput<TType, TSlots>>((value) => {\n\t\tif (typeof value !== 'object' || value === null || Array.isArray(value)) {\n\t\t\treturn { issues: [{ message: 'Expected a view object.', path: [] }] };\n\t\t}\n\t\tconst view = value as Record<string, unknown>;\n\t\tconst issues: StandardSchemaV1.Issue[] = [];\n\t\tif (view.$type !== $type) {\n\t\t\tissues.push({ message: `Expected $type '${$type}'.`, path: ['$type'] });\n\t\t}\n\t\tfor (const key of Object.keys(view)) {\n\t\t\tif (key !== '$type' && !slots.includes(key)) {\n\t\t\t\tissues.push({ message: unknownViewKeyMessage($type, key, slots), path: [key] });\n\t\t\t}\n\t\t}\n\t\tconst output: Record<string, unknown> = { $type };\n\t\tfor (const slot of slots) {\n\t\t\tconst schema = slotSchemas[slot];\n\t\t\tif (!schema) continue;\n\t\t\tconst result = safeParseStandardSchema(schema, view[slot] === undefined ? {} : view[slot]);\n\t\t\tif (result.success) {\n\t\t\t\toutput[slot] = result.data;\n\t\t\t} else {\n\t\t\t\tissues.push(...result.error.issues.map((issue) => ({ ...issue, path: [slot, ...(issue.path ?? [])] })));\n\t\t\t}\n\t\t}\n\t\treturn issues.length > 0 ? { issues } : { value: output as RecipeViewSchemaOutput<TType, TSlots> };\n\t});\n}\n\n/**\n * One `<path>: <message>` line per location a slot schema issue points at, so a message names the offending key.\n *\n * @remarks\n * A Standard Schema issue carries a message and a path. A library may also report the offending `keys` of the object\n * at that path (Zod's unknown keys do, with the generic `Invalid input` when no locale is loaded), so each reported\n * key gets its own line at the key, the same place forms' validation points such an issue at. An empty path reads `(value)`.\n */\nfunction describeSlotIssue(issue: StandardSchemaV1.Issue): string[] {\n\tconst reported: unknown = (issue as StandardSchemaV1.Issue & { keys?: unknown }).keys;\n\tconst keys = Array.isArray(reported)\n\t\t? reported.filter((key): key is string | number => typeof key === 'string' || typeof key === 'number')\n\t\t: [];\n\tconst paths = keys.length > 0 ? keys.map((key) => [...(issue.path ?? []), key]) : [issue.path];\n\treturn paths.map((path) => `${formatIssuePath(path) || '(value)'}: ${issue.message}`);\n}\n\n/**\n * @remarks\n * Validation only: the parsed output is discarded. The defaults are merged under the author's\n * slot config before the view schema parses, so schema defaults still fill what they leave unset.\n */\nfunction assertSlotDefaults(\n\t$type: string,\n\tslotSchemas: ProtocolRecipeSlotSchemas,\n\tslotDefaults: Record<string, unknown> | undefined,\n): void {\n\tfor (const [slot, value] of Object.entries(slotDefaults ?? {})) {\n\t\tconst schema = slotSchemas[slot];\n\t\tif (!schema) {\n\t\t\tthrow new Error(`Recipe '${$type}' slotDefaults.${slot}: the recipe does not declare a '${slot}' slot.`);\n\t\t}\n\t\tconst result = safeParseStandardSchema(schema, value);\n\t\tif (!result.success) {\n\t\t\tconst problems = result.error.issues.flatMap(describeSlotIssue);\n\t\t\tthrow new Error(`Recipe '${$type}' slotDefaults.${slot} is invalid: ${problems.join('; ')}`);\n\t\t}\n\t}\n}\n\n/**\n * Validation only: a slot that declares appearance axes must exist.\n *\n * @remarks\n * That the slot schema accepts an `appearance` key is a type constraint on\n * {@link ProtocolRecipeSpecDefinition.appearanceAxes}, not a runtime probe: Standard Schema reports no issue codes\n * to find a rejected key with, and validation removes `appearance` before the slot schema parses.\n */\nfunction assertAppearanceSlots(\n\t$type: string,\n\tslotSchemas: ProtocolRecipeSlotSchemas,\n\tappearanceAxes: SlotAppearanceAxes | undefined,\n): void {\n\tfor (const [slot, axes] of Object.entries(appearanceAxes ?? {})) {\n\t\tif (axes && !slotSchemas[slot]) {\n\t\t\tthrow new Error(`Recipe '${$type}' appearanceAxes.${slot}: the recipe does not declare a '${slot}' slot.`);\n\t\t}\n\t}\n}\n\n/**\n * Declares a recipe's `$type`, kind, slot schemas, and metadata against a domain's protocol.\n *\n * @remarks\n * The protocol decides which slots and kinds exist, in the types and at runtime, and its rules run\n * here for an early failure. The spec lists its declared slots in the protocol's order.\n *\n * The rules run before the slots are listed, because listing filters the protocol's slots and would\n * otherwise drop a slot the protocol does not declare without a word.\n *\n * A slot schema is any Standard Schema that validates synchronously. A spec that leaves out `slotSchemas` declares\n * no slots, so `TSlots` defaults to the empty object type.\n */\nexport function defineProtocolRecipeSpec<\n\tTSlot extends string,\n\tTKind extends string,\n\tconst TType extends string,\n\tconst TSlots extends ProtocolRecipeSlotSchemas<TSlot> = {},\n>(\n\tprotocol: RecipeProtocol<TSlot, TKind>,\n\tdefinition: ProtocolRecipeSpecDefinition<TSlot, TKind, TType, TSlots>,\n): ProtocolRecipeSpec<TSlot, TKind, TType, RecipeViewSchema<TType, TSlots>, TSlots> {\n\tconst slotSchemas = (definition.slotSchemas ?? {}) as TSlots;\n\tconst declared = Object.keys(slotSchemas).filter((slot) => slotSchemas[slot as TSlot]);\n\tassertRecipeRules(protocol, { $type: definition.$type, kind: definition.kind, slots: declared });\n\tconst slots = protocol.slots.filter((slot) => slotSchemas[slot]);\n\tassertSlotDefaults(definition.$type, slotSchemas, definition.slotDefaults);\n\tassertAppearanceSlots(definition.$type, slotSchemas, definition.appearanceAxes as SlotAppearanceAxes | undefined);\n\tconst schema = createRecipeViewSchema(definition.$type, slots, slotSchemas);\n\treturn {\n\t\t$type: definition.$type,\n\t\tkind: definition.kind,\n\t\tslots,\n\t\tslotSchemas,\n\t\tslotDefaults: definition.slotDefaults,\n\t\tappearanceAxes: definition.appearanceAxes,\n\t\tmetadata: definition.metadata,\n\t\tschema,\n\t};\n}\n", "import {\n\tassertStandardSchema,\n\tcreateRegistry,\n\ttype BaseRegistration,\n\ttype ReadOnlyRegistry,\n} from '@schema-engine/registry';\n\n/** The part of a recipe that a protocol reads: its `$type`, kind and the slots it declares. */\nexport interface RecipeShape<TSlot extends string = string, TKind extends string = string> {\n\treadonly $type: string;\n\treadonly kind: TKind;\n\treadonly slots: readonly TSlot[];\n}\n\n/**\n * A named check a domain runs on every recipe of its protocol.\n *\n * @remarks\n * `check` returns the problem as a phrase that continues \"Recipe 'x' breaks rule 'name': \", or\n * `undefined` when the recipe passes. Rules read the declared kind and slots only. The slot and\n * kind vocabulary is checked before rules run, so a rule never sees a name outside the protocol.\n */\nexport interface RecipeRule<TSlot extends string = string, TKind extends string = string> {\n\treadonly name: string;\n\tcheck(recipe: RecipeShape<TSlot, TKind>): string | undefined;\n}\n\n/**\n * The slots, kinds and rules one domain gives its recipes.\n *\n * @remarks\n * `slots` is ordered: it is the order a spec lists its declared slots in, and the order a renderer\n * can compose them in.\n */\nexport interface RecipeProtocol<TSlot extends string = string, TKind extends string = string> {\n\treadonly slots: readonly TSlot[];\n\treadonly kinds: readonly TKind[];\n\treadonly rules: readonly RecipeRule<TSlot, TKind>[];\n}\n\nexport type SlotOf<TProtocol extends RecipeProtocol> = TProtocol extends RecipeProtocol<infer TSlot> ? TSlot : never;\n\nexport type KindOf<TProtocol extends RecipeProtocol> =\n\tTProtocol extends RecipeProtocol<string, infer TKind> ? TKind : never;\n\nfunction assertUnique(values: readonly string[], noun: 'slot' | 'kind'): void {\n\tif (values.length === 0) {\n\t\tthrow new Error(`A recipe protocol must declare at least one ${noun}.`);\n\t}\n\tconst seen = new Set<string>();\n\tfor (const value of values) {\n\t\tif (seen.has(value)) {\n\t\t\tthrow new Error(`A recipe protocol's ${noun} '${value}' is declared twice.`);\n\t\t}\n\t\tseen.add(value);\n\t}\n}\n\n/**\n * Declares the slots, kinds and rules of one domain's recipes, once.\n *\n * @param definition.slots - Slot names in composition order\n * @param definition.kinds - Kind names a recipe can take\n * @param definition.rules - Checks run on each recipe when a spec is defined and when a registry is built\n * @throws {Error} When no slot or kind is declared, or a name repeats\n */\nexport function defineRecipeProtocol<const TSlot extends string, const TKind extends string>(definition: {\n\tslots: readonly TSlot[];\n\tkinds: readonly TKind[];\n\trules?: readonly RecipeRule<NoInfer<TSlot>, NoInfer<TKind>>[];\n}): RecipeProtocol<TSlot, TKind> {\n\tassertUnique(definition.slots, 'slot');\n\tassertUnique(definition.kinds, 'kind');\n\treturn Object.freeze({\n\t\tslots: Object.freeze([...definition.slots]),\n\t\tkinds: Object.freeze([...definition.kinds]),\n\t\trules: Object.freeze([...(definition.rules ?? [])]),\n\t});\n}\n\n/**\n * Checks a recipe against its protocol: the kind and every slot must be declared, then each rule runs.\n *\n * @throws {Error} Naming the recipe, and the rule when one fails\n *\n * @remarks\n * Runs in `defineProtocolRecipeSpec` for an early failure and in {@link createRecipeRegistry} for each winning\n * registration, which also covers hand-written recipes whose schema is not a Zod schema.\n *\n * The vocabulary is checked before any rule runs, so the narrowing of the recipe to the protocol's\n * own slot and kind names, which the rules receive, holds.\n */\nexport function assertRecipeRules<TSlot extends string, TKind extends string>(\n\tprotocol: RecipeProtocol<TSlot, TKind>,\n\trecipe: RecipeShape,\n): void {\n\tconst kinds: readonly string[] = protocol.kinds;\n\tconst slots: readonly string[] = protocol.slots;\n\tif (!kinds.includes(recipe.kind)) {\n\t\tthrow new Error(\n\t\t\t`Recipe '${recipe.$type}' has kind '${recipe.kind}', which the protocol does not declare (kinds: ${protocol.kinds.join(', ')}).`,\n\t\t);\n\t}\n\tfor (const slot of recipe.slots) {\n\t\tif (!slots.includes(slot)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Recipe '${recipe.$type}' declares slot '${slot}', which the protocol does not declare (slots: ${protocol.slots.join(', ')}).`,\n\t\t\t);\n\t\t}\n\t}\n\tfor (const rule of protocol.rules) {\n\t\tconst problem = rule.check(recipe as RecipeShape<TSlot, TKind>);\n\t\tif (problem !== undefined) {\n\t\t\tthrow new Error(`Recipe '${recipe.$type}' breaks rule '${rule.name}': ${problem}.`);\n\t\t}\n\t}\n}\n\n/**\n * Checks that the slot schemas a registration carries are exactly its declared slots, each a Standard Schema.\n *\n * @throws {Error} Naming the recipe, its kind and `$type`\n *\n * @remarks\n * A registration without `slotSchemas` passes: a hand-written one need not state them.\n */\nfunction assertSlotSchemas(\n\tkind: string,\n\trecipe: RecipeShape & { readonly slotSchemas?: Readonly<Partial<Record<string, unknown>>> },\n): void {\n\tconst { slotSchemas } = recipe;\n\tif (slotSchemas === undefined) return;\n\tconst context = `${kind} '${recipe.$type}' slotSchemas`;\n\tconst listed = Object.keys(slotSchemas).filter((slot) => slotSchemas[slot] !== undefined);\n\tconst missing = recipe.slots.filter((slot) => !listed.includes(slot));\n\tconst extra = listed.filter((slot) => !recipe.slots.includes(slot));\n\tif (missing.length > 0 || extra.length > 0) {\n\t\tthrow new Error(\n\t\t\t`${context} must list exactly the recipe's slots (${recipe.slots.join(', ') || 'none'}): ${[\n\t\t\t\t...missing.map((slot) => `'${slot}' has no schema`),\n\t\t\t\t...extra.map((slot) => `'${slot}' is not a declared slot`),\n\t\t\t].join(', ')}.`,\n\t\t);\n\t}\n\tfor (const slot of listed) {\n\t\tassertStandardSchema(slotSchemas[slot], `${context}.${slot}`);\n\t}\n}\n\n/**\n * Builds the read-only `Recipe` registry of a domain, with its protocol rules run at build.\n *\n * @throws {Error} Naming the recipe when a winning registration breaks the protocol, has no Standard Schema, or\n * carries `slotSchemas` that differ from its slots or are not Standard Schemas\n *\n * @remarks\n * Only the winning registration of each `$type` is checked, the same as the registry's schema check: a\n * recipe overridden later in the list is skipped.\n */\nexport function createRecipeRegistry<\n\tTSlot extends string,\n\tTKind extends string,\n\tTRecipe extends BaseRegistration &\n\t\tRecipeShape<TSlot, TKind> & { readonly slotSchemas?: Readonly<Partial<Record<string, unknown>>> },\n>(protocol: RecipeProtocol<TSlot, TKind>, recipes: readonly TRecipe[]): ReadOnlyRegistry<TRecipe> {\n\tconst registry = createRegistry('Recipe', recipes);\n\tfor (const recipe of registry.all()) {\n\t\tassertRecipeRules(protocol, recipe);\n\t\tassertSlotSchemas(registry.kind, recipe);\n\t}\n\treturn registry;\n}\n", "import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { safeParseStandardSchema } from '@schema-engine/registry';\nimport { checkAppearance, mergeAppearance, pickSupportedAppearance, type SlotAppearanceAxes } from '../lib/appearance';\nimport type { LayoutIssue } from '../lib/layout-issue';\nimport type { LayoutTheme } from '../lib/layout-theme';\nimport { mergeSlotDefaults } from './merge-slot-defaults';\n\n/** Appearance picks a view inherits: the theme's vocabulary, and what the containing document picked. */\nexport interface RecipeViewScope {\n\treadonly axes: LayoutTheme['axes'];\n\treadonly inherited: Readonly<Record<string, string>>;\n}\n\n/** The part of a recipe registration that resolving a view reads. */\nexport interface RecipeViewSource {\n\treadonly $type: string;\n\treadonly slots: readonly string[];\n\treadonly schema: StandardSchemaV1;\n\treadonly slotDefaults?: Readonly<Record<string, unknown>>;\n\treadonly appearanceAxes?: SlotAppearanceAxes;\n}\n\n/** An authored view: the recipe's `$type` and the config of its slots. */\nexport type RecipeViewInput = Readonly<Record<string, unknown>> & { readonly $type: string };\n\n/**\n * What {@link resolveRecipeView} found.\n *\n * @remarks\n * `view` is present when the schema parsed and kept its `$type`; it can still come with `issues`\n * (an appearance pick that is not valid, or a key the recipe does not declare). `schemaIssues` is\n * present, with no `view`, when the schema rejected the view: the caller formats them, since only\n * the domain knows how it reports a schema's issues.\n */\nexport interface ResolvedRecipeView {\n\t/** One issue per problem, with a path relative to the view (`[slot, 'appearance', axis]`, `[key]`). */\n\tissues: LayoutIssue[];\n\tview?: Record<string, unknown>;\n\tschemaIssues?: StandardSchemaV1.Issue[];\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n\tif (typeof value !== 'object' || value === null) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\nfunction withoutAppearance(config: Record<string, unknown>): Record<string, unknown> {\n\tif (!('appearance' in config)) return config;\n\tconst { appearance: _authored, ...rest } = config;\n\treturn rest;\n}\n\n/** The issue message for a view key that the recipe does not declare, shared by the view schema and {@link resolveRecipeView}. */\nexport function unknownViewKeyMessage($type: string, key: string, allowed: readonly string[]): string {\n\treturn `Recipe '${$type}' does not accept view key '${key}'. Allowed: ${allowed.join(', ') || '(none)'}.`;\n}\n\n/**\n * Resolves the view a document selects for a recipe: the recipe defaults laid under the author's\n * slot config, each slot's appearance, the schema parse, and the keys the recipe does not declare.\n *\n * @param recipe - The winning registration the view's `$type` selects\n * @param view - The authored view; not changed\n * @param scope - The picks the view inherits from its document\n *\n * @remarks\n * Slot appearance follows the recipe's inheritance rule: the document's picks reach a slot for the\n * axes the recipe declares on it, and the slot's own pick wins. The authored `appearance` key is\n * removed before the slot schema parses, so a schema only has to type it, and the resolved\n * selection is written back on the slot when it is not empty. Domain rules that need the document\n * (a kind that wants one step, a default recipe) stay with the domain's validator.\n */\nexport function resolveRecipeView(\n\trecipe: RecipeViewSource,\n\tview: RecipeViewInput,\n\tscope: RecipeViewScope,\n): ResolvedRecipeView {\n\tconst issues: LayoutIssue[] = [];\n\tconst stripped: Record<string, unknown> = { ...view };\n\tconst resolved: Record<string, Record<string, string>> = {};\n\tfor (const slot of recipe.slots) {\n\t\tconst authoredSlot = view[slot];\n\t\tconst supported = recipe.appearanceAxes?.[slot] ?? [];\n\t\tconst checked = checkAppearance(isPlainRecord(authoredSlot) ? authoredSlot.appearance : undefined, {\n\t\t\taxes: scope.axes,\n\t\t\tsubject: `Slot '${slot}' of recipe '${recipe.$type}'`,\n\t\t\tsupported,\n\t\t});\n\t\tissues.push(...checked.issues.map((issue) => ({ ...issue, path: [slot, ...issue.path] })));\n\t\tconst selection = pickSupportedAppearance(mergeAppearance(scope.inherited, checked.appearance), supported);\n\t\tif (Object.keys(selection).length > 0) resolved[slot] = selection;\n\t\tif (isPlainRecord(authoredSlot)) stripped[slot] = withoutAppearance(authoredSlot);\n\t}\n\n\tconst parsed = safeParseStandardSchema(recipe.schema, mergeSlotDefaults(stripped, recipe.slotDefaults));\n\tif (!parsed.success) return { issues, schemaIssues: parsed.error.issues };\n\tconst output = parsed.data;\n\tif (typeof output !== 'object' || output === null || !('$type' in output) || typeof output.$type !== 'string') {\n\t\tissues.push({\n\t\t\tpath: ['$type'],\n\t\t\tmessage: `Invalid view configuration for recipe '${recipe.$type}': parsed output is missing $type.`,\n\t\t});\n\t\treturn { issues };\n\t}\n\n\tconst allowedSlots = new Set<string>(recipe.slots);\n\tfor (const key of Object.keys(view)) {\n\t\tif (key !== '$type' && !allowedSlots.has(key)) {\n\t\t\tissues.push({ path: [key], message: unknownViewKeyMessage(recipe.$type, key, recipe.slots) });\n\t\t}\n\t}\n\n\tconst next: Record<string, unknown> = { ...output };\n\tfor (const [slot, selection] of Object.entries(resolved)) {\n\t\tconst slotConfig = (output as Record<string, unknown>)[slot];\n\t\tif (isPlainRecord(slotConfig)) next[slot] = { ...slotConfig, appearance: selection };\n\t}\n\treturn { issues, view: next };\n}\n"],
|
|
5
|
+
"mappings": "AACA,OAAS,mBAAAA,EAAiB,2BAAAC,EAAyB,kBAAAC,MAAsB,0BCDzE,OACC,wBAAAC,EACA,kBAAAC,MAGM,0BAuFA,SAASC,EACfC,EACAC,EACO,CACP,IAAMC,EAA2BF,EAAS,MACpCG,EAA2BH,EAAS,MAC1C,GAAI,CAACE,EAAM,SAASD,EAAO,IAAI,EAC9B,MAAM,IAAI,MACT,WAAWA,EAAO,KAAK,eAAeA,EAAO,IAAI,kDAAkDD,EAAS,MAAM,KAAK,IAAI,CAAC,IAC7H,EAED,QAAWI,KAAQH,EAAO,MACzB,GAAI,CAACE,EAAM,SAASC,CAAI,EACvB,MAAM,IAAI,MACT,WAAWH,EAAO,KAAK,oBAAoBG,CAAI,kDAAkDJ,EAAS,MAAM,K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V,CAAK,oBAAoBU,CAAI,oCAAoCA,CAAI,SAAS,CAG5G,CAeO,SAASgB,EAMfC,EACAC,EACmF,CACnF,IAAM1B,EAAe0B,EAAW,aAAe,CAAC,EAC1CC,EAAW,OAAO,KAAK3B,CAAW,EAAE,OAAQQ,GAASR,EAAYQ,CAAa,CAAC,EACrFoB,EAAkBH,EAAU,CAAE,MAAOC,EAAW,MAAO,KAAMA,EAAW,KAAM,MAAOC,CAAS,CAAC,EAC/F,IAAM5B,EAAQ0B,EAAS,MAAM,OAAQjB,GAASR,EAAYQ,CAAI,CAAC,EAC/DU,EAAmBQ,EAAW,MAAO1B,EAAa0B,EAAW,YAAY,EACzEL,EAAsBK,EAAW,MAAO1B,EAAa0B,EAAW,cAAgD,EAChH,IAAMjB,EAASZ,EAAuB6B,EAAW,MAAO3B,EAAOC,CAAW,EAC1E,MAAO,CACN,MAAO0B,EAAW,MAClB,KAAMA,EAAW,KACjB,MAAA3B,EACA,YAAAC,EACA,aAAc0B,EAAW,aACzB,eAAgBA,EAAW,eAC3B,SAAUA,EAAW,SACrB,OAAAjB,CACD,CACD",
|
|
6
|
+
"names": ["formatIssuePath", "safeParseStandardSchema", "standardSchema", "assertStandardSchema", "createRegistry", "assertRecipeRules", "protocol", "recipe", "kinds", "slots", "slot", "rule", "problem", "safeParseStandardSchema", "unknownViewKeyMessage", "$type", "key", "allowed", "createRecipeViewSchema", "$type", "slots", "slotSchemas", "standardSchema", "value", "view", "issues", "key", "unknownViewKeyMessage", "output", "slot", "schema", "result", "safeParseStandardSchema", "issue", "describeSlotIssue", "reported", "keys", "path", "formatIssuePath", "assertSlotDefaults", "slotDefaults", "problems", "assertAppearanceSlots", "appearanceAxes", "axes", "defineProtocolRecipeSpec", "protocol", "definition", "declared", "assertRecipeRules"]
|
|
7
7
|
}
|
|
@@ -60,10 +60,13 @@ export declare function assertRecipeRules<TSlot extends string, TKind extends st
|
|
|
60
60
|
/**
|
|
61
61
|
* Builds the read-only `Recipe` registry of a domain, with its protocol rules run at build.
|
|
62
62
|
*
|
|
63
|
-
* @throws {Error} Naming the recipe when a winning registration breaks the protocol
|
|
63
|
+
* @throws {Error} Naming the recipe when a winning registration breaks the protocol, has no Standard Schema, or
|
|
64
|
+
* carries `slotSchemas` that differ from its slots or are not Standard Schemas
|
|
64
65
|
*
|
|
65
66
|
* @remarks
|
|
66
67
|
* Only the winning registration of each `$type` is checked, the same as the registry's schema check: a
|
|
67
68
|
* recipe overridden later in the list is skipped.
|
|
68
69
|
*/
|
|
69
|
-
export declare function createRecipeRegistry<TSlot extends string, TKind extends string, TRecipe extends BaseRegistration & RecipeShape<TSlot, TKind
|
|
70
|
+
export declare function createRecipeRegistry<TSlot extends string, TKind extends string, TRecipe extends BaseRegistration & RecipeShape<TSlot, TKind> & {
|
|
71
|
+
readonly slotSchemas?: Readonly<Partial<Record<string, unknown>>>;
|
|
72
|
+
}>(protocol: RecipeProtocol<TSlot, TKind>, recipes: readonly TRecipe[]): ReadOnlyRegistry<TRecipe>;
|
package/dist/recipes/protocol.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRegistry as
|
|
1
|
+
import{assertStandardSchema as c,createRegistry as a}from"@schema-engine/registry";function d(e,t){if(e.length===0)throw new Error(`A recipe protocol must declare at least one ${t}.`);let n=new Set;for(let s of e){if(n.has(s))throw new Error(`A recipe protocol's ${t} '${s}' is declared twice.`);n.add(s)}}function f(e){return d(e.slots,"slot"),d(e.kinds,"kind"),Object.freeze({slots:Object.freeze([...e.slots]),kinds:Object.freeze([...e.kinds]),rules:Object.freeze([...e.rules??[]])})}function p(e,t){let n=e.kinds,s=e.slots;if(!n.includes(t.kind))throw new Error(`Recipe '${t.$type}' has kind '${t.kind}', which the protocol does not declare (kinds: ${e.kinds.join(", ")}).`);for(let r of t.slots)if(!s.includes(r))throw new Error(`Recipe '${t.$type}' declares slot '${r}', which the protocol does not declare (slots: ${e.slots.join(", ")}).`);for(let r of e.rules){let i=r.check(t);if(i!==void 0)throw new Error(`Recipe '${t.$type}' breaks rule '${r.name}': ${i}.`)}}function T(e,t){let{slotSchemas:n}=t;if(n===void 0)return;let s=`${e} '${t.$type}' slotSchemas`,r=Object.keys(n).filter(o=>n[o]!==void 0),i=t.slots.filter(o=>!r.includes(o)),l=r.filter(o=>!t.slots.includes(o));if(i.length>0||l.length>0)throw new Error(`${s} must list exactly the recipe's slots (${t.slots.join(", ")||"none"}): ${[...i.map(o=>`'${o}' has no schema`),...l.map(o=>`'${o}' is not a declared slot`)].join(", ")}.`);for(let o of r)c(n[o],`${s}.${o}`)}function g(e,t){let n=a("Recipe",t);for(let s of n.all())p(e,s),T(n.kind,s);return n}export{p as assertRecipeRules,g as createRecipeRegistry,f as defineRecipeProtocol};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/recipes/protocol.ts"],
|
|
4
|
-
"sourcesContent": ["import {
|
|
5
|
-
"mappings": "AAAA,
|
|
6
|
-
"names": ["createRegistry", "assertUnique", "values", "noun", "seen", "value", "defineRecipeProtocol", "definition", "assertRecipeRules", "protocol", "recipe", "kinds", "slots", "slot", "rule", "problem", "createRecipeRegistry", "recipes", "registry"]
|
|
4
|
+
"sourcesContent": ["import {\n\tassertStandardSchema,\n\tcreateRegistry,\n\ttype BaseRegistration,\n\ttype ReadOnlyRegistry,\n} from '@schema-engine/registry';\n\n/** The part of a recipe that a protocol reads: its `$type`, kind and the slots it declares. */\nexport interface RecipeShape<TSlot extends string = string, TKind extends string = string> {\n\treadonly $type: string;\n\treadonly kind: TKind;\n\treadonly slots: readonly TSlot[];\n}\n\n/**\n * A named check a domain runs on every recipe of its protocol.\n *\n * @remarks\n * `check` returns the problem as a phrase that continues \"Recipe 'x' breaks rule 'name': \", or\n * `undefined` when the recipe passes. Rules read the declared kind and slots only. The slot and\n * kind vocabulary is checked before rules run, so a rule never sees a name outside the protocol.\n */\nexport interface RecipeRule<TSlot extends string = string, TKind extends string = string> {\n\treadonly name: string;\n\tcheck(recipe: RecipeShape<TSlot, TKind>): string | undefined;\n}\n\n/**\n * The slots, kinds and rules one domain gives its recipes.\n *\n * @remarks\n * `slots` is ordered: it is the order a spec lists its declared slots in, and the order a renderer\n * can compose them in.\n */\nexport interface RecipeProtocol<TSlot extends string = string, TKind extends string = string> {\n\treadonly slots: readonly TSlot[];\n\treadonly kinds: readonly TKind[];\n\treadonly rules: readonly RecipeRule<TSlot, TKind>[];\n}\n\nexport type SlotOf<TProtocol extends RecipeProtocol> = TProtocol extends RecipeProtocol<infer TSlot> ? TSlot : never;\n\nexport type KindOf<TProtocol extends RecipeProtocol> =\n\tTProtocol extends RecipeProtocol<string, infer TKind> ? TKind : never;\n\nfunction assertUnique(values: readonly string[], noun: 'slot' | 'kind'): void {\n\tif (values.length === 0) {\n\t\tthrow new Error(`A recipe protocol must declare at least one ${noun}.`);\n\t}\n\tconst seen = new Set<string>();\n\tfor (const value of values) {\n\t\tif (seen.has(value)) {\n\t\t\tthrow new Error(`A recipe protocol's ${noun} '${value}' is declared twice.`);\n\t\t}\n\t\tseen.add(value);\n\t}\n}\n\n/**\n * Declares the slots, kinds and rules of one domain's recipes, once.\n *\n * @param definition.slots - Slot names in composition order\n * @param definition.kinds - Kind names a recipe can take\n * @param definition.rules - Checks run on each recipe when a spec is defined and when a registry is built\n * @throws {Error} When no slot or kind is declared, or a name repeats\n */\nexport function defineRecipeProtocol<const TSlot extends string, const TKind extends string>(definition: {\n\tslots: readonly TSlot[];\n\tkinds: readonly TKind[];\n\trules?: readonly RecipeRule<NoInfer<TSlot>, NoInfer<TKind>>[];\n}): RecipeProtocol<TSlot, TKind> {\n\tassertUnique(definition.slots, 'slot');\n\tassertUnique(definition.kinds, 'kind');\n\treturn Object.freeze({\n\t\tslots: Object.freeze([...definition.slots]),\n\t\tkinds: Object.freeze([...definition.kinds]),\n\t\trules: Object.freeze([...(definition.rules ?? [])]),\n\t});\n}\n\n/**\n * Checks a recipe against its protocol: the kind and every slot must be declared, then each rule runs.\n *\n * @throws {Error} Naming the recipe, and the rule when one fails\n *\n * @remarks\n * Runs in `defineProtocolRecipeSpec` for an early failure and in {@link createRecipeRegistry} for each winning\n * registration, which also covers hand-written recipes whose schema is not a Zod schema.\n *\n * The vocabulary is checked before any rule runs, so the narrowing of the recipe to the protocol's\n * own slot and kind names, which the rules receive, holds.\n */\nexport function assertRecipeRules<TSlot extends string, TKind extends string>(\n\tprotocol: RecipeProtocol<TSlot, TKind>,\n\trecipe: RecipeShape,\n): void {\n\tconst kinds: readonly string[] = protocol.kinds;\n\tconst slots: readonly string[] = protocol.slots;\n\tif (!kinds.includes(recipe.kind)) {\n\t\tthrow new Error(\n\t\t\t`Recipe '${recipe.$type}' has kind '${recipe.kind}', which the protocol does not declare (kinds: ${protocol.kinds.join(', ')}).`,\n\t\t);\n\t}\n\tfor (const slot of recipe.slots) {\n\t\tif (!slots.includes(slot)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Recipe '${recipe.$type}' declares slot '${slot}', which the protocol does not declare (slots: ${protocol.slots.join(', ')}).`,\n\t\t\t);\n\t\t}\n\t}\n\tfor (const rule of protocol.rules) {\n\t\tconst problem = rule.check(recipe as RecipeShape<TSlot, TKind>);\n\t\tif (problem !== undefined) {\n\t\t\tthrow new Error(`Recipe '${recipe.$type}' breaks rule '${rule.name}': ${problem}.`);\n\t\t}\n\t}\n}\n\n/**\n * Checks that the slot schemas a registration carries are exactly its declared slots, each a Standard Schema.\n *\n * @throws {Error} Naming the recipe, its kind and `$type`\n *\n * @remarks\n * A registration without `slotSchemas` passes: a hand-written one need not state them.\n */\nfunction assertSlotSchemas(\n\tkind: string,\n\trecipe: RecipeShape & { readonly slotSchemas?: Readonly<Partial<Record<string, unknown>>> },\n): void {\n\tconst { slotSchemas } = recipe;\n\tif (slotSchemas === undefined) return;\n\tconst context = `${kind} '${recipe.$type}' slotSchemas`;\n\tconst listed = Object.keys(slotSchemas).filter((slot) => slotSchemas[slot] !== undefined);\n\tconst missing = recipe.slots.filter((slot) => !listed.includes(slot));\n\tconst extra = listed.filter((slot) => !recipe.slots.includes(slot));\n\tif (missing.length > 0 || extra.length > 0) {\n\t\tthrow new Error(\n\t\t\t`${context} must list exactly the recipe's slots (${recipe.slots.join(', ') || 'none'}): ${[\n\t\t\t\t...missing.map((slot) => `'${slot}' has no schema`),\n\t\t\t\t...extra.map((slot) => `'${slot}' is not a declared slot`),\n\t\t\t].join(', ')}.`,\n\t\t);\n\t}\n\tfor (const slot of listed) {\n\t\tassertStandardSchema(slotSchemas[slot], `${context}.${slot}`);\n\t}\n}\n\n/**\n * Builds the read-only `Recipe` registry of a domain, with its protocol rules run at build.\n *\n * @throws {Error} Naming the recipe when a winning registration breaks the protocol, has no Standard Schema, or\n * carries `slotSchemas` that differ from its slots or are not Standard Schemas\n *\n * @remarks\n * Only the winning registration of each `$type` is checked, the same as the registry's schema check: a\n * recipe overridden later in the list is skipped.\n */\nexport function createRecipeRegistry<\n\tTSlot extends string,\n\tTKind extends string,\n\tTRecipe extends BaseRegistration &\n\t\tRecipeShape<TSlot, TKind> & { readonly slotSchemas?: Readonly<Partial<Record<string, unknown>>> },\n>(protocol: RecipeProtocol<TSlot, TKind>, recipes: readonly TRecipe[]): ReadOnlyRegistry<TRecipe> {\n\tconst registry = createRegistry('Recipe', recipes);\n\tfor (const recipe of registry.all()) {\n\t\tassertRecipeRules(protocol, recipe);\n\t\tassertSlotSchemas(registry.kind, recipe);\n\t}\n\treturn registry;\n}\n"],
|
|
5
|
+
"mappings": "AAAA,OACC,wBAAAA,EACA,kBAAAC,MAGM,0BAwCP,SAASC,EAAaC,EAA2BC,EAA6B,CAC7E,GAAID,EAAO,SAAW,EACrB,MAAM,IAAI,MAAM,+CAA+CC,CAAI,GAAG,EAEvE,IAAMC,EAAO,IAAI,IACjB,QAAWC,KAASH,EAAQ,CAC3B,GAAIE,EAAK,IAAIC,CAAK,EACjB,MAAM,IAAI,MAAM,uBAAuBF,CAAI,KAAKE,CAAK,s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CAAI,CAAC,EAC9DS,EAAQF,EAAO,OAAQP,GAAS,CAACH,EAAO,MAAM,SAASG,CAAI,CAAC,EAClE,GAAIQ,EAAQ,OAAS,GAAKC,EAAM,OAAS,EACxC,MAAM,IAAI,MACT,GAAGH,CAAO,0CAA0CT,EAAO,MAAM,KAAK,IAAI,GAAK,MAAM,MAAM,CAC1F,GAAGW,EAAQ,IAAKR,GAAS,IAAIA,CAAI,iBAAiB,EAClD,GAAGS,EAAM,IAAKT,GAAS,IAAIA,CAAI,0BAA0B,CAC1D,EAAE,KAAK,IAAI,CAAC,GACb,EAED,QAAWA,KAAQO,EAClBrB,EAAqBmB,EAAYL,CAAI,EAAG,GAAGM,CAAO,IAAIN,CAAI,EAAE,CAE9D,CAYO,SAASU,EAKdd,EAAwCe,EAAwD,CACjG,IAAMC,EAAWzB,EAAe,SAAUwB,CAAO,EACjD,QAAWd,KAAUe,EAAS,IAAI,EACjCjB,EAAkBC,EAAUC,CAAM,EAClCM,EAAkBS,EAAS,KAAMf,CAAM,EAExC,OAAOe,CACR",
|
|
6
|
+
"names": ["assertStandardSchema", "createRegistry", "assertUnique", "values", "noun", "seen", "value", "defineRecipeProtocol", "definition", "assertRecipeRules", "protocol", "recipe", "kinds", "slots", "slot", "rule", "problem", "assertSlotSchemas", "kind", "slotSchemas", "context", "listed", "missing", "extra", "createRecipeRegistry", "recipes", "registry"]
|
|
7
7
|
}
|
|
@@ -34,6 +34,8 @@ export interface ResolvedRecipeView {
|
|
|
34
34
|
view?: Record<string, unknown>;
|
|
35
35
|
schemaIssues?: StandardSchemaV1.Issue[];
|
|
36
36
|
}
|
|
37
|
+
/** The issue message for a view key that the recipe does not declare, shared by the view schema and {@link resolveRecipeView}. */
|
|
38
|
+
export declare function unknownViewKeyMessage($type: string, key: string, allowed: readonly string[]): string;
|
|
37
39
|
/**
|
|
38
40
|
* Resolves the view a document selects for a recipe: the recipe defaults laid under the author's
|
|
39
41
|
* slot config, each slot's appearance, the schema parse, and the keys the recipe does not declare.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRegistry as
|
|
1
|
+
import{safeParseStandardSchema as L}from"@schema-engine/registry";import{createRegistry as _}from"@schema-engine/registry";import*as d from"zod/mini";var S=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,j=/^[A-Za-z0-9][A-Za-z0-9_-]*$/,O=/[{};<]|\/\*/,A=2,h=5;function V(e){let t=e.$type;if(!S.test(t))throw new Error(`Invalid appearance axis name '${t}': use lowercase letters, digits and hyphens, starting with a letter.`);let n=Object.entries(e.values);if(n.length<A||n.length>h)throw new Error(`Invalid appearance axis '${t}': an axis has ${A} to ${h} values, found ${n.length}. A raw value is a token override, not an axis value.`);if(!Object.hasOwn(e.values,e.default))throw new Error(`Invalid appearance axis '${t}': default '${e.default}' is not one of its values (${n.map(([s])=>s).join(", ")}).`);for(let[s,o]of n){if(!j.test(s))throw new Error(`Invalid appearance value '${s}' on axis '${t}': use letters, digits, hyphens and underscores.`);for(let[r,c]of Object.entries(o)){if(!r.startsWith("--")||r.length<3)throw new Error(`Invalid appearance token '${r}' on '${t}.${s}': tokens are CSS custom properties and start with '--'.`);if(O.test(String(c)))throw new Error(`Invalid appearance token value for '${r}' on '${t}.${s}'.`)}}}function R(e){let t={$type:e.$type,values:e.values,default:e.default,metadata:e.metadata,schema:d.enum(Object.keys(e.values)).check(d.describe(e.metadata.description??e.metadata.name))};return V(t),Object.freeze(t)}var C=R({$type:"size",metadata:{name:"Size",description:"How much room components take: spacing, type size, control height and readable width."},default:"default",values:{compact:{"--se-space":"var(--se-space-compact, var(--se-renderer-space-compact, 1rem))","--se-font-size":"0.875rem","--se-measure":"24rem","--se-control-height":"var(--se-control-height-compact, var(--se-renderer-control-height-compact, 1.75rem))"},default:{"--se-space":"initial","--se-font-size":"initial","--se-measure":"initial","--se-control-height":"initial"},comfortable:{"--se-space":"var(--se-space-comfortable, var(--se-renderer-space-comfortable, 2rem))","--se-font-size":"1.0625rem","--se-measure":"32rem","--se-control-height":"var(--se-control-height-comfortable, var(--se-renderer-control-height-comfortable, 2.25rem))"}}}),M=R({$type:"surface",metadata:{name:"Surface",description:"How a container sets itself apart: border, shadow and background."},default:"elevated",values:{flat:{"--se-border-width":"0","--se-shadow":"none","--se-surface-background":"initial"},outlined:{"--se-border-width":"1px","--se-shadow":"none","--se-surface-background":"initial"},elevated:{"--se-border-width":"initial","--se-shadow":"initial","--se-surface-background":"initial"}}});function $(e,t){return{...e,...t}}function I(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function w(e,t){let n=[],s={};if(e===void 0)return{issues:n,appearance:s};if(!I(e))return{issues:[{path:["appearance"],message:"Expected an object of axis names to values."}],appearance:s};let o=Object.keys(t.axes).join(", ");for(let[r,c]of Object.entries(e)){let i=Object.hasOwn(t.axes,r)?t.axes[r]:void 0;if(!i){n.push({path:["appearance",r],message:`Unknown axis '${r}'. Declared axes: ${o}.`});continue}if(t.supported!==void 0&&!t.supported.includes(r)){let l=t.supported.length>0?t.supported.join(", "):"(none)";n.push({path:["appearance",r],message:`${t.subject} does not support the axis '${r}'. Supported axes: ${l}.`});continue}if(typeof c!="string"){n.push({path:["appearance",r],message:`Expected one of ${i.join(", ")}.`});continue}if(!i.includes(c)){n.push({path:["appearance",r],message:`'${c}' is not a value of '${r}'. Allowed: ${i.join(", ")}.`});continue}s[r]=c}return{issues:n,appearance:s}}function k(e,t){let n={};for(let s of t??[]){let o=e[s];o!==void 0&&(n[s]=o)}return n}function b(e){if(typeof e!="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function v(e,t){if(t===void 0)return e;if(!b(e)||!b(t))return t;let n={...e};for(let[s,o]of Object.entries(t))n[s]=v(e[s],o);return n}function T(e,t){if(!t)return e;let n={...e};for(let[s,o]of Object.entries(t))n[s]=v(o,e[s]);return n}function f(e){if(typeof e!="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function z(e){if(!("appearance"in e))return e;let{appearance:t,...n}=e;return n}function E(e,t,n){return`Recipe '${e}' does not accept view key '${t}'. Allowed: ${n.join(", ")||"(none)"}.`}function B(e,t,n){let s=[],o={...t},r={};for(let a of e.slots){let p=t[a],u=e.appearanceAxes?.[a]??[],y=w(f(p)?p.appearance:void 0,{axes:n.axes,subject:`Slot '${a}' of recipe '${e.$type}'`,supported:u});s.push(...y.issues.map(m=>({...m,path:[a,...m.path]})));let x=k($(n.inherited,y.appearance),u);Object.keys(x).length>0&&(r[a]=x),f(p)&&(o[a]=z(p))}let c=L(e.schema,T(o,e.slotDefaults));if(!c.success)return{issues:s,schemaIssues:c.error.issues};let i=c.data;if(typeof i!="object"||i===null||!("$type"in i)||typeof i.$type!="string")return s.push({path:["$type"],message:`Invalid view configuration for recipe '${e.$type}': parsed output is missing $type.`}),{issues:s};let l=new Set(e.slots);for(let a of Object.keys(t))a!=="$type"&&!l.has(a)&&s.push({path:[a],message:E(e.$type,a,e.slots)});let g={...i};for(let[a,p]of Object.entries(r)){let u=i[a];f(u)&&(g[a]={...u,appearance:p})}return{issues:s,view:g}}export{B as resolveRecipeView,E as unknownViewKeyMessage};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../../src/
|
|
4
|
-
"sourcesContent": ["import {\n\tcreateRegistry,\n\ttype BaseRegistration,\n\ttype ReadOnlyRegistry,\n\ttype RegistrationMetadata,\n} from '@schema-engine/registry';\nimport * as z from 'zod/mini';\nimport type { LayoutIssue } from './layout-issue';\nimport type { LayoutTheme, LayoutThemeCompilerOptions } from './layout-theme';\n\n/**\n * Appearance axes a document picks values on and renderers emit as data attributes.\n *\n * @remarks\n * An axis is one independent dimension of appearance, with two to five named values. Each value\n * stands for a set of semantic CSS tokens, which components read; components never read an axis\n * value. The theme declares the axes ({@link defineAxis}, stored in a registry), a registration\n * declares which axes it responds to, and a document picks values that pass down.\n *\n * A domain checks the pick against the vocabulary and the owner's declared axes\n * ({@link checkAppearance}), merges it with the pick it inherits ({@link mergeAppearance}), and a\n * renderer emits the result as `data-se-<axis>=\"<value>\"` ({@link getAppearanceAttributes}).\n * Walking the document tree to inherit picks belongs to the domain, because only it knows the\n * tree's shape.\n *\n * Compile once, where the theme is built ({@link createLayoutTheme} does, with the grid). Token rules are\n * emitted inside `:where()`, so they add no specificity and an author's `className` always wins; they\n * are scoped to the theme by `data-se-theme` and the nearest theme above an element wins, so two themes\n * with different tokens cannot overwrite each other ({@link getAppearanceCss} has the details).\n */\n\n/** Custom properties a value stands for, keyed `--name`. */\nexport type AppearanceTokens = Readonly<Record<`--${string}`, string | number>>;\n\n/** A pick of one value per axis. */\nexport type AppearanceSelection = Readonly<Record<string, string>>;\n\n/**\n * An appearance axis, stored in a registry like every other registration.\n *\n * @remarks\n * `schema` is a Standard Schema that accepts exactly the value names, which satisfies the\n * registry's build check and is what a catalog or JSON Schema export lists. {@link defineAxis}\n * produces it.\n */\nexport interface AxisRegistration<\n\tTName extends string = string,\n\tTValue extends string = string,\n> extends BaseRegistration<unknown, RegistrationMetadata> {\n\treadonly $type: TName;\n\t/** Each value name and the semantic tokens it stands for. */\n\treadonly values: Readonly<Record<TValue, AppearanceTokens>>;\n\t/**\n\t * The value that stands for no pick.\n\t *\n\t * @remarks\n\t * A component's own CSS fallbacks are the look of this value, so a document that picks it looks\n\t * like one that picks nothing. To make that true under an inherited pick, a default value that\n\t * leaves the tokens to the component sets them to `initial`: a custom property set to `initial`\n\t * makes `var(--token, fallback)` use its fallback, so a step that picks `default` inside a\n\t * `compact` form undoes the compact tokens.\n\t */\n\treadonly default: TValue;\n}\n\n/** Any axis registration, whatever its name and values. */\nexport type AnyAxisRegistration = AxisRegistration;\n\n/** A registry of axes, as {@link createLayoutTheme} builds it. */\nexport type AxisRegistry = ReadOnlyRegistry<AnyAxisRegistration>;\n\n/** Input to {@link defineAxis}. */\nexport interface AxisDefinition<TName extends string, TValues extends Readonly<Record<string, AppearanceTokens>>> {\n\t/** The axis name, which becomes the `data-se-<axis>` attribute and the key of a pick. */\n\treadonly $type: TName;\n\t/** Each value name and the semantic tokens it stands for. Two to five values. */\n\treadonly values: TValues;\n\t/** One of the value names. */\n\treadonly default: keyof TValues & string;\n\treadonly metadata: RegistrationMetadata;\n}\n\nconst AXIS_NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;\nconst VALUE_NAME = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;\nconst UNSAFE_TOKEN_VALUE = /[{};<]|\\/\\*/;\nconst MIN_AXIS_VALUES = 2;\nconst MAX_AXIS_VALUES = 5;\n\n/**\n * Throws when an axis name is one a domain reserves.\n *\n * @remarks The one place the message lives, shared by the compiler and by {@link assertAxesNotReserved}.\n */\nexport function assertAxisNotReserved(axisName: string, reserved: ReadonlySet<string>): void {\n\tif (reserved.has(axisName)) {\n\t\tthrow new Error(`Invalid appearance axis name '${axisName}': data-se-${axisName} is reserved by the renderer.`);\n\t}\n}\n\n/**\n * Throws when an axis is not a usable one: a bad name, fewer than two or more than five values, a\n * value that would break a selector, a token that is not a custom property, or a `default` that is\n * not a value.\n *\n * @remarks\n * Axis names become `data-se-<axis>` attribute names and values go into attribute selectors, so\n * both are restricted to plain identifiers. {@link defineAxis} and the compiler both run this, so an\n * object that did not come from `defineAxis` is held to the same rules.\n */\nfunction assertValidAxis(axis: AnyAxisRegistration): void {\n\tconst name = axis.$type;\n\tif (!AXIS_NAME.test(name)) {\n\t\tthrow new Error(\n\t\t\t`Invalid appearance axis name '${name}': use lowercase letters, digits and hyphens, starting with a letter.`,\n\t\t);\n\t}\n\tconst entries = Object.entries(axis.values);\n\tif (entries.length < MIN_AXIS_VALUES || entries.length > MAX_AXIS_VALUES) {\n\t\tthrow new Error(\n\t\t\t`Invalid appearance axis '${name}': an axis has ${MIN_AXIS_VALUES} to ${MAX_AXIS_VALUES} values, found ${entries.length}. A raw value is a token override, not an axis value.`,\n\t\t);\n\t}\n\tif (!Object.hasOwn(axis.values, axis.default)) {\n\t\tthrow new Error(\n\t\t\t`Invalid appearance axis '${name}': default '${axis.default}' is not one of its values (${entries.map(([value]) => value).join(', ')}).`,\n\t\t);\n\t}\n\tfor (const [value, tokens] of entries) {\n\t\tif (!VALUE_NAME.test(value)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid appearance value '${value}' on axis '${name}': use letters, digits, hyphens and underscores.`,\n\t\t\t);\n\t\t}\n\t\tfor (const [token, tokenValue] of Object.entries(tokens)) {\n\t\t\tif (!token.startsWith('--') || token.length < 3) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Invalid appearance token '${token}' on '${name}.${value}': tokens are CSS custom properties and start with '--'.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (UNSAFE_TOKEN_VALUE.test(String(tokenValue))) {\n\t\t\t\tthrow new Error(`Invalid appearance token value for '${token}' on '${name}.${value}'.`);\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Defines an appearance axis: one independent dimension of appearance with a small closed set of\n * named values.\n *\n * @remarks\n * Each value stands for a set of semantic CSS custom properties (`--se-space`, `--se-shadow`) that\n * components read; components never read the axis value. A token names a role, not a component, so\n * it means the same on every component that reads it. A value that sets a token to `initial`\n * hands it back to the component's own fallback. Appearance only: structure is slot config or the grid.\n *\n * The axis carries a Standard Schema that accepts exactly its value names. Throws on an axis with\n * a name that is not a lowercase identifier, fewer than 2 or more than 5 values, a value name that\n * would break a selector, a token that is not a custom property or has an unsafe value, or a\n * `default` that is not one of the values.\n */\nexport function defineAxis<\n\tconst TName extends string,\n\tconst TValues extends Readonly<Record<string, AppearanceTokens>>,\n>(definition: AxisDefinition<TName, TValues>): AxisRegistration<TName, keyof TValues & string> {\n\tconst axis: AxisRegistration<TName, keyof TValues & string> = {\n\t\t$type: definition.$type,\n\t\tvalues: definition.values,\n\t\tdefault: definition.default,\n\t\tmetadata: definition.metadata,\n\t\tschema: z\n\t\t\t.enum(Object.keys(definition.values) as [string, ...string[]])\n\t\t\t.check(z.describe(definition.metadata.description ?? definition.metadata.name)),\n\t};\n\tassertValidAxis(axis);\n\treturn Object.freeze(axis);\n}\n\nconst sizeAxis = defineAxis({\n\t$type: 'size',\n\tmetadata: {\n\t\tname: 'Size',\n\t\tdescription: 'How much room components take: spacing, type size, control height and readable width.',\n\t},\n\tdefault: 'default',\n\tvalues: {\n\t\tcompact: {\n\t\t\t'--se-space': 'var(--se-space-compact, var(--se-renderer-space-compact, 1rem))',\n\t\t\t'--se-font-size': '0.875rem',\n\t\t\t'--se-measure': '24rem',\n\t\t\t'--se-control-height':\n\t\t\t\t'var(--se-control-height-compact, var(--se-renderer-control-height-compact, 1.75rem))',\n\t\t},\n\t\tdefault: {\n\t\t\t'--se-space': 'initial',\n\t\t\t'--se-font-size': 'initial',\n\t\t\t'--se-measure': 'initial',\n\t\t\t'--se-control-height': 'initial',\n\t\t},\n\t\tcomfortable: {\n\t\t\t'--se-space': 'var(--se-space-comfortable, var(--se-renderer-space-comfortable, 2rem))',\n\t\t\t'--se-font-size': '1.0625rem',\n\t\t\t'--se-measure': '32rem',\n\t\t\t'--se-control-height':\n\t\t\t\t'var(--se-control-height-comfortable, var(--se-renderer-control-height-comfortable, 2.25rem))',\n\t\t},\n\t},\n});\n\nconst surfaceAxis = defineAxis({\n\t$type: 'surface',\n\tmetadata: {\n\t\tname: 'Surface',\n\t\tdescription: 'How a container sets itself apart: border, shadow and background.',\n\t},\n\tdefault: 'elevated',\n\tvalues: {\n\t\tflat: {\n\t\t\t'--se-border-width': '0',\n\t\t\t'--se-shadow': 'none',\n\t\t\t'--se-surface-background': 'initial',\n\t\t},\n\t\toutlined: {\n\t\t\t'--se-border-width': '1px',\n\t\t\t'--se-shadow': 'none',\n\t\t\t'--se-surface-background': 'initial',\n\t\t},\n\t\televated: {\n\t\t\t'--se-border-width': 'initial',\n\t\t\t'--se-shadow': 'initial',\n\t\t\t'--se-surface-background': 'initial',\n\t\t},\n\t},\n});\n\n/**\n * The axes every layout theme starts from: `size` (compact, default, comfortable) and `surface`\n * (flat, outlined, elevated).\n *\n * @remarks\n * The tokens are renderer-neutral and name no host theme; `size` reads hooks an author sets (`--se-space-compact`,\n * `--se-control-height-compact` and their `comfortable` twins), then the `--se-renderer-*` twin of each, which a renderer sets from its theme, then a neutral value. `size.default` and the background of\n * `surface.elevated` are `initial`, which hands the token back to the component's own fallback, so\n * a renderer's fallbacks, which it maps to its host theme, stay in force and `size: default`\n * looks like no pick, also inside a `compact` form. Override an axis by listing another\n * with the same `$type` after these: `createLayoutTheme({ appearance: [...builtInAxes, mine] })`.\n */\nexport const builtInAxes = [sizeAxis, surfaceAxis] as const;\n\n/** The value names of an axis registration. */\ntype AxisValueNames<TAxis> = TAxis extends AxisRegistration<string, infer V> ? V : never;\n\ntype Flatten<T> = { [K in keyof T]: T[K] & string };\n\ntype AxesOfTuple<TAxes extends readonly AnyAxisRegistration[]> = TAxes extends readonly [\n\t...infer Rest extends readonly AnyAxisRegistration[],\n\tinfer Last extends AnyAxisRegistration,\n]\n\t? Omit<AxesOfTuple<Rest>, Last['$type']> & { [K in Last['$type']]: AxisValueNames<Last> }\n\t: unknown;\n\n/**\n * Axis-to-value-union map of a theme: the axes a host lists in `appearance`, the last of a name winning.\n *\n * @remarks Typed authoring narrows a pick to these literals. `TAxes` should be a const-inferred list;\n * a list that is not a tuple, or a member typed as a plain `AnyAxisRegistration` (name `string`),\n * widens to any axis name and any value.\n */\nexport type ResolvedAppearanceAxes<TAxes extends readonly AnyAxisRegistration[] = typeof builtInAxes> =\n\tnumber extends TAxes['length'] ? Record<string, string> : Flatten<AxesOfTuple<TAxes>>;\n\n/** Built-in axes and their values, as literal types, for typed authoring. */\nexport type BuiltInAppearanceAxes = ResolvedAppearanceAxes;\n\n/** The axes an element or a recipe slot declares it supports. */\nexport type AppearanceAxisList = readonly string[];\n\n/** The axes each slot of a recipe supports, keyed by slot name. */\nexport type SlotAppearanceAxes<TSlot extends PropertyKey = string> = { [K in TSlot]?: AppearanceAxisList };\n\n/** Authoring shape of a pick: any declared axis, restricted to its values. */\nexport type AppearanceInput<TAxes extends Record<string, string>> = { readonly [A in keyof TAxes]?: TAxes[A] };\n\n/** A theme's compiled appearance vocabulary. */\nexport interface CompiledAppearance {\n\t/** The axes, last registration of a `$type` winning, in first-registration order. */\n\treadonly registry: AxisRegistry;\n\t/** Axis name to its closed value list. */\n\treadonly axes: Readonly<Record<string, readonly string[]>>;\n}\n\n/**\n * The token rules of a compiled appearance, scoped to the layout theme with the given id.\n *\n * @remarks\n * Every rule sits inside `:where()`, so it adds no specificity and an author's class always wins.\n * Every grid and item carries `data-se-theme`, so a form of theme B inside a grid item of theme A\n * has both themes above it; the nearest theme's rule must be the one that matches, whatever the\n * order of the stylesheets. Empty when no value declares tokens. Two sets of rules say so:\n *\n * 1. Plain rules, which match an element that carries the theme and the pick together, or a\n * descendant of the theme's root with no element of another theme between. They need only\n * `:where()` and complex selectors in `:not()`, so they hold in server-rendered output in every\n * browser the renderers support. They cannot say \"no other theme between\" for a theme re-entered\n * below another theme (A in B in A): its descendants match no plain rule, so they inherit the\n * custom properties of the nearest element that did.\n * 2. `@scope` rules, emitted after the plain ones in one block: the theme's roots down to the nearest\n * element of another theme. A browser without `@scope` drops the block and keeps the plain rules;\n * one with it is exact, A in B in A included. About 1.1 KB per theme with the built-in axes.\n *\n * The `@scope` rules change one cascade detail: scope proximity outranks source order, and an\n * unscoped rule is the farthest from any root. A zero-specificity author rule such as `:where(.x)`\n * therefore loses to a token rule in a browser with `@scope`, where it won on order alone before;\n * a class with any specificity still wins.\n */\nexport function getAppearanceCss(appearance: CompiledAppearance, themeId: string): string {\n\tconst plain: string[] = [];\n\tconst scoped: string[] = [];\n\tconst scope = `[data-se-theme=\"${themeId}\"]`;\n\tconst foreign = `[data-se-theme]:not(${scope})`;\n\tfor (const axis of appearance.registry.all()) {\n\t\tfor (const [value, tokens] of Object.entries(axis.values)) {\n\t\t\tconst declarations = Object.entries(tokens).map(([token, tokenValue]) => `${token}:${tokenValue};`);\n\t\t\tif (declarations.length === 0) continue;\n\t\t\tconst block = `{${declarations.join('')}}`;\n\t\t\tconst match = `[data-se-${axis.$type}=\"${value}\"]`;\n\t\t\tconst descendant = `${scope} ${match}:not(${foreign},${scope} ${foreign} *)`;\n\t\t\tplain.push(`:where(${scope}${match},${descendant})${block}`);\n\t\t\tscoped.push(`:where(:scope${match},${match})${block}`);\n\t\t}\n\t}\n\tif (scoped.length === 0) return '';\n\treturn [...plain, `@scope (${scope}) to (${foreign}){${scoped.join('')}}`].join('\\n');\n}\n\n/**\n * Compiles a list of axes into the theme's appearance vocabulary.\n *\n * @param axes - The axes of the theme; defaults to {@link builtInAxes}. A later axis with the same\n * `$type` replaces the earlier one, so `[...builtInAxes, mine]` overrides.\n *\n * @remarks\n * Stores the axes with `createRegistry`, so each needs a Standard Schema, and holds every winner to\n * the rules {@link defineAxis} states. Throws on an invalid axis and on one named in `reservedNames`.\n */\nexport function compileAppearance(\n\taxes: readonly AnyAxisRegistration[] = builtInAxes,\n\tcompiler: LayoutThemeCompilerOptions = {},\n): CompiledAppearance {\n\tconst registry = createRegistry<AnyAxisRegistration>('Axis', axes);\n\tconst reserved = new Set(compiler.reservedNames);\n\tfor (const axis of registry.all()) {\n\t\tassertValidAxis(axis);\n\t\tassertAxisNotReserved(axis.$type, reserved);\n\t}\n\treturn Object.freeze({\n\t\tregistry,\n\t\taxes: Object.freeze(\n\t\t\tObject.fromEntries(registry.all().map((axis) => [axis.$type, Object.freeze(Object.keys(axis.values))])),\n\t\t),\n\t});\n}\n\n/**\n * The `data-se-<axis>` attributes for a resolved selection.\n *\n * @remarks A renderer spreads this on every element that carries a pick.\n */\nexport function getAppearanceAttributes(appearance: AppearanceSelection | undefined): Record<string, string> {\n\tconst attributes: Record<string, string> = {};\n\tfor (const [axis, value] of Object.entries(appearance ?? {})) attributes[`data-se-${axis}`] = value;\n\treturn attributes;\n}\n\n/**\n * A child's picks laid over the picks it inherits: the child's value wins per axis.\n *\n * @remarks Pure merge; checking that the child's axes are valid is {@link checkAppearance}'s job.\n */\nexport function mergeAppearance(\n\tinherited: AppearanceSelection | undefined,\n\town: AppearanceSelection | undefined,\n): Record<string, string> {\n\treturn { ...inherited, ...own };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Checks an authored pick against the vocabulary and, when given, the axes its owner supports.\n *\n * @param subject Names the owner in a message, for example `Element 'fieldSet'`.\n * @param supported The axes the owner declares; an owner that declares none passes `[]`. Omit it for an owner that accepts every axis.\n * @returns One issue per problem, with a path relative to the authored pick (`['appearance', axis]`), and the valid picks.\n */\nexport function checkAppearance(\n\tauthored: unknown,\n\toptions: { axes: LayoutTheme['axes']; subject: string; supported?: readonly string[] },\n): { issues: LayoutIssue[]; appearance: Record<string, string> } {\n\tconst issues: LayoutIssue[] = [];\n\tconst appearance: Record<string, string> = {};\n\tif (authored === undefined) return { issues, appearance };\n\tif (!isRecord(authored)) {\n\t\treturn {\n\t\t\tissues: [{ path: ['appearance'], message: 'Expected an object of axis names to values.' }],\n\t\t\tappearance,\n\t\t};\n\t}\n\tconst declared = Object.keys(options.axes).join(', ');\n\tfor (const [axis, value] of Object.entries(authored)) {\n\t\tconst values = Object.hasOwn(options.axes, axis) ? options.axes[axis] : undefined;\n\t\tif (!values) {\n\t\t\tissues.push({ path: ['appearance', axis], message: `Unknown axis '${axis}'. Declared axes: ${declared}.` });\n\t\t\tcontinue;\n\t\t}\n\t\tif (options.supported !== undefined && !options.supported.includes(axis)) {\n\t\t\tconst supported = options.supported.length > 0 ? options.supported.join(', ') : '(none)';\n\t\t\tissues.push({\n\t\t\t\tpath: ['appearance', axis],\n\t\t\t\tmessage: `${options.subject} does not support the axis '${axis}'. Supported axes: ${supported}.`,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (typeof value !== 'string') {\n\t\t\tissues.push({ path: ['appearance', axis], message: `Expected one of ${values.join(', ')}.` });\n\t\t\tcontinue;\n\t\t}\n\t\tif (!values.includes(value)) {\n\t\t\tissues.push({\n\t\t\t\tpath: ['appearance', axis],\n\t\t\t\tmessage: `'${value}' is not a value of '${axis}'. Allowed: ${values.join(', ')}.`,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tappearance[axis] = value;\n\t}\n\treturn { issues, appearance };\n}\n\n/** Keeps the axes an owner supports. An owner that declares none keeps none. */\nexport function pickSupportedAppearance(\n\tselection: AppearanceSelection,\n\tsupported: readonly string[] | undefined,\n): Record<string, string> {\n\tconst picked: Record<string, string> = {};\n\tfor (const axis of supported ?? []) {\n\t\tconst value = selection[axis];\n\t\tif (value !== undefined) picked[axis] = value;\n\t}\n\treturn picked;\n}\n", "/**\n * @remarks\n * Duplicates the helper the forms package keeps for its own deep operations on purpose: this\n * package cannot import forms.\n */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\tif (typeof value !== 'object' || value === null) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\nfunction mergeDeep(base: unknown, override: unknown): unknown {\n\tif (override === undefined) return base;\n\tif (!isPlainObject(base) || !isPlainObject(override)) return override;\n\tconst merged: Record<string, unknown> = { ...base };\n\tfor (const [key, value] of Object.entries(override)) {\n\t\tmerged[key] = mergeDeep(base[key], value);\n\t}\n\treturn merged;\n}\n\n/**\n * Lays a view's slot config over the recipe's `slotDefaults`, deep for plain objects.\n *\n * @remarks\n * Runs before the view schema parses, so schema defaults fill only what neither the author\n * nor the recipe set. Arrays and other non-plain values replace the default whole. A key the author sets to `undefined` keeps the recipe default.\n */\nexport function mergeSlotDefaults(\n\tview: Record<string, unknown>,\n\tslotDefaults: Record<string, unknown> | undefined,\n): Record<string, unknown> {\n\tif (!slotDefaults) return view;\n\tconst merged = { ...view };\n\tfor (const [slot, defaults] of Object.entries(slotDefaults)) {\n\t\tmerged[slot] = mergeDeep(defaults, view[slot]);\n\t}\n\treturn merged;\n}\n", "import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { checkAppearance, mergeAppearance, pickSupportedAppearance, type SlotAppearanceAxes } from '../lib/appearance';\nimport type { LayoutIssue } from '../lib/layout-issue';\nimport type { LayoutTheme } from '../lib/layout-theme';\nimport { mergeSlotDefaults } from './merge-slot-defaults';\n\n/** Appearance picks a view inherits: the theme's vocabulary, and what the containing document picked. */\nexport interface RecipeViewScope {\n\treadonly axes: LayoutTheme['axes'];\n\treadonly inherited: Readonly<Record<string, string>>;\n}\n\n/** The part of a recipe registration that resolving a view reads. */\nexport interface RecipeViewSource {\n\treadonly $type: string;\n\treadonly slots: readonly string[];\n\treadonly schema: StandardSchemaV1;\n\treadonly slotDefaults?: Readonly<Record<string, unknown>>;\n\treadonly appearanceAxes?: SlotAppearanceAxes;\n}\n\n/** An authored view: the recipe's `$type` and the config of its slots. */\nexport type RecipeViewInput = Readonly<Record<string, unknown>> & { readonly $type: string };\n\n/**\n * What {@link resolveRecipeView} found.\n *\n * @remarks\n * `view` is present when the schema parsed and kept its `$type`; it can still come with `issues`\n * (an appearance pick that is not valid, or a key the recipe does not declare). `schemaIssues` is\n * present, with no `view`, when the schema rejected the view: the caller formats them, since only\n * the domain knows how it reports a schema's issues.\n */\nexport interface ResolvedRecipeView {\n\t/** One issue per problem, with a path relative to the view (`[slot, 'appearance', axis]`, `[key]`). */\n\tissues: LayoutIssue[];\n\tview?: Record<string, unknown>;\n\tschemaIssues?: StandardSchemaV1.Issue[];\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n\tif (typeof value !== 'object' || value === null) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\nfunction withoutAppearance(config: Record<string, unknown>): Record<string, unknown> {\n\tif (!('appearance' in config)) return config;\n\tconst { appearance: _authored, ...rest } = config;\n\treturn rest;\n}\n\nfunction parseSync(schema: StandardSchemaV1, value: unknown): StandardSchemaV1.Result<unknown> {\n\tconst result = schema['~standard'].validate(value);\n\tif (result && typeof (result as Promise<unknown>).then === 'function') {\n\t\tthrow new Error('Async Standard Schema validation is not supported in this context');\n\t}\n\tif (result === null || typeof result !== 'object') {\n\t\tthrow new Error('Standard Schema validation returned an invalid result');\n\t}\n\treturn result as StandardSchemaV1.Result<unknown>;\n}\n\n/**\n * Resolves the view a document selects for a recipe: the recipe defaults laid under the author's\n * slot config, each slot's appearance, the schema parse, and the keys the recipe does not declare.\n *\n * @param recipe - The winning registration the view's `$type` selects\n * @param view - The authored view; not changed\n * @param scope - The picks the view inherits from its document\n *\n * @remarks\n * Slot appearance follows the recipe's inheritance rule: the document's picks reach a slot for the\n * axes the recipe declares on it, and the slot's own pick wins. The authored `appearance` key is\n * removed before the slot schema parses, so a schema only has to type it, and the resolved\n * selection is written back on the slot when it is not empty. Domain rules that need the document\n * (a kind that wants one step, a default recipe) stay with the domain's validator.\n */\nexport function resolveRecipeView(\n\trecipe: RecipeViewSource,\n\tview: RecipeViewInput,\n\tscope: RecipeViewScope,\n): ResolvedRecipeView {\n\tconst issues: LayoutIssue[] = [];\n\tconst stripped: Record<string, unknown> = { ...view };\n\tconst resolved: Record<string, Record<string, string>> = {};\n\tfor (const slot of recipe.slots) {\n\t\tconst authoredSlot = view[slot];\n\t\tconst supported = recipe.appearanceAxes?.[slot] ?? [];\n\t\tconst checked = checkAppearance(isPlainRecord(authoredSlot) ? authoredSlot.appearance : undefined, {\n\t\t\taxes: scope.axes,\n\t\t\tsubject: `Slot '${slot}' of recipe '${recipe.$type}'`,\n\t\t\tsupported,\n\t\t});\n\t\tissues.push(...checked.issues.map((issue) => ({ ...issue, path: [slot, ...issue.path] })));\n\t\tconst selection = pickSupportedAppearance(mergeAppearance(scope.inherited, checked.appearance), supported);\n\t\tif (Object.keys(selection).length > 0) resolved[slot] = selection;\n\t\tif (isPlainRecord(authoredSlot)) stripped[slot] = withoutAppearance(authoredSlot);\n\t}\n\n\tconst parsed = parseSync(recipe.schema, mergeSlotDefaults(stripped, recipe.slotDefaults));\n\tif (parsed.issues !== undefined) return { issues, schemaIssues: [...parsed.issues] };\n\tconst output = parsed.value;\n\tif (typeof output !== 'object' || output === null || !('$type' in output) || typeof output.$type !== 'string') {\n\t\tissues.push({\n\t\t\tpath: ['$type'],\n\t\t\tmessage: `Invalid view configuration for recipe '${recipe.$type}': parsed output is missing $type.`,\n\t\t});\n\t\treturn { issues };\n\t}\n\n\tconst allowedSlots = new Set<string>(recipe.slots);\n\tfor (const key of Object.keys(view)) {\n\t\tif (key !== '$type' && !allowedSlots.has(key)) {\n\t\t\tissues.push({\n\t\t\t\tpath: [key],\n\t\t\t\tmessage: `Recipe '${recipe.$type}' does not accept view key '${key}'. Allowed: ${[...allowedSlots].join(', ') || '(none)'}.`,\n\t\t\t});\n\t\t}\n\t}\n\n\tconst next: Record<string, unknown> = { ...output };\n\tfor (const [slot, selection] of Object.entries(resolved)) {\n\t\tconst slotConfig = (output as Record<string, unknown>)[slot];\n\t\tif (isPlainRecord(slotConfig)) next[slot] = { ...slotConfig, appearance: selection };\n\t}\n\treturn { issues, view: next };\n}\n"],
|
|
5
|
-
"mappings": "
|
|
6
|
-
"names": ["createRegistry", "z", "AXIS_NAME", "VALUE_NAME", "UNSAFE_TOKEN_VALUE", "MIN_AXIS_VALUES", "MAX_AXIS_VALUES", "assertValidAxis", "axis", "name", "AXIS_NAME", "entries", "MIN_AXIS_VALUES", "MAX_AXIS_VALUES", "value", "tokens", "VALUE_NAME", "token", "tokenValue", "UNSAFE_TOKEN_VALUE", "defineAxis", "definition", "sizeAxis", "surfaceAxis", "mergeAppearance", "inherited", "own", "isRecord", "value", "checkAppearance", "authored", "options", "issues", "appearance", "declared", "axis", "values", "supported", "pickSupportedAppearance", "selection", "picked", "isPlainObject", "value", "prototype", "mergeDeep", "base", "override", "merged", "key", "mergeSlotDefaults", "view", "slotDefaults", "slot", "defaults", "isPlainRecord", "value", "prototype", "withoutAppearance", "config", "_authored", "rest", "
|
|
3
|
+
"sources": ["../../src/recipes/resolve-recipe-view.ts", "../../src/lib/appearance.ts", "../../src/recipes/merge-slot-defaults.ts"],
|
|
4
|
+
"sourcesContent": ["import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { safeParseStandardSchema } from '@schema-engine/registry';\nimport { checkAppearance, mergeAppearance, pickSupportedAppearance, type SlotAppearanceAxes } from '../lib/appearance';\nimport type { LayoutIssue } from '../lib/layout-issue';\nimport type { LayoutTheme } from '../lib/layout-theme';\nimport { mergeSlotDefaults } from './merge-slot-defaults';\n\n/** Appearance picks a view inherits: the theme's vocabulary, and what the containing document picked. */\nexport interface RecipeViewScope {\n\treadonly axes: LayoutTheme['axes'];\n\treadonly inherited: Readonly<Record<string, string>>;\n}\n\n/** The part of a recipe registration that resolving a view reads. */\nexport interface RecipeViewSource {\n\treadonly $type: string;\n\treadonly slots: readonly string[];\n\treadonly schema: StandardSchemaV1;\n\treadonly slotDefaults?: Readonly<Record<string, unknown>>;\n\treadonly appearanceAxes?: SlotAppearanceAxes;\n}\n\n/** An authored view: the recipe's `$type` and the config of its slots. */\nexport type RecipeViewInput = Readonly<Record<string, unknown>> & { readonly $type: string };\n\n/**\n * What {@link resolveRecipeView} found.\n *\n * @remarks\n * `view` is present when the schema parsed and kept its `$type`; it can still come with `issues`\n * (an appearance pick that is not valid, or a key the recipe does not declare). `schemaIssues` is\n * present, with no `view`, when the schema rejected the view: the caller formats them, since only\n * the domain knows how it reports a schema's issues.\n */\nexport interface ResolvedRecipeView {\n\t/** One issue per problem, with a path relative to the view (`[slot, 'appearance', axis]`, `[key]`). */\n\tissues: LayoutIssue[];\n\tview?: Record<string, unknown>;\n\tschemaIssues?: StandardSchemaV1.Issue[];\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n\tif (typeof value !== 'object' || value === null) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\nfunction withoutAppearance(config: Record<string, unknown>): Record<string, unknown> {\n\tif (!('appearance' in config)) return config;\n\tconst { appearance: _authored, ...rest } = config;\n\treturn rest;\n}\n\n/** The issue message for a view key that the recipe does not declare, shared by the view schema and {@link resolveRecipeView}. */\nexport function unknownViewKeyMessage($type: string, key: string, allowed: readonly string[]): string {\n\treturn `Recipe '${$type}' does not accept view key '${key}'. Allowed: ${allowed.join(', ') || '(none)'}.`;\n}\n\n/**\n * Resolves the view a document selects for a recipe: the recipe defaults laid under the author's\n * slot config, each slot's appearance, the schema parse, and the keys the recipe does not declare.\n *\n * @param recipe - The winning registration the view's `$type` selects\n * @param view - The authored view; not changed\n * @param scope - The picks the view inherits from its document\n *\n * @remarks\n * Slot appearance follows the recipe's inheritance rule: the document's picks reach a slot for the\n * axes the recipe declares on it, and the slot's own pick wins. The authored `appearance` key is\n * removed before the slot schema parses, so a schema only has to type it, and the resolved\n * selection is written back on the slot when it is not empty. Domain rules that need the document\n * (a kind that wants one step, a default recipe) stay with the domain's validator.\n */\nexport function resolveRecipeView(\n\trecipe: RecipeViewSource,\n\tview: RecipeViewInput,\n\tscope: RecipeViewScope,\n): ResolvedRecipeView {\n\tconst issues: LayoutIssue[] = [];\n\tconst stripped: Record<string, unknown> = { ...view };\n\tconst resolved: Record<string, Record<string, string>> = {};\n\tfor (const slot of recipe.slots) {\n\t\tconst authoredSlot = view[slot];\n\t\tconst supported = recipe.appearanceAxes?.[slot] ?? [];\n\t\tconst checked = checkAppearance(isPlainRecord(authoredSlot) ? authoredSlot.appearance : undefined, {\n\t\t\taxes: scope.axes,\n\t\t\tsubject: `Slot '${slot}' of recipe '${recipe.$type}'`,\n\t\t\tsupported,\n\t\t});\n\t\tissues.push(...checked.issues.map((issue) => ({ ...issue, path: [slot, ...issue.path] })));\n\t\tconst selection = pickSupportedAppearance(mergeAppearance(scope.inherited, checked.appearance), supported);\n\t\tif (Object.keys(selection).length > 0) resolved[slot] = selection;\n\t\tif (isPlainRecord(authoredSlot)) stripped[slot] = withoutAppearance(authoredSlot);\n\t}\n\n\tconst parsed = safeParseStandardSchema(recipe.schema, mergeSlotDefaults(stripped, recipe.slotDefaults));\n\tif (!parsed.success) return { issues, schemaIssues: parsed.error.issues };\n\tconst output = parsed.data;\n\tif (typeof output !== 'object' || output === null || !('$type' in output) || typeof output.$type !== 'string') {\n\t\tissues.push({\n\t\t\tpath: ['$type'],\n\t\t\tmessage: `Invalid view configuration for recipe '${recipe.$type}': parsed output is missing $type.`,\n\t\t});\n\t\treturn { issues };\n\t}\n\n\tconst allowedSlots = new Set<string>(recipe.slots);\n\tfor (const key of Object.keys(view)) {\n\t\tif (key !== '$type' && !allowedSlots.has(key)) {\n\t\t\tissues.push({ path: [key], message: unknownViewKeyMessage(recipe.$type, key, recipe.slots) });\n\t\t}\n\t}\n\n\tconst next: Record<string, unknown> = { ...output };\n\tfor (const [slot, selection] of Object.entries(resolved)) {\n\t\tconst slotConfig = (output as Record<string, unknown>)[slot];\n\t\tif (isPlainRecord(slotConfig)) next[slot] = { ...slotConfig, appearance: selection };\n\t}\n\treturn { issues, view: next };\n}\n", "import {\n\tcreateRegistry,\n\ttype BaseRegistration,\n\ttype ReadOnlyRegistry,\n\ttype RegistrationMetadata,\n} from '@schema-engine/registry';\nimport * as z from 'zod/mini';\nimport type { LayoutIssue } from './layout-issue';\nimport type { LayoutTheme, LayoutThemeCompilerOptions } from './layout-theme';\n\n/**\n * Appearance axes a document picks values on and renderers emit as data attributes.\n *\n * @remarks\n * An axis is one independent dimension of appearance, with two to five named values. Each value\n * stands for a set of semantic CSS tokens, which components read; components never read an axis\n * value. The theme declares the axes ({@link defineAxis}, stored in a registry), a registration\n * declares which axes it responds to, and a document picks values that pass down.\n *\n * A domain checks the pick against the vocabulary and the owner's declared axes\n * ({@link checkAppearance}), merges it with the pick it inherits ({@link mergeAppearance}), and a\n * renderer emits the result as `data-se-<axis>=\"<value>\"` ({@link getAppearanceAttributes}).\n * Walking the document tree to inherit picks belongs to the domain, because only it knows the\n * tree's shape.\n *\n * Compile once, where the theme is built ({@link createLayoutTheme} does, with the grid). Token rules are\n * emitted inside `:where()`, so they add no specificity and an author's `className` always wins; they\n * are scoped to the theme by `data-se-theme` and the nearest theme above an element wins, so two themes\n * with different tokens cannot overwrite each other ({@link getAppearanceCss} has the details).\n */\n\n/** Custom properties a value stands for, keyed `--name`. */\nexport type AppearanceTokens = Readonly<Record<`--${string}`, string | number>>;\n\n/** A pick of one value per axis. */\nexport type AppearanceSelection = Readonly<Record<string, string>>;\n\n/**\n * An appearance axis, stored in a registry like every other registration.\n *\n * @remarks\n * `schema` is a Standard Schema that accepts exactly the value names, which satisfies the\n * registry's build check and is what a catalog or JSON Schema export lists. {@link defineAxis}\n * produces it.\n */\nexport interface AxisRegistration<\n\tTName extends string = string,\n\tTValue extends string = string,\n> extends BaseRegistration<unknown, RegistrationMetadata> {\n\treadonly $type: TName;\n\t/** Each value name and the semantic tokens it stands for. */\n\treadonly values: Readonly<Record<TValue, AppearanceTokens>>;\n\t/**\n\t * The value that stands for no pick.\n\t *\n\t * @remarks\n\t * A component's own CSS fallbacks are the look of this value, so a document that picks it looks\n\t * like one that picks nothing. To make that true under an inherited pick, a default value that\n\t * leaves the tokens to the component sets them to `initial`: a custom property set to `initial`\n\t * makes `var(--token, fallback)` use its fallback, so a step that picks `default` inside a\n\t * `compact` form undoes the compact tokens.\n\t */\n\treadonly default: TValue;\n}\n\n/** Any axis registration, whatever its name and values. */\nexport type AnyAxisRegistration = AxisRegistration;\n\n/** A registry of axes, as {@link createLayoutTheme} builds it. */\nexport type AxisRegistry = ReadOnlyRegistry<AnyAxisRegistration>;\n\n/** Input to {@link defineAxis}. */\nexport interface AxisDefinition<TName extends string, TValues extends Readonly<Record<string, AppearanceTokens>>> {\n\t/** The axis name, which becomes the `data-se-<axis>` attribute and the key of a pick. */\n\treadonly $type: TName;\n\t/** Each value name and the semantic tokens it stands for. Two to five values. */\n\treadonly values: TValues;\n\t/** One of the value names. */\n\treadonly default: keyof TValues & string;\n\treadonly metadata: RegistrationMetadata;\n}\n\nconst AXIS_NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;\nconst VALUE_NAME = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;\nconst UNSAFE_TOKEN_VALUE = /[{};<]|\\/\\*/;\nconst MIN_AXIS_VALUES = 2;\nconst MAX_AXIS_VALUES = 5;\n\n/**\n * Throws when an axis name is one a domain reserves.\n *\n * @remarks The one place the message lives, shared by the compiler and by {@link assertAxesNotReserved}.\n */\nexport function assertAxisNotReserved(axisName: string, reserved: ReadonlySet<string>): void {\n\tif (reserved.has(axisName)) {\n\t\tthrow new Error(`Invalid appearance axis name '${axisName}': data-se-${axisName} is reserved by the renderer.`);\n\t}\n}\n\n/**\n * Throws when an axis is not a usable one: a bad name, fewer than two or more than five values, a\n * value that would break a selector, a token that is not a custom property, or a `default` that is\n * not a value.\n *\n * @remarks\n * Axis names become `data-se-<axis>` attribute names and values go into attribute selectors, so\n * both are restricted to plain identifiers. {@link defineAxis} and the compiler both run this, so an\n * object that did not come from `defineAxis` is held to the same rules.\n */\nfunction assertValidAxis(axis: AnyAxisRegistration): void {\n\tconst name = axis.$type;\n\tif (!AXIS_NAME.test(name)) {\n\t\tthrow new Error(\n\t\t\t`Invalid appearance axis name '${name}': use lowercase letters, digits and hyphens, starting with a letter.`,\n\t\t);\n\t}\n\tconst entries = Object.entries(axis.values);\n\tif (entries.length < MIN_AXIS_VALUES || entries.length > MAX_AXIS_VALUES) {\n\t\tthrow new Error(\n\t\t\t`Invalid appearance axis '${name}': an axis has ${MIN_AXIS_VALUES} to ${MAX_AXIS_VALUES} values, found ${entries.length}. A raw value is a token override, not an axis value.`,\n\t\t);\n\t}\n\tif (!Object.hasOwn(axis.values, axis.default)) {\n\t\tthrow new Error(\n\t\t\t`Invalid appearance axis '${name}': default '${axis.default}' is not one of its values (${entries.map(([value]) => value).join(', ')}).`,\n\t\t);\n\t}\n\tfor (const [value, tokens] of entries) {\n\t\tif (!VALUE_NAME.test(value)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid appearance value '${value}' on axis '${name}': use letters, digits, hyphens and underscores.`,\n\t\t\t);\n\t\t}\n\t\tfor (const [token, tokenValue] of Object.entries(tokens)) {\n\t\t\tif (!token.startsWith('--') || token.length < 3) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Invalid appearance token '${token}' on '${name}.${value}': tokens are CSS custom properties and start with '--'.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (UNSAFE_TOKEN_VALUE.test(String(tokenValue))) {\n\t\t\t\tthrow new Error(`Invalid appearance token value for '${token}' on '${name}.${value}'.`);\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Defines an appearance axis: one independent dimension of appearance with a small closed set of\n * named values.\n *\n * @remarks\n * Each value stands for a set of semantic CSS custom properties (`--se-space`, `--se-shadow`) that\n * components read; components never read the axis value. A token names a role, not a component, so\n * it means the same on every component that reads it. A value that sets a token to `initial`\n * hands it back to the component's own fallback. Appearance only: structure is slot config or the grid.\n *\n * The axis carries a Standard Schema that accepts exactly its value names. Throws on an axis with\n * a name that is not a lowercase identifier, fewer than 2 or more than 5 values, a value name that\n * would break a selector, a token that is not a custom property or has an unsafe value, or a\n * `default` that is not one of the values.\n */\nexport function defineAxis<\n\tconst TName extends string,\n\tconst TValues extends Readonly<Record<string, AppearanceTokens>>,\n>(definition: AxisDefinition<TName, TValues>): AxisRegistration<TName, keyof TValues & string> {\n\tconst axis: AxisRegistration<TName, keyof TValues & string> = {\n\t\t$type: definition.$type,\n\t\tvalues: definition.values,\n\t\tdefault: definition.default,\n\t\tmetadata: definition.metadata,\n\t\tschema: z\n\t\t\t.enum(Object.keys(definition.values) as [string, ...string[]])\n\t\t\t.check(z.describe(definition.metadata.description ?? definition.metadata.name)),\n\t};\n\tassertValidAxis(axis);\n\treturn Object.freeze(axis);\n}\n\nconst sizeAxis = defineAxis({\n\t$type: 'size',\n\tmetadata: {\n\t\tname: 'Size',\n\t\tdescription: 'How much room components take: spacing, type size, control height and readable width.',\n\t},\n\tdefault: 'default',\n\tvalues: {\n\t\tcompact: {\n\t\t\t'--se-space': 'var(--se-space-compact, var(--se-renderer-space-compact, 1rem))',\n\t\t\t'--se-font-size': '0.875rem',\n\t\t\t'--se-measure': '24rem',\n\t\t\t'--se-control-height':\n\t\t\t\t'var(--se-control-height-compact, var(--se-renderer-control-height-compact, 1.75rem))',\n\t\t},\n\t\tdefault: {\n\t\t\t'--se-space': 'initial',\n\t\t\t'--se-font-size': 'initial',\n\t\t\t'--se-measure': 'initial',\n\t\t\t'--se-control-height': 'initial',\n\t\t},\n\t\tcomfortable: {\n\t\t\t'--se-space': 'var(--se-space-comfortable, var(--se-renderer-space-comfortable, 2rem))',\n\t\t\t'--se-font-size': '1.0625rem',\n\t\t\t'--se-measure': '32rem',\n\t\t\t'--se-control-height':\n\t\t\t\t'var(--se-control-height-comfortable, var(--se-renderer-control-height-comfortable, 2.25rem))',\n\t\t},\n\t},\n});\n\nconst surfaceAxis = defineAxis({\n\t$type: 'surface',\n\tmetadata: {\n\t\tname: 'Surface',\n\t\tdescription: 'How a container sets itself apart: border, shadow and background.',\n\t},\n\tdefault: 'elevated',\n\tvalues: {\n\t\tflat: {\n\t\t\t'--se-border-width': '0',\n\t\t\t'--se-shadow': 'none',\n\t\t\t'--se-surface-background': 'initial',\n\t\t},\n\t\toutlined: {\n\t\t\t'--se-border-width': '1px',\n\t\t\t'--se-shadow': 'none',\n\t\t\t'--se-surface-background': 'initial',\n\t\t},\n\t\televated: {\n\t\t\t'--se-border-width': 'initial',\n\t\t\t'--se-shadow': 'initial',\n\t\t\t'--se-surface-background': 'initial',\n\t\t},\n\t},\n});\n\n/**\n * The axes every layout theme starts from: `size` (compact, default, comfortable) and `surface`\n * (flat, outlined, elevated).\n *\n * @remarks\n * The tokens are renderer-neutral and name no host theme; `size` reads hooks an author sets (`--se-space-compact`,\n * `--se-control-height-compact` and their `comfortable` twins), then the `--se-renderer-*` twin of each, which a renderer sets from its theme, then a neutral value. `size.default` and the background of\n * `surface.elevated` are `initial`, which hands the token back to the component's own fallback, so\n * a renderer's fallbacks, which it maps to its host theme, stay in force and `size: default`\n * looks like no pick, also inside a `compact` form. Override an axis by listing another\n * with the same `$type` after these: `createLayoutTheme({ appearance: [...builtInAxes, mine] })`.\n */\nexport const builtInAxes = [sizeAxis, surfaceAxis] as const;\n\n/** The value names of an axis registration. */\ntype AxisValueNames<TAxis> = TAxis extends AxisRegistration<string, infer V> ? V : never;\n\ntype Flatten<T> = { [K in keyof T]: T[K] & string };\n\ntype AxesOfTuple<TAxes extends readonly AnyAxisRegistration[]> = TAxes extends readonly [\n\t...infer Rest extends readonly AnyAxisRegistration[],\n\tinfer Last extends AnyAxisRegistration,\n]\n\t? Omit<AxesOfTuple<Rest>, Last['$type']> & { [K in Last['$type']]: AxisValueNames<Last> }\n\t: unknown;\n\n/**\n * Axis-to-value-union map of a theme: the axes a host lists in `appearance`, the last of a name winning.\n *\n * @remarks Typed authoring narrows a pick to these literals. `TAxes` should be a const-inferred list;\n * a list that is not a tuple, or a member typed as a plain `AnyAxisRegistration` (name `string`),\n * widens to any axis name and any value.\n */\nexport type ResolvedAppearanceAxes<TAxes extends readonly AnyAxisRegistration[] = typeof builtInAxes> =\n\tnumber extends TAxes['length'] ? Record<string, string> : Flatten<AxesOfTuple<TAxes>>;\n\n/** Built-in axes and their values, as literal types, for typed authoring. */\nexport type BuiltInAppearanceAxes = ResolvedAppearanceAxes;\n\n/** The axes an element or a recipe slot declares it supports. */\nexport type AppearanceAxisList = readonly string[];\n\n/** The axes each slot of a recipe supports, keyed by slot name. */\nexport type SlotAppearanceAxes<TSlot extends PropertyKey = string> = { [K in TSlot]?: AppearanceAxisList };\n\n/** Authoring shape of a pick: any declared axis, restricted to its values. */\nexport type AppearanceInput<TAxes extends Record<string, string>> = { readonly [A in keyof TAxes]?: TAxes[A] };\n\n/** A theme's compiled appearance vocabulary. */\nexport interface CompiledAppearance {\n\t/** The axes, last registration of a `$type` winning, in first-registration order. */\n\treadonly registry: AxisRegistry;\n\t/** Axis name to its closed value list. */\n\treadonly axes: Readonly<Record<string, readonly string[]>>;\n}\n\n/**\n * The token rules of a compiled appearance, scoped to the layout theme with the given id.\n *\n * @remarks\n * Every rule sits inside `:where()`, so it adds no specificity and an author's class always wins.\n * Every grid and item carries `data-se-theme`, so a form of theme B inside a grid item of theme A\n * has both themes above it; the nearest theme's rule must be the one that matches, whatever the\n * order of the stylesheets. Empty when no value declares tokens. Two sets of rules say so:\n *\n * 1. Plain rules, which match an element that carries the theme and the pick together, or a\n * descendant of the theme's root with no element of another theme between. They need only\n * `:where()` and complex selectors in `:not()`, so they hold in server-rendered output in every\n * browser the renderers support. They cannot say \"no other theme between\" for a theme re-entered\n * below another theme (A in B in A): its descendants match no plain rule, so they inherit the\n * custom properties of the nearest element that did.\n * 2. `@scope` rules, emitted after the plain ones in one block: the theme's roots down to the nearest\n * element of another theme. A browser without `@scope` drops the block and keeps the plain rules;\n * one with it is exact, A in B in A included. About 1.1 KB per theme with the built-in axes.\n *\n * The `@scope` rules change one cascade detail: scope proximity outranks source order, and an\n * unscoped rule is the farthest from any root. A zero-specificity author rule such as `:where(.x)`\n * therefore loses to a token rule in a browser with `@scope`, where it won on order alone before;\n * a class with any specificity still wins.\n */\nexport function getAppearanceCss(appearance: CompiledAppearance, themeId: string): string {\n\tconst plain: string[] = [];\n\tconst scoped: string[] = [];\n\tconst scope = `[data-se-theme=\"${themeId}\"]`;\n\tconst foreign = `[data-se-theme]:not(${scope})`;\n\tfor (const axis of appearance.registry.all()) {\n\t\tfor (const [value, tokens] of Object.entries(axis.values)) {\n\t\t\tconst declarations = Object.entries(tokens).map(([token, tokenValue]) => `${token}:${tokenValue};`);\n\t\t\tif (declarations.length === 0) continue;\n\t\t\tconst block = `{${declarations.join('')}}`;\n\t\t\tconst match = `[data-se-${axis.$type}=\"${value}\"]`;\n\t\t\tconst descendant = `${scope} ${match}:not(${foreign},${scope} ${foreign} *)`;\n\t\t\tplain.push(`:where(${scope}${match},${descendant})${block}`);\n\t\t\tscoped.push(`:where(:scope${match},${match})${block}`);\n\t\t}\n\t}\n\tif (scoped.length === 0) return '';\n\treturn [...plain, `@scope (${scope}) to (${foreign}){${scoped.join('')}}`].join('\\n');\n}\n\n/**\n * Compiles a list of axes into the theme's appearance vocabulary.\n *\n * @param axes - The axes of the theme; defaults to {@link builtInAxes}. A later axis with the same\n * `$type` replaces the earlier one, so `[...builtInAxes, mine]` overrides.\n *\n * @remarks\n * Stores the axes with `createRegistry`, so each needs a Standard Schema, and holds every winner to\n * the rules {@link defineAxis} states. Throws on an invalid axis and on one named in `reservedNames`.\n */\nexport function compileAppearance(\n\taxes: readonly AnyAxisRegistration[] = builtInAxes,\n\tcompiler: LayoutThemeCompilerOptions = {},\n): CompiledAppearance {\n\tconst registry = createRegistry<AnyAxisRegistration>('Axis', axes);\n\tconst reserved = new Set(compiler.reservedNames);\n\tfor (const axis of registry.all()) {\n\t\tassertValidAxis(axis);\n\t\tassertAxisNotReserved(axis.$type, reserved);\n\t}\n\treturn Object.freeze({\n\t\tregistry,\n\t\taxes: Object.freeze(\n\t\t\tObject.fromEntries(registry.all().map((axis) => [axis.$type, Object.freeze(Object.keys(axis.values))])),\n\t\t),\n\t});\n}\n\n/**\n * The `data-se-<axis>` attributes for a resolved selection.\n *\n * @remarks A renderer spreads this on every element that carries a pick.\n */\nexport function getAppearanceAttributes(appearance: AppearanceSelection | undefined): Record<string, string> {\n\tconst attributes: Record<string, string> = {};\n\tfor (const [axis, value] of Object.entries(appearance ?? {})) attributes[`data-se-${axis}`] = value;\n\treturn attributes;\n}\n\n/**\n * A child's picks laid over the picks it inherits: the child's value wins per axis.\n *\n * @remarks Pure merge; checking that the child's axes are valid is {@link checkAppearance}'s job.\n */\nexport function mergeAppearance(\n\tinherited: AppearanceSelection | undefined,\n\town: AppearanceSelection | undefined,\n): Record<string, string> {\n\treturn { ...inherited, ...own };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Checks an authored pick against the vocabulary and, when given, the axes its owner supports.\n *\n * @param subject Names the owner in a message, for example `Element 'fieldSet'`.\n * @param supported The axes the owner declares; an owner that declares none passes `[]`. Omit it for an owner that accepts every axis.\n * @returns One issue per problem, with a path relative to the authored pick (`['appearance', axis]`), and the valid picks.\n */\nexport function checkAppearance(\n\tauthored: unknown,\n\toptions: { axes: LayoutTheme['axes']; subject: string; supported?: readonly string[] },\n): { issues: LayoutIssue[]; appearance: Record<string, string> } {\n\tconst issues: LayoutIssue[] = [];\n\tconst appearance: Record<string, string> = {};\n\tif (authored === undefined) return { issues, appearance };\n\tif (!isRecord(authored)) {\n\t\treturn {\n\t\t\tissues: [{ path: ['appearance'], message: 'Expected an object of axis names to values.' }],\n\t\t\tappearance,\n\t\t};\n\t}\n\tconst declared = Object.keys(options.axes).join(', ');\n\tfor (const [axis, value] of Object.entries(authored)) {\n\t\tconst values = Object.hasOwn(options.axes, axis) ? options.axes[axis] : undefined;\n\t\tif (!values) {\n\t\t\tissues.push({ path: ['appearance', axis], message: `Unknown axis '${axis}'. Declared axes: ${declared}.` });\n\t\t\tcontinue;\n\t\t}\n\t\tif (options.supported !== undefined && !options.supported.includes(axis)) {\n\t\t\tconst supported = options.supported.length > 0 ? options.supported.join(', ') : '(none)';\n\t\t\tissues.push({\n\t\t\t\tpath: ['appearance', axis],\n\t\t\t\tmessage: `${options.subject} does not support the axis '${axis}'. Supported axes: ${supported}.`,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (typeof value !== 'string') {\n\t\t\tissues.push({ path: ['appearance', axis], message: `Expected one of ${values.join(', ')}.` });\n\t\t\tcontinue;\n\t\t}\n\t\tif (!values.includes(value)) {\n\t\t\tissues.push({\n\t\t\t\tpath: ['appearance', axis],\n\t\t\t\tmessage: `'${value}' is not a value of '${axis}'. Allowed: ${values.join(', ')}.`,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tappearance[axis] = value;\n\t}\n\treturn { issues, appearance };\n}\n\n/** Keeps the axes an owner supports. An owner that declares none keeps none. */\nexport function pickSupportedAppearance(\n\tselection: AppearanceSelection,\n\tsupported: readonly string[] | undefined,\n): Record<string, string> {\n\tconst picked: Record<string, string> = {};\n\tfor (const axis of supported ?? []) {\n\t\tconst value = selection[axis];\n\t\tif (value !== undefined) picked[axis] = value;\n\t}\n\treturn picked;\n}\n", "/**\n * @remarks\n * Duplicates the helper the forms package keeps for its own deep operations on purpose: this\n * package cannot import forms.\n */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\tif (typeof value !== 'object' || value === null) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\nfunction mergeDeep(base: unknown, override: unknown): unknown {\n\tif (override === undefined) return base;\n\tif (!isPlainObject(base) || !isPlainObject(override)) return override;\n\tconst merged: Record<string, unknown> = { ...base };\n\tfor (const [key, value] of Object.entries(override)) {\n\t\tmerged[key] = mergeDeep(base[key], value);\n\t}\n\treturn merged;\n}\n\n/**\n * Lays a view's slot config over the recipe's `slotDefaults`, deep for plain objects.\n *\n * @remarks\n * Runs before the view schema parses, so schema defaults fill only what neither the author\n * nor the recipe set. Arrays and other non-plain values replace the default whole. A key the author sets to `undefined` keeps the recipe default.\n */\nexport function mergeSlotDefaults(\n\tview: Record<string, unknown>,\n\tslotDefaults: Record<string, unknown> | undefined,\n): Record<string, unknown> {\n\tif (!slotDefaults) return view;\n\tconst merged = { ...view };\n\tfor (const [slot, defaults] of Object.entries(slotDefaults)) {\n\t\tmerged[slot] = mergeDeep(defaults, view[slot]);\n\t}\n\treturn merged;\n}\n"],
|
|
5
|
+
"mappings": "AACA,OAAS,2BAAAA,MAA+B,0BCDxC,OACC,kBAAAC,MAIM,0BACP,UAAYC,MAAO,WA4EnB,IAAMC,EAAY,kCACZC,EAAa,8BACbC,EAAqB,cACrBC,EAAkB,EAClBC,EAAkB,EAuBxB,SAASC,EAAgBC,EAAiC,CACzD,IAAMC,EAAOD,EAAK,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AAQP,CAAQ,EAAG,CACzD,IAAMgB,EAAcH,EAAmCZ,CAAI,EACvDlB,EAAciC,CAAU,IAAGD,EAAKd,CAAI,EAAI,CAAE,GAAGe,EAAY,WAAYT,CAAU,EACpF,CACA,MAAO,CAAE,OAAAT,EAAQ,KAAMiB,CAAK,CAC7B",
|
|
6
|
+
"names": ["safeParseStandardSchema", "createRegistry", "z", "AXIS_NAME", "VALUE_NAME", "UNSAFE_TOKEN_VALUE", "MIN_AXIS_VALUES", "MAX_AXIS_VALUES", "assertValidAxis", "axis", "name", "AXIS_NAME", "entries", "MIN_AXIS_VALUES", "MAX_AXIS_VALUES", "value", "tokens", "VALUE_NAME", "token", "tokenValue", "UNSAFE_TOKEN_VALUE", "defineAxis", "definition", "sizeAxis", "surfaceAxis", "mergeAppearance", "inherited", "own", "isRecord", "value", "checkAppearance", "authored", "options", "issues", "appearance", "declared", "axis", "values", "supported", "pickSupportedAppearance", "selection", "picked", "isPlainObject", "value", "prototype", "mergeDeep", "base", "override", "merged", "key", "mergeSlotDefaults", "view", "slotDefaults", "slot", "defaults", "isPlainRecord", "value", "prototype", "withoutAppearance", "config", "_authored", "rest", "unknownViewKeyMessage", "$type", "key", "allowed", "resolveRecipeView", "recipe", "view", "scope", "issues", "stripped", "resolved", "slot", "authoredSlot", "supported", "checked", "checkAppearance", "issue", "selection", "pickSupportedAppearance", "mergeAppearance", "parsed", "safeParseStandardSchema", "mergeSlotDefaults", "output", "allowedSlots", "next", "slotConfig"]
|
|
7
7
|
}
|
package/dist/recipes/types.d.ts
CHANGED
|
@@ -1,10 +1,17 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import type { StandardSchemaV1 } from '@standard-schema/spec';
|
|
2
2
|
import type { BaseRegistration, ComponentMetadata } from '@schema-engine/registry';
|
|
3
3
|
import type { SlotAppearanceAxes } from '../lib/appearance';
|
|
4
4
|
export interface RecipeMetadata extends ComponentMetadata {
|
|
5
5
|
category?: string;
|
|
6
6
|
}
|
|
7
|
-
|
|
7
|
+
/**
|
|
8
|
+
* The schema of each slot a spec declares: any Standard Schema that validates synchronously.
|
|
9
|
+
*
|
|
10
|
+
* @remarks
|
|
11
|
+
* The view schema runs each slot schema synchronously, as `resolveRecipeView` and the registry's `safeParseNode` need
|
|
12
|
+
* an immediate result, so a slot schema that returns a Promise throws where a view is parsed.
|
|
13
|
+
*/
|
|
14
|
+
export type ProtocolRecipeSlotSchemas<TSlot extends string = string> = Partial<Record<TSlot, StandardSchemaV1>>;
|
|
8
15
|
/**
|
|
9
16
|
* Slot config applied beneath a view's own slot config, typed as the input of each declared slot schema.
|
|
10
17
|
*
|
|
@@ -12,10 +19,10 @@ export type ProtocolRecipeSlotSchemas<TSlot extends string = string> = Partial<R
|
|
|
12
19
|
* Undeclared slots and misspelled keys are compile errors; `defineProtocolRecipeSpec` also parses each
|
|
13
20
|
* default against its slot schema.
|
|
14
21
|
*/
|
|
15
|
-
export type RecipeSlotDefaults<TSlots extends
|
|
16
|
-
[K in keyof TSlots]?: TSlots[K] extends
|
|
22
|
+
export type RecipeSlotDefaults<TSlots extends ProtocolRecipeSlotSchemas> = {
|
|
23
|
+
[K in keyof TSlots]?: TSlots[K] extends StandardSchemaV1 ? StandardSchemaV1.InferInput<TSlots[K]> : never;
|
|
17
24
|
};
|
|
18
|
-
export interface ProtocolRecipeSpec<TSlot extends string = string, TKind extends string = string, TType extends string = string, TSchema extends
|
|
25
|
+
export interface ProtocolRecipeSpec<TSlot extends string = string, TKind extends string = string, TType extends string = string, TSchema extends StandardSchemaV1 = StandardSchemaV1, TSlots extends ProtocolRecipeSlotSchemas<TSlot> = ProtocolRecipeSlotSchemas<TSlot>> {
|
|
19
26
|
$type: TType;
|
|
20
27
|
kind: TKind;
|
|
21
28
|
slots: TSlot[];
|
|
@@ -25,7 +32,7 @@ export interface ProtocolRecipeSpec<TSlot extends string = string, TKind extends
|
|
|
25
32
|
* Appearance axes each slot supports (`{ shell: ['size', 'surface'] }`); undeclared axes fail validation on that slot.
|
|
26
33
|
*
|
|
27
34
|
* @remarks
|
|
28
|
-
* A slot that declares axes must accept an `appearance` key in its schema, so authored
|
|
35
|
+
* A slot that declares axes must accept an `appearance` key in its schema input, which the types enforce, so authored
|
|
29
36
|
* configs type-check and the JSON Schema lists it. A validator that resolves the view (forms: `validateForm`) does not
|
|
30
37
|
* pass the key to the slot schema when it parses it, and writes the resolved selection back, so a renderer reading the
|
|
31
38
|
* normalized slot sees it.
|
|
@@ -49,5 +56,13 @@ export interface ProtocolRecipeRegistration<TSlot extends string = string, TKind
|
|
|
49
56
|
metadata: RecipeMetadata;
|
|
50
57
|
slotDefaults?: Partial<Record<TSlot, Record<string, unknown>>>;
|
|
51
58
|
appearanceAxes?: SlotAppearanceAxes<TSlot>;
|
|
59
|
+
/**
|
|
60
|
+
* The schema of each declared slot, as the spec declared it.
|
|
61
|
+
*
|
|
62
|
+
* @remarks
|
|
63
|
+
* Set by `bindRecipe`. A domain's export reads it (forms: the JSON Schema of each slot); validation reads `schema`.
|
|
64
|
+
* A hand-written registration may leave it out. When set, its keys must be the recipe's `slots`.
|
|
65
|
+
*/
|
|
66
|
+
readonly slotSchemas?: ProtocolRecipeSlotSchemas<TSlot>;
|
|
52
67
|
render: TRender;
|
|
53
68
|
}
|