@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,683 @@
1
+ /**
2
+ * Message blocks (20 §6) — custom message content as **data, not code**.
3
+ *
4
+ * A plugin's message part carries a block tree in `data.blocks`; core renders
5
+ * it with its own components. Nothing to sanitize (no HTML crosses the
6
+ * boundary), theming and accessibility are core's once for everyone, and
7
+ * interactivity is *declared*: a `choices` button or a `form` submit names a
8
+ * function key, and pressing it fires the trigger machinery with the message
9
+ * as subject — the same audited path every contributed button already takes.
10
+ *
11
+ * The validator is the write-time gate: a hostile or malformed tree is refused
12
+ * with the block path named, and the caps make "render whatever a sandboxed
13
+ * hook produced" a bounded promise. Findings carry a `fix` like every finding
14
+ * in this SDK (15 §1.3).
15
+ */
16
+ import { checkSchema } from './settings.js';
17
+ import { ACTION_IDENTITY, ACTION_IDENTITY_MAX_LENGTH, actionsOf, effectsOf, worldActionCrossing, } from './actions.js';
18
+ import { isParticipantRef } from './participants.js';
19
+ // The two verdicts declared here rather than in `verdicts.ts` (01 §13): their
20
+ // judges call `worldBlockFunctions` and `isFormStale`, which live here, and
21
+ // `verdicts.ts` must stay below every door — see its docblock.
22
+ import { defineVerdict } from './verdicts.js';
23
+ /** The caps that make rendering a sandbox's output a bounded promise. @experimental */
24
+ export const MESSAGE_BLOCK_LIMITS = {
25
+ maxBlocks: 64,
26
+ maxDepth: 3,
27
+ maxText: 64 * 1024,
28
+ maxRows: 64,
29
+ maxActions: 12
30
+ };
31
+ /** The longest block id the validator accepts; a host's uuid is 36. @experimental */
32
+ export const BLOCK_ID_MAX_LENGTH = 64;
33
+ const finding = (path, message, fix) => ({
34
+ path,
35
+ message,
36
+ fix,
37
+ });
38
+ /**
39
+ * Validate a candidate block tree. Empty findings = renderable. Total, never
40
+ * throws — the host refuses a write on findings rather than crashing on one.
41
+ * @internal
42
+ */
43
+ export function checkMessageBlocks(value) {
44
+ const f = [];
45
+ if (!Array.isArray(value))
46
+ return [finding('blocks', 'is not an array', 'send an array of blocks')];
47
+ let count = 0;
48
+ const str = (v, path, what) => {
49
+ if (typeof v !== 'string') {
50
+ f.push(finding(path, `${what} is not a string`, 'send text'));
51
+ return false;
52
+ }
53
+ if (v.length > MESSAGE_BLOCK_LIMITS.maxText)
54
+ f.push(finding(path, `${what} exceeds ${MESSAGE_BLOCK_LIMITS.maxText} bytes`, 'shorten it — a block is a card, not a document'));
55
+ return true;
56
+ };
57
+ /** `action` is optional; present, it is an identity and nothing looser. */
58
+ const identity = (v, path) => {
59
+ if (v === undefined)
60
+ return;
61
+ if (typeof v !== 'string' || v.length > ACTION_IDENTITY_MAX_LENGTH || !ACTION_IDENTITY.test(v))
62
+ f.push(finding(path, 'is not an action identity', "name the declaration as '<spec slug>#<key>', or omit it — the outlet stamps it"));
63
+ };
64
+ /** The form fields (`FormBlockFields`): an optional id, an optional head, an optional participant reference. */
65
+ const formFields = (b, p) => {
66
+ if (b.id !== undefined && (typeof b.id !== 'string' || !b.id || b.id.length > BLOCK_ID_MAX_LENGTH))
67
+ f.push(finding(`${p}.id`, 'is not a block id', 'omit it — the host stamps one at the write'));
68
+ // Host-owned like `id` (U5f): a well-formed value passes, a malformed
69
+ // one is named; either way the host stamps its own at the write.
70
+ if (b.head !== undefined && !isChannelHead(b.head))
71
+ f.push(finding(`${p}.head`, 'is not a channel head', 'omit it — the host stamps the channel head at the write'));
72
+ if (b.addressee !== undefined && !isParticipantRef(b.addressee))
73
+ f.push(finding(`${p}.addressee`, 'is not a participant reference', "address the form to 'character:<id>', 'envoy:<slug>', 'owner' or 'user:<id>', or omit it"));
74
+ if (b.question !== undefined)
75
+ str(b.question, `${p}.question`, 'question');
76
+ else if (b.addressee !== undefined)
77
+ f.push(finding(`${p}.question`, 'is missing on an addressed form', 'say what is being asked — the addressee (or the oracle answering for them) needs the question'));
78
+ if (b.referent !== undefined)
79
+ str(b.referent, `${p}.referent`, 'referent');
80
+ if (b.vantage !== undefined)
81
+ str(b.vantage, `${p}.vantage`, 'vantage');
82
+ if (b.answered !== undefined && !isFormAnswered(b.answered))
83
+ f.push(finding(`${p}.answered`, 'is not an answer record', "omit it — the host stamps { by, at, choice? } once the form is answered"));
84
+ };
85
+ const walk = (blocks, path, depth) => {
86
+ if (depth > MESSAGE_BLOCK_LIMITS.maxDepth) {
87
+ f.push(finding(path, `nesting exceeds depth ${MESSAGE_BLOCK_LIMITS.maxDepth}`, 'flatten the groups'));
88
+ return;
89
+ }
90
+ for (let i = 0; i < blocks.length; i++) {
91
+ const p = `${path}[${i}]`;
92
+ if (++count > MESSAGE_BLOCK_LIMITS.maxBlocks) {
93
+ f.push(finding(p, `more than ${MESSAGE_BLOCK_LIMITS.maxBlocks} blocks in the tree`, 'split the message'));
94
+ return;
95
+ }
96
+ const b = blocks[i];
97
+ if (!b || typeof b !== 'object' || Array.isArray(b)) {
98
+ f.push(finding(p, 'is not a block object', 'send {kind, …}'));
99
+ continue;
100
+ }
101
+ switch (b.kind) {
102
+ case 'md':
103
+ str(b.text, `${p}.text`, 'text');
104
+ break;
105
+ case 'kv': {
106
+ if (!Array.isArray(b.rows)) {
107
+ f.push(finding(`${p}.rows`, 'is not an array', 'send label/value rows'));
108
+ break;
109
+ }
110
+ if (b.rows.length > MESSAGE_BLOCK_LIMITS.maxRows)
111
+ f.push(finding(`${p}.rows`, `more than ${MESSAGE_BLOCK_LIMITS.maxRows} rows`, 'trim the list'));
112
+ for (let r = 0; r < b.rows.length; r++) {
113
+ const row = b.rows[r];
114
+ str(row?.label, `${p}.rows[${r}].label`, 'label');
115
+ str(row?.value, `${p}.rows[${r}].value`, 'value');
116
+ }
117
+ break;
118
+ }
119
+ case 'table': {
120
+ if (!Array.isArray(b.columns) || !b.columns.every((c) => typeof c === 'string'))
121
+ f.push(finding(`${p}.columns`, 'is not a string array', 'send column names'));
122
+ if (!Array.isArray(b.rows))
123
+ f.push(finding(`${p}.rows`, 'is not an array', 'send rows'));
124
+ else {
125
+ if (b.rows.length > MESSAGE_BLOCK_LIMITS.maxRows)
126
+ f.push(finding(`${p}.rows`, `more than ${MESSAGE_BLOCK_LIMITS.maxRows} rows`, 'trim the table'));
127
+ for (let r = 0; r < b.rows.length; r++)
128
+ if (!Array.isArray(b.rows[r]) || !b.rows[r].every((c) => typeof c === 'string'))
129
+ f.push(finding(`${p}.rows[${r}]`, 'is not a string array', 'send cell text'));
130
+ }
131
+ break;
132
+ }
133
+ case 'stat':
134
+ str(b.label, `${p}.label`, 'label');
135
+ if (typeof b.value !== 'number' || !Number.isFinite(b.value))
136
+ f.push(finding(`${p}.value`, 'is not a number', 'send a finite number'));
137
+ if (b.max !== undefined && (typeof b.max !== 'number' || !Number.isFinite(b.max)))
138
+ f.push(finding(`${p}.max`, 'is not a number', 'send a finite number, or omit it'));
139
+ break;
140
+ case 'image':
141
+ if (!Number.isInteger(b.assetId))
142
+ f.push(finding(`${p}.assetId`, 'is not a session-asset id', 'attach the bytes first; blocks reference assets, never foreign URLs'));
143
+ break;
144
+ case 'choices': {
145
+ if (!Array.isArray(b.actions) || !b.actions.length) {
146
+ f.push(finding(`${p}.actions`, 'is empty or not an array', 'send at least one action'));
147
+ break;
148
+ }
149
+ if (b.actions.length > MESSAGE_BLOCK_LIMITS.maxActions)
150
+ f.push(finding(`${p}.actions`, `more than ${MESSAGE_BLOCK_LIMITS.maxActions} actions`, 'fewer, clearer choices'));
151
+ formFields(b, p);
152
+ const choices = new Set();
153
+ for (let a = 0; a < b.actions.length; a++) {
154
+ const act = b.actions[a];
155
+ str(act?.fn, `${p}.actions[${a}].fn`, 'fn');
156
+ identity(act?.action, `${p}.actions[${a}].action`);
157
+ str(act?.label, `${p}.actions[${a}].label`, 'label');
158
+ if (act?.choice !== undefined) {
159
+ if (typeof act.choice !== 'string' || !act.choice)
160
+ f.push(finding(`${p}.actions[${a}].choice`, 'is not an option key', 'name the option with a non-empty string, or omit it'));
161
+ else if (choices.has(act.choice))
162
+ f.push(finding(`${p}.actions[${a}].choice`, `repeats the option key '${act.choice}'`, 'give each option its own key — an answer names one'));
163
+ else
164
+ choices.add(act.choice);
165
+ }
166
+ else if (b.addressee !== undefined)
167
+ f.push(finding(`${p}.actions[${a}].choice`, 'is missing on an addressed question', "give each option a 'choice' key — a form's answer names one, and the oracle's schema is an enum of them"));
168
+ }
169
+ break;
170
+ }
171
+ case 'form': {
172
+ str(b.fn, `${p}.fn`, 'fn');
173
+ identity(b.action, `${p}.action`);
174
+ formFields(b, p);
175
+ if (!b.fields || typeof b.fields !== 'object' || Array.isArray(b.fields))
176
+ f.push(finding(`${p}.fields`, 'is not a settings schema', 'declare fields with the one field language'));
177
+ else
178
+ for (const sf of checkSchema(b.fields))
179
+ f.push(finding(`${p}.fields.${sf.field ?? ''}`, sf.message, sf.fix));
180
+ break;
181
+ }
182
+ case 'group':
183
+ if (!Array.isArray(b.blocks))
184
+ f.push(finding(`${p}.blocks`, 'is not an array', 'nest an array of blocks'));
185
+ else
186
+ walk(b.blocks, `${p}.blocks`, depth + 1);
187
+ break;
188
+ default:
189
+ f.push(finding(p, `unknown block kind '${String(b.kind)}'`, 'use one of: md, kv, table, stat, image, choices, form, group'));
190
+ }
191
+ }
192
+ };
193
+ walk(value, 'blocks', 1);
194
+ return f;
195
+ }
196
+ /**
197
+ * Stamp each `choices` button and `form` in a tree with the identity of the
198
+ * declaration it fires — the outlet's half of W-E, called where a block part
199
+ * is written with the run's spec in hand. That is the host's seam, not the
200
+ * SDK's: in Serene Pub the executor's host scope carries the running
201
+ * document's slug (`runtime/host.ts`, `HostScope.specId`) and its message
202
+ * outlet is where the stamp lands; the `blocks` port U5d builds is built on
203
+ * this call. The SDK declares no `HostScope` — a host wired by hand passes
204
+ * `{ id, contributes }` from wherever it keeps the running spec.
205
+ *
206
+ * The identity is `<spec id>#<key>` for the action of `spec` whose `key`
207
+ * is the block's `fn` (plans/31 V2: the key is the identity's second half,
208
+ * so `fn` names at most one). A block whose `fn` the spec declares no
209
+ * action for is left unstamped — it fires as legacy and gets the
210
+ * owner floor — rather than guessed; and a block that already carries an
211
+ * `action` keeps it, so a spec may name a declaration of another spec's on
212
+ * purpose. Returns a copy; the input is never mutated.
213
+ * @internal
214
+ */
215
+ export function stampBlockActions(blocks, spec) {
216
+ const byKey = new Map();
217
+ for (const a of actionsOf(spec))
218
+ byKey.set(a.key, `${spec.id}#${a.key}`);
219
+ const identityFor = (fn) => byKey.get(fn);
220
+ const stamp = (ref) => {
221
+ if (ref.action !== undefined)
222
+ return ref;
223
+ const action = identityFor(ref.fn);
224
+ return action === undefined ? ref : { ...ref, action };
225
+ };
226
+ const walk = (list) => list.map((b) => {
227
+ switch (b.kind) {
228
+ case 'choices':
229
+ return { ...b, actions: b.actions.map(stamp) };
230
+ case 'form':
231
+ return stamp(b);
232
+ case 'group':
233
+ return { ...b, blocks: walk(b.blocks) };
234
+ default:
235
+ return b;
236
+ }
237
+ });
238
+ return walk(blocks);
239
+ }
240
+ /* ── Forms: what the host reads off a block tree (30 §U5d) ───────────────── */
241
+ /** A well-formed `FormAnswered` — the shape the host stamps and the validator accepts. @experimental */
242
+ export function isFormAnswered(v) {
243
+ if (!v || typeof v !== 'object' || Array.isArray(v))
244
+ return false;
245
+ const a = v;
246
+ return (isParticipantRef(a.by) &&
247
+ typeof a.at === 'string' &&
248
+ !!a.at &&
249
+ (a.choice === undefined || (typeof a.choice === 'string' && !!a.choice)));
250
+ }
251
+ /**
252
+ * Every `choices` and `form` block in a tree, in render order, groups
253
+ * flattened — the blocks a fire, an event or an answer can name.
254
+ * @internal
255
+ */
256
+ export function formBlocksOf(blocks) {
257
+ const out = [];
258
+ const walk = (list) => {
259
+ for (const b of list) {
260
+ if (b.kind === 'choices' || b.kind === 'form')
261
+ out.push(b);
262
+ else if (b.kind === 'group')
263
+ walk(b.blocks);
264
+ }
265
+ };
266
+ walk(blocks);
267
+ return out;
268
+ }
269
+ /** The form block carrying `id`, or undefined. @internal */
270
+ export function findFormBlock(blocks, id) {
271
+ return formBlocksOf(blocks).find((b) => b.id === id);
272
+ }
273
+ /**
274
+ * Every function a `choices` option or a `form` names, deduplicated — what
275
+ * the writing spec must declare an action for. A block whose `fn` the spec
276
+ * declares no action for is refused at the write: nothing would ever be held
277
+ * to an audience for it.
278
+ * @experimental
279
+ */
280
+ export function blockFunctionsOf(blocks) {
281
+ const fns = new Set();
282
+ for (const b of formBlocksOf(blocks))
283
+ if (b.kind === 'choices')
284
+ for (const a of b.actions)
285
+ fns.add(a.fn);
286
+ else
287
+ fns.add(b.fn);
288
+ return [...fns];
289
+ }
290
+ /**
291
+ * The functions a tree names that `spec` declares no action for — the
292
+ * refusal the host makes before it stamps (`stampBlockActions` leaves such a
293
+ * block unstamped rather than guessing; the write refuses it instead, with
294
+ * the function named). A reference that already **names its action** — a
295
+ * spec pointing a block at another spec's declaration on purpose, the way
296
+ * the Adventure genre's Ask points its options at Answer — is not judged
297
+ * here: the host holds the named identity to the installed declaration
298
+ * instead (`foreignBlockActions`).
299
+ * @internal
300
+ */
301
+ export function undeclaredBlockFunctions(blocks, spec) {
302
+ const declared = new Set(actionsOf(spec).map((a) => a.key));
303
+ const fns = new Set();
304
+ for (const b of formBlocksOf(blocks))
305
+ if (b.kind === 'choices') {
306
+ for (const a of b.actions)
307
+ if (a.action === undefined && !declared.has(a.fn))
308
+ fns.add(a.fn);
309
+ }
310
+ else if (b.action === undefined && !declared.has(b.fn))
311
+ fns.add(b.fn);
312
+ return [...fns];
313
+ }
314
+ /**
315
+ * The action identities a tree names that are **not** `spec`'s own — the
316
+ * declarations of other specs a block points at on purpose. The host holds
317
+ * each to the installed declaration: it must exist for the session's genre,
318
+ * and it may not be `world` (the effects line).
319
+ * @internal
320
+ */
321
+ export function foreignBlockActions(blocks, spec) {
322
+ const own = new Set(actionsOf(spec).map((a) => `${spec.id}#${a.key}`));
323
+ const out = new Set();
324
+ for (const b of formBlocksOf(blocks))
325
+ if (b.kind === 'choices') {
326
+ for (const a of b.actions)
327
+ if (a.action !== undefined && !own.has(a.action))
328
+ out.add(a.action);
329
+ }
330
+ else if (b.action !== undefined && !own.has(b.action))
331
+ out.add(b.action);
332
+ return [...out];
333
+ }
334
+ /**
335
+ * **The one addressee a `world` action may be named to** (L1, ruled
336
+ * 2026-09-17): the session's owner, and nobody else.
337
+ *
338
+ * `owner` the role, never `user:<id>` — this half of the law is pure and
339
+ * holds no session, so it cannot know which person owns one; a reference that
340
+ * happens to name the owner is resolved at the press, where the host can ask.
341
+ * @experimental
342
+ */
343
+ export const isOwnerAddressed = (addressee) => addressee === 'owner';
344
+ /**
345
+ * The effects line (plans/29 R-15 *The line*; 09-B F39): a block naming a
346
+ * `world` action — one whose result touches cards, lorebooks, settings,
347
+ * permissions, connections — is refused. Such an action lives in the
348
+ * composer or the review gate and is owner-only; a message carrying it would
349
+ * put an out-of-fiction effect where a character could be asked to answer
350
+ * it. Returns the functions of the offending actions.
351
+ *
352
+ * ## The one exception: a block addressed to the **owner** (L1, 2026-09-17)
353
+ *
354
+ * A `choices` or `form` block whose `addressee` is `owner` may name a `world`
355
+ * action. The reasoning is the line's own: the rule exists so that an
356
+ * out-of-fiction effect is never *a question a character could be asked*, and
357
+ * a form put to the owner is not that question — the owner is already the
358
+ * whole of such an action's `act` audience (`WORLD_ACTION_ACTORS`), and
359
+ * pressing the button is the owner acting, in the one place the line has
360
+ * always allowed them to. Every other addressee — a character, a persona,
361
+ * a user by id, or none at all (“nobody in particular”, which anyone the
362
+ * audience admits may press) — keeps the refusal.
363
+ *
364
+ * ⚠ The **venue** half of F41 is untouched: an action declaring
365
+ * `venue: { kind: 'form' }` still may not be `world`, because a venue is
366
+ * declared and an addressee is decided at run time, so the construction-time
367
+ * check cannot see one. An owner-addressed block therefore names a
368
+ * `composer`-venue world action — the Lair genre's knock does exactly this
369
+ * — and `form` stays fiction-only.
370
+ * @experimental
371
+ */
372
+ export function worldBlockFunctions(blocks, spec) {
373
+ const world = new Set(actionsOf(spec)
374
+ .filter((a) => effectsOf(a) === 'world')
375
+ .map((a) => a.key));
376
+ const fns = new Set();
377
+ for (const b of formBlocksOf(blocks)) {
378
+ if (isOwnerAddressed(b.addressee))
379
+ continue;
380
+ if (b.kind === 'choices') {
381
+ for (const a of b.actions)
382
+ if (world.has(a.fn))
383
+ fns.add(a.fn);
384
+ }
385
+ else if (world.has(b.fn))
386
+ fns.add(b.fn);
387
+ }
388
+ return [...fns];
389
+ }
390
+ /** The one sentence a block that carries a `world` action is refused with, whichever way it named it. */
391
+ const worldBlockSentence = (named) => `the blocks name ${named}, whose action changes something outside the story (effects: 'world'). ` +
392
+ `Such an action is the owner's, from the composer or the review gate — the one block that may ` +
393
+ `carry it is one addressed to 'owner' (the effects line, R-15)`;
394
+ /**
395
+ * The effects line (plans/29 R-15 *The line*; F41), as one verdict: an
396
+ * out-of-fiction effect — cards, lore, settings, permissions — is the
397
+ * owner's (or an administrator's), from the composer or the review gate, and
398
+ * never a question a character could be asked. Heard at the declaration
399
+ * (`actionFindingsByLaw`: the builder, `validate()`, the packager, a host's
400
+ * publish), at the write (`worldBlockFunctions`, the host's block gate) and
401
+ * at the fire (the host's `fireAction`). The one exception is L1's: a block
402
+ * addressed to the **owner** may carry it, because the owner is already the
403
+ * whole of such an action's `act` audience and pressing the button is the
404
+ * owner acting. A fire made **as** a participant has no exception — that is
405
+ * the answer pipeline answering for someone, and an oracle granting a
406
+ * permission is the thing the line exists to make impossible.
407
+ * @internal
408
+ */
409
+ export const effectsLineVerdict = defineVerdict({
410
+ id: 'core:verdict/effects-line',
411
+ law: 'F41',
412
+ doors: ['construction', 'validate', 'publish', 'write', 'fire'],
413
+ judge(input) {
414
+ switch (input.kind) {
415
+ case 'venue':
416
+ case 'actor':
417
+ return worldActionCrossing(input);
418
+ case 'block': {
419
+ const world = worldBlockFunctions(input.blocks, input.spec);
420
+ if (!world.length)
421
+ return { ok: true };
422
+ return { ok: false, sentence: worldBlockSentence(world.map((f) => `'${f}'`).join(', ')) };
423
+ }
424
+ case 'identity': {
425
+ // Admitted only when every block naming it is the owner's — and
426
+ // there is at least one: an identity nobody is known to have put
427
+ // to the owner is not known to be the owner's.
428
+ const ownersOnly = input.addressees.length > 0 && input.addressees.every(isOwnerAddressed);
429
+ if (input.effects !== 'world' || ownersOnly)
430
+ return { ok: true };
431
+ return { ok: false, sentence: worldBlockSentence(`'${input.identity}'`) };
432
+ }
433
+ case 'press': {
434
+ if (input.effects !== 'world')
435
+ return { ok: true };
436
+ if (!input.as && !(input.onBlock && !isOwnerAddressed(input.blockAddressee)))
437
+ return { ok: true };
438
+ return {
439
+ ok: false,
440
+ sentence: `'${input.name}' changes something outside the story, so it is the owner's to ` +
441
+ `invoke from the composer, or from a question put to them — never a question ` +
442
+ `put to anybody else.`,
443
+ };
444
+ }
445
+ default:
446
+ return {
447
+ ok: false,
448
+ sentence: `'${String(input.kind)}' is not a shape this verdict judges — one of 'venue', 'actor', 'block', 'identity', 'press'.`,
449
+ };
450
+ }
451
+ },
452
+ failing: (door) => door === 'write'
453
+ ? {
454
+ kind: 'block',
455
+ blocks: [
456
+ {
457
+ kind: 'choices',
458
+ question: 'Give them the keys?',
459
+ actions: [{ fn: 'grant', label: 'Yes', choice: 'yes' }],
460
+ },
461
+ ],
462
+ spec: {
463
+ id: 'conformance:spec/world-in-composer',
464
+ contributes: {
465
+ actions: [
466
+ {
467
+ key: 'grant',
468
+ genre: 'core:genre/chat',
469
+ venue: { kind: 'composer' },
470
+ label: { en: 'Grant' },
471
+ description: { en: 'Grant a permission outside the story.' },
472
+ effects: 'world',
473
+ },
474
+ ],
475
+ },
476
+ },
477
+ }
478
+ : door === 'fire'
479
+ ? { kind: 'press', name: 'Grant', effects: 'world', as: true, onBlock: false, blockAddressee: undefined }
480
+ : { kind: 'venue', where: 'contributes.actions[grant]', effects: 'world', venue: 'widget' },
481
+ });
482
+ /**
483
+ * Stamp an `id` on every `choices` and `form` block that has none — the
484
+ * host's half, at the write, with the host's id maker (a uuid). A block that
485
+ * already carries one keeps it. Returns a copy; the input is never mutated.
486
+ * @internal
487
+ */
488
+ export function assignBlockIds(blocks, makeId) {
489
+ const walk = (list) => list.map((b) => {
490
+ switch (b.kind) {
491
+ case 'choices':
492
+ case 'form':
493
+ return b.id ? b : { ...b, id: makeId() };
494
+ case 'group':
495
+ return { ...b, blocks: walk(b.blocks) };
496
+ default:
497
+ return b;
498
+ }
499
+ });
500
+ return walk(blocks);
501
+ }
502
+ /** A channel head as a block carries it: a positive integer message id. @experimental */
503
+ export const isChannelHead = (v) => typeof v === 'number' && Number.isInteger(v) && v > 0;
504
+ /**
505
+ * Stamp the **channel head** on every `choices` and `form` block (plans/29
506
+ * R-15 *Staleness and order*; 30 §U5f) — the host's half, at the write,
507
+ * with the head it read off the channel. Unlike `assignBlockIds`, a value
508
+ * the block already carries is **replaced**: the head is a fact about the
509
+ * channel at the write, and only the host holds the channel. Returns a
510
+ * copy; the input is never mutated.
511
+ * @internal
512
+ */
513
+ export function assignBlockHead(blocks, head) {
514
+ const walk = (list) => list.map((b) => {
515
+ switch (b.kind) {
516
+ case 'choices':
517
+ case 'form':
518
+ return { ...b, head };
519
+ case 'group':
520
+ return { ...b, blocks: walk(b.blocks) };
521
+ default:
522
+ return b;
523
+ }
524
+ });
525
+ return walk(blocks);
526
+ }
527
+ /**
528
+ * Is this form **stale** — issued at a channel head the channel has since
529
+ * moved past, and still unanswered? The one rule (R-15 *Staleness and
530
+ * order*), written once so the host's door and a client's render agree:
531
+ *
532
+ * !answered && head != null && headNow > head
533
+ *
534
+ * `headNow` is the greatest message id on the block's row's channel as the
535
+ * caller holds it, leaving out the row's own answers (rows whose
536
+ * `metadata.answersForm.messageId` is the block's row) — deleted rows are
537
+ * gone and do not count, hidden rows still exist and do. Answered beats
538
+ * stale everywhere: a form answered before the head moved stays answered.
539
+ * A block with no `head` is never stale.
540
+ * @experimental
541
+ */
542
+ export function isFormStale(block, headNow) {
543
+ if (block.answered)
544
+ return false;
545
+ if (!isChannelHead(block.head))
546
+ return false;
547
+ if (headNow == null)
548
+ return false;
549
+ return headNow > block.head;
550
+ }
551
+ /** @internal */
552
+ export const stalenessVerdict = defineVerdict({
553
+ id: 'core:verdict/staleness',
554
+ law: 'U5f',
555
+ doors: ['fire', 'list'],
556
+ judge({ block, headNow }) {
557
+ if (!isFormStale(block, headNow))
558
+ return { ok: true };
559
+ return {
560
+ ok: false,
561
+ sentence: 'That question was overtaken — the conversation moved on before it was answered.',
562
+ };
563
+ },
564
+ failing: () => ({ block: { head: 3 }, headNow: 4 }),
565
+ });
566
+ /**
567
+ * The JSON Schema an oracle answers a form against (R-15: "an oracle with
568
+ * `json` capability answers against the form's schema").
569
+ *
570
+ * - `choices` → `{ choice: <enum of the option keys> }`, required.
571
+ * - `form` → the field schema, mapped field by field (`fieldsToJsonSchema`).
572
+ *
573
+ * A `choices` block whose options carry no keys yields an empty enum, which
574
+ * is what the validator refuses on an addressed block before it is written.
575
+ * @internal
576
+ */
577
+ export function formAnswerSchema(block) {
578
+ if (block.kind === 'choices')
579
+ return {
580
+ type: 'object',
581
+ properties: {
582
+ choice: {
583
+ type: 'string',
584
+ enum: block.actions.map((a) => a.choice).filter((c) => !!c),
585
+ },
586
+ },
587
+ required: ['choice'],
588
+ additionalProperties: false,
589
+ };
590
+ return fieldsToJsonSchema(block.fields);
591
+ }
592
+ /**
593
+ * The one field language as JSON Schema — for a `form` block's answer, and
594
+ * for anything else that hands a `SettingsSchema` to a model. Every field
595
+ * type maps; `secret` and `media` map to strings because that is what a
596
+ * model could produce, and a form asking a character for either is a form
597
+ * the author should not have written.
598
+ * @experimental
599
+ */
600
+ export function fieldsToJsonSchema(fields) {
601
+ const properties = {};
602
+ const required = [];
603
+ for (const [key, decl] of Object.entries(fields)) {
604
+ properties[key] = fieldToJsonSchema(decl);
605
+ if (decl.required)
606
+ required.push(key);
607
+ }
608
+ return {
609
+ type: 'object',
610
+ properties,
611
+ ...(required.length ? { required } : {}),
612
+ additionalProperties: false,
613
+ };
614
+ }
615
+ function fieldToJsonSchema(decl) {
616
+ const describe = typeof decl.description === 'string' ? { description: decl.description } : {};
617
+ switch (decl.type) {
618
+ case 'boolean':
619
+ return { type: 'boolean', ...describe };
620
+ case 'integer':
621
+ case 'number':
622
+ return {
623
+ type: decl.type,
624
+ ...(decl.min !== undefined ? { minimum: decl.min } : {}),
625
+ ...(decl.max !== undefined ? { maximum: decl.max } : {}),
626
+ ...describe,
627
+ };
628
+ case 'enum': {
629
+ const of = decl.of ?? decl.members?.map((m) => m.key) ?? [];
630
+ return { type: 'string', enum: [...of], ...describe };
631
+ }
632
+ case 'string[]':
633
+ return { type: 'array', items: { type: 'string' }, ...describe };
634
+ case 'list':
635
+ return {
636
+ type: 'array',
637
+ items: decl.item ? fieldToJsonSchema(decl.item) : {},
638
+ ...(decl.min !== undefined ? { minItems: decl.min } : {}),
639
+ ...(decl.max !== undefined ? { maxItems: decl.max } : {}),
640
+ ...describe,
641
+ };
642
+ case 'object':
643
+ return { ...fieldsToJsonSchema(decl.fields ?? {}), ...describe };
644
+ case 'share':
645
+ case 'perMember':
646
+ case 'strengths':
647
+ return {
648
+ type: 'object',
649
+ properties: Object.fromEntries((decl.members ?? []).map((m) => [m.key, { type: 'number' }])),
650
+ additionalProperties: false,
651
+ ...describe,
652
+ };
653
+ default:
654
+ return { type: 'string', ...describe };
655
+ }
656
+ }
657
+ /**
658
+ * The fire a form's answer becomes — what a press sends, and what the
659
+ * answer pipeline commits "exactly as a click would": the block's function,
660
+ * its stamped identity, and the payload. For `choices` the payload is
661
+ * `{ choice }`; for `form` it is the answered values. Null when the answer
662
+ * names no option the block offers, or is not an object — an oracle's
663
+ * answer is checked here before anything is fired.
664
+ * @internal
665
+ */
666
+ export function formFireOf(block, answer) {
667
+ if (!answer || typeof answer !== 'object' || Array.isArray(answer))
668
+ return null;
669
+ const a = answer;
670
+ if (block.kind === 'choices') {
671
+ const option = block.actions.find((o) => o.choice !== undefined && o.choice === a.choice);
672
+ if (!option)
673
+ return null;
674
+ return {
675
+ fn: option.fn,
676
+ action: option.action,
677
+ payload: { choice: option.choice },
678
+ label: option.label,
679
+ };
680
+ }
681
+ return { fn: block.fn, action: block.action, payload: { ...a } };
682
+ }
683
+ //# sourceMappingURL=messageBlocks.js.map