@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,292 @@
1
+ /**
2
+ * Declared UI surfaces, and the preview manifest a harness reads from them.
3
+ *
4
+ * A package's UI arrives in exactly two shapes, and the difference is a trust
5
+ * decision, not a taste one:
6
+ *
7
+ * **frame** — a document (`ui/map.html`) mounted in an opaque-origin iframe
8
+ * (`sandbox="allow-scripts"`, never `allow-same-origin`). Zero ambient
9
+ * anything: no cookies, no DOM reach, no socket. Everything it knows arrives
10
+ * on the MessageChannel the host owns (the frame protocol below). This is the
11
+ * shape the app ships today — session-view replacement, page, panel grid
12
+ * (20 §12, 21 §7).
13
+ *
14
+ * **component** — a module the page's UI worker runs (§3.5, R25): one
15
+ * worker per owner per session page, no DOM, no network. It places
16
+ * elements from the host vocabulary (`SP_HOST_ELEMENTS`, `hostElements.ts`)
17
+ * and the host mirrors them into the widget box, dropping anything not
18
+ * listed; its data arrives on the same widget wire a frame's does. A
19
+ * widget names one by `component`; what needs a real document gets one
20
+ * inside the component through `sp-frame`. A frame is a remote minus the
21
+ * worker: the same envelope, a different boundary.
22
+ *
23
+ * The preview harness (`serene-pub preview`) renders both. It reads what the
24
+ * package **announces**, never what a directory happens to contain — a surface
25
+ * a modder sees in the harness is a surface an instance would see in the
26
+ * manifest, or it is a bug in one of them.
27
+ *
28
+ * ## Reading is tolerant on purpose
29
+ *
30
+ * `previewManifest()` never throws on a malformed declaration. The app's
31
+ * `surfacesOf` reads the stored manifest the same way — "a malformed
32
+ * declaration is a missing surface, not a crash" — and a dev harness that
33
+ * dies on a half-typed entry path is a harness that gets closed. Problems come
34
+ * back in `problems[]` so the harness can show them beside the list instead of
35
+ * replacing it.
36
+ *
37
+ * ## The frame protocol (host ⇄ frame, over the transferred port)
38
+ *
39
+ * The types below are the one declaration of the wire the app's `PluginFrame`
40
+ * and the preview harness both speak — both import these unions rather than
41
+ * restating them, so a message a host sends is a message this file declares.
42
+ * They are data, not behaviour: the SDK ships no host and no client, because
43
+ * the host is core's (it owns the scoping) and the client is the author's.
44
+ *
45
+ * What travels is the widget envelope (`widgets.ts`) with the boundary added:
46
+ * a frame receives the same sections a native widget reads off its context,
47
+ * one push per section. `FRAME_PROTOCOL` says which vintage of that wire the
48
+ * host speaks.
49
+ */
50
+ import { WIDGET_PROTOCOL, } from './widgets.js';
51
+ /**
52
+ * Where a package's entry module lives, in the order the toolchain looks.
53
+ * One list, shared by `serene-pub build` and the preview harness, so "the
54
+ * harness found my plugin but the packager didn't" cannot happen.
55
+ * @experimental
56
+ */
57
+ export const ENTRY_CANDIDATES = ['dist/index.js', 'src/index.ts', 'index.ts', 'index.js'];
58
+ /**
59
+ * The plugin slug grammar, mirrored from `defineExtension` — lowercase
60
+ * letters, digits, dots and hyphens, `chariot.dice-tray`, never a slash and
61
+ * never a colon.
62
+ *
63
+ * Here as well as there for the reason {@link isServablePanelId} is here: this
64
+ * module owns the two halves of a namespaced widget id, and a parser that
65
+ * borrowed one grammar and restated the other would be half a contract.
66
+ */
67
+ const SAFE_PLUGIN_ID = /^[a-z0-9]+([.-][a-z0-9]+)*$/;
68
+ /**
69
+ * The widget id a plugin's own panel is seated under: `<pluginId>:<panelId>`.
70
+ *
71
+ * A plugin's widgets are namespaced and core's and a genre's are not, because
72
+ * only a plugin's id is outside anyone's control: a package picks `map` in
73
+ * private and would otherwise collide with every other package that did, and
74
+ * with core's own widgets, in a layout row that outlives the install. The
75
+ * separator can only be `:` — neither grammar admits one — and it is the
76
+ * separator core already uses for an owned id (`core:genre/chat`).
77
+ *
78
+ * Pure: the two halves are NOT validated here. The host reads a stored
79
+ * manifest and knows what it accepted; a helper that refused a second time
80
+ * would have to say so in a second vocabulary, and a composer that can fail is
81
+ * a composer every caller has to branch on. Reading one back DOES validate,
82
+ * because a stored id arrives with no such provenance —
83
+ * {@link parsePluginWidgetId}. The asymmetry is deliberate: composing is the
84
+ * host's own string, parsing is anyone's.
85
+ * @experimental
86
+ */
87
+ export const pluginWidgetId = (pluginId, panelId) => `${pluginId}:${panelId}`;
88
+ /**
89
+ * A namespaced widget id taken back apart, or `null` when the string is not
90
+ * one.
91
+ *
92
+ * `null` is the answer for every core and genre widget id, which is what makes
93
+ * this the test for "is this widget a plugin's": both halves must satisfy the
94
+ * grammars a host would have accepted them under, so exactly the ids
95
+ * {@link pluginWidgetId} can produce round-trip and nothing else does. A
96
+ * second colon lands in the panel half and fails there, so `a:b:c` is not a
97
+ * plugin widget id rather than being read as one with a surprising panel.
98
+ * @experimental
99
+ */
100
+ export function parsePluginWidgetId(id) {
101
+ const cut = id.indexOf(':');
102
+ if (cut <= 0)
103
+ return null;
104
+ const pluginId = id.slice(0, cut);
105
+ const panelId = id.slice(cut + 1);
106
+ if (!SAFE_PLUGIN_ID.test(pluginId) || !isServablePanelId(panelId))
107
+ return null;
108
+ return { pluginId, panelId };
109
+ }
110
+ /**
111
+ * The version the host announces in `init`, and the number a frame reads to
112
+ * know what it may send.
113
+ *
114
+ * **2 comprises** everything declared in the two unions above: the widget
115
+ * envelope's sections as pushes (`settings`, `layout`, `event`,
116
+ * `actions`) alongside `session` / `messages` / `message` / `channel` /
117
+ * `props` / `theme` / `suspend` / `resume`, and, frame → host, `invoke`
118
+ * beside `ready` and `action`, plus `error`, `request` and `save-state` with
119
+ * their `page` and `state` replies.
120
+ *
121
+ * A host may DECLINE any of the last three and still be a v2 host: a `request`
122
+ * is not a grant, `save-state` may be capped or dropped, and an `error` may go
123
+ * no further than a log. What 2 promises is that the frame may send them
124
+ * without breaking the wire — never that the host will act on them. A frame
125
+ * that needs an answer must therefore tolerate not getting one, just as it
126
+ * ignores a host message it has never heard of.
127
+ *
128
+ * A v1 frame keeps working unchanged: it never sends the frame → host
129
+ * additions, and it must already ignore host messages it does not recognise. A
130
+ * v2 host must still accept `init` from a v1 frame — the version says what the
131
+ * frame *may* send, not what it must.
132
+ *
133
+ * ONE number with the native lane (`WIDGET_PROTOCOL`): native is frame minus
134
+ * the iframe, so a second clock here would be a second contract by accident.
135
+ * @experimental
136
+ */
137
+ export const FRAME_PROTOCOL = WIDGET_PROTOCOL;
138
+ /**
139
+ * What the instance will actually accept — mirrored from the app's `frameHost`
140
+ * (`isSafeUiPath`, and the panel-id test inside `surfacesOf`).
141
+ *
142
+ * These live here, and not only there, because core **silently drops** a
143
+ * surface that fails them: no error, no log, just a panel that never appears.
144
+ * The author has to be told at build time and at preview time, which means the
145
+ * grammar has to exist on this side of the boundary too. If the app's changes,
146
+ * this changes with it — the pins in `surfaces.test.ts` name the function to
147
+ * check against.
148
+ */
149
+ const SAFE_ENTRY = /^[a-zA-Z0-9_\-][a-zA-Z0-9._\-]*(\/[a-zA-Z0-9._\-]+)*$/;
150
+ const SAFE_PANEL_ID = /^[a-z0-9_-]+$/;
151
+ /** Would an instance serve this entry path, or quietly drop the surface? @internal */
152
+ export const isServableEntry = (path) => SAFE_ENTRY.test(path) && !path.split('/').some((seg) => seg === '.' || seg === '..');
153
+ /** Would an instance accept this panel id, or quietly drop the panel? @internal */
154
+ export const isServablePanelId = (id) => SAFE_PANEL_ID.test(id);
155
+ const SAFE_ID = /[^a-z0-9]+/g;
156
+ const slugify = (s) => s.toLowerCase().replace(SAFE_ID, '-').replace(/^-|-$/g, '') || 'surface';
157
+ const str = (v) => (typeof v === 'string' && v.trim() ? v : undefined);
158
+ /** A settings schema, or nothing — never a half-read object. */
159
+ const settingsOf = (v) => v && typeof v === 'object' && !Array.isArray(v) && Object.keys(v).length
160
+ ? v
161
+ : undefined;
162
+ /** i18n values are `string | {en: …}` across the SDK; display needs one line. */
163
+ const label = (v, fallback) => str(v) ?? str(v?.en) ?? fallback;
164
+ /**
165
+ * Read a package's UI declarations into the harness's list.
166
+ *
167
+ * Takes the entry module's default export: a `defineExtension` result. An
168
+ * `AnnouncementBuilder` or a compiled `AnnouncementDocument` is still read, for
169
+ * packages built before `defineExtension` became the one entry.
170
+ * @experimental
171
+ */
172
+ export function previewManifest(entry) {
173
+ const problems = [];
174
+ const targets = [];
175
+ const seen = new Set();
176
+ const source = unwrap(entry, problems);
177
+ const id = source.id;
178
+ const push = (t) => {
179
+ let unique = t.id;
180
+ for (let n = 2; seen.has(unique); n++)
181
+ unique = `${t.id}-${n}`;
182
+ seen.add(unique);
183
+ targets.push({ ...t, id: unique });
184
+ };
185
+ // ── frames declared under `surfaces` ────────────────────────────────────
186
+ const s = source.surfaces;
187
+ const frame = (decl, point, where) => {
188
+ const entryPath = str(decl?.entry);
189
+ if (!entryPath) {
190
+ problems.push(`${where}: no entry — a frame surface is a document to mount`);
191
+ return;
192
+ }
193
+ // Refused here rather than previewed, because an instance refuses it
194
+ // too — and does so without saying anything. A harness that rendered
195
+ // this surface would be showing one that can never exist.
196
+ if (!isServableEntry(entryPath)) {
197
+ problems.push(`${where}: '${entryPath}' is not a path a pub will serve, and it drops ` +
198
+ `such a surface silently. Use relative segments of letters, digits, '.', ` +
199
+ `'-' and '_' — no leading slash, no '..'.`);
200
+ return;
201
+ }
202
+ push({
203
+ id: point,
204
+ label: label(decl.title, point),
205
+ kind: 'frame',
206
+ point,
207
+ entry: entryPath,
208
+ source: 'surfaces',
209
+ });
210
+ };
211
+ if (s?.['session-view'])
212
+ frame(s['session-view'], 'session-view', "surfaces['session-view']");
213
+ if (s?.page)
214
+ frame(s.page, 'page', 'surfaces.page');
215
+ // ── components: modules the page's UI worker runs (§3.5, R25) ───────────
216
+ for (const [i, c] of source.components.entries()) {
217
+ const slug = str(c?.slug);
218
+ const entryPath = str(c?.entry);
219
+ if (!slug || !entryPath) {
220
+ problems.push(`components[${i}]: ${!slug ? 'no slug' : 'no entry'} — both are required (12 §3b)`);
221
+ continue;
222
+ }
223
+ push({
224
+ id: slugify(slug),
225
+ label: label(c.label, slug),
226
+ kind: 'component',
227
+ point: 'widget',
228
+ entry: entryPath,
229
+ framework: c.framework,
230
+ settings: settingsOf(c.settings),
231
+ source: 'components',
232
+ });
233
+ }
234
+ return { id, title: source.title, version: source.version, targets, problems };
235
+ }
236
+ /**
237
+ * Accept the three entry shapes without importing the announce builder — a
238
+ * structural read keeps this module free of the cycle announce↔surfaces would
239
+ * otherwise create, and keeps a hand-written document just as readable.
240
+ */
241
+ function unwrap(entry, problems) {
242
+ const e = (entry ?? {});
243
+ // An AnnouncementBuilder: build it, so its own validation still runs and a
244
+ // refusal shows up as a problem rather than an empty harness.
245
+ if (typeof e.build === 'function' && e.identity?.ns) {
246
+ try {
247
+ const { document } = e.build();
248
+ return unwrap(document, problems);
249
+ }
250
+ catch (err) {
251
+ problems.push(`announcement refused: ${err.message}`);
252
+ return {
253
+ id: e.identity.ns,
254
+ title: str(e.identity.title) ?? e.identity.ns,
255
+ genres: [],
256
+ components: [],
257
+ widgets: [],
258
+ };
259
+ }
260
+ }
261
+ // A compiled AnnouncementDocument.
262
+ if (e.schemaVersion === 1 && e.identity?.ns) {
263
+ return {
264
+ id: e.identity.ns,
265
+ title: str(e.identity.title) ?? e.identity.ns,
266
+ version: str(e.identity.version),
267
+ surfaces: e.surfaces,
268
+ genres: Array.isArray(e.genres) ? e.genres : [],
269
+ components: Array.isArray(e.components) ? e.components : [],
270
+ widgets: Array.isArray(e.widgets) ? e.widgets : [],
271
+ };
272
+ }
273
+ // A defineExtension result. Its `genres` are read for the same reason an
274
+ // announcement's are: since D-1 a plugin declares its genre here, and a genre
275
+ // may point a panel at its own package's frame — a harness reading only
276
+ // `surfaces` would render fewer surfaces than an instance mounts.
277
+ if (str(e.slug)) {
278
+ return {
279
+ id: e.slug,
280
+ title: str(e.name) ?? e.slug,
281
+ version: str(e.version),
282
+ surfaces: e.surfaces,
283
+ genres: Array.isArray(e.genres) ? e.genres : [],
284
+ components: Array.isArray(e.components) ? e.components : [],
285
+ widgets: Array.isArray(e.widgets) ? e.widgets : [],
286
+ };
287
+ }
288
+ problems.push('the entry module has no default export this harness recognises — export ' +
289
+ 'your defineExtension(…) result');
290
+ return { id: 'unknown', title: 'unknown package', genres: [], components: [], widgets: [] };
291
+ }
292
+ //# sourceMappingURL=surfaces.js.map
@@ -0,0 +1,312 @@
1
+ /**
2
+ * A minimal template engine, enough to demonstrate variable awareness (16 §4).
3
+ *
4
+ * Supports `{{ a.b.c }}` and `{% for x in items %}…{% endfor %}`. Not Jinja — just
5
+ * enough surface to answer the question the docs make a promise about: *can the editor
6
+ * tell an author which variables exist, and flag one that doesn't?*
7
+ *
8
+ * ⚠ Writing this surfaced a correction to 16 §4 — see `templateScope`.
9
+ */
10
+ import type { I18n, SlotDecl } from './descriptors.js';
11
+ import type { FieldDecl } from './settings.js';
12
+ /** @experimental */
13
+ export interface TemplateRef {
14
+ /** The root identifier, e.g. `message` in `{{ message.author.name }}`. */
15
+ root: string;
16
+ path: string[];
17
+ /** True when the reference is inside a loop and bound by it. */
18
+ bound: boolean;
19
+ dynamic: boolean;
20
+ }
21
+ /**
22
+ * Extract top-level variable references. Loop-bound names are marked so they are not
23
+ * reported as unknown, and anything computed is marked dynamic rather than verified —
24
+ * an editor that promises correctness and lets a typo through is worse than one that
25
+ * says what it checks (16 §4).
26
+ * @experimental
27
+ */
28
+ export declare function extractRefs(src: string): TemplateRef[];
29
+ /** Render. Missing values become empty strings — templates never throw at run time. @experimental */
30
+ export declare function render(src: string, baseScope: Record<string, unknown>): string;
31
+ /**
32
+ * ⚠ CORRECTION TO 16 §4.
33
+ *
34
+ * The docs say template variable awareness "falls out of typed ports with no new
35
+ * mechanism." Building it shows that is only true for the **assembly** template, whose
36
+ * scope really is its input ports.
37
+ *
38
+ * A **source** template renders one *item* out of a collection — one lorebook entry, one
39
+ * message — and the item's shape lives *inside* the port's payload, not on the port. No
40
+ * amount of port typing recovers it.
41
+ *
42
+ * So the template slot must **declare its own variable scope**. That is one extra field on
43
+ * the descriptor, not a new mechanism, but the docs currently claim something that isn't
44
+ * quite true and would have been discovered by the first plugin author who tried it.
45
+ */
46
+ /**
47
+ * The kinds a declared value can be.
48
+ *
49
+ * Deliberately closed and deliberately small. This is not JSON Schema: an
50
+ * editor has to *walk* this to offer completions, and every case it cannot walk
51
+ * is a case where the author is back to guessing. Six kinds cover every value
52
+ * core renders, and a seventh should have to earn its place by naming the
53
+ * variable that needs it.
54
+ * @experimental
55
+ */
56
+ export type VarType = 'string' | 'number' | 'boolean'
57
+ /** A fixed set of named fields — `fields`. */
58
+ | 'object'
59
+ /** A positional collection — `of` describes an element. */
60
+ | 'list'
61
+ /** Keyed by author-chosen strings — `of` describes a value. */
62
+ | 'record';
63
+ /** @experimental */
64
+ export interface VarField {
65
+ type: VarType;
66
+ /** Shown in the editor's completion list and on hover. */
67
+ description?: I18n;
68
+ /** `object` — the fields it carries. */
69
+ fields?: Record<string, VarField>;
70
+ /** `list` / `record` — the shape of each entry. */
71
+ of?: VarField;
72
+ /**
73
+ * May be absent, or present and null.
74
+ *
75
+ * The two are one flag rather than two because a template cannot tell them
76
+ * apart: `{{ this.personality }}` renders empty either way. What the author
77
+ * needs to know is "do not promise this will be here", and that is the same
78
+ * answer for a dropped key and a null one.
79
+ */
80
+ optional?: boolean;
81
+ }
82
+ /**
83
+ * What one root name in a template's scope is.
84
+ *
85
+ * The two legacy forms stay valid, and stay *meaningfully* valid rather than
86
+ * being quietly coerced:
87
+ *
88
+ * - `'any'` means unchecked. It is what every variable said before schemas
89
+ * existed and it is still the honest answer for a value whose shape genuinely
90
+ * varies.
91
+ * - `string[]` is a bare list of field names, untyped and unnested.
92
+ *
93
+ * Neither is an error. A plugin published against the old form keeps working
94
+ * across this upgrade, which is the whole reason they survive — lint can nudge
95
+ * an author toward a real schema, but an upgrade that broke every third-party
96
+ * node's declaration to buy nothing but tidiness is not a trade worth making.
97
+ * @experimental
98
+ */
99
+ export type VarDecl = VarField | 'any' | string[];
100
+ /** @experimental */
101
+ export type TemplateScope = Record<string, VarDecl>;
102
+ /** @experimental */
103
+ export declare function templateScope(decl: {
104
+ variables?: TemplateScope;
105
+ } | undefined): TemplateScope;
106
+ /**
107
+ * What a template check found wrong.
108
+ *
109
+ * `checkTemplate` (the mini engine) fills the first three; the source checker
110
+ * (`@serene-pub/sdk/template-check`) fills the rest too — which name, where in
111
+ * the source, and what was there instead.
112
+ * @experimental
113
+ */
114
+ export interface TemplateFinding {
115
+ severity: 'error' | 'warning';
116
+ message: string;
117
+ fix: string;
118
+ kind?: TemplateFindingKind;
119
+ /** The root name (or helper) the finding is about, as the template spells it. */
120
+ name?: string;
121
+ /** The whole reference as written — `characters.nmae`, `../injectionsByIndx`. */
122
+ path?: string;
123
+ /** 1-based, as both engines report it. */
124
+ line?: number;
125
+ column?: number;
126
+ /** 0-based offsets of the reference in the source. */
127
+ start?: number;
128
+ end?: number;
129
+ /** The enclosing tag (`{{ … }}`), when the engine reports one. */
130
+ tag?: {
131
+ start: number;
132
+ end: number;
133
+ };
134
+ /** What does exist where the name was looked up. */
135
+ available?: string[];
136
+ /** The nearest of `available`, when one is near enough to say "did you mean". */
137
+ suggestion?: string;
138
+ }
139
+ /**
140
+ * - `syntax` — the source does not parse (always an error).
141
+ * - `unknown-name` — a root the scope does not have.
142
+ * - `unknown-path` — a field the declared type contradicts.
143
+ * - `unknown-helper` — a Handlebars helper nobody registered.
144
+ * @experimental
145
+ */
146
+ export type TemplateFindingKind = 'syntax' | 'unknown-name' | 'unknown-path' | 'unknown-helper';
147
+ /**
148
+ * What a host's engines register, as names — the checker's input
149
+ * (`@serene-pub/sdk/template-check`). Declared here, on the barrel, so a
150
+ * dependency-free module can take a checker as a value without importing the
151
+ * engines (typed templates P5).
152
+ * @experimental
153
+ */
154
+ export interface TemplateCheckOptions {
155
+ /** Handlebars helpers the host registers beyond the built-ins. */
156
+ helpers?: Iterable<string>;
157
+ /** What the host's Liquid instance registers — the checker parses with the same vocabulary. */
158
+ liquid?: {
159
+ /** `{% name %}…{% endname %}` tags; `key: value` arguments are read as expressions. */
160
+ blockTags?: Iterable<string>;
161
+ /** Filters beyond Liquid's own. Filters are strict: an unknown one does not parse. */
162
+ filters?: Iterable<string>;
163
+ /** Tags refused at parse time, each with the sentence that says why. */
164
+ refusedTags?: Readonly<Record<string, string>>;
165
+ /** Characters one parse may consume. */
166
+ parseLimit?: number;
167
+ };
168
+ /**
169
+ * `templateScopeReport().untyped` — producers whose keys reach the template
170
+ * undeclared. Non-empty: name and path findings are warnings.
171
+ */
172
+ untyped?: readonly string[];
173
+ }
174
+ /** @experimental */
175
+ export interface TemplateSourceCheck {
176
+ /**
177
+ * False when nothing was looked at — an engine this checker does not read
178
+ * (a plugin's), or an analyser that failed on a source that parsed. An
179
+ * empty `findings` then means "not checked", never "clean".
180
+ */
181
+ checked: boolean;
182
+ findings: TemplateFinding[];
183
+ }
184
+ /** @experimental */
185
+ export declare function checkTemplate(src: string, scope: TemplateScope): TemplateFinding[];
186
+ /**
187
+ * Walking a path against a schema.
188
+ *
189
+ * The whole point of widening `TemplateScope` was to be able to answer "is
190
+ * `{{ this.nickanme }}` a field?" — and answering it needs one rule the
191
+ * name-only lint never had to state: **what may go unchecked stays unchecked**.
192
+ * A declaration that says `'any'`, a legacy `string[]`, a record's
193
+ * author-chosen key — none of those can be verified, and reporting them would
194
+ * put a red squiggle under working templates. A lint that cries wolf gets
195
+ * turned off, and then it catches nothing at all.
196
+ *
197
+ * So `ok: false` is reserved for a path the schema positively contradicts.
198
+ * Everything else resolves, with `checked` saying whether the answer means
199
+ * anything downstream.
200
+ * @experimental
201
+ */
202
+ export interface PathResolution {
203
+ ok: boolean;
204
+ /** The type at the end of the path, when one is known. */
205
+ field?: VarField;
206
+ /** Whether the schema could actually speak to this path. */
207
+ checked: boolean;
208
+ /** The segment that failed. */
209
+ at?: string;
210
+ /** What does exist there, when that is a listable answer. */
211
+ available?: string[];
212
+ message?: string;
213
+ }
214
+ /**
215
+ * Resolve `path` against a declared type.
216
+ *
217
+ * `list` is the interesting case. A list is reached by *position*, so
218
+ * `characters.name` is not a near-miss to be corrected — it is a category
219
+ * error, and saying so is the whole reason the old flattened `string[]` form
220
+ * had to go: it accepted exactly that and rejected `characters.0.name`.
221
+ * @internal
222
+ */
223
+ export declare function resolvePath(decl: VarDecl | undefined, path: readonly string[], base?: string): PathResolution;
224
+ /** @internal */
225
+ export declare function elementOf(decl: VarDecl | undefined): VarField | undefined;
226
+ /**
227
+ * Does a value match a declared schema?
228
+ *
229
+ * This exists so a `sample` and its `scope` cannot drift apart. A sample is not
230
+ * decoration: it is what the layout editor renders a live preview against, so a
231
+ * sample whose shape is wrong shows the author a preview that works and a chat
232
+ * that doesn't — a lie told at exactly the moment they are trusting the tool.
233
+ * The declaration and the example of it have to be checkable against each
234
+ * other, and this is the check.
235
+ *
236
+ * Findings are errors, not warnings, and an undeclared key is one of them. A
237
+ * sample carrying a field the schema omits means the schema is incomplete, and
238
+ * an incomplete schema is a completion list missing an entry the author needs —
239
+ * silently, with no way to tell it apart from a field that truly is not there.
240
+ * @experimental
241
+ */
242
+ export declare function checkValue(value: unknown, field: VarField, path?: string): string[];
243
+ /**
244
+ * Check every key of a scope against the values a declaration samples for it.
245
+ *
246
+ * Legacy declarations are skipped rather than guessed at. `'any'` means
247
+ * unchecked by definition, and a bare `string[]` carries no types to check
248
+ * against — pretending otherwise would fail honest declarations that simply
249
+ * predate the schema.
250
+ * @experimental
251
+ */
252
+ export declare function checkScopeSample(values: Record<string, unknown>, scope: TemplateScope, label?: string): string[];
253
+ /** An object's fields as TS: optional ones may be absent or null (see `VarField.optional`). */
254
+ type ObjectValue<Fs> = {
255
+ -readonly [K in keyof Fs as Fs[K] extends {
256
+ optional: true;
257
+ } ? never : K]: VarValue<Fs[K]>;
258
+ } & {
259
+ -readonly [K in keyof Fs as Fs[K] extends {
260
+ optional: true;
261
+ } ? K : never]?: VarValue<Fs[K]> | null;
262
+ };
263
+ /**
264
+ * The TypeScript type of a value a declaration describes.
265
+ *
266
+ * `VarValue<{ type: 'record', of: { type: 'string' } }>` is
267
+ * `Record<string, string>`. A declaration written as a literal (or `as const`)
268
+ * types exactly; one widened to `VarField` — or `'any'` — is `unknown`, which
269
+ * is the honest answer for a shape the compiler cannot see. What makes a
270
+ * variable's `sample` and a layout's in-code fallback compile-checked.
271
+ * @experimental
272
+ */
273
+ export type VarValue<F> = F extends 'any' ? unknown : F extends readonly string[] ? {
274
+ [K in F[number]]?: unknown;
275
+ } : F extends {
276
+ type: 'string';
277
+ } ? string : F extends {
278
+ type: 'number';
279
+ } ? number : F extends {
280
+ type: 'boolean';
281
+ } ? boolean : F extends {
282
+ type: 'list';
283
+ of: infer O;
284
+ } ? VarValue<O>[] : F extends {
285
+ type: 'record';
286
+ of: infer O;
287
+ } ? Record<string, VarValue<O>> : F extends {
288
+ type: 'object';
289
+ fields: infer Fs;
290
+ } ? ObjectValue<Fs> : unknown;
291
+ /** Every root of a template scope, typed — `ScopeValues<typeof decl.scope>`. @experimental */
292
+ export type ScopeValues<S extends TemplateScope> = {
293
+ -readonly [K in keyof S]: VarValue<S[K]>;
294
+ };
295
+ /**
296
+ * A `FieldDecl`, in the template type language — `undefined` for what never enters a template.
297
+ * @internal
298
+ */
299
+ export declare function fieldToVarField(f: FieldDecl | undefined): VarField | undefined;
300
+ /**
301
+ * What a slot's configured value looks like to a template, as a `VarField`.
302
+ *
303
+ * `prompts` — an object of the authored text fields, each a string.
304
+ * `parameters` / `settings` — an object of the declared schema's fields, typed
305
+ * from the field language; a `secret` field is left out, because a secret
306
+ * never enters a template's scope. Every other kind (a template, a connection,
307
+ * a variables slot) is not a value a template reads, and is `undefined`.
308
+ * @experimental
309
+ */
310
+ export declare function slotToVarField(slot: SlotDecl): VarField | undefined;
311
+ export {};
312
+ //# sourceMappingURL=template.d.ts.map