@serene-pub/sdk 0.6.0-pr-1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (187) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +17 -0
  3. package/README.md +368 -0
  4. package/dist/actions.d.ts +572 -0
  5. package/dist/actions.js +829 -0
  6. package/dist/annexFields.d.ts +234 -0
  7. package/dist/annexFields.js +413 -0
  8. package/dist/announce.d.ts +464 -0
  9. package/dist/announce.js +426 -0
  10. package/dist/attributes.d.ts +670 -0
  11. package/dist/attributes.js +904 -0
  12. package/dist/bands.d.ts +125 -0
  13. package/dist/bands.js +256 -0
  14. package/dist/builder.d.ts +683 -0
  15. package/dist/builder.js +677 -0
  16. package/dist/candidates.d.ts +109 -0
  17. package/dist/candidates.js +118 -0
  18. package/dist/capabilities.d.ts +744 -0
  19. package/dist/capabilities.js +679 -0
  20. package/dist/channels.d.ts +106 -0
  21. package/dist/channels.js +129 -0
  22. package/dist/clauses.d.ts +40 -0
  23. package/dist/clauses.js +43 -0
  24. package/dist/component.d.ts +33 -0
  25. package/dist/component.js +27 -0
  26. package/dist/componentBuild.d.ts +48 -0
  27. package/dist/componentBuild.js +84 -0
  28. package/dist/componentClient.d.ts +100 -0
  29. package/dist/componentClient.js +13 -0
  30. package/dist/componentImports.d.ts +51 -0
  31. package/dist/componentImports.js +106 -0
  32. package/dist/componentModule.d.ts +8 -0
  33. package/dist/componentModule.js +270 -0
  34. package/dist/componentWire.d.ts +130 -0
  35. package/dist/componentWire.js +280 -0
  36. package/dist/config.d.ts +295 -0
  37. package/dist/config.js +231 -0
  38. package/dist/connections.d.ts +89 -0
  39. package/dist/connections.js +131 -0
  40. package/dist/declarations.d.ts +290 -0
  41. package/dist/declarations.js +794 -0
  42. package/dist/descriptors.d.ts +1774 -0
  43. package/dist/descriptors.js +1329 -0
  44. package/dist/dev.d.ts +136 -0
  45. package/dist/dev.js +161 -0
  46. package/dist/document.d.ts +202 -0
  47. package/dist/document.js +312 -0
  48. package/dist/engines.d.ts +117 -0
  49. package/dist/engines.js +203 -0
  50. package/dist/eventMapLaws.d.ts +63 -0
  51. package/dist/eventMapLaws.js +128 -0
  52. package/dist/events.d.ts +554 -0
  53. package/dist/events.js +633 -0
  54. package/dist/executor.d.ts +771 -0
  55. package/dist/executor.js +1829 -0
  56. package/dist/extension.d.ts +448 -0
  57. package/dist/extension.js +315 -0
  58. package/dist/facets.d.ts +53 -0
  59. package/dist/facets.js +60 -0
  60. package/dist/foldedSections.d.ts +74 -0
  61. package/dist/foldedSections.js +161 -0
  62. package/dist/genres.d.ts +507 -0
  63. package/dist/genres.js +633 -0
  64. package/dist/guardedConnection.d.ts +138 -0
  65. package/dist/guardedConnection.js +341 -0
  66. package/dist/handlebarsReach.d.ts +122 -0
  67. package/dist/handlebarsReach.js +222 -0
  68. package/dist/hash.d.ts +146 -0
  69. package/dist/hash.js +166 -0
  70. package/dist/hookGrants.d.ts +47 -0
  71. package/dist/hookGrants.js +68 -0
  72. package/dist/hooks.d.ts +290 -0
  73. package/dist/hooks.js +113 -0
  74. package/dist/hostElements.d.ts +447 -0
  75. package/dist/hostElements.js +702 -0
  76. package/dist/i18n.d.ts +94 -0
  77. package/dist/i18n.js +123 -0
  78. package/dist/identity.d.ts +93 -0
  79. package/dist/identity.js +135 -0
  80. package/dist/index.d.ts +85 -0
  81. package/dist/index.js +176 -0
  82. package/dist/layout.d.ts +194 -0
  83. package/dist/layout.js +40 -0
  84. package/dist/media.d.ts +202 -0
  85. package/dist/media.js +70 -0
  86. package/dist/messageBlocks.d.ts +487 -0
  87. package/dist/messageBlocks.js +683 -0
  88. package/dist/migration.d.ts +128 -0
  89. package/dist/migration.js +261 -0
  90. package/dist/names.d.ts +78 -0
  91. package/dist/names.js +136 -0
  92. package/dist/nodeInput.d.ts +399 -0
  93. package/dist/nodeInput.js +178 -0
  94. package/dist/participants.d.ts +291 -0
  95. package/dist/participants.js +252 -0
  96. package/dist/personGate.d.ts +62 -0
  97. package/dist/personGate.js +77 -0
  98. package/dist/pick.d.ts +84 -0
  99. package/dist/pick.js +103 -0
  100. package/dist/pluginHarness.d.ts +235 -0
  101. package/dist/pluginHarness.js +558 -0
  102. package/dist/pluginPermissions.d.ts +25 -0
  103. package/dist/pluginPermissions.js +97 -0
  104. package/dist/pluginRuleRef.d.ts +13 -0
  105. package/dist/pluginRuleRef.js +10 -0
  106. package/dist/predicates.d.ts +182 -0
  107. package/dist/predicates.js +249 -0
  108. package/dist/preview.d.ts +120 -0
  109. package/dist/preview.js +82 -0
  110. package/dist/promptBlocks.d.ts +130 -0
  111. package/dist/promptBlocks.js +197 -0
  112. package/dist/rankingDecisions.d.ts +60 -0
  113. package/dist/rankingDecisions.js +48 -0
  114. package/dist/receipt.d.ts +313 -0
  115. package/dist/receipt.js +60 -0
  116. package/dist/receiverRules.d.ts +24 -0
  117. package/dist/receiverRules.js +94 -0
  118. package/dist/refs.d.ts +117 -0
  119. package/dist/refs.js +137 -0
  120. package/dist/registry.d.ts +230 -0
  121. package/dist/registry.js +273 -0
  122. package/dist/review.d.ts +108 -0
  123. package/dist/review.js +97 -0
  124. package/dist/sampling.d.ts +152 -0
  125. package/dist/sampling.js +712 -0
  126. package/dist/scope.d.ts +65 -0
  127. package/dist/scope.js +128 -0
  128. package/dist/scripts.d.ts +243 -0
  129. package/dist/scripts.js +326 -0
  130. package/dist/sessionLayout.d.ts +339 -0
  131. package/dist/sessionLayout.js +503 -0
  132. package/dist/sessionSettings.d.ts +70 -0
  133. package/dist/sessionSettings.js +2 -0
  134. package/dist/settings.d.ts +501 -0
  135. package/dist/settings.js +604 -0
  136. package/dist/settingsSlot.d.ts +108 -0
  137. package/dist/settingsSlot.js +166 -0
  138. package/dist/shapes.d.ts +373 -0
  139. package/dist/shapes.js +408 -0
  140. package/dist/sheets.d.ts +165 -0
  141. package/dist/sheets.js +251 -0
  142. package/dist/statShapes.d.ts +96 -0
  143. package/dist/statShapes.js +112 -0
  144. package/dist/status.d.ts +103 -0
  145. package/dist/status.js +125 -0
  146. package/dist/storage.d.ts +145 -0
  147. package/dist/storage.js +33 -0
  148. package/dist/storyTime.d.ts +308 -0
  149. package/dist/storyTime.js +560 -0
  150. package/dist/surfaces.d.ts +501 -0
  151. package/dist/surfaces.js +292 -0
  152. package/dist/template.d.ts +312 -0
  153. package/dist/template.js +554 -0
  154. package/dist/templateCheck.d.ts +60 -0
  155. package/dist/templateCheck.js +516 -0
  156. package/dist/templateFit.d.ts +157 -0
  157. package/dist/templateFit.js +349 -0
  158. package/dist/templateIds.d.ts +138 -0
  159. package/dist/templateIds.js +144 -0
  160. package/dist/templateScopeAt.d.ts +131 -0
  161. package/dist/templateScopeAt.js +354 -0
  162. package/dist/testing.d.ts +177 -0
  163. package/dist/testing.js +383 -0
  164. package/dist/tokenizers.d.ts +113 -0
  165. package/dist/tokenizers.js +184 -0
  166. package/dist/turnLock.d.ts +96 -0
  167. package/dist/turnLock.js +79 -0
  168. package/dist/turnOrder.d.ts +143 -0
  169. package/dist/turnOrder.js +128 -0
  170. package/dist/validate.d.ts +74 -0
  171. package/dist/validate.js +1399 -0
  172. package/dist/values.d.ts +212 -0
  173. package/dist/values.js +390 -0
  174. package/dist/variables.d.ts +493 -0
  175. package/dist/variables.js +662 -0
  176. package/dist/verdicts.d.ts +275 -0
  177. package/dist/verdicts.js +348 -0
  178. package/dist/widgetDecls.d.ts +88 -0
  179. package/dist/widgetDecls.js +119 -0
  180. package/dist/widgets.d.ts +1527 -0
  181. package/dist/widgets.js +208 -0
  182. package/dist/wire.d.ts +126 -0
  183. package/dist/wire.js +140 -0
  184. package/dist/worldinfo.d.ts +150 -0
  185. package/dist/worldinfo.js +212 -0
  186. package/host-elements.d.ts +914 -0
  187. package/package.json +67 -0
