@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,904 @@
1
+ /**
2
+ * Attribute slots — the declared vocabulary behind stats and states.
3
+ *
4
+ * ## Three levels, and only the middle one is new here
5
+ *
6
+ * A stat is three things, not one (entries plan Part 3): a **declaration**
7
+ * ("Health is an integer with a max, and it attaches to cast members"), a
8
+ * **configuration** ("this character's Health caps at 20"), and a **value**
9
+ * ("health = 12, as of message 47"). This file owns the first. The other two
10
+ * are rows in the host's `attribute_configs` and `attribute_values`, keyed by
11
+ * the id declared here.
12
+ *
13
+ * ## Core owns the types; nobody owns them but core
14
+ *
15
+ * `SlotType` is a **closed set of six**, and it is closed because each member
16
+ * is logic core implements: a bounded integer is a bar, an enum is a chip, a
17
+ * list is a chip row, a derived slot is never written at all. Genres, plugins
18
+ * and admins compose *definitions* from those types — `hp`, `gold`, `weather`,
19
+ * `mood` — the same way a genre composes a session shape from declared fields.
20
+ * A composed definition cannot introduce behaviour core does not already
21
+ * understand, which is why authorship can be open here where it is not for the
22
+ * types.
23
+ *
24
+ * ## One registry, two sources
25
+ *
26
+ * Node types project into `pipeline_definition_registry` rows because a *spec* has to
27
+ * be able to reference one that this build does not declare. A slot has no such
28
+ * consumer: every read of one goes through this registry in-process, and every
29
+ * write is validated against it at write time.
30
+ *
31
+ * People author slots too, and theirs live in the host's
32
+ * `attribute_declarations` table — but that table is a **source**, never a
33
+ * second answer. The host loads every stored row into *this* registry, at boot
34
+ * and again on every write (`defineStoredAttributeSlot`), and validation
35
+ * consults nothing else: `getAttributeSlot` stays the only door, and `origin`
36
+ * says which source an entry came through. A table a validator read directly
37
+ * would be a second answer to "what is Health" that nothing reconciles, and the
38
+ * two would drift the first time a row was written without this registry
39
+ * hearing about it.
40
+ *
41
+ * A card or lorebook naming a slot this install lacks keeps its values as
42
+ * opaque data — shown, not validated — which is the standing "never refuse,
43
+ * fall back and say so" rule for a stale binding.
44
+ *
45
+ * ## The catch: two kinds of prose
46
+ *
47
+ * `label` and `description` are what a person reads, so they are stripped from
48
+ * the content hash and copyediting one is free. **`descriptor` is what the
49
+ * model reads**, so editing it changes every prompt the slot appears in — it is
50
+ * contract, it is inside the hash, and changing it means `@N+1`. Conflating
51
+ * the two would ship prompt-changing edits silently.
52
+ *
53
+ * `derive`, `rules` and `scripts` sit inside the hash beside `descriptor`, for
54
+ * a plainer reason still: they are what the number *does* to itself, and that
55
+ * is never a copyedit. `examples` are stripped along with the display text and
56
+ * the reason is the inverse — an example is the *test* of a declaration rather
57
+ * than part of it, and writing one down must not force an `@N+1` on everything
58
+ * already storing values under the id.
59
+ *
60
+ * ⚠ **"Slot" here is not a pipeline slot.** NOMENCLATURE §"slot" is a declared
61
+ * parameter address on a node type (`SlotDecl` in descriptors.ts). This is an
62
+ * *attribute* slot, and prose says the qualified word. The two never meet: one
63
+ * is a key on a descriptor, the other is an id in this registry.
64
+ *
65
+ * The exported API says the qualified word too — `defineAttributeSlot`,
66
+ * `getAttributeSlot`, `attributeSlots` — because the unqualified names sat one
67
+ * import line away from the pipeline `slot()` address helper, and a name that
68
+ * reads correctly only if you know which module it came from is a name that
69
+ * will be imported wrong. The *types* keep the short names (`SlotId`,
70
+ * `SlotConfig`, `SlotValue`): they are only ever written next to this file's
71
+ * functions, so they cannot be mistaken at a call site.
72
+ */
73
+ import { i18nFindings } from './i18n.js';
74
+ import { refuseUnlessIdentical } from './hash.js';
75
+ import { getStatShape, statShapeKindOf } from './statShapes.js';
76
+ import { parseStoryTime } from './storyTime.js';
77
+ const SLOT_ID = /^[a-z0-9]+(?:[.-][a-z0-9]+)*:slot\/[a-z0-9]+(?:-[a-z0-9]+)*@\d+$/;
78
+ /** @experimental */
79
+ export function assertSlotId(id) {
80
+ if (!SLOT_ID.test(id))
81
+ throw new Error(`'${id}' is not a valid attribute slot id. Use 'owner:slot/name@N' — ` +
82
+ `'core:slot/hp@1', 'acme.rp:slot/tension@1'. The id is what a stored value ` +
83
+ `is filed under for the life of the card that carries it; the display name ` +
84
+ `lives in the declaration.`);
85
+ }
86
+ /**
87
+ * The parts of an attribute id, for the callers that need one of them.
88
+ *
89
+ * One regex for `slot` and `sheet` alike, because a sheet is addressed on the
90
+ * same grammar as the slots it names (`sheets.ts`) and the owner segment is
91
+ * what reservation is checked against for both. Two parsers would be two
92
+ * chances to disagree about what `acme.rp` is.
93
+ */
94
+ const ATTRIBUTE_ID = /^([a-z0-9]+(?:[.-][a-z0-9]+)*):(slot|sheet)\/([a-z0-9]+(?:-[a-z0-9]+)*)@(\d+)$/;
95
+ /**
96
+ * An id that is not an address answers with an empty owner and slug rather
97
+ * than throwing. These three are read on display paths over *stored* rows —
98
+ * a value filed under an id from a build that is not this one — where a stale
99
+ * id has to render, not crash.
100
+ */
101
+ const parts = (id) => ATTRIBUTE_ID.exec(id);
102
+ /** Who declared it: `core`, a plugin's id, or the username frozen in at authoring. @internal */
103
+ export const slotOwner = (id) => parts(id)?.[1] ?? '';
104
+ /** The slug — the data key a value is filed under for the life of the card carrying it. @experimental */
105
+ export const slotSlug = (id) => parts(id)?.[3] ?? '';
106
+ /** The major. `@N+1` is a different slot, not an edit to this one. @experimental */
107
+ export const slotVersion = (id) => Number(parts(id)?.[4] ?? 0);
108
+ // ── Reserved owners ─────────────────────────────────────────────────────────
109
+ /**
110
+ * Owner segments a person may not author under.
111
+ *
112
+ * `core` always, plus every installed plugin id — which is why this is a
113
+ * mutable registry and not a constant. The SDK cannot know what is installed;
114
+ * the host can, and calls `reserveAttributeOwner` as it installs. Reserving is
115
+ * what stops somebody whose username happens to match a plugin's namespace
116
+ * from authoring a slot that the next install silently redefines underneath
117
+ * their stored values.
118
+ *
119
+ * Deliberately no grammar check on the segment. A plugin id is not always a
120
+ * legal owner segment (`acme/rp` has a slash the id grammar forbids), and a
121
+ * host reserving what it has installed must not have to filter the list first:
122
+ * a reservation that can never match an id is harmless, while refusing one
123
+ * would make the obvious loop the wrong thing to write.
124
+ */
125
+ const reservedOwners = new Set(['core']);
126
+ /** @internal */
127
+ export function reserveAttributeOwner(segment) {
128
+ if (!segment?.trim())
129
+ throw new Error(`reserveAttributeOwner() was given an empty segment. Reserving nothing quietly ` +
130
+ `succeeds, and the first user slug to collide with a plugin is the bug report.`);
131
+ reservedOwners.add(segment);
132
+ }
133
+ /** @internal */
134
+ export const isReservedAttributeOwner = (segment) => reservedOwners.has(segment);
135
+ /** Back to `core` alone — for tests, and for a host tearing an install down. @internal */
136
+ export function _clearReservedAttributeOwners() {
137
+ reservedOwners.clear();
138
+ reservedOwners.add('core');
139
+ }
140
+ /** @experimental */
141
+ export const derivations = Object.freeze({
142
+ /**
143
+ * How old someone is: a `birthdate` value on the same owner, against the
144
+ * session's story date. Absent — not zero — when either is missing, which
145
+ * is the whole reason age is derived and not typed in.
146
+ */
147
+ age: Object.freeze({
148
+ id: 'core:derive/age@1',
149
+ requiresFrom: true,
150
+ description: "A birthdate slot on the same owner, read against the session's story date.",
151
+ }),
152
+ /**
153
+ * A LiquidJS expression written on the declaration itself (`derive`),
154
+ * evaluated over the state pinned at run start.
155
+ *
156
+ * It earns an id even though the *text* is the author's, because a derived
157
+ * slot always names the computation behind it: a receipt says which one
158
+ * produced a number, and "an expression" is an answer only if it is one
159
+ * declared thing rather than a hole in the set. What the author supplies is
160
+ * the expression; the evaluator is still core's.
161
+ *
162
+ * `requiresFrom: false` — the expression names whatever it reads, which is
163
+ * exactly the reason it is not `age`.
164
+ */
165
+ liquid: Object.freeze({
166
+ id: 'core:derive/liquid@1',
167
+ requiresFrom: false,
168
+ description: 'A LiquidJS expression on the declaration, evaluated over the state pinned at run start.',
169
+ }),
170
+ });
171
+ /** @experimental */
172
+ export const getDerivation = (id) => Object.values(derivations).find((d) => d.id === id);
173
+ /** Is this list item a lore reference? @experimental */
174
+ export const isSlotLoreRef = (item) => !!item &&
175
+ typeof item === 'object' &&
176
+ !Array.isArray(item) &&
177
+ Number.isInteger(item.entryId) &&
178
+ item.entryId > 0;
179
+ /** 🚧 How many of its entry a reference holds: its `count`, or one when it states none. @experimental */
180
+ export const slotLoreRefCount = (ref) => typeof ref.count === 'number' ? ref.count : 1;
181
+ /**
182
+ * 🚧 How many of one entry a stored value holds — the held count summed over
183
+ * every reference to it (a valid list has at most one). A word never counts,
184
+ * and a value that is not a list holds nothing. The reader a pipeline's supply
185
+ * check sums across owners (phase 3a).
186
+ * @experimental
187
+ */
188
+ export function heldCountIn(value, entryId) {
189
+ if (!Array.isArray(value))
190
+ return 0;
191
+ let held = 0;
192
+ for (const item of value)
193
+ if (isSlotLoreRef(item) && item.entryId === entryId)
194
+ held += slotLoreRefCount(item);
195
+ return held;
196
+ }
197
+ /**
198
+ * 🚧 One list item as a person or a prompt reads it: a word as itself, a lore
199
+ * reference by its title (the one a read filled in, else `entry N`) with its
200
+ * held count when it holds more than one — `Rusty key ×2`. The one spelling a
201
+ * state block, a ledger line and a widget share, so none of them shows a
202
+ * `{ entryId }` object.
203
+ * @experimental
204
+ */
205
+ export function slotListItemText(item) {
206
+ if (isSlotLoreRef(item)) {
207
+ const title = item.name?.trim() || `entry ${item.entryId}`;
208
+ const count = slotLoreRefCount(item);
209
+ return count > 1 ? `${title} ×${count}` : title;
210
+ }
211
+ if (item === null)
212
+ return 'cleared';
213
+ if (typeof item === 'boolean')
214
+ return item ? 'on' : 'off';
215
+ return String(item);
216
+ }
217
+ /**
218
+ * A value as it is STORED: every lore reference down to its `entryId` and its
219
+ * held `count` (the `name` a read filled in is dropped; a count of one is
220
+ * dropped too — one held is spelled bare). Everything else is itself.
221
+ * @experimental
222
+ */
223
+ export function slotValueForStorage(value) {
224
+ // A single reference (a text slot's place): its entry, and nothing else.
225
+ if (isSlotLoreRef(value))
226
+ return { entryId: value.entryId };
227
+ if (!Array.isArray(value))
228
+ return value;
229
+ return value.map((item) => isSlotLoreRef(item)
230
+ ? // One held is stored bare (phase 4): `count: 1` and no count are
231
+ // one value, and it has one spelling on disk.
232
+ item.count === undefined || item.count === 1
233
+ ? { entryId: item.entryId }
234
+ : { entryId: item.entryId, count: item.count }
235
+ : item);
236
+ }
237
+ /** The identity two list items are "the same item" by: a word by its text, a reference by its entry. */
238
+ const listItemKey = (item) => isSlotLoreRef(item) ? `entry:${item.entryId}` : `${typeof item}:${String(item)}`;
239
+ /** 🚧 The earshots a slot may declare. @experimental */
240
+ export const SLOT_EARSHOTS = Object.freeze(['all', 'holder']);
241
+ /** 🚧 A slot's earshot, the default read in: `'holder'` only when it says so. @experimental */
242
+ export const slotEarshot = (decl) => decl.earshot === 'holder' ? 'holder' : 'all';
243
+ /** 🚧 May a session pick this slot as an attribute of its own or carry it in from its world? @experimental */
244
+ export const slotPickable = (decl) => decl.pickable !== false;
245
+ const registry = new Map();
246
+ /**
247
+ * What is kept out of this registry's content hash beyond `i18n`/`description`.
248
+ *
249
+ * `label`, because renaming a bar is a copyedit. `examples`, because they are
250
+ * the declaration's tests rather than its content — see `SlotExample`.
251
+ *
252
+ * `descriptor`, `derive`, `rules` and `scripts` are deliberately absent:
253
+ * model-facing prose and behaviour are both content, and editing either means
254
+ * `@N+1` rather than a quiet republish.
255
+ * @experimental
256
+ */
257
+ export const SLOT_DISPLAY_KEYS = { display: ['label', 'examples'] };
258
+ /** Why one source may not take an id the other holds — the same refusal, both ways round. */
259
+ const crossOriginRefusal = (id, held) => held === 'code'
260
+ ? `'${id}' is declared in code by the package that owns it, so an authored slot may ` +
261
+ `not claim it: the id would mean one thing or another depending on what is ` +
262
+ `installed, and the values filed under it would change meaning with it. Author ` +
263
+ `it under your own namespace instead.`
264
+ : `'${id}' is already held by a slot somebody authored here. Code claiming it would ` +
265
+ `silently take over the key their values are filed under — retire theirs first, ` +
266
+ `or publish under a different id.`;
267
+ /**
268
+ * The one way into the registry, whichever door was knocked on.
269
+ *
270
+ * The two origins differ in exactly one rule and it is worth stating why. A
271
+ * code entry keeps the hash comparison, because two *different* declarations
272
+ * under one id there really are two packages disagreeing and one of them wins
273
+ * by load order. A stored entry replaces, because the row **is** the
274
+ * declaration and there is one author: an edited row re-loading is that person
275
+ * finishing a sentence, not a second party arriving.
276
+ */
277
+ function register(id, rawProps, origin, authorUserId) {
278
+ assertSlotId(id);
279
+ // The display text (R-20): refused where an author writes code; on a
280
+ // stored row it is dropped with a warning — see `withDisplayTextTolerated`.
281
+ const shown = origin === 'code' ? assertDisplayText(id, rawProps) : withDisplayTextTolerated(id, rawProps);
282
+ const props = { ...shown, type: typeOfDeclaration(id, shown) };
283
+ checkSlotDeclaration(id, props);
284
+ // The default said aloud is the default: one declaration, one hash.
285
+ if (props.earshot === 'all')
286
+ delete props.earshot;
287
+ const decl = Object.freeze({
288
+ ...props,
289
+ id,
290
+ origin,
291
+ ...(authorUserId === undefined ? {} : { authorUserId }),
292
+ });
293
+ const existing = registry.get(id);
294
+ if (existing) {
295
+ if (existing.origin !== origin)
296
+ throw new Error(crossOriginRefusal(id, existing.origin));
297
+ if (origin === 'code')
298
+ refuseUnlessIdentical(existing, decl, `duplicate attribute slot id: ${id}`, SLOT_DISPLAY_KEYS);
299
+ }
300
+ registry.set(id, decl);
301
+ return decl;
302
+ }
303
+ /**
304
+ * Declare an attribute slot in code.
305
+ *
306
+ * The same two refusals every registry here makes: an id has exactly one owner,
307
+ * and an identical re-declaration is a no-op (a dev-server reload re-running a
308
+ * module must not throw). A *different* declaration under a claimed id throws
309
+ * with both hashes named.
310
+ * @internal
311
+ */
312
+ export function defineAttributeSlot(id, props) {
313
+ return register(id, props, 'code');
314
+ }
315
+ /**
316
+ * The plugin-facing door — same registration, minus the ability to claim core's
317
+ * namespace. A plugin that could redefine `core:slot/hp@1` would change what
318
+ * every character's health means on the instance without appearing anywhere.
319
+ * @experimental
320
+ */
321
+ export function definePluginAttributeSlot(pluginId, id, props) {
322
+ if (id.startsWith('core:'))
323
+ throw new Error(`plugin '${pluginId}' may not declare '${id}': the 'core:' namespace is reserved. ` +
324
+ `Publish it under your own namespace — a slot two parties can define is one ` +
325
+ `where a stored value means different things depending on load order.`);
326
+ return defineAttributeSlot(id, props);
327
+ }
328
+ /**
329
+ * The person-facing door: a slot somebody authored, loaded from the host's
330
+ * `attribute_declarations` row.
331
+ *
332
+ * Every check `defineAttributeSlot` makes, plus one of its own — the owner
333
+ * segment must not be reserved. `core` and every installed plugin id are off
334
+ * limits, because a user slug that collided with one would be redefined the
335
+ * next time that package loaded, underneath values already filed against it.
336
+ *
337
+ * It **replaces** rather than comparing hashes, which is the whole difference
338
+ * between the two doors and is explained at `register`.
339
+ * @internal
340
+ */
341
+ export function defineStoredAttributeSlot(id, props, meta) {
342
+ assertSlotId(id);
343
+ const owner = slotOwner(id);
344
+ if (isReservedAttributeOwner(owner))
345
+ throw new Error(`'${id}' is authored under the reserved owner '${owner}'. 'core' and every installed ` +
346
+ `plugin id are reserved: a stored slot sharing one would be redefined the next ` +
347
+ `time that package loaded, and the values filed under it would quietly change ` +
348
+ `meaning. Author it under your own namespace.`);
349
+ return register(id, props, 'stored', meta.userId);
350
+ }
351
+ /** @internal */
352
+ export const getAttributeSlot = (id) => registry.get(id);
353
+ /** @internal */
354
+ export const attributeSlots = () => [...registry.values()];
355
+ /** @internal */
356
+ export function _clearAttributeSlots() {
357
+ registry.clear();
358
+ }
359
+ /**
360
+ * Withdraw a package's slot declaration (plugin disabled, uninstalled or
361
+ * upgraded). Values stay where they are and read as opaque data; a write is
362
+ * refused as undeclared until the package declares it again. Only a code
363
+ * declaration outside `core:` is withdrawn — a stored slot is somebody's and
364
+ * leaves by retirement, and core's leave with the build.
365
+ * @internal
366
+ */
367
+ export function _withdrawAttributeSlot(id) {
368
+ const decl = registry.get(id);
369
+ if (!decl || decl.origin !== 'code' || id.startsWith('core:'))
370
+ return false;
371
+ return registry.delete(id);
372
+ }
373
+ /** The entry retire and revive are allowed to touch — a stored one, and only that. */
374
+ function storedSlot(id, verb) {
375
+ const decl = registry.get(id);
376
+ if (!decl)
377
+ throw new Error(`cannot ${verb} '${id}': no slot is declared under that id. There is nothing to ` +
378
+ `${verb} — check the id, and that the row was loaded into the registry.`);
379
+ if (decl.origin !== 'stored')
380
+ throw new Error(`'${id}' is declared in code, and code declarations are never retired by hand. A ` +
381
+ `core or plugin slot arrives and leaves with the package that declares it: ` +
382
+ `uninstall or upgrade that, and every value stays exactly where it is. Only a ` +
383
+ `slot somebody authored here can be retired.`);
384
+ return decl;
385
+ }
386
+ /**
387
+ * Retire a stored slot: nothing new is written to it, everything already
388
+ * written stays.
389
+ *
390
+ * Not a delete, and the difference is the point. Panels grey it with the label
391
+ * it last had, the ledger and the charts keep every row, the prompt drops it,
392
+ * and a write is refused with a sentence (`checkSlotValue`). A hard delete is a
393
+ * separate, explicit purge *after* retirement that shows the counts first —
394
+ * because what is being deleted is somebody's play, not a definition.
395
+ * @internal
396
+ */
397
+ export function retireAttributeSlot(id) {
398
+ const next = Object.freeze({ ...storedSlot(id, 'retire'), retired: true });
399
+ registry.set(id, next);
400
+ return next;
401
+ }
402
+ /** Undo a retirement. Writes are taken again; nothing about the stored values changed either way. @internal */
403
+ export function reviveAttributeSlot(id) {
404
+ const { retired: _wasRetired, ...rest } = storedSlot(id, 'revive');
405
+ const next = Object.freeze(rest);
406
+ registry.set(id, next);
407
+ return next;
408
+ }
409
+ /**
410
+ * The display-text findings of one slot declaration (R-20): `label` and
411
+ * `description`, both optional — a slot may be listed by its id — but a blank
412
+ * one is a label that draws nothing where the author meant to say something.
413
+ * Run by the code door here and by the host's **write** door for an authored
414
+ * slot (the app's `declareSlot` / `updateSlot`), never by a reload.
415
+ * @internal
416
+ */
417
+ export function attributeSlotDisplayFindings(id, props) {
418
+ return [
419
+ ...i18nFindings(props.label, `${id} label`),
420
+ ...i18nFindings(props.description, `${id} description`),
421
+ ];
422
+ }
423
+ function assertDisplayText(id, props) {
424
+ const display = attributeSlotDisplayFindings(id, props);
425
+ if (display.length)
426
+ throw new Error(`${id} declares display text a publish refuses (R-20):\n · ${display.join('\n · ')}`);
427
+ return props;
428
+ }
429
+ /**
430
+ * A stored row reloading at boot is never refused for its display text
431
+ * (ruled 2026-09-17, U5i review): the gate is the write door, and a row that
432
+ * was stored with a blank `description` would otherwise vanish from every
433
+ * boot after. The offending field is dropped — a blank label reads as "listed
434
+ * by id" — and a warning names the row and the finding, so the defect is
435
+ * visible without the slot being lost.
436
+ */
437
+ function withDisplayTextTolerated(id, props) {
438
+ const findings = attributeSlotDisplayFindings(id, props);
439
+ if (!findings.length)
440
+ return props;
441
+ console.warn(`[attributes] stored slot '${id}' carries display text a publish refuses; ` +
442
+ `dropped on reload, fix the row: ${findings.join('; ')}`);
443
+ const tolerated = { ...props };
444
+ if (i18nFindings(props.label, 'label').length)
445
+ delete tolerated.label;
446
+ if (i18nFindings(props.description, 'description').length)
447
+ delete tolerated.description;
448
+ return tolerated;
449
+ }
450
+ // ── Stat shapes on a slot ──────────────────────────────────────────────────
451
+ /** The `SlotType` each stat kind is stored and checked as. @experimental */
452
+ export function slotTypeForKind(kind) {
453
+ switch (kind) {
454
+ case 'number':
455
+ return 'integer';
456
+ case 'choice':
457
+ return 'enum';
458
+ case 'list':
459
+ return 'list';
460
+ case 'boolean':
461
+ return 'boolean';
462
+ case 'story-time':
463
+ case 'text':
464
+ return 'text';
465
+ }
466
+ }
467
+ /**
468
+ * The field a slot declared by `type` alone is read as — how every slot from
469
+ * before stat shapes means what it always meant. `derived` has none: it is
470
+ * computed, and what it computes is not declared as a field.
471
+ * @experimental
472
+ */
473
+ export function fieldForSlotType(type) {
474
+ switch (type) {
475
+ case 'integer':
476
+ return { type: 'integer' };
477
+ case 'enum':
478
+ return { type: 'enum' };
479
+ case 'list':
480
+ return { type: 'list', item: { type: 'string' } };
481
+ case 'text':
482
+ return { type: 'text' };
483
+ case 'boolean':
484
+ return { type: 'boolean' };
485
+ case 'derived':
486
+ return undefined;
487
+ }
488
+ }
489
+ /** The shape a slot's value takes, as a field: its catalogue shape's, its own inline one, or its type's. @experimental */
490
+ export function slotField(decl) {
491
+ if (decl.type === 'derived')
492
+ return undefined;
493
+ if (typeof decl.shape === 'string')
494
+ return getStatShape(decl.shape)?.field;
495
+ if (decl.shape)
496
+ return decl.shape;
497
+ return decl.type ? fieldForSlotType(decl.type) : undefined;
498
+ }
499
+ /** The catalogue shape a slot names, when it names one (an inline `FieldDecl` names none). @experimental */
500
+ export const slotStatShapeId = (decl) => typeof decl.shape === 'string' ? decl.shape : undefined;
501
+ /** Which kind of stat a slot is; `undefined` for a derived slot, which is computed rather than kept. @experimental */
502
+ export const slotStatShapeKind = (decl) => statShapeKindOf(slotField(decl));
503
+ /**
504
+ * What a field bounds, as the configuration keys a layer deviates from: a
505
+ * number's `min`/`max`; a choice's options (`of`, or its `members`' keys); a
506
+ * list's item count (`max` → `maxItems`), its items' closed set and length; a
507
+ * line's length (`max` → `maxLength`).
508
+ * @experimental
509
+ */
510
+ export function fieldSlotConfig(field) {
511
+ const out = {};
512
+ const kind = statShapeKindOf(field);
513
+ if (!field || !kind)
514
+ return out;
515
+ const options = (f) => f.of ?? f.members?.map((m) => m.key);
516
+ switch (kind) {
517
+ case 'number':
518
+ if (typeof field.min === 'number')
519
+ out.min = field.min;
520
+ if (typeof field.max === 'number')
521
+ out.max = field.max;
522
+ break;
523
+ case 'choice': {
524
+ const of = options(field);
525
+ if (of?.length)
526
+ out.of = [...of];
527
+ break;
528
+ }
529
+ case 'list': {
530
+ if (typeof field.max === 'number')
531
+ out.maxItems = field.max;
532
+ const item = field.item;
533
+ if (item?.type === 'enum') {
534
+ const of = options(item);
535
+ if (of?.length)
536
+ out.of = [...of];
537
+ }
538
+ else if (item && typeof item.max === 'number')
539
+ out.maxLength = item.max;
540
+ break;
541
+ }
542
+ case 'text':
543
+ if (typeof field.max === 'number')
544
+ out.maxLength = field.max;
545
+ break;
546
+ }
547
+ return out;
548
+ }
549
+ /**
550
+ * The type a declaration is, from what it said: `type`, `shape`, or both
551
+ * agreeing. Refused with a sentence when neither is said, when the shape is
552
+ * one nothing declares or core cannot keep, and when the two disagree.
553
+ */
554
+ function typeOfDeclaration(id, props) {
555
+ if (props.shape === undefined) {
556
+ if (!props.type)
557
+ throw new Error(`${id} declares neither a type nor a shape. Name a stat shape ` +
558
+ `('core:stat-shape/number@1') or write the value's field — a slot has to say what it holds.`);
559
+ return props.type;
560
+ }
561
+ if (props.type === 'derived')
562
+ throw new Error(`${id} is derived and declares a shape. A derived slot is computed, never kept, so there is ` +
563
+ `no stored value for a shape to describe. Drop the shape.`);
564
+ let field;
565
+ if (typeof props.shape === 'string') {
566
+ field = getStatShape(props.shape)?.field;
567
+ if (!field)
568
+ throw new Error(`${id} names the stat shape '${props.shape}', which nothing declares. Shapes are declared ` +
569
+ `above the slots that name them — a slot shaped like nothing validates against nothing.`);
570
+ }
571
+ else
572
+ field = props.shape;
573
+ const kind = statShapeKindOf(field);
574
+ if (!kind)
575
+ throw new Error(`${id} is shaped as a '${field?.type}' field, which is not a value core can keep as a stat. ` +
576
+ `A stat is a number, a choice, a list of text, a story time, a line of text or a switch.`);
577
+ const type = slotTypeForKind(kind);
578
+ if (props.type && props.type !== type)
579
+ throw new Error(`${id} says it is '${props.type}' and is shaped as a ${kind}, which is stored as '${type}'. ` +
580
+ `Say one of them — the shape is enough.`);
581
+ return type;
582
+ }
583
+ /** What a declaration must satisfy before it is worth storing values against. */
584
+ function checkSlotDeclaration(id, props) {
585
+ if (props.pickable !== undefined && props.pickable !== false)
586
+ throw new Error(`${id}.pickable: only \`false\` is said — a slot is pickable unless it says otherwise.`);
587
+ if (props.earshot !== undefined && !SLOT_EARSHOTS.includes(props.earshot))
588
+ throw new Error(`${id}.earshot is '${String(props.earshot)}'. A slot is heard by 'all' (the default) or ` +
589
+ `by its 'holder' alone.`);
590
+ if (props.earshot === 'holder' &&
591
+ !(props.appliesTo?.length === 1 && props.appliesTo[0] === 'cast'))
592
+ throw new Error(`${id} declares earshot 'holder' and applies to ${props.appliesTo?.length ? props.appliesTo.map((o) => `'${o}'`).join(', ') : 'nothing'}. Only a cast member has a voice of their own to hold a value in — a world or a place ` +
593
+ `has none, so a 'holder' slot there would reach no prompt at all. Apply it to ` +
594
+ `['cast'] alone, or let everyone hear it.`);
595
+ if (!props.descriptor?.trim())
596
+ throw new Error(`${id} declares no descriptor. It is the sentence the model reads about this ` +
597
+ `slot; a slot without one reaches a prompt as a bare number.`);
598
+ if (!props.appliesTo?.length)
599
+ throw new Error(`${id} declares no appliesTo. Say whether it attaches to 'cast', to 'world', to ` +
600
+ `'location', or to several — a slot nothing may carry can never hold a value.`);
601
+ if (props.type === 'enum' && !(props.config?.of ?? fieldSlotConfig(slotField(props)).of)?.length)
602
+ throw new Error(`${id} is an enum with no options. Declare config.of — the closed set is what ` +
603
+ `makes it a chip rather than a text field.`);
604
+ if (props.derive !== undefined) {
605
+ if (props.type !== 'derived')
606
+ throw new Error(`${id} is a '${props.type}' slot and declares 'derive'. An expression that computes ` +
607
+ `the value is what 'derived' means; on a stored slot it would overwrite what ` +
608
+ `somebody wrote, every read. Declare type 'derived', or drop the expression.`);
609
+ if (!props.derive.trim())
610
+ throw new Error(`${id} declares an empty 'derive'. A derived slot with no expression computes ` +
611
+ `nothing and reads absent forever, which is a slot that is never there.`);
612
+ const named = props.config?.derivation;
613
+ if (named && named !== derivations.liquid.id)
614
+ throw new Error(`${id} declares both 'derive' and config.derivation '${named}' — two answers to ` +
615
+ `how one number is computed, and nothing to choose between them. An ` +
616
+ `expression already means ${derivations.liquid.id}; drop the config key, or ` +
617
+ `drop the expression.`);
618
+ }
619
+ // An expression IS the derivation (`slotDerivation`), so the named-derivation
620
+ // checks below are for the other spelling only.
621
+ if (props.type === 'derived' && props.derive === undefined) {
622
+ const derivation = props.config?.derivation;
623
+ const decl = derivation ? getDerivation(derivation) : undefined;
624
+ if (!decl)
625
+ throw new Error(`${id} is derived but names ${derivation ? `'${derivation}'` : 'no derivation'}, ` +
626
+ `which is not one of core's: ${Object.values(derivations)
627
+ .map((d) => d.id)
628
+ .join(', ')}. Derivations are core-owned logic, not composable.`);
629
+ if (decl.requiresFrom && !props.config?.from)
630
+ throw new Error(`${id} names ${decl.id}, which reads another slot — declare config.from with ` +
631
+ `that slot's id. ${decl.description}`);
632
+ }
633
+ if (props.default !== undefined && props.type === 'derived')
634
+ throw new Error(`${id} is derived and declares a default. A derived slot is computed or absent; a ` +
635
+ `default would be a stored answer to a question whose whole point is that it ` +
636
+ `must not be stored.`);
637
+ props.rules?.forEach((rule, i) => {
638
+ const ops = ['set', 'add', 'remove'].filter((k) => rule[k] !== undefined);
639
+ if (ops.length !== 1)
640
+ throw new Error(`${id} rule ${i} declares ${ops.length ? ops.join(' and ') : 'no operation'}. A ` +
641
+ `rule does exactly one thing — set, add or remove — because a rule that did ` +
642
+ `two has no order anybody could read off it.`);
643
+ if (ops[0] === 'add' && props.type !== 'list' && props.type !== 'integer')
644
+ throw new Error(`${id} is a '${props.type}' slot and rule ${i} declares 'add'. Adding to a value ` +
645
+ `means something only where the value has parts or arithmetic: a list, or an ` +
646
+ `integer, where 'add' is a signed delta. Use 'set'.`);
647
+ if (ops[0] === 'remove' && props.type !== 'list')
648
+ throw new Error(`${id} is a '${props.type}' slot and rule ${i} declares 'remove'. Only a list has ` +
649
+ `items to take away; an integer that should go down is 'add' with a negative ` +
650
+ `delta, and anything else is 'set'.`);
651
+ });
652
+ }
653
+ // ── Validation, at the write ────────────────────────────────────────────────
654
+ /**
655
+ * The configuration in force for one owner: the declaration's own config with
656
+ * each layer's deviations laid over it, nearest layer last.
657
+ *
658
+ * Merging keys rather than replacing objects is what makes "deviations only"
659
+ * real — a session that raised a cap must not silently drop the enum options
660
+ * the lorebook declared beside it.
661
+ * @internal
662
+ */
663
+ export function resolveSlotConfig(decl, ...layers) {
664
+ return layers.reduce((acc, layer) => (layer ? { ...acc, ...layer } : acc), { ...fieldSlotConfig(slotField(decl)), ...(decl.config ?? {}) });
665
+ }
666
+ /**
667
+ * Why this value may not be stored under this slot, or `null` if it may.
668
+ *
669
+ * A sentence rather than a boolean, because every caller — a socket handler, a
670
+ * node, a review gate — has to tell a person what was wrong, and three callers
671
+ * inventing three wordings for one rule is how a validator stops being one.
672
+ *
673
+ * ⚠ A value is checked against the configuration valid at **its own anchor**,
674
+ * not against the current one (plan Part 3). Callers pass that config in; this
675
+ * function never reaches for a current one, because doing so is precisely the
676
+ * mistake that retroactively invalidates a legitimate historical value.
677
+ * @internal
678
+ */
679
+ export function checkSlotValue(decl, value, config = resolveSlotConfig(decl)) {
680
+ // Retirement answers first. It is the newest fact about the slot and the
681
+ // only one that explains why a write that worked last week does not now.
682
+ if (decl.retired)
683
+ return (`${decl.id} is retired, so nothing new is written to it. Everything already stored ` +
684
+ `is kept and still shown — revive the slot to write to it again.`);
685
+ if (decl.type === 'derived')
686
+ return `${decl.id} is derived, so it has no value to set — it is computed ${decl.derive ? 'from its own expression' : `from ${config.from ?? 'another slot'}`} every time it is read.`;
687
+ // Clearing is always legal: it is how a layer says "inherit again", and a
688
+ // cleared value must not have to satisfy a bound it is opting out of.
689
+ if (value === null)
690
+ return null;
691
+ switch (decl.type) {
692
+ case 'integer': {
693
+ // A shape declared as `number` takes fractions; everything else
694
+ // stored as `integer` is a whole number, as it always was.
695
+ if (slotField(decl)?.type === 'number') {
696
+ if (typeof value !== 'number' || !Number.isFinite(value))
697
+ return `${decl.id} is a number; '${String(value)}' is not one.`;
698
+ }
699
+ else if (typeof value !== 'number' || !Number.isInteger(value))
700
+ return `${decl.id} is a whole number; '${String(value)}' is not one.`;
701
+ if (typeof config.min === 'number' && value < config.min)
702
+ return `${decl.id} does not go below ${config.min}.`;
703
+ if (typeof config.max === 'number' && value > config.max)
704
+ return `${decl.id} does not go above ${config.max}.`;
705
+ return null;
706
+ }
707
+ case 'enum': {
708
+ const of = config.of ?? [];
709
+ if (typeof value !== 'string' || !of.includes(value))
710
+ return `${decl.id} is one of ${of.join(', ') || '(nothing declared)'}; '${String(value)}' is not.`;
711
+ return null;
712
+ }
713
+ case 'text': {
714
+ // 🚧 A reference to a lore entry, when the slot names the entry
715
+ // types it may point at (`config.entryTypes`). Once, with no held
716
+ // count: somebody is in one place, not two of it.
717
+ if (isSlotLoreRef(value) && config.entryTypes?.length) {
718
+ const extra = Object.keys(value).filter((k) => k !== 'entryId' && k !== 'name');
719
+ if (extra.length || (value.name !== undefined && typeof value.name !== 'string'))
720
+ return `${decl.id} is text or a reference to a lore entry as { entryId }; '${JSON.stringify(value)}' is not one.`;
721
+ return null;
722
+ }
723
+ if (typeof value !== 'string')
724
+ return config.entryTypes?.length
725
+ ? `${decl.id} is text or a reference to a lore entry (${config.entryTypes.join(', ')}).`
726
+ : `${decl.id} is text.`;
727
+ if (slotField(decl)?.format === 'story-time' && !parseStoryTime(value))
728
+ return (`${decl.id} is a story time — a year, then optionally month, day and time, as ` +
729
+ `'412-03-05 22:30'; '${value}' is not one.`);
730
+ if (typeof config.maxLength === 'number' && value.length > config.maxLength)
731
+ return `${decl.id} is at most ${config.maxLength} characters.`;
732
+ return null;
733
+ }
734
+ case 'list': {
735
+ if (!Array.isArray(value))
736
+ return `${decl.id} holds a list of items; '${String(value)}' is one thing.`;
737
+ const items = value;
738
+ if (typeof config.maxItems === 'number' && items.length > config.maxItems)
739
+ return `${decl.id} holds at most ${config.maxItems} items; this is ${items.length}.`;
740
+ const of = config.of;
741
+ const unique = config.unique !== false;
742
+ const seen = new Set();
743
+ for (const item of items) {
744
+ // A lore reference is an item in its own right — unless the
745
+ // list is closed over words, where only those words are.
746
+ if (isSlotLoreRef(item)) {
747
+ if (of)
748
+ return `${decl.id} holds items from ${of.join(', ') || '(nothing declared)'}; a lore entry is not one of them.`;
749
+ const extra = Object.keys(item).filter((k) => k !== 'entryId' && k !== 'name' && k !== 'count');
750
+ if (extra.length || (item.name !== undefined && typeof item.name !== 'string'))
751
+ return `${decl.id} holds lore references as { entryId, count? }; '${JSON.stringify(item)}' is not one.`;
752
+ if (item.count !== undefined && !(Number.isInteger(item.count) && item.count >= 1))
753
+ return `${decl.id} holds a lore entry with a whole count of at least 1; '${String(item.count)}' is not one.`;
754
+ // Whatever `unique` says: the count is a reference's
755
+ // multiplicity, so a second reference to the same entry is
756
+ // a second answer to "how many".
757
+ if (seen.has(listItemKey(item)))
758
+ return `${decl.id} holds each lore entry once, with a count; lore entry ${item.entryId} is in it twice.`;
759
+ seen.add(listItemKey(item));
760
+ continue;
761
+ }
762
+ if (typeof item !== 'string')
763
+ return `${decl.id} holds a list of text items and lore references; '${item && typeof item === 'object' ? JSON.stringify(item) : String(item)}' is neither.`;
764
+ if (of && !of.includes(item))
765
+ return `${decl.id} holds items from ${of.join(', ') || '(nothing declared)'}; '${item}' is not one of them.`;
766
+ if (!of && typeof config.maxLength === 'number' && item.length > config.maxLength)
767
+ return `${decl.id} holds items of at most ${config.maxLength} characters; '${item}' is longer.`;
768
+ if (unique && seen.has(listItemKey(item)))
769
+ return `${decl.id} holds each item once; '${item}' is in it twice.`;
770
+ seen.add(listItemKey(item));
771
+ }
772
+ return null;
773
+ }
774
+ case 'boolean':
775
+ return typeof value === 'boolean' ? null : `${decl.id} is on or off.`;
776
+ }
777
+ }
778
+ /**
779
+ * Apply one list op, purely.
780
+ *
781
+ * It shapes the list; it does not judge the items. `unique` and `maxItems` are
782
+ * properties of the *list*, so they belong here — `add` dedups rather than
783
+ * growing a set that is not one, and an overflow is refused rather than
784
+ * trimmed, because silently dropping the sword somebody just picked up is how
785
+ * an inventory starts lying. Whether `sword` is a legal item at all is
786
+ * `checkSlotValue`'s question, asked of the result.
787
+ *
788
+ * `remove` of something that is not there is not an error: the state asked for
789
+ * — it is not in the list — is the state afterwards, and refusing would make a
790
+ * rule that fires twice fail the second time for having already worked.
791
+ *
792
+ * The refusal says "this list" rather than naming the slot, because the op is
793
+ * given a config and not a declaration. The caller knows which slot it asked
794
+ * about; only it can put the label in front.
795
+ * @experimental
796
+ */
797
+ export function applyListOp(current, op, items, config = {}) {
798
+ const held = current ?? [];
799
+ const unique = config.unique !== false;
800
+ // A lore reference is deduped whatever `unique` says: its count is its
801
+ // multiplicity (phase 3a), so the same entry twice is merged, never kept.
802
+ const dedup = (list) => {
803
+ const seen = new Set();
804
+ const out = [];
805
+ for (const item of list) {
806
+ if (!unique && !isSlotLoreRef(item)) {
807
+ out.push(item);
808
+ continue;
809
+ }
810
+ const key = listItemKey(item);
811
+ if (seen.has(key))
812
+ continue;
813
+ seen.add(key);
814
+ out.push(item);
815
+ }
816
+ return out;
817
+ };
818
+ // A count of one is spelled bare (phase 4): absent reads as one, so
819
+ // `count: 1` would be a second spelling of the same holding.
820
+ const withCount = (ref, count) => ({
821
+ entryId: ref.entryId,
822
+ ...(count === 1 ? {} : { count }),
823
+ ...(ref.name === undefined ? {} : { name: ref.name }),
824
+ });
825
+ let next;
826
+ switch (op) {
827
+ case 'set':
828
+ next = dedup(items);
829
+ break;
830
+ case 'add': {
831
+ // A reference that states a count adds that many to what is held
832
+ // (an uncounted holding is one); one without a count is a set add —
833
+ // "it is in the list" — exactly as before counts existed.
834
+ const out = [...held];
835
+ const rest = [];
836
+ for (const item of items) {
837
+ if (!isSlotLoreRef(item) || item.count === undefined) {
838
+ rest.push(item);
839
+ continue;
840
+ }
841
+ const at = out.findIndex((h) => isSlotLoreRef(h) && h.entryId === item.entryId);
842
+ if (at < 0)
843
+ out.push(withCount(item, item.count));
844
+ else
845
+ out[at] = withCount(out[at], slotLoreRefCount(out[at]) + item.count);
846
+ }
847
+ next = dedup([...out, ...rest]);
848
+ break;
849
+ }
850
+ case 'remove': {
851
+ // A counted reference takes that many and drops the item at zero;
852
+ // an uncounted one (and every word) takes the item out entirely.
853
+ const out = new Set(items.filter((item) => !isSlotLoreRef(item) || item.count === undefined).map(listItemKey));
854
+ const less = new Map();
855
+ for (const item of items)
856
+ if (isSlotLoreRef(item) && item.count !== undefined)
857
+ less.set(item.entryId, (less.get(item.entryId) ?? 0) + item.count);
858
+ next = held.flatMap((item) => {
859
+ if (out.has(listItemKey(item)))
860
+ return [];
861
+ if (!isSlotLoreRef(item) || !less.has(item.entryId))
862
+ return [item];
863
+ const left = slotLoreRefCount(item) - less.get(item.entryId);
864
+ return left > 0 ? [withCount(item, left)] : [];
865
+ });
866
+ break;
867
+ }
868
+ }
869
+ if (typeof config.maxItems === 'number' && next.length > config.maxItems)
870
+ return {
871
+ value: Object.freeze([...held]),
872
+ refusal: `this list holds at most ${config.maxItems} ` +
873
+ `item${config.maxItems === 1 ? '' : 's'}, and that would make it ${next.length}. ` +
874
+ `Take something out first — nothing was dropped to make room.`,
875
+ };
876
+ return { value: Object.freeze(next), refusal: null };
877
+ }
878
+ /**
879
+ * Whether a slot may attach to this kind of owner.
880
+ *
881
+ * The owner *kinds* the host stores (`card`, `cast_member`, `lorebook`,
882
+ * `session`, `session_cast`, `location`, `session_location`) collapse to the
883
+ * three a declaration talks about: a lorebook and a session are the **world**,
884
+ * a location entry and its session layer are a **location**, everything that
885
+ * is somebody is the **cast**. A declaration should not have to know the
886
+ * host's storage layout to say "this is a character stat".
887
+ * @internal
888
+ */
889
+ export const slotAppliesTo = (decl, owner) => decl.appliesTo.includes(owner);
890
+ /**
891
+ * Which derivation computes this slot, or `undefined` when nothing does.
892
+ *
893
+ * One reader, because the question now has two spellings: an expression on the
894
+ * declaration means `core:derive/liquid@1`, one of core's computations names
895
+ * itself in `config`. A host, a client and a receipt each working that out for
896
+ * themselves is how the three start disagreeing about which one ran.
897
+ * @experimental
898
+ */
899
+ export const slotDerivation = (decl) => decl.type !== 'derived'
900
+ ? undefined
901
+ : decl.derive
902
+ ? derivations.liquid.id
903
+ : decl.config?.derivation;
904
+ //# sourceMappingURL=attributes.js.map