@zvndev/darkmown 0.18.0 → 0.20.0

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.
@@ -0,0 +1,1149 @@
1
+ // ---------------------------------------------------------------------------
2
+ // Directive handlers: the `handle*` family dispatched per line by the body
3
+ // parser (state/store/fetch/computed/effect/form/input/bind/submit/textarea/
4
+ // select/checkbox/radio/button/if/include/container) plus the `:button` action
5
+ // parser and the documentation-demo directives (`:try`/`:note`/`:sprint`).
6
+ //
7
+ // Every handler receives the 0-based line `index` so its malformed/invalid
8
+ // errors report `file:line` (via `at`) — matching the unclosed-block errors —
9
+ // while keeping the message text and `Use:` hints intact.
10
+ // ---------------------------------------------------------------------------
11
+
12
+ import { compileBody } from "./body.js";
13
+ import { at, createScope, LOOP_META } from "./context.js";
14
+ import { resolveInclude } from "./includes.js";
15
+ import {
16
+ escapeHtml,
17
+ getPath,
18
+ humanizeName,
19
+ lookupPath,
20
+ lookupVar,
21
+ parseScalar,
22
+ parseStateValue,
23
+ resolveStateKey,
24
+ safeScriptJson,
25
+ stripQuotes,
26
+ validatePath
27
+ } from "./interpolation.js";
28
+ import { compileFile } from "./page.js";
29
+ import { compileComputedExpr, compileWhen, evalPredicate } from "./predicates.js";
30
+
31
+ /**
32
+ * @typedef {import("./context.js").Ctx} Ctx
33
+ * @typedef {import("./context.js").Action} Action
34
+ */
35
+
36
+ /**
37
+ * @param {string} line
38
+ * @param {Ctx} ctx
39
+ * @param {number} index 0-based line index for `file:line` errors.
40
+ * @returns {string}
41
+ */
42
+ export function handleInclude(line, ctx, index) {
43
+ const match = line.match(/^@include\s+(\S+)(?:\s+with\s+(.+))?$/);
44
+ if (!match) throw new Error(`Malformed @include in ${at(ctx.file, index)}: ${line}`);
45
+ const target = resolveInclude(match[1], ctx.file, ctx.context);
46
+ const args = parseIncludeArgs(match[2] || "", ctx);
47
+ const scope = createScope(ctx.scope, args);
48
+ const child = compileFile(
49
+ target,
50
+ ctx.context,
51
+ ctx.stack,
52
+ scope,
53
+ ctx.comp,
54
+ ctx.sections,
55
+ ctx.loopItem
56
+ );
57
+ return child.html;
58
+ }
59
+
60
+ /**
61
+ * @param {string} raw
62
+ * @param {Ctx} ctx
63
+ * @returns {Record<string, unknown>}
64
+ */
65
+ function parseIncludeArgs(raw, ctx) {
66
+ /** @type {Record<string, unknown>} */
67
+ const args = {};
68
+ const re = /([A-Za-z0-9_-]+)=("[^"]*"|'[^']*'|\{[^}]*\}|\S+)/g;
69
+ for (const match of raw.matchAll(re)) {
70
+ const value = match[2];
71
+ if (value.startsWith("{")) {
72
+ const expr = value.slice(1, -1).trim();
73
+ const resolved = lookupPath(expr, ctx);
74
+ if (!resolved.found) {
75
+ throw new Error(
76
+ `@include argument ${match[1]}={ ${expr} } in ${ctx.file} does not match any value in scope`
77
+ );
78
+ }
79
+ args[match[1]] = resolved.value;
80
+ } else {
81
+ args[match[1]] = parseScalar(value);
82
+ }
83
+ }
84
+ return args;
85
+ }
86
+
87
+ /**
88
+ * @param {string} header
89
+ * @param {string[]} bodyLines
90
+ * @param {Ctx} ctx
91
+ * @param {number} index 0-based line index for `file:line` errors.
92
+ * @returns {string}
93
+ */
94
+ export function handleContainer(header, bodyLines, ctx, index) {
95
+ let rest = header.trim();
96
+ let tag = "section";
97
+ /** @type {string[]} Static classes baked into class="". */
98
+ const extraClass = [];
99
+ /** @type {[string, string][]} Reactive loop-item class bindings (data-wd-each-class). */
100
+ const eachClasses = [];
101
+ /** @type {[string, string][]} Global state-driven class bindings (data-wd-class). */
102
+ const stateClasses = [];
103
+ let id = "";
104
+ // Leading tag/name token (anything not starting with . or #). "section" keeps
105
+ // the <section> tag; any other name becomes a <div> and also a class.
106
+ const lead = rest.match(/^([^\s.#]\S*)/);
107
+ let nameToken = "section";
108
+ if (lead) {
109
+ nameToken = lead[1];
110
+ rest = rest.slice(lead[0].length).trim();
111
+ }
112
+ if (nameToken !== "section") {
113
+ tag = "div";
114
+ extraClass.push(nameToken);
115
+ }
116
+ while (rest.length) {
117
+ if (rest.startsWith("#")) {
118
+ const m = rest.match(/^#(\S+)/);
119
+ id = m ? m[1] : "";
120
+ rest = rest.slice((m ? m[0] : rest).length).trim();
121
+ continue;
122
+ }
123
+ const cm = rest.match(/^\.([A-Za-z_][\w-]*)/);
124
+ if (!cm)
125
+ throw new Error(
126
+ `Unexpected token "${rest.split(/\s+/)[0]}" in container "::: ${header}" in ${at(ctx.file, index)}`
127
+ );
128
+ const cls = cm[1];
129
+ rest = rest.slice(cm[0].length).trim();
130
+ // Optional `when <predicate>` makes the class reactive. The predicate runs to
131
+ // the next ` .`/` #` token or the end of the header.
132
+ const whenMatch = rest.match(/^when\s+(.+?)(?=\s+[.#]|$)/);
133
+ if (whenMatch) {
134
+ rest = rest.slice(whenMatch[0].length).trim();
135
+ const compiled = compileWhen(whenMatch[1].trim(), ctx);
136
+ if (compiled.static) {
137
+ if (compiled.value) extraClass.push(cls);
138
+ } else if (compiled.item) eachClasses.push([cls, compiled.body]);
139
+ else stateClasses.push([cls, compiled.body]);
140
+ } else {
141
+ extraClass.push(cls);
142
+ }
143
+ }
144
+ const explicitId = Boolean(id);
145
+ if (!id) id = `wd-s${++ctx.comp.sectionCounter}`;
146
+
147
+ ctx.sections.push(id);
148
+ let inner;
149
+ try {
150
+ inner = compileBody(bodyLines, ctx);
151
+ } finally {
152
+ ctx.sections.pop();
153
+ }
154
+ const idAttr = explicitId ? ` id="${escapeHtml(id)}"` : "";
155
+ const classAttr = extraClass.length ? ` class="${escapeHtml(extraClass.join(" "))}"` : "";
156
+ let classBind = "";
157
+ if (eachClasses.length) {
158
+ ctx.comp.assets.runtime = true;
159
+ classBind += ` data-wd-each-class="${escapeHtml(JSON.stringify(eachClasses))}"`;
160
+ }
161
+ if (stateClasses.length) {
162
+ ctx.comp.assets.runtime = true;
163
+ classBind += ` data-wd-class="${escapeHtml(JSON.stringify(stateClasses))}"`;
164
+ }
165
+ return `<${tag}${idAttr}${classAttr}${classBind}>\n${inner}\n</${tag}>`;
166
+ }
167
+
168
+ /**
169
+ * @param {string} line
170
+ * @param {Ctx} ctx
171
+ * @param {number} index 0-based line index for `file:line` errors.
172
+ * @returns {string}
173
+ */
174
+ export function handleState(line, ctx, index) {
175
+ const match = line.match(/^:state\s+([A-Za-z_$][\w$]*)\s*=\s*(.+?)(\s+persist)?$/);
176
+ if (!match) throw new Error(`Malformed :state in ${at(ctx.file, index)}: ${line}`);
177
+ const value = parseStateValue(match[2]);
178
+ const key = declareState(match[1], value, ctx);
179
+ const persistAttr = match[3] ? ` data-wd-persist="${key}"` : "";
180
+ return `<script type="application/json" data-wd-state${persistAttr}>${safeScriptJson({ [key]: value })}</script>`;
181
+ }
182
+
183
+ /**
184
+ * Register a state key in the current section scope, enabling the runtime.
185
+ * @param {string} name
186
+ * @param {unknown} value
187
+ * @param {Ctx} ctx
188
+ * @returns {string} The fully-qualified state key.
189
+ */
190
+ function declareState(name, value, ctx) {
191
+ if (ctx.loopItem)
192
+ throw new Error(`State cannot be declared inside a reactive @loop body (${ctx.file})`);
193
+ if (ctx.comp.stores.has(name))
194
+ throw new Error(
195
+ `State "${name}" collides with a :store of the same name in ${ctx.file}. Use: :store name = value for the global, or rename one.`
196
+ );
197
+ const key = ctx.sections.length ? `${ctx.sections.at(-1)}:${name}` : name;
198
+ if (ctx.comp.state.has(key))
199
+ throw new Error(`State "${name}" is declared twice in the same scope (${ctx.file})`);
200
+ ctx.comp.state.set(key, value);
201
+ ctx.comp.assets.runtime = true;
202
+ return key;
203
+ }
204
+
205
+ /**
206
+ * @param {string} line
207
+ * @param {Ctx} ctx
208
+ * @param {number} index 0-based line index for `file:line` errors.
209
+ * @returns {string}
210
+ */
211
+ export function handleStore(line, ctx, index) {
212
+ const match = line.match(/^:store\s+([A-Za-z_$][\w$]*)\s*=\s*(.+?)(\s+ephemeral)?$/);
213
+ if (!match)
214
+ throw new Error(
215
+ `Malformed :store in ${at(ctx.file, index)}: ${line}. Use: :store name = value [ephemeral]`
216
+ );
217
+ const value = parseStateValue(match[2]);
218
+ const name = declareStore(match[1], value, ctx);
219
+ const ephemeral = match[3] ? " data-wd-store-ephemeral" : "";
220
+ return `<script type="application/json" data-wd-store="${name}"${ephemeral}>${safeScriptJson(value)}</script>`;
221
+ }
222
+
223
+ /**
224
+ * Register a page-global store. The bare name is added to `comp.state` so every
225
+ * resolver (interpolation, :if, @loop, :computed, actions) sees it, and tracked
226
+ * in `comp.stores` for collision checks. Never section-scoped.
227
+ * @param {string} name
228
+ * @param {unknown} value
229
+ * @param {Ctx} ctx
230
+ * @returns {string} The store name (also its bare state key).
231
+ */
232
+ function declareStore(name, value, ctx) {
233
+ if (ctx.comp.stores.has(name))
234
+ throw new Error(`Store "${name}" is declared twice in ${ctx.file}. Use: :store name = value`);
235
+ if (ctx.comp.state.has(name))
236
+ throw new Error(
237
+ `Store "${name}" collides with a :state of the same name in ${ctx.file}. Use: :store name = value for the global, or rename one.`
238
+ );
239
+ ctx.comp.stores.add(name);
240
+ ctx.comp.state.set(name, value);
241
+ ctx.comp.assets.runtime = true;
242
+ return name;
243
+ }
244
+
245
+ /**
246
+ * Seed a `<name>_error` state key (null) if absent. Shared by :fetch and the
247
+ * round-trip :form so error fallbacks have a key to bind.
248
+ * @param {string} key
249
+ * @param {Ctx} ctx
250
+ * @returns {void}
251
+ */
252
+ function declareErrorState(key, ctx) {
253
+ const errorKey = `${key}_error`;
254
+ if (!ctx.comp.state.has(errorKey)) ctx.comp.state.set(errorKey, null);
255
+ }
256
+
257
+ const FETCH_USE =
258
+ 'Use: :fetch name from "url" [method=…] [timeout=ms] [retry=N] [when=visible] [headers=key] [body=key] [refresh=url]';
259
+
260
+ /**
261
+ * Parse a keyword-arg `:fetch` directive into a lifecycle-aware marker.
262
+ * Auto-declares four state keys (value/error/loading/empty), seeds them, and
263
+ * emits `data-wd-fetch-*` attributes (url/method/when/timeout/retry/headers/
264
+ * body/deps) consumed by the runtime's `startFetch`.
265
+ * @param {string} line
266
+ * @param {Ctx} ctx
267
+ * @param {number} index 0-based line index for `file:line` errors.
268
+ * @returns {string}
269
+ */
270
+ export function handleFetch(line, ctx, index) {
271
+ const head = line.match(/^:fetch\s+([A-Za-z_$][\w$]*)\s+from\s+("[^"]+"|\S+)\s*(.*)$/);
272
+ if (!head) throw new Error(`Malformed :fetch in ${at(ctx.file, index)}: ${line}. ${FETCH_USE}`);
273
+ const name = head[1];
274
+ const url = validateFetchUrl(stripQuotes(head[2]), ctx);
275
+ /** @type {Record<string, string>} */
276
+ const opts = {};
277
+ for (const part of head[3].trim().split(/\s+/).filter(Boolean)) {
278
+ const kv = part.match(/^([A-Za-z]+)=(.+)$/);
279
+ if (!kv)
280
+ throw new Error(`Unknown :fetch option "${part}" in ${at(ctx.file, index)}. ${FETCH_USE}`);
281
+ const optName = kv[1];
282
+ if (!["method", "when", "timeout", "retry", "headers", "body", "refresh"].includes(optName)) {
283
+ throw new Error(`Unknown :fetch option "${optName}" in ${at(ctx.file, index)}. ${FETCH_USE}`);
284
+ }
285
+ opts[optName] = stripQuotes(kv[2]);
286
+ }
287
+
288
+ if (
289
+ opts.method &&
290
+ !["GET", "POST", "PUT", "PATCH", "DELETE"].includes(opts.method.toUpperCase())
291
+ ) {
292
+ throw new Error(
293
+ `:fetch method "${opts.method}" is not allowed in ${at(ctx.file, index)}. ${FETCH_USE}`
294
+ );
295
+ }
296
+ if (opts.when && !["load", "visible"].includes(opts.when)) {
297
+ throw new Error(
298
+ `:fetch when "${opts.when}" is not allowed in ${at(ctx.file, index)}. ${FETCH_USE}`
299
+ );
300
+ }
301
+ for (const n of ["timeout", "retry"]) {
302
+ if (opts[n] !== undefined && !/^\d+$/.test(opts[n])) {
303
+ throw new Error(
304
+ `:fetch ${n} must be a non-negative integer in ${at(ctx.file, index)}. ${FETCH_USE}`
305
+ );
306
+ }
307
+ }
308
+ if (opts.refresh !== undefined) {
309
+ // Layer 2: a 401 triggers a token-refresh POST to this URL, then one retry.
310
+ // The new token is written back into the `headers=` state, so it is required.
311
+ if (!opts.headers) {
312
+ throw new Error(
313
+ `:fetch refresh= needs headers= (the state key holding the token to renew) in ${at(ctx.file, index)}. ${FETCH_USE}`
314
+ );
315
+ }
316
+ opts.refresh = validateFetchUrl(opts.refresh, ctx, ":fetch refresh");
317
+ }
318
+
319
+ // Extract `{ path }` dependency keys from the URL (validated against poison
320
+ // segments). The runtime fills them from state on each (re)fetch.
321
+ /** @type {string[]} */
322
+ const deps = [];
323
+ for (const dep of url.matchAll(/\{\s*([A-Za-z_$][\w$.]*)\s*\}/g)) {
324
+ validatePath(dep[1], ctx, FETCH_USE);
325
+ const headKey = dep[1].split(".")[0];
326
+ if (!deps.includes(headKey)) deps.push(headKey);
327
+ }
328
+
329
+ // Auto-declare the four lifecycle keys. `name` is declared via declareState
330
+ // (collision-checked); the derived keys are seeded directly.
331
+ const key = declareState(name, null, ctx);
332
+ /** @type {Record<string, unknown>} */
333
+ const seeds = { [key]: null };
334
+ for (const [suffix, seed] of [
335
+ ["_error", null],
336
+ ["_loading", false],
337
+ ["_empty", false]
338
+ ]) {
339
+ const k = `${key}${suffix}`;
340
+ if (!ctx.comp.state.has(k)) ctx.comp.state.set(k, seed);
341
+ seeds[k] = seed;
342
+ }
343
+
344
+ /** @param {string} n @param {string | null | false | undefined} v */
345
+ const attr = (n, v) =>
346
+ v != null && v !== false && v !== "" ? ` data-wd-fetch-${n}="${escapeHtml(v)}"` : "";
347
+ const marker =
348
+ `<span data-wd-fetch data-wd-fetch-key="${key}" data-wd-fetch-url="${escapeHtml(url)}"` +
349
+ attr("method", opts.method && opts.method.toUpperCase()) +
350
+ attr("when", opts.when === "visible" ? "visible" : "") +
351
+ attr("timeout", opts.timeout) +
352
+ attr("retry", opts.retry) +
353
+ attr("headers", opts.headers && resolveStateKey(opts.headers, ctx)) +
354
+ attr("body", opts.body && resolveStateKey(opts.body, ctx)) +
355
+ attr("refresh", opts.refresh) +
356
+ attr("deps", deps.join(",")) +
357
+ `></span>`;
358
+ return `<script type="application/json" data-wd-state>${safeScriptJson(seeds)}</script>${marker}`;
359
+ }
360
+
361
+ /**
362
+ * Validate a `:fetch` (or `refresh=`) URL's scheme at compile time. Mirrors the
363
+ * `:try` href guard: relative paths (`/`, `./`, `../`, bare), an `http(s)://`
364
+ * URL, or a leading `{ state }` interpolation are allowed; a protocol-relative
365
+ * `//host` or any non-http(s) scheme (`file:`, `data:`, `javascript:`, …) is
366
+ * rejected. Interpolated values are percent-encoded by the runtime, so a scheme
367
+ * cannot be injected through state at request time.
368
+ * @param {string} url
369
+ * @param {Ctx} ctx
370
+ * @param {string} [what] Option name for the error message.
371
+ * @returns {string}
372
+ */
373
+ function validateFetchUrl(url, ctx, what = ":fetch") {
374
+ const value = url.trim();
375
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: intentional — rejects control characters in URLs/hrefs.
376
+ if (value !== url || value === "" || /[\u0000-\u001F\u007F]/.test(value)) {
377
+ throw new Error(
378
+ `Unsafe ${what} URL "${escapeHtml(url)}" in ${ctx.file}. Use a relative path (/, ./, ../), an http(s):// URL, or a { state } interpolation.`
379
+ );
380
+ }
381
+ if (value.startsWith("//")) {
382
+ throw new Error(
383
+ `Unsafe ${what} URL "${escapeHtml(url)}" in ${ctx.file}. Protocol-relative URLs are not allowed; use http:// or https:// explicitly.`
384
+ );
385
+ }
386
+ if (value.startsWith("{")) return value; // interpolation-first; the runtime percent-encodes state values
387
+ const scheme = value.match(/^([A-Za-z][A-Za-z0-9+.-]*):/);
388
+ if (scheme && !["http", "https"].includes(scheme[1].toLowerCase())) {
389
+ throw new Error(
390
+ `Unsafe ${what} URL "${escapeHtml(url)}" in ${ctx.file}. The "${scheme[1]}:" scheme is not allowed; use http://, https://, or a relative path.`
391
+ );
392
+ }
393
+ return value;
394
+ }
395
+
396
+ /**
397
+ * @param {string} line
398
+ * @param {Ctx} ctx
399
+ * @param {number} index 0-based line index for `file:line` errors.
400
+ * @returns {string}
401
+ */
402
+ export function handleComputed(line, ctx, index) {
403
+ const match = line.match(/^:computed\s+([A-Za-z_$][\w$]*)\s*=\s*(.+)$/);
404
+ if (!match)
405
+ throw new Error(
406
+ `Malformed :computed in ${at(ctx.file, index)}: ${line}. Use: :computed total = items.length * 4`
407
+ );
408
+ const expr = compileComputedExpr(match[2].trim(), ctx);
409
+ /** @type {unknown} */
410
+ let initial;
411
+ try {
412
+ /** @param {string} key @param {string} [path] */
413
+ const read = (key, path) => getPath(ctx.comp.state.get(key), path ? path.split(".") : []);
414
+ initial = new Function("S", `return (${expr});`)(read);
415
+ } catch {
416
+ console.warn(
417
+ `:computed "${match[2].trim()}" in ${ctx.file} could not be evaluated at build time; falling back to null. Check the expression.`
418
+ );
419
+ initial = null;
420
+ }
421
+ const key = declareState(match[1], initial ?? null, ctx);
422
+ return `<span data-wd-computed data-wd-computed-key="${key}" data-wd-computed-expr="${escapeHtml(expr)}"></span><script type="application/json" data-wd-state>${safeScriptJson({ [key]: initial ?? null })}</script>`;
423
+ }
424
+
425
+ /**
426
+ * @param {string} line
427
+ * @param {string[]} bodyLines
428
+ * @param {Ctx} ctx
429
+ * @param {number} index 0-based line index for `file:line` errors.
430
+ * @returns {string}
431
+ */
432
+ export function handleForm(line, bodyLines, ctx, index) {
433
+ const rest = line.slice(":form".length).trim();
434
+ const rawAction = rest.match(/action="([^"]+)"/)?.[1];
435
+ const method = rest.match(/method="([^"]+)"/)?.[1] || "post";
436
+ const into = rest.match(/(?:^|\s)into\s+([A-Za-z_$][\w$]*)/)?.[1];
437
+ const leftover = rest
438
+ .replace(/action="[^"]+"/, "")
439
+ .replace(/method="[^"]+"/, "")
440
+ .replace(/(?:^|\s)into\s+[A-Za-z_$][\w$]*/, "")
441
+ .trim();
442
+ if ((!rawAction && !into) || leftover) {
443
+ throw new Error(
444
+ `Malformed :form in ${at(ctx.file, index)}: ${line}. Use ':form into name' (client state), ':form action="/url"' (native post), or both (fetch round-trip into state).`
445
+ );
446
+ }
447
+ const action = rawAction ? validateFetchUrl(rawAction, ctx, ":form action") : undefined;
448
+ const inner = compileBody(bodyLines, ctx).trim();
449
+ if (!into) {
450
+ return `<form action="${escapeHtml(action)}" method="${escapeHtml(method)}">${inner}</form>`;
451
+ }
452
+ const key = declareState(into, null, ctx);
453
+ declareErrorState(key, ctx);
454
+ const actionAttrs = action
455
+ ? ` action="${escapeHtml(action)}" method="${escapeHtml(method)}"`
456
+ : "";
457
+ return `<script type="application/json" data-wd-state>${safeScriptJson({ [key]: null })}</script><form data-wd-form="${key}"${actionAttrs}>${inner}</form>`;
458
+ }
459
+
460
+ /**
461
+ * @param {string} line
462
+ * @param {Ctx} ctx
463
+ * @param {number} index 0-based line index for `file:line` errors.
464
+ * @returns {string}
465
+ */
466
+ export function handleInput(line, ctx, index) {
467
+ const match = line.match(/^:input\s+([A-Za-z_][\w-]*)\s*(.*)$/);
468
+ if (!match) throw new Error(`Malformed :input in ${at(ctx.file, index)}: ${line}`);
469
+ const attrs = [`name="${escapeHtml(match[1])}"`];
470
+ let type = "text";
471
+ let placeholder;
472
+ let hasAria = false;
473
+ const re = /([A-Za-z-]+)=("[^"]*"|\S+)|([A-Za-z-]+)/g;
474
+ for (const token of (match[2] || "").matchAll(re)) {
475
+ if (token[3]) {
476
+ if (!["required", "autofocus", "disabled", "readonly"].includes(token[3])) {
477
+ throw new Error(`Unknown :input flag "${token[3]}" in ${at(ctx.file, index)}`);
478
+ }
479
+ attrs.push(token[3]);
480
+ continue;
481
+ }
482
+ const value = stripQuotes(token[2]);
483
+ if (token[1] === "type") {
484
+ type = value;
485
+ continue;
486
+ }
487
+ if (
488
+ ![
489
+ "placeholder",
490
+ "value",
491
+ "min",
492
+ "max",
493
+ "step",
494
+ "pattern",
495
+ "autocomplete",
496
+ "aria-label",
497
+ "aria-describedby"
498
+ ].includes(token[1])
499
+ ) {
500
+ throw new Error(`Unknown :input attribute "${token[1]}" in ${at(ctx.file, index)}`);
501
+ }
502
+ if (token[1] === "placeholder") placeholder = value;
503
+ if (token[1] === "aria-label" || token[1] === "aria-describedby") hasAria = true;
504
+ attrs.push(`${token[1]}="${escapeHtml(value)}"`);
505
+ }
506
+ // Accessible name: if the author supplied neither aria-label nor aria-describedby,
507
+ // derive a non-visual aria-label from the placeholder, else from the field name.
508
+ // Never overrides an author-supplied aria attribute (zero layout impact).
509
+ if (!hasAria) {
510
+ attrs.push(`aria-label="${escapeHtml(placeholder || humanizeName(match[1]))}"`);
511
+ }
512
+ return `<input type="${escapeHtml(type)}" ${attrs.join(" ")}>`;
513
+ }
514
+
515
+ // :bind <state> [placeholder="…"] [type=…] — a live two-way input bound to a
516
+ // declared :state. Updates state on every keystroke; reflects state back when
517
+ // not focused. The state must be declared first (with :state).
518
+ /**
519
+ * @param {string} line
520
+ * @param {Ctx} ctx
521
+ * @param {number} index 0-based line index for `file:line` errors.
522
+ * @returns {string}
523
+ */
524
+ export function handleBind(line, ctx, index) {
525
+ const match = line.match(/^:bind\s+([A-Za-z_$][\w$]*)\s*(.*)$/);
526
+ if (!match)
527
+ throw new Error(
528
+ `Malformed :bind in ${at(ctx.file, index)}: ${line}. Use: :bind query placeholder="Search"`
529
+ );
530
+ const key = resolveStateKey(match[1], ctx);
531
+ if (!key) {
532
+ throw new Error(
533
+ `:bind ${match[1]} in ${ctx.file} has no matching state. Declare it first: :state ${match[1]} = ""`
534
+ );
535
+ }
536
+ ctx.comp.assets.runtime = true;
537
+ let type = "text";
538
+ let placeholder;
539
+ let hasAria = false;
540
+ const attrs = [];
541
+ const re = /([A-Za-z-]+)=("[^"]*"|\S+)|([A-Za-z-]+)/g;
542
+ for (const token of (match[2] || "").matchAll(re)) {
543
+ if (token[3]) {
544
+ if (!["required", "autofocus"].includes(token[3]))
545
+ throw new Error(`Unknown :bind flag "${token[3]}" in ${at(ctx.file, index)}`);
546
+ attrs.push(token[3]);
547
+ continue;
548
+ }
549
+ const value = stripQuotes(token[2]);
550
+ if (token[1] === "type") {
551
+ type = value;
552
+ continue;
553
+ }
554
+ if (!["placeholder", "autocomplete", "aria-label", "aria-describedby"].includes(token[1])) {
555
+ throw new Error(`Unknown :bind attribute "${token[1]}" in ${at(ctx.file, index)}`);
556
+ }
557
+ if (token[1] === "placeholder") placeholder = value;
558
+ if (token[1] === "aria-label" || token[1] === "aria-describedby") hasAria = true;
559
+ attrs.push(`${token[1]}="${escapeHtml(value)}"`);
560
+ }
561
+ // Accessible name (see handleInput): default a non-visual aria-label from the
562
+ // placeholder, else a humanized version of the bound state key. The author's own
563
+ // aria-label/aria-describedby always wins.
564
+ if (!hasAria) {
565
+ attrs.push(`aria-label="${escapeHtml(placeholder || humanizeName(match[1]))}"`);
566
+ }
567
+ const initial = ctx.comp.state.get(key);
568
+ const valueAttr =
569
+ initial === undefined || initial === null ? "" : ` value="${escapeHtml(String(initial))}"`;
570
+ return `<input type="${escapeHtml(type)}" data-wd-bind-input="${key}"${valueAttr} ${attrs.join(" ")}>`;
571
+ }
572
+
573
+ /**
574
+ * @param {string} line
575
+ * @param {Ctx} ctx
576
+ * @param {number} index 0-based line index for `file:line` errors.
577
+ * @returns {string}
578
+ */
579
+ export function handleSubmit(line, ctx, index) {
580
+ const match = line.match(/^:submit\s+"([^"]+)"\s*$/);
581
+ if (!match)
582
+ throw new Error(`Malformed :submit in ${at(ctx.file, index)}: ${line}. Use: :submit "Label"`);
583
+ return `<button type="submit">${escapeHtml(match[1])}</button>`;
584
+ }
585
+
586
+ /**
587
+ * `:textarea name [placeholder="…"] [rows=N] [required]` → a `<textarea>`. Like
588
+ * `:input`, it derives a non-visual aria-label from the placeholder (else the
589
+ * humanized name) when the author supplies none. Captured by the runtime's
590
+ * FormData exactly like `:input` — no runtime change needed.
591
+ * @param {string} line
592
+ * @param {Ctx} ctx
593
+ * @param {number} index 0-based line index for `file:line` errors.
594
+ * @returns {string}
595
+ */
596
+ export function handleTextarea(line, ctx, index) {
597
+ const match = line.match(/^:textarea\s+([A-Za-z_][\w-]*)\s*(.*)$/);
598
+ if (!match)
599
+ throw new Error(
600
+ `Malformed :textarea in ${at(ctx.file, index)}: ${line}. Use: :textarea name [placeholder="…"] [rows=N] [required]`
601
+ );
602
+ const attrs = [`name="${escapeHtml(match[1])}"`];
603
+ let placeholder;
604
+ let hasAria = false;
605
+ const re = /([A-Za-z-]+)=("[^"]*"|\S+)|([A-Za-z-]+)/g;
606
+ for (const token of (match[2] || "").matchAll(re)) {
607
+ if (token[3]) {
608
+ if (!["required", "autofocus", "disabled", "readonly"].includes(token[3])) {
609
+ throw new Error(`Unknown :textarea flag "${token[3]}" in ${at(ctx.file, index)}`);
610
+ }
611
+ attrs.push(token[3]);
612
+ continue;
613
+ }
614
+ const value = stripQuotes(token[2]);
615
+ if (
616
+ ![
617
+ "placeholder",
618
+ "rows",
619
+ "cols",
620
+ "minlength",
621
+ "maxlength",
622
+ "autocomplete",
623
+ "aria-label",
624
+ "aria-describedby"
625
+ ].includes(token[1])
626
+ ) {
627
+ throw new Error(`Unknown :textarea attribute "${token[1]}" in ${at(ctx.file, index)}`);
628
+ }
629
+ if (token[1] === "placeholder") placeholder = value;
630
+ if (token[1] === "aria-label" || token[1] === "aria-describedby") hasAria = true;
631
+ attrs.push(`${token[1]}="${escapeHtml(value)}"`);
632
+ }
633
+ if (!hasAria) {
634
+ attrs.push(`aria-label="${escapeHtml(placeholder || humanizeName(match[1]))}"`);
635
+ }
636
+ return `<textarea ${attrs.join(" ")}></textarea>`;
637
+ }
638
+
639
+ /**
640
+ * `:select name [required]` followed by `- Label` list lines → a `<select>` with
641
+ * one `<option>` per label (value === label). Derives an aria-label from the
642
+ * humanized name when none is given. Captured by FormData like the other fields.
643
+ * @param {string} line
644
+ * @param {string[]} optionLines The following `- Label` lines consumed by dispatch.
645
+ * @param {Ctx} ctx
646
+ * @param {number} index 0-based line index for `file:line` errors.
647
+ * @returns {string}
648
+ */
649
+ export function handleSelect(line, optionLines, ctx, index) {
650
+ const match = line.match(/^:select\s+([A-Za-z_][\w-]*)\s*(.*)$/);
651
+ if (!match)
652
+ throw new Error(
653
+ `Malformed :select in ${at(ctx.file, index)}: ${line}. Use: :select name [required] then "- Label" lines`
654
+ );
655
+ const attrs = [`name="${escapeHtml(match[1])}"`];
656
+ let hasAria = false;
657
+ const re = /([A-Za-z-]+)=("[^"]*"|\S+)|([A-Za-z-]+)/g;
658
+ for (const token of (match[2] || "").matchAll(re)) {
659
+ if (token[3]) {
660
+ if (!["required", "disabled", "autofocus"].includes(token[3])) {
661
+ throw new Error(`Unknown :select flag "${token[3]}" in ${at(ctx.file, index)}`);
662
+ }
663
+ attrs.push(token[3]);
664
+ continue;
665
+ }
666
+ const value = stripQuotes(token[2]);
667
+ if (!["autocomplete", "aria-label", "aria-describedby"].includes(token[1])) {
668
+ throw new Error(`Unknown :select attribute "${token[1]}" in ${at(ctx.file, index)}`);
669
+ }
670
+ if (token[1] === "aria-label" || token[1] === "aria-describedby") hasAria = true;
671
+ attrs.push(`${token[1]}="${escapeHtml(value)}"`);
672
+ }
673
+ if (!hasAria) {
674
+ attrs.push(`aria-label="${escapeHtml(humanizeName(match[1]))}"`);
675
+ }
676
+ const options = optionLines.map((l) => l.replace(/^\s*-\s+/, "").trim()).filter(Boolean);
677
+ if (!options.length) {
678
+ throw new Error(
679
+ `:select "${match[1]}" in ${at(ctx.file, index)} has no options. Add "- Label" lines beneath it.`
680
+ );
681
+ }
682
+ const opts = options
683
+ .map((o) => `<option value="${escapeHtml(o)}">${escapeHtml(o)}</option>`)
684
+ .join("");
685
+ return `<select ${attrs.join(" ")}>${opts}</select>`;
686
+ }
687
+
688
+ /**
689
+ * `:checkbox name [required]` / `:radio name [required]` followed by `- Label`
690
+ * lines → a labelled group of `<input type=checkbox|radio>`, each sharing `name`
691
+ * with value === label and wrapped in its own `<label>`. The group is a
692
+ * `role="group"` / `role="radiogroup"` container with an aria-label (explicit or
693
+ * humanized from the name). Checkbox groups are marked `data-wd-multi="name"` so
694
+ * the runtime captures every checked value as an array (`FormData.getAll`); radio
695
+ * groups capture a single value like `:input`. Flags: `required` (radio → the
696
+ * group; not emitted on checkboxes, where "at least one" has no native HTML form),
697
+ * `disabled` (whole group), `autofocus` (first control).
698
+ * @param {string} line
699
+ * @param {string[]} optionLines The following `- Label` lines consumed by dispatch.
700
+ * @param {Ctx} ctx
701
+ * @param {"checkbox" | "radio"} kind
702
+ * @param {number} index 0-based line index for `file:line` errors.
703
+ * @returns {string}
704
+ */
705
+ export function handleChoiceGroup(line, optionLines, ctx, kind, index) {
706
+ const directive = `:${kind}`;
707
+ const match = line.match(
708
+ kind === "checkbox"
709
+ ? /^:checkbox\s+([A-Za-z_][\w-]*)\s*(.*)$/
710
+ : /^:radio\s+([A-Za-z_][\w-]*)\s*(.*)$/
711
+ );
712
+ if (!match)
713
+ throw new Error(
714
+ `Malformed ${directive} in ${at(ctx.file, index)}: ${line}. Use: ${directive} name [required] then "- Label" lines`
715
+ );
716
+ const name = match[1];
717
+ const flags = [];
718
+ let ariaLabel = null;
719
+ let ariaDescribedby = null;
720
+ const re = /([A-Za-z-]+)=("[^"]*"|\S+)|([A-Za-z-]+)/g;
721
+ for (const token of (match[2] || "").matchAll(re)) {
722
+ if (token[3]) {
723
+ if (!["required", "disabled", "autofocus"].includes(token[3])) {
724
+ throw new Error(`Unknown ${directive} flag "${token[3]}" in ${at(ctx.file, index)}`);
725
+ }
726
+ flags.push(token[3]);
727
+ continue;
728
+ }
729
+ const value = stripQuotes(token[2]);
730
+ if (token[1] === "aria-label") ariaLabel = value;
731
+ else if (token[1] === "aria-describedby") ariaDescribedby = value;
732
+ else throw new Error(`Unknown ${directive} attribute "${token[1]}" in ${at(ctx.file, index)}`);
733
+ }
734
+ const options = optionLines.map((l) => l.replace(/^\s*-\s+/, "").trim()).filter(Boolean);
735
+ if (!options.length) {
736
+ throw new Error(
737
+ `${directive} "${name}" in ${at(ctx.file, index)} has no options. Add "- Label" lines beneath it.`
738
+ );
739
+ }
740
+ const isCheckbox = kind === "checkbox";
741
+ const groupAttrs = [
742
+ `class="wd-${isCheckbox ? "checkboxes" : "radios"}"`,
743
+ `role="${isCheckbox ? "group" : "radiogroup"}"`
744
+ ];
745
+ if (isCheckbox) groupAttrs.push(`data-wd-multi="${escapeHtml(name)}"`);
746
+ groupAttrs.push(`aria-label="${escapeHtml(ariaLabel || humanizeName(name))}"`);
747
+ if (ariaDescribedby) groupAttrs.push(`aria-describedby="${escapeHtml(ariaDescribedby)}"`);
748
+ const disabled = flags.includes("disabled");
749
+ const required = flags.includes("required");
750
+ const autofocus = flags.includes("autofocus");
751
+ const controls = options
752
+ .map((opt, idx) => {
753
+ const a = [`type="${kind}"`, `name="${escapeHtml(name)}"`, `value="${escapeHtml(opt)}"`];
754
+ if (disabled) a.push("disabled");
755
+ if (required && !isCheckbox) a.push("required");
756
+ if (autofocus && idx === 0) a.push("autofocus");
757
+ return `<label><input ${a.join(" ")}> ${escapeHtml(opt)}</label>`;
758
+ })
759
+ .join("");
760
+ return `<div ${groupAttrs.join(" ")}>${controls}</div>`;
761
+ }
762
+
763
+ /**
764
+ * @param {string} line
765
+ * @param {Ctx} ctx
766
+ * @param {number} index 0-based line index for `file:line` errors.
767
+ * @returns {string}
768
+ */
769
+ export function handleButton(line, ctx, index) {
770
+ const match = line.match(/^:button\s+"([^"]+)"\s*->\s*(.+)$/);
771
+ if (!match) throw new Error(`Malformed :button in ${at(ctx.file, index)}: ${line}`);
772
+ ctx.comp.assets.runtime = true;
773
+ const action = parseAction(match[2], ctx);
774
+ if (Array.isArray(action)) {
775
+ return `<button type="button" data-wd-actions="${escapeHtml(JSON.stringify(action))}">${escapeHtml(match[1])}</button>`;
776
+ }
777
+ const valueAttr =
778
+ action.value === undefined
779
+ ? ""
780
+ : ` data-wd-value="${escapeHtml(JSON.stringify(action.value))}"`;
781
+ return `<button type="button" data-wd-action="${action.op}" data-wd-target="${action.target}"${valueAttr}>${escapeHtml(match[1])}</button>`;
782
+ }
783
+
784
+ const EFFECT_USE =
785
+ "Use: :effect watchedState -> action[; action…] (actions use the :button vocabulary).";
786
+
787
+ /**
788
+ * Parse `:effect <watched> -> <actions>` into a zero-output marker the runtime
789
+ * watches: when `<watched>` state changes, it runs `<actions>` (the same `:button`
790
+ * action vocabulary, `;`-chained). For arbitrary side effects beyond `:computed`
791
+ * (derive state) and fetch deps (auto-refetch).
792
+ * @param {string} line
793
+ * @param {Ctx} ctx
794
+ * @param {number} index 0-based line index for `file:line` errors.
795
+ * @returns {string}
796
+ */
797
+ export function handleEffect(line, ctx, index) {
798
+ const match = line.match(/^:effect\s+([A-Za-z_$][\w$.]*)\s*->\s*(.+)$/);
799
+ if (!match)
800
+ throw new Error(`Malformed :effect in ${at(ctx.file, index)}: ${line}. ${EFFECT_USE}`);
801
+ const segs = validatePath(match[1], ctx, EFFECT_USE);
802
+ const key = resolveStateKey(segs[0], ctx);
803
+ if (!key)
804
+ throw new Error(
805
+ `:effect watches unknown state "${segs[0]}" in ${ctx.file}. Declare it first with :state ${segs[0]} = ...`
806
+ );
807
+ ctx.comp.assets.runtime = true;
808
+ const watch = [key, ...segs.slice(1)].join(".");
809
+ const action = parseAction(match[2], ctx);
810
+ const actions = Array.isArray(action) ? action : [action];
811
+ return `<script type="application/json" data-wd-effect>${safeScriptJson({ watch, actions })}</script>`;
812
+ }
813
+
814
+ /**
815
+ * @param {string} line
816
+ * @param {string[]} truthyLines
817
+ * @param {string[]} falsyLines
818
+ * @param {Ctx} ctx
819
+ * @param {number} index 0-based line index for `file:line` errors.
820
+ * @returns {string}
821
+ */
822
+ export function handleIf(line, truthyLines, falsyLines, ctx, index) {
823
+ const condition = line.replace(/^:if\s+/, "").trim();
824
+ // Fast path: a bare truthy dotted path (`:if open`, `:if item.done`). Keeps the
825
+ // existing markup/behavior identical. Anything with operators (`>`, `==`, `and`,
826
+ // `not`, …) falls through to the predicate path below.
827
+ const match = condition.match(/^([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)$/);
828
+ if (match) {
829
+ const segs = match[1].split(".");
830
+ const head = segs[0];
831
+
832
+ // Per-row meta vars in :if — only valid inside a loop.
833
+ if (LOOP_META[head]) {
834
+ if (!ctx.loopMeta)
835
+ throw new Error(
836
+ `":if ${match[1]}" uses the loop meta variable "${head}" outside a @loop in ${ctx.file}. Use it inside a loop body.`
837
+ );
838
+ if (ctx.loopItem) {
839
+ const truthy = compileBody(truthyLines, ctx).trim();
840
+ const falsy = compileBody(falsyLines, ctx).trim();
841
+ return `<span data-wd-each-if data-wd-meta="${LOOP_META[head]}"><template data-wd-if-true>${truthy}</template><template data-wd-if-false>${falsy}</template><span data-wd-each-if-out></span></span>`;
842
+ }
843
+ // static: the meta boolean is in scope — fall through to the static branch below.
844
+ }
845
+
846
+ const staticValue = lookupVar(ctx.scope, head);
847
+ if (staticValue.found) {
848
+ const active = Boolean(getPath(staticValue.value, segs.slice(1)));
849
+ return compileBody(active ? truthyLines : falsyLines, ctx);
850
+ }
851
+
852
+ if (ctx.loopItem && head === ctx.loopItem) {
853
+ const truthy = compileBody(truthyLines, ctx).trim();
854
+ const falsy = compileBody(falsyLines, ctx).trim();
855
+ const rest = segs.slice(1).join(".");
856
+ const pathAttr = ` data-wd-path="${escapeHtml(rest)}"`;
857
+ return `<span data-wd-each-if${pathAttr}><template data-wd-if-true>${truthy}</template><template data-wd-if-false>${falsy}</template><span data-wd-each-if-out></span></span>`;
858
+ }
859
+
860
+ const key = resolveStateKey(head, ctx);
861
+ if (!key) {
862
+ throw new Error(
863
+ `:if ${match[1]} in ${ctx.file} does not match a :state or in-scope value. Declare it first.`
864
+ );
865
+ }
866
+ ctx.comp.assets.runtime = true;
867
+ const truthy = compileBody(truthyLines, ctx).trim();
868
+ const falsy = compileBody(falsyLines, ctx).trim();
869
+ const restPath = segs.slice(1).join(".");
870
+ const pathAttr = restPath ? ` data-wd-path="${escapeHtml(restPath)}"` : "";
871
+ const initialTruthy = Boolean(getPath(ctx.comp.state.get(key), segs.slice(1)));
872
+ const active = initialTruthy ? truthy : falsy;
873
+ return `<div data-wd-if="${key}"${pathAttr} data-wd-if-active="${initialTruthy}"><template data-wd-true>${truthy}</template><template data-wd-false>${falsy}</template><div data-wd-if-out>${active}</div></div>`;
874
+ }
875
+
876
+ // Predicate path: a comparison / logical condition. Compiles through the same
877
+ // whitelist as `@loop … where` / `.class when` (with `not`), so it folds at
878
+ // build when static, drives a per-row each-if when it reads the loop item, and
879
+ // a global if-region (evaluated each render) when it reads state. No raw eval.
880
+ if (!condition)
881
+ throw new Error(
882
+ `Malformed :if in ${at(ctx.file, index)}: ${line}. Use ":if name" or ":if a <op> b [and|or|not …]".`
883
+ );
884
+ const compiled = compileWhen(condition, ctx, '":if"');
885
+ if (compiled.static) return compileBody(compiled.value ? truthyLines : falsyLines, ctx);
886
+ ctx.comp.assets.runtime = true;
887
+ const truthy = compileBody(truthyLines, ctx).trim();
888
+ const falsy = compileBody(falsyLines, ctx).trim();
889
+ const exprAttr = ` data-wd-if-expr="${escapeHtml(compiled.body)}"`;
890
+ if (compiled.item) {
891
+ return `<span data-wd-each-if${exprAttr}><template data-wd-if-true>${truthy}</template><template data-wd-if-false>${falsy}</template><span data-wd-each-if-out></span></span>`;
892
+ }
893
+ const initialTruthy = evalPredicate(compiled.body, undefined, ctx);
894
+ const active = initialTruthy ? truthy : falsy;
895
+ return `<div data-wd-if=""${exprAttr} data-wd-if-active="${initialTruthy}"><template data-wd-true>${truthy}</template><template data-wd-false>${falsy}</template><div data-wd-if-out>${active}</div></div>`;
896
+ }
897
+
898
+ /**
899
+ * Render the documentation-demo directives (`:try`, `:note`, `:sprint`).
900
+ * @param {string} line
901
+ * @param {Ctx} ctx
902
+ * @returns {string}
903
+ */
904
+ export function renderDemoDirective(line, ctx) {
905
+ const tryMatch = line.match(/^:try\s+"([^"]+)"\s+href="([^"]+)"$/);
906
+ if (tryMatch) {
907
+ const href = validateDemoHref(tryMatch[2], ctx);
908
+ return `<a class="try-card" href="${escapeHtml(href)}"><span>Try</span>${escapeHtml(tryMatch[1])}</a>`;
909
+ }
910
+ const note = line.match(/^:note\s+"([^"]+)"$/);
911
+ if (note) return `<aside class="note">${escapeHtml(note[1])}</aside>`;
912
+ const sprint = line.match(/^:sprint\s+min=(\d+)\s+max=(\d+)\s+roles="([^"]+)"$/);
913
+ if (sprint) {
914
+ const roles = sprint[3]
915
+ .split(",")
916
+ .map((role) => role.trim())
917
+ .filter(Boolean);
918
+ return `<section class="sprint-board" data-min="${sprint[1]}" data-max="${sprint[2]}">${roles.map((role) => `<article><strong>${escapeHtml(role)}</strong><span>active lane</span></article>`).join("")}</section>`;
919
+ }
920
+ return "";
921
+ }
922
+
923
+ /**
924
+ * Validate demo-card links without adding arbitrary URL passthrough.
925
+ * @param {string} href
926
+ * @param {Ctx} ctx
927
+ * @returns {string}
928
+ */
929
+ function validateDemoHref(href, ctx) {
930
+ const value = href.trim();
931
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: intentional — rejects control characters in URLs/hrefs.
932
+ if (value !== href || /[\u0000-\u001F\u007F]/.test(value)) {
933
+ throw new Error(
934
+ `Unsafe :try href "${escapeHtml(href)}" in ${ctx.file}. Use a relative URL starting with /, ./, ../, or #, or an http:, https:, or mailto: URL.`
935
+ );
936
+ }
937
+ if (value.startsWith("//")) {
938
+ throw new Error(
939
+ `Unsafe :try href "${escapeHtml(href)}" in ${ctx.file}. Protocol-relative URLs are not allowed; use http: or https: explicitly.`
940
+ );
941
+ }
942
+ if (
943
+ value.startsWith("/") ||
944
+ value.startsWith("./") ||
945
+ value.startsWith("../") ||
946
+ value.startsWith("#")
947
+ ) {
948
+ return value;
949
+ }
950
+ const scheme = value.match(/^([A-Za-z][A-Za-z0-9+.-]*):/);
951
+ if (scheme && ["http", "https", "mailto"].includes(scheme[1].toLowerCase())) {
952
+ return value;
953
+ }
954
+ throw new Error(
955
+ `Unsafe :try href "${escapeHtml(href)}" in ${ctx.file}. Use a relative URL starting with /, ./, ../, or #, or an http:, https:, or mailto: URL.`
956
+ );
957
+ }
958
+
959
+ // ---------------------------------------------------------------------------
960
+ // Actions
961
+ // ---------------------------------------------------------------------------
962
+
963
+ const ACTION_USE =
964
+ 'Use: name++, name--, n += k, n -= k, name = v, flag toggle, list append/prepend v, list toggle v, list remove v, x clear, obj merge other, obj delete key, name reset — chain with ";".';
965
+
966
+ /**
967
+ * Parse a `:button` action expression into a validated `{ op, target, value }`,
968
+ * or — when `;`-separated — an ordered array of them applied in sequence.
969
+ * @param {string} raw
970
+ * @param {Ctx} ctx
971
+ * @returns {Action | Action[]}
972
+ */
973
+ function parseAction(raw, ctx) {
974
+ const parts = raw
975
+ .split(";")
976
+ .map((p) => p.trim())
977
+ .filter(Boolean);
978
+ if (parts.length > 1) return parts.map((part) => parseSingleAction(part, raw, ctx));
979
+ return parseSingleAction(raw.trim(), raw, ctx);
980
+ }
981
+
982
+ /**
983
+ * Parse one (non-`;`) action expression into a validated `{ op, target, value }`.
984
+ * Targets may be dotted paths (`cart.count`); a bare name is a 1-segment path.
985
+ * @param {string} expression
986
+ * @param {string} raw The full original action source (for error context).
987
+ * @param {Ctx} ctx
988
+ * @returns {Action}
989
+ */
990
+ function parseSingleAction(expression, raw, ctx) {
991
+ const PATH = "[A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*)*";
992
+ /** @param {string} name @returns {string} */
993
+ const resolveTarget = (name) => {
994
+ const segs = validatePath(name, ctx, ACTION_USE);
995
+ const key = resolveStateKey(segs[0], ctx);
996
+ if (!key) {
997
+ throw new Error(
998
+ `Button action targets unknown state "${segs[0]}" in ${ctx.file}. Declare it first with :state ${segs[0]} = ...`
999
+ );
1000
+ }
1001
+ return [key, ...segs.slice(1)].join(".");
1002
+ };
1003
+
1004
+ const increment = expression.match(new RegExp(`^(${PATH})\\+\\+$`));
1005
+ if (increment) return { op: "inc", target: resolveTarget(increment[1]) };
1006
+ const decrement = expression.match(new RegExp(`^(${PATH})--$`));
1007
+ if (decrement) return { op: "dec", target: resolveTarget(decrement[1]) };
1008
+ const sub = expression.match(new RegExp(`^(${PATH})\\s*-=\\s*(.+)$`));
1009
+ if (sub)
1010
+ return { op: "sub", target: resolveTarget(sub[1]), value: parseActionLiteral(sub[2], ctx) };
1011
+ // Per-row: carry the current loop item into another list — `cart += product`.
1012
+ // Only inside a reactive @loop; the runtime resolves the row from the DOM.
1013
+ const add = expression.match(new RegExp(`^(${PATH})\\s*\\+=\\s*(.+)$`));
1014
+ if (add) {
1015
+ const rhs = add[2].trim();
1016
+ if (ctx.loopItem && rhs === ctx.loopItem) {
1017
+ const target = resolveTarget(add[1]);
1018
+ if (!Array.isArray(ctx.comp.state.get(target))) {
1019
+ throw new Error(
1020
+ `Button action "${raw}" needs ${add[1]} to be a :state list (declare it "${add[1]} = []") in ${ctx.file}.`
1021
+ );
1022
+ }
1023
+ return { op: "append-row", target };
1024
+ }
1025
+ const target = resolveTarget(add[1]);
1026
+ const value = parseActionLiteral(rhs, ctx);
1027
+ if (Array.isArray(ctx.comp.state.get(target))) return { op: "append", target, value };
1028
+ if (typeof value === "number") return { op: "add", target, value };
1029
+ throw new Error(
1030
+ `Unsupported button action "${raw}" in ${ctx.file}. += with non-number values requires a list state target — declare it "${add[1]} = []".`
1031
+ );
1032
+ }
1033
+ // `flag toggle` (no operand) → boolean flip; `list toggle v` → member-toggle.
1034
+ const toggle = expression.match(new RegExp(`^(${PATH})\\s+toggle(?:\\s+(.+))?$`));
1035
+ if (toggle) {
1036
+ const target = resolveTarget(toggle[1]);
1037
+ if (toggle[2] === undefined) return { op: "toggle", target };
1038
+ return { op: "member-toggle", target, value: parseActionLiteral(toggle[2], ctx) };
1039
+ }
1040
+ const prepend = expression.match(new RegExp(`^(${PATH})\\s+(?:append|prepend)\\s+(.+)$`));
1041
+ if (prepend) {
1042
+ const op = expression.includes(" prepend ") ? "prepend" : "append";
1043
+ return { op, target: resolveTarget(prepend[1]), value: parseActionLiteral(prepend[2], ctx) };
1044
+ }
1045
+ // Per-row: remove the current row from the list being looped — `todos remove todo`.
1046
+ // Disambiguation: operand IS the loop item name → `remove` (current row);
1047
+ // otherwise the operand is a value → `remove-value`.
1048
+ const remove = expression.match(new RegExp(`^(${PATH})\\s+remove\\s+(.+)$`));
1049
+ if (remove) {
1050
+ const operand = remove[2].trim();
1051
+ if (ctx.loopItem && operand === ctx.loopItem) {
1052
+ // A nested (item-relative) loop has a loop item but no top-level state key —
1053
+ // its source is a path off the outer row, which the runtime's row-remove
1054
+ // can't target. Fail loud with the honest workaround.
1055
+ if (!ctx.loopKey) {
1056
+ throw new Error(
1057
+ `Button action "${raw}" can't delete a row of a nested (item-relative) loop in ${ctx.file}. Per-row "remove" needs a top-level :state/:store list; carry the row into one (cart += ${ctx.loopItem}) and remove it there.`
1058
+ );
1059
+ }
1060
+ if (resolveStateKey(remove[1], ctx) !== ctx.loopKey) {
1061
+ throw new Error(
1062
+ `Button action "${raw}" must target the :state list being looped (@loop ${remove[1]} into ${ctx.loopItem}) in ${ctx.file}.`
1063
+ );
1064
+ }
1065
+ return { op: "remove", target: ctx.loopKey };
1066
+ }
1067
+ return {
1068
+ op: "remove-value",
1069
+ target: resolveTarget(remove[1]),
1070
+ value: parseActionLiteral(operand, ctx)
1071
+ };
1072
+ }
1073
+ const clear = expression.match(new RegExp(`^(${PATH})\\s+clear$`));
1074
+ if (clear) return { op: "clear", target: resolveTarget(clear[1]) };
1075
+ const merge = expression.match(new RegExp(`^(${PATH})\\s+merge\\s+(.+)$`));
1076
+ if (merge)
1077
+ return {
1078
+ op: "merge",
1079
+ target: resolveTarget(merge[1]),
1080
+ value: parseMergeOperand(merge[2], ctx)
1081
+ };
1082
+ const del = expression.match(new RegExp(`^(${PATH})\\s+delete\\s+(.+)$`));
1083
+ if (del)
1084
+ return { op: "delete", target: resolveTarget(del[1]), value: parseActionLiteral(del[2], ctx) };
1085
+ const reset = expression.match(new RegExp(`^(${PATH})\\s+reset$`));
1086
+ if (reset) return { op: "reset", target: resolveTarget(reset[1]) };
1087
+ // `name refetch` re-invokes the matching :fetch node. The target is the fetch
1088
+ // key (bare name); the runtime finds the [data-wd-fetch-key] node and re-runs.
1089
+ const refetch = expression.match(new RegExp(`^(${PATH})\\s+refetch$`));
1090
+ if (refetch) return { op: "refetch", target: resolveTarget(refetch[1]) };
1091
+ const assign = expression.match(new RegExp(`^(${PATH})\\s*=\\s*(.+)$`));
1092
+ if (assign)
1093
+ return {
1094
+ op: "set",
1095
+ target: resolveTarget(assign[1]),
1096
+ value: parseActionLiteral(assign[2], ctx)
1097
+ };
1098
+ throw new Error(`Unsupported button action "${raw}" in ${ctx.file}. ${ACTION_USE}`);
1099
+ }
1100
+
1101
+ /**
1102
+ * `merge` operand: either an inline JSON object literal, or a state/store key
1103
+ * name (emitted as a string the runtime resolves via getPath).
1104
+ * @param {string} raw
1105
+ * @param {Ctx} ctx
1106
+ * @returns {unknown}
1107
+ */
1108
+ function parseMergeOperand(raw, ctx) {
1109
+ const value = raw.trim();
1110
+ if (/^[A-Za-z_$][\w$]*$/.test(value)) {
1111
+ const key = resolveStateKey(value, ctx);
1112
+ if (!key)
1113
+ throw new Error(
1114
+ `Button action merge targets unknown state "${value}" in ${ctx.file}. Declare it first with :state ${value} = ...`
1115
+ );
1116
+ return key;
1117
+ }
1118
+ const parsed = parseActionLiteral(value, ctx);
1119
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
1120
+ throw new Error(
1121
+ `Unsupported merge operand "${raw}" in ${ctx.file}. Use: obj merge other (a state key or an inline {…} object).`
1122
+ );
1123
+ }
1124
+
1125
+ /**
1126
+ * @param {string} raw
1127
+ * @param {Ctx} ctx
1128
+ * @returns {unknown}
1129
+ */
1130
+ function parseActionLiteral(raw, ctx) {
1131
+ const value = raw.trim();
1132
+ if (/^["'].*["']$/.test(value)) return stripQuotes(value);
1133
+ if (value === "true") return true;
1134
+ if (value === "false") return false;
1135
+ if (value === "null") return null;
1136
+ if (/^-?\d+(?:\.\d+)?$/.test(value)) return Number(value);
1137
+ if (/^[[{]/.test(value)) {
1138
+ try {
1139
+ return JSON.parse(value);
1140
+ } catch {
1141
+ throw new Error(
1142
+ `Unsupported action literal "${raw}" in ${ctx.file}. Use: a quoted string, number, boolean, null, or valid JSON.`
1143
+ );
1144
+ }
1145
+ }
1146
+ throw new Error(
1147
+ `Unsupported action literal "${raw}" in ${ctx.file}. Use: a quoted string, number, boolean, null, or valid JSON.`
1148
+ );
1149
+ }