@@ -0,0 +1,212 @@
1
+ /**
2
+ * The value-type system (24 §8).
3
+ *
4
+ * Authoring goes through a toolkit facade — `v.integer({})`, `v.weights({})`,
5
+ * `v.stackedBar({})` — for ergonomics and dot-discoverability; the output is
6
+ * always **frozen plain data** in single-key typed serialization:
7
+ *
8
+ * v.integer({ min: 0, max: 4096 }) → { "integer@1": { min: 0, max: 4096 } }
9
+ *
10
+ * The key IS the type id, versioned exactly like node types: `integer@2` is a
11
+ * new key, never a mutated schema under the old one. Package-minted kinds
12
+ * serialize namespaced (`acme.dice:roll@1`) via a context-bound toolkit, so
13
+ * collision with core or another package is impossible by construction.
14
+ * Unknown keys degrade safely: consumers render a read-only fallback and
15
+ * refuse writes to types they cannot validate.
16
+ *
17
+ * Constraints come in two tiers, both pure data (24 §8):
18
+ * - T1 declarative: min/max/step/pattern/options; group: sumTo/normalize.
19
+ * - T2 predicates: `requiredWhen`/`visibleWhen`/`enabledWhen`, reusing the
20
+ * route-predicate shape ({path, equals, truthy}) — declarations that read
21
+ * as sentences, renderable without running anything.
22
+ * T3 (validator code) is deliberately absent.
23
+ *
24
+ * Four consumers key off the same id — factory (here), validator (here),
25
+ * control renderer (@serene-pub/controls), scaffold printer (cli) — and a
26
+ * conformance canary asserts no shipped type is missing any of the four.
27
+ */
28
+ import { type I18n } from './i18n.js';
29
+ /**
30
+ * One condition over sibling values — the route-predicate shape (20 §10).
31
+ * A settings-form field's gate, not the action-level **enabled-when** of
32
+ * `predicates.ts` (which reads the session's published values and carries a
33
+ * `reason`); the two share the shape, not the document.
34
+ * @experimental
35
+ */
36
+ export interface ValuePredicate {
37
+ /** Dot path into the sibling value map. */
38
+ path: string;
39
+ /** Fires when the value strictly equals this literal. */
40
+ equals?: unknown;
41
+ /** Fires when the value is truthy. */
42
+ truthy?: boolean;
43
+ }
44
+ /** Fields every declaration may carry, regardless of kind. @experimental */
45
+ export interface ValueCommon {
46
+ /** What a person reads beside the control — a string or a locale map with `en` (R-20). */
47
+ label?: I18n;
48
+ description?: I18n;
49
+ /**
50
+ * No shipped default — a config MUST supply this value. Requiredness is
51
+ * what makes "missing" a fact the coverage report can state (24 §7).
52
+ */
53
+ required?: boolean;
54
+ requiredWhen?: ValuePredicate;
55
+ visibleWhen?: ValuePredicate;
56
+ enabledWhen?: ValuePredicate;
57
+ }
58
+ /**
59
+ * A value declaration in single-key form: exactly one key, which is the
60
+ * versioned type id; the payload is that type's own schema.
61
+ * @experimental
62
+ */
63
+ export type ValueDecl = {
64
+ readonly [definitionId: string]: Record<string, unknown>;
65
+ };
66
+ /** The one key of a declaration — its type id. Throws on malformed decls. @experimental */
67
+ export declare function valueKind(decl: ValueDecl): string;
68
+ /** @experimental */
69
+ export declare function assertValueTypeId(id: string): void;
70
+ /** @experimental */
71
+ export interface IntegerProps extends ValueCommon {
72
+ min?: number;
73
+ max?: number;
74
+ step?: number;
75
+ default?: number;
76
+ }
77
+ /** @experimental */
78
+ export interface NumberProps extends ValueCommon {
79
+ min?: number;
80
+ max?: number;
81
+ step?: number;
82
+ default?: number;
83
+ }
84
+ /** @experimental */
85
+ export interface WeightsProps extends ValueCommon {
86
+ /** Part name → author-default weight. The parts are the group. */
87
+ parts: Record<string, number>;
88
+ /**
89
+ * The pinned sum (100 for percents, 1 for fractions). Absent = free
90
+ * weights; add `normalize: true` when the consumer reads them normalized.
91
+ */
92
+ total?: number;
93
+ step?: number;
94
+ /** Per-part floor/ceiling. */
95
+ min?: number;
96
+ max?: number;
97
+ normalize?: boolean;
98
+ /** Which control edits this — presentation, not domain. */
99
+ control?: 'stacked-bar' | 'sliders';
100
+ }
101
+ /** @experimental */
102
+ export interface SelectProps extends ValueCommon {
103
+ /**
104
+ * A closed set. `description` is part of the option because the control
105
+ * shows it under the picker — a stored value like `rag` is not a word
106
+ * anybody chose to read, and the place to say what it means is the
107
+ * declaration, not the host.
108
+ */
109
+ options: ReadonlyArray<string | {
110
+ value: string;
111
+ label?: I18n;
112
+ description?: I18n;
113
+ }>;
114
+ default?: string;
115
+ }
116
+ /** @experimental */
117
+ export interface RankingProps extends ValueCommon {
118
+ /** The orderable set; the value is a permutation of it. */
119
+ options: ReadonlyArray<string>;
120
+ default?: ReadonlyArray<string>;
121
+ }
122
+ /** @experimental */
123
+ export interface TextProps extends ValueCommon {
124
+ minLength?: number;
125
+ maxLength?: number;
126
+ /** Anchored ECMAScript regex source. */
127
+ pattern?: string;
128
+ default?: string;
129
+ multiline?: boolean;
130
+ }
131
+ /** @experimental */
132
+ export interface BooleanProps extends ValueCommon {
133
+ default?: boolean;
134
+ }
135
+ /** A prompts-ref slot: the value is a reference to a shipped/named prompt. @experimental */
136
+ export interface PromptProps extends ValueCommon {
137
+ }
138
+ /** @experimental */
139
+ export interface ValueToolkit {
140
+ integer(props?: IntegerProps): ValueDecl;
141
+ number(props?: NumberProps): ValueDecl;
142
+ /** Sugar: a number in [0, 1] with a 0.01 step. */
143
+ fraction(props?: Omit<NumberProps, 'min' | 'max'>): ValueDecl;
144
+ weights(props: WeightsProps): ValueDecl;
145
+ /** Sugar: weights rendered as a stacked bar. */
146
+ stackedBar(props: Omit<WeightsProps, 'control'>): ValueDecl;
147
+ select(options: SelectProps['options'] | SelectProps, props?: Omit<SelectProps, 'options'>): ValueDecl;
148
+ ranking(options: RankingProps['options'], props?: Omit<RankingProps, 'options'>): ValueDecl;
149
+ text(props?: TextProps): ValueDecl;
150
+ boolean(props?: BooleanProps): ValueDecl;
151
+ prompt(props?: PromptProps): ValueDecl;
152
+ /**
153
+ * A package-minted kind. With a context-bound toolkit the id is prefixed
154
+ * with the package namespace automatically; the bare toolkit refuses,
155
+ * because an unprefixed custom kind could shadow a future core one.
156
+ */
157
+ custom(kind: string, version: number, props: Record<string, unknown>): ValueDecl;
158
+ }
159
+ /**
160
+ * Construct a toolkit. `ns` is the declaring package's namespace — your
161
+ * plugin's slug — and prefixes every custom kind. The bare exported `v` has no
162
+ * namespace and mints no custom kinds.
163
+ * @experimental
164
+ */
165
+ export declare function makeValueToolkit(ns?: string): ValueToolkit;
166
+ /** The bare toolkit: core kinds only, no custom minting. @experimental */
167
+ export declare const v: ValueToolkit;
168
+ type Validator = (schema: Record<string, unknown>, value: unknown) => string[];
169
+ /**
170
+ * Validators for the shipped kinds, keyed by type id. Kept beside the
171
+ * factories so adding a kind is one edit — the conformance canary refuses a
172
+ * factory output whose kind has no validator here.
173
+ * @experimental
174
+ */
175
+ export declare const valueValidators: Record<string, Validator>;
176
+ /**
177
+ * Validate one value against its declaration. Unknown type ids refuse —
178
+ * a consumer must never accept a write it cannot check (24 §8).
179
+ * @experimental
180
+ */
181
+ export declare function validateValue(declaration: ValueDecl, value: unknown): string[];
182
+ /**
183
+ * A deliberate hole (24 §7): type-checks wherever a value goes, so authoring
184
+ * can continue — but the coverage report lists it as a named gap, and
185
+ * validation refuses it like any other unknown.
186
+ * @experimental
187
+ */
188
+ export declare function todo(note: string): {
189
+ 'todo@1': {
190
+ note: string;
191
+ };
192
+ };
193
+ /** @experimental */
194
+ export declare const isTodo: (value: unknown) => value is {
195
+ 'todo@1': {
196
+ note: string;
197
+ };
198
+ };
199
+ /** Every kind the bare toolkit can mint — the registry the canary checks. @experimental */
200
+ export declare const shippedValueKinds: readonly string[];
201
+ /**
202
+ * The bridge from the settings-schema vocabulary (`{type:'integer', …}` on
203
+ * node-type slots) to value declarations (24 T6c). Derived at read, never
204
+ * stored — no document or hash changes — so panels and controls can speak
205
+ * the value-decl contract while the schemas migrate underneath at their own
206
+ * pace. Unknown entry types map to nothing, and the caller keeps its
207
+ * legacy rendering for them.
208
+ * @experimental
209
+ */
210
+ export declare function valueDeclOf(entry: unknown): ValueDecl | null;
211
+ export {};
212
+ //# sourceMappingURL=values.d.ts.map
package/dist/values.js ADDED
@@ -0,0 +1,390 @@
1
+ /**
2
+ * The value-type system (24 §8).
3
+ *
4
+ * Authoring goes through a toolkit facade — `v.integer({})`, `v.weights({})`,
5
+ * `v.stackedBar({})` — for ergonomics and dot-discoverability; the output is
6
+ * always **frozen plain data** in single-key typed serialization:
7
+ *
8
+ * v.integer({ min: 0, max: 4096 }) → { "integer@1": { min: 0, max: 4096 } }
9
+ *
10
+ * The key IS the type id, versioned exactly like node types: `integer@2` is a
11
+ * new key, never a mutated schema under the old one. Package-minted kinds
12
+ * serialize namespaced (`acme.dice:roll@1`) via a context-bound toolkit, so
13
+ * collision with core or another package is impossible by construction.
14
+ * Unknown keys degrade safely: consumers render a read-only fallback and
15
+ * refuse writes to types they cannot validate.
16
+ *
17
+ * Constraints come in two tiers, both pure data (24 §8):
18
+ * - T1 declarative: min/max/step/pattern/options; group: sumTo/normalize.
19
+ * - T2 predicates: `requiredWhen`/`visibleWhen`/`enabledWhen`, reusing the
20
+ * route-predicate shape ({path, equals, truthy}) — declarations that read
21
+ * as sentences, renderable without running anything.
22
+ * T3 (validator code) is deliberately absent.
23
+ *
24
+ * Four consumers key off the same id — factory (here), validator (here),
25
+ * control renderer (@serene-pub/controls), scaffold printer (cli) — and a
26
+ * conformance canary asserts no shipped type is missing any of the four.
27
+ */
28
+ import { i18nFindings } from './i18n.js';
29
+ /** The one key of a declaration — its type id. Throws on malformed decls. @experimental */
30
+ export function valueKind(decl) {
31
+ const keys = Object.keys(decl);
32
+ if (keys.length !== 1)
33
+ throw new Error(`a value declaration holds exactly one key (its type id); got [${keys.join(', ')}]`);
34
+ return keys[0];
35
+ }
36
+ /** Type id syntax: `name@N` or `owner:name@N` — same discipline as node types. */
37
+ const VALUE_TYPE_ID = /^([a-z0-9]+(?:[.-][a-z0-9]+)*:)?[a-z0-9]+(?:-[a-z0-9]+)*@\d+$/;
38
+ /** @experimental */
39
+ export function assertValueTypeId(id) {
40
+ if (!VALUE_TYPE_ID.test(id))
41
+ throw new Error(`'${id}' is not a valid value-type id. Use 'name@N' for core kinds or ` +
42
+ `'owner:name@N' for package-minted ones — the version lives in the key ` +
43
+ `('integer@2' is a new key, never a mutated 'integer@1').`);
44
+ }
45
+ const freeze = (o) => Object.freeze(o);
46
+ /** Builds the single-key object, dropping undefined fields for canonical JSON. */
47
+ function decl(definitionId, props) {
48
+ assertValueTypeId(definitionId);
49
+ const clean = {};
50
+ for (const [k, val] of Object.entries(props))
51
+ if (val !== undefined)
52
+ clean[k] = val;
53
+ return freeze({ [definitionId]: freeze(clean) });
54
+ }
55
+ /**
56
+ * The authoring door's half of R-20: a declaration's `label` and
57
+ * `description`, and each select option's, are display text — a string or a
58
+ * locale map with `en` — refused at the author's line otherwise. `decl()`
59
+ * itself stays unchecked because `valueDeclOf` bridges stored schemas through
60
+ * it at read time, and a panel is not the place to refuse a row.
61
+ */
62
+ function declared(definitionId, props) {
63
+ const findings = [
64
+ ...i18nFindings(props.label, `${definitionId} label`),
65
+ ...i18nFindings(props.description, `${definitionId} description`),
66
+ ];
67
+ if (Array.isArray(props.options))
68
+ props.options.forEach((o, i) => {
69
+ if (!o || typeof o !== 'object')
70
+ return;
71
+ const at = `${definitionId} options[${typeof o.value === 'string' ? o.value : i}]`;
72
+ findings.push(...i18nFindings(o.label, `${at}.label`));
73
+ findings.push(...i18nFindings(o.description, `${at}.description`));
74
+ });
75
+ if (findings.length)
76
+ throw new Error(`${definitionId} declares display text a publish refuses (R-20):\n · ${findings.join('\n · ')}`);
77
+ return decl(definitionId, props);
78
+ }
79
+ /**
80
+ * Construct a toolkit. `ns` is the declaring package's namespace — your
81
+ * plugin's slug — and prefixes every custom kind. The bare exported `v` has no
82
+ * namespace and mints no custom kinds.
83
+ * @experimental
84
+ */
85
+ export function makeValueToolkit(ns) {
86
+ return freeze({
87
+ integer: (p = {}) => declared('integer@1', { ...p }),
88
+ number: (p = {}) => declared('number@1', { ...p }),
89
+ fraction: (p = {}) => declared('number@1', { min: 0, max: 1, step: p.step ?? 0.01, ...p }),
90
+ weights: (p) => {
91
+ validateWeightsProps(p);
92
+ return declared('weights@1', { ...p });
93
+ },
94
+ stackedBar: (p) => {
95
+ validateWeightsProps(p);
96
+ return declared('weights@1', { ...p, control: 'stacked-bar' });
97
+ },
98
+ select: (options, props) => {
99
+ const p = Array.isArray(options)
100
+ ? { options, ...props }
101
+ : options;
102
+ if (!p.options?.length)
103
+ throw new Error('select needs at least one option');
104
+ return declared('select@1', { ...p });
105
+ },
106
+ ranking: (options, props) => {
107
+ if (!options?.length)
108
+ throw new Error('ranking needs at least one option');
109
+ return declared('ranking@1', { options, ...props });
110
+ },
111
+ text: (p = {}) => {
112
+ if (p.pattern !== undefined)
113
+ new RegExp(p.pattern); // throws at the author's line
114
+ return declared('text@1', { ...p });
115
+ },
116
+ boolean: (p = {}) => declared('boolean@1', { ...p }),
117
+ prompt: (p = {}) => declared('prompt-ref@1', { ...p }),
118
+ custom: (kind, version, props) => {
119
+ if (!ns)
120
+ throw new Error(`custom value kinds need a package context — mint them with makeValueToolkit('<your slug>'), ` +
121
+ `so '${kind}' serializes namespaced ('yourpkg:${kind}@${version}') and cannot ` +
122
+ `shadow a core kind.`);
123
+ return declared(`${ns}:${kind}@${version}`, props);
124
+ },
125
+ });
126
+ }
127
+ /** Eager construction checks — thrown at the author's line, not in a document pass. */
128
+ function validateWeightsProps(p) {
129
+ const parts = Object.entries(p.parts ?? {});
130
+ if (!parts.length)
131
+ throw new Error('weights needs at least one part');
132
+ if (p.total !== undefined) {
133
+ const sum = parts.reduce((a, [, w]) => a + w, 0);
134
+ // Author defaults must satisfy the constraint they impose on everyone else.
135
+ if (Math.abs(sum - p.total) > 1e-9)
136
+ throw new Error(`weights parts sum to ${sum}, but total is pinned to ${p.total} — ` +
137
+ `the author defaults must satisfy the constraint they declare`);
138
+ }
139
+ for (const [name, w] of parts) {
140
+ if (p.min !== undefined && w < p.min)
141
+ throw new Error(`part '${name}' is below min ${p.min}`);
142
+ if (p.max !== undefined && w > p.max)
143
+ throw new Error(`part '${name}' is above max ${p.max}`);
144
+ }
145
+ }
146
+ /** The bare toolkit: core kinds only, no custom minting. @experimental */
147
+ export const v = makeValueToolkit();
148
+ const num = (x) => typeof x === 'number' && Number.isFinite(x);
149
+ const numberValidator = (integer) => (s, value) => {
150
+ const errors = [];
151
+ if (!num(value))
152
+ return [`expected a number, got ${typeof value}`];
153
+ if (integer && !Number.isInteger(value))
154
+ errors.push('expected an integer');
155
+ if (num(s.min) && value < s.min)
156
+ errors.push(`below min ${s.min}`);
157
+ if (num(s.max) && value > s.max)
158
+ errors.push(`above max ${s.max}`);
159
+ return errors;
160
+ };
161
+ /**
162
+ * Validators for the shipped kinds, keyed by type id. Kept beside the
163
+ * factories so adding a kind is one edit — the conformance canary refuses a
164
+ * factory output whose kind has no validator here.
165
+ * @experimental
166
+ */
167
+ export const valueValidators = {
168
+ 'integer@1': numberValidator(true),
169
+ 'number@1': numberValidator(false),
170
+ 'weights@1': (s, value) => {
171
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
172
+ return ['expected an object of part → weight'];
173
+ const errors = [];
174
+ const declared = Object.keys(s.parts ?? {});
175
+ const got = value;
176
+ for (const k of Object.keys(got))
177
+ if (!declared.includes(k))
178
+ errors.push(`unknown part '${k}'`);
179
+ for (const k of declared) {
180
+ const w = got[k];
181
+ if (!num(w)) {
182
+ errors.push(`part '${k}' is not a number`);
183
+ continue;
184
+ }
185
+ if (num(s.min) && w < s.min)
186
+ errors.push(`part '${k}' below min ${s.min}`);
187
+ if (num(s.max) && w > s.max)
188
+ errors.push(`part '${k}' above max ${s.max}`);
189
+ }
190
+ if (num(s.total)) {
191
+ const sum = declared.reduce((a, k) => a + (num(got[k]) ? got[k] : 0), 0);
192
+ if (Math.abs(sum - s.total) > 1e-9)
193
+ errors.push(`parts sum to ${sum}, expected ${s.total}`);
194
+ }
195
+ return errors;
196
+ },
197
+ 'select@1': (s, value) => {
198
+ const opts = (s.options ?? []).map((o) => typeof o === 'string' ? o : o.value);
199
+ return typeof value === 'string' && opts.includes(value)
200
+ ? []
201
+ : [`expected one of [${opts.join(', ')}]`];
202
+ },
203
+ 'ranking@1': (s, value) => {
204
+ const opts = s.options ?? [];
205
+ if (!Array.isArray(value))
206
+ return ['expected an array'];
207
+ const sorted = [...value].sort();
208
+ const expected = [...opts].sort();
209
+ return JSON.stringify(sorted) === JSON.stringify(expected)
210
+ ? []
211
+ : [`expected a permutation of [${opts.join(', ')}]`];
212
+ },
213
+ 'text@1': (s, value) => {
214
+ if (typeof value !== 'string')
215
+ return ['expected a string'];
216
+ const errors = [];
217
+ if (num(s.minLength) && value.length < s.minLength)
218
+ errors.push(`shorter than minLength ${s.minLength}`);
219
+ if (num(s.maxLength) && value.length > s.maxLength)
220
+ errors.push(`longer than maxLength ${s.maxLength}`);
221
+ if (typeof s.pattern === 'string' && !new RegExp(s.pattern).test(value))
222
+ errors.push(`does not match pattern ${s.pattern}`);
223
+ return errors;
224
+ },
225
+ 'boolean@1': (_s, value) => (typeof value === 'boolean' ? [] : ['expected a boolean']),
226
+ 'prompt-ref@1': (_s, value) => typeof value === 'string' || typeof value === 'number'
227
+ ? []
228
+ : ['expected a prompt reference'],
229
+ // A media value is the blob's public address — the uuid, never a path and
230
+ // never bytes. Validated by shape rather than by looking it up: whether it
231
+ // still exists is the host's question at read time, not the schema's.
232
+ 'media-ref@1': (_s, value) => typeof value === 'string' &&
233
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value)
234
+ ? []
235
+ : ['expected a media uuid'],
236
+ };
237
+ /**
238
+ * Validate one value against its declaration. Unknown type ids refuse —
239
+ * a consumer must never accept a write it cannot check (24 §8).
240
+ * @experimental
241
+ */
242
+ export function validateValue(declaration, value) {
243
+ const kind = valueKind(declaration);
244
+ const validator = valueValidators[kind];
245
+ if (!validator)
246
+ return [`unknown value type '${kind}' — refusing the write`];
247
+ return validator(declaration[kind], value);
248
+ }
249
+ /**
250
+ * A deliberate hole (24 §7): type-checks wherever a value goes, so authoring
251
+ * can continue — but the coverage report lists it as a named gap, and
252
+ * validation refuses it like any other unknown.
253
+ * @experimental
254
+ */
255
+ export function todo(note) {
256
+ return freeze({ 'todo@1': freeze({ note }) });
257
+ }
258
+ /** @experimental */
259
+ export const isTodo = (value) => typeof value === 'object' &&
260
+ value !== null &&
261
+ Object.keys(value).length === 1 &&
262
+ 'todo@1' in value;
263
+ /** Every kind the bare toolkit can mint — the registry the canary checks. @experimental */
264
+ export const shippedValueKinds = Object.freeze(Object.keys(valueValidators));
265
+ /**
266
+ * The bridge from the settings-schema vocabulary (`{type:'integer', …}` on
267
+ * node-type slots) to value declarations (24 T6c). Derived at read, never
268
+ * stored — no document or hash changes — so panels and controls can speak
269
+ * the value-decl contract while the schemas migrate underneath at their own
270
+ * pace. Unknown entry types map to nothing, and the caller keeps its
271
+ * legacy rendering for them.
272
+ * @experimental
273
+ */
274
+ export function valueDeclOf(entry) {
275
+ const e = entry;
276
+ if (!e || typeof e !== 'object')
277
+ return null;
278
+ const common = {};
279
+ if (e.default !== undefined)
280
+ common.default = e.default;
281
+ if (e.min !== undefined)
282
+ common.min = e.min;
283
+ if (e.max !== undefined)
284
+ common.max = e.max;
285
+ switch (e.type) {
286
+ case 'integer':
287
+ return decl('integer@1', common);
288
+ case 'number':
289
+ return decl('number@1', common);
290
+ case 'boolean':
291
+ return decl('boolean@1', {
292
+ ...(e.default !== undefined ? { default: e.default } : {}),
293
+ });
294
+ case 'string':
295
+ return decl('text@1', {
296
+ ...(e.default !== undefined ? { default: e.default } : {}),
297
+ });
298
+ // The plugin-settings vocabulary (settings.ts `FieldDecl`) spells a
299
+ // multiline string `text`, and marks structured payloads a form cannot
300
+ // decompose with `format: 'json'`. Both are the same value type — a
301
+ // text box that wants rows — so they bridge here rather than growing a
302
+ // second bridge beside this one.
303
+ //
304
+ // The node-slot vocabulary's `text` control is the same multi-line
305
+ // string (an envoy's instructions are the first parameter to declare
306
+ // one, U5g), so the app's config panel hands it through unchanged.
307
+ case 'text':
308
+ return decl('text@1', {
309
+ multiline: true,
310
+ ...(e.default !== undefined
311
+ ? {
312
+ default: e.format === 'json'
313
+ ? JSON.stringify(e.default, null, 2)
314
+ : e.default,
315
+ }
316
+ : {}),
317
+ });
318
+ case 'enum': {
319
+ const options = (e.of ??
320
+ e.members?.map((m) => ({
321
+ value: String(m.key ?? m),
322
+ label: m.label,
323
+ })) ??
324
+ []);
325
+ if (!options.length)
326
+ return null;
327
+ return decl('select@1', { options, ...common });
328
+ }
329
+ case 'share': {
330
+ // Normalised fractions: the consumer reads shares, zero is a
331
+ // band's off switch — weights with normalize, drawn as the bar.
332
+ const parts = Object.fromEntries((e.members ?? []).map((m) => [
333
+ String(m.key ?? m),
334
+ Number((e.default ?? {})[String(m.key ?? m)] ?? 0),
335
+ ]));
336
+ if (!Object.keys(parts).length)
337
+ return null;
338
+ return decl('weights@1', {
339
+ parts,
340
+ normalize: true,
341
+ control: 'stacked-bar',
342
+ });
343
+ }
344
+ case 'media': {
345
+ // Like `prompt-ref`, the choices are instance data — this user's
346
+ // media library, not anything a declaration can enumerate — so the
347
+ // host supplies the control. The declaration carries only which
348
+ // kinds to offer; `accepts` defaults to images, which is what
349
+ // nearly every such field wants.
350
+ return decl('media-ref@1', {
351
+ accepts: Array.isArray(e.accepts) && e.accepts.length
352
+ ? e.accepts
353
+ : ['image'],
354
+ ...(e.default !== undefined ? { default: e.default } : {}),
355
+ });
356
+ }
357
+ case 'perMember': {
358
+ // Free numbers per member — weights without a pinned total.
359
+ const parts = Object.fromEntries((e.members ?? []).map((m) => [
360
+ String(m.key ?? m),
361
+ Number((e.default ?? {})[String(m.key ?? m)] ?? 0),
362
+ ]));
363
+ if (!Object.keys(parts).length)
364
+ return null;
365
+ return decl('weights@1', { parts, min: 0 });
366
+ }
367
+ case 'strengths': {
368
+ // Independent 0..1 strengths — weights with a range and **no**
369
+ // normalisation, which is the one thing that separates this from
370
+ // `share` above. Bounded here rather than left to the control, so a
371
+ // host that renders `weights@1` without knowing about this type
372
+ // still clamps to the range the declaration promised.
373
+ const parts = Object.fromEntries((e.members ?? []).map((m) => [
374
+ String(m.key ?? m),
375
+ Number((e.default ?? {})[String(m.key ?? m)] ?? 0),
376
+ ]));
377
+ if (!Object.keys(parts).length)
378
+ return null;
379
+ return decl('weights@1', {
380
+ parts,
381
+ min: e.min ?? 0,
382
+ max: e.max ?? 1,
383
+ control: 'sliders',
384
+ });
385
+ }
386
+ default:
387
+ return null;
388
+ }
389
+ }
390
+ //# sourceMappingURL=values.js.map