aktion-runtime 0.5.7 → 0.5.8

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.
package/dist/testing.js CHANGED
@@ -2188,6 +2188,839 @@ function isCompiledProgram(value) {
2188
2188
  const candidate = value;
2189
2189
  return candidate.__aktionCompiled === COMPILED_PROGRAM_VERSION && typeof candidate.source === "string" && typeof candidate.path === "string" && !!candidate.program && Array.isArray(candidate.program.statements);
2190
2190
  }
2191
+ function defineCompiledProgram(compiled) {
2192
+ return compiled;
2193
+ }
2194
+ const INDENT = " ";
2195
+ const SAFE_IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
2196
+ const NEEDS_DOUBLE_QUOTE = /[\\"]/;
2197
+ function printProgram(program) {
2198
+ const lines = [];
2199
+ let prev = null;
2200
+ for (const stmt of program.statements) {
2201
+ if (prev && needsBlankLineBetween(prev, stmt)) lines.push("");
2202
+ lines.push(printStatement(stmt, 0));
2203
+ prev = stmt;
2204
+ }
2205
+ return lines.join("\n") + "\n";
2206
+ }
2207
+ function needsBlankLineBetween(prev, next) {
2208
+ const heavy = /* @__PURE__ */ new Set([
2209
+ "ComponentDeclaration",
2210
+ "EffectDeclaration",
2211
+ "ActionDeclaration",
2212
+ "HookDeclaration"
2213
+ ]);
2214
+ if (heavy.has(prev.kind) || heavy.has(next.kind)) return true;
2215
+ return false;
2216
+ }
2217
+ function printStatement(stmt, indent) {
2218
+ const pad = INDENT.repeat(indent);
2219
+ const exp = "exported" in stmt && stmt.exported ? "export " : "";
2220
+ switch (stmt.kind) {
2221
+ case "Import": {
2222
+ const specs = stmt.specifiers.map((s) => {
2223
+ const imported = s.isState ? `$${s.imported}` : s.imported;
2224
+ if (s.local === s.imported) return imported;
2225
+ const local2 = s.isState ? `$${s.local}` : s.local;
2226
+ return `${imported} as ${local2}`;
2227
+ }).join(", ");
2228
+ return `${pad}import { ${specs} } from "${stmt.source}"`;
2229
+ }
2230
+ case "Assignment": {
2231
+ const lhs = stmt.isState ? `$${stmt.identifier}` : stmt.identifier;
2232
+ const expr = printExpression(stmt.expression, indent);
2233
+ return `${pad}${exp}${lhs} = ${expr}`;
2234
+ }
2235
+ case "ComponentDeclaration": {
2236
+ const params = stmt.params.map(printDeclParam).join(", ");
2237
+ const head = `${pad}${exp}function ${stmt.name}(${params}) {`;
2238
+ const body = printBlock(stmt.body.body, indent + 1);
2239
+ return body.length > 0 ? `${head}
2240
+ ${body}
2241
+ ${pad}}` : `${head}
2242
+ ${pad}}`;
2243
+ }
2244
+ case "EffectDeclaration": {
2245
+ const deps = stmt.triggers.map(printTrigger).filter((s) => s.length > 0);
2246
+ if (stmt.rateLimit) {
2247
+ deps.push(`"${stmt.rateLimit.kind}(${stmt.rateLimit.ms})"`);
2248
+ }
2249
+ const body = printBlock(stmt.body.body, indent + 1);
2250
+ const depsArray = `[${deps.join(", ")}]`;
2251
+ return `${pad}$effect(() => {
2252
+ ${body}
2253
+ ${pad}}, ${depsArray})`;
2254
+ }
2255
+ case "ActionDeclaration": {
2256
+ const params = stmt.params.map(printDeclParam).join(", ");
2257
+ const head = `${pad}${exp}function ${stmt.name}(${params}) {`;
2258
+ const body = printBlock(stmt.body.body, indent + 1);
2259
+ return `${head}
2260
+ ${body}
2261
+ ${pad}}`;
2262
+ }
2263
+ case "HookDeclaration": {
2264
+ const params = stmt.params.map(printDeclParam).join(", ");
2265
+ const head = `${pad}${exp}function $${stmt.name}(${params}) {`;
2266
+ const body = printBlock(stmt.body.body, indent + 1);
2267
+ return `${head}
2268
+ ${body}
2269
+ ${pad}}`;
2270
+ }
2271
+ case "Await": {
2272
+ return `${pad}await ${printExpression(stmt.argument, indent)}`;
2273
+ }
2274
+ case "Return": {
2275
+ return stmt.argument ? `${pad}return ${printExpression(stmt.argument, indent)}` : `${pad}return`;
2276
+ }
2277
+ case "ExpressionStatement": {
2278
+ return `${pad}${printExpression(stmt.expression, indent)}`;
2279
+ }
2280
+ case "IfStatement": {
2281
+ const test = printExpression(stmt.test, indent);
2282
+ const cons = `{
2283
+ ${printBlock(stmt.consequent.body, indent + 1)}
2284
+ ${pad}}`;
2285
+ if (!stmt.alternate) return `${pad}if (${test}) ${cons}`;
2286
+ const alt = stmt.alternate.kind === "IfStatement" ? printStatement(stmt.alternate, indent).trimStart() : `{
2287
+ ${printBlock(stmt.alternate.body, indent + 1)}
2288
+ ${pad}}`;
2289
+ return `${pad}if (${test}) ${cons} else ${alt}`;
2290
+ }
2291
+ case "SwitchStatement": {
2292
+ const disc = printExpression(stmt.discriminant, indent);
2293
+ const cases = stmt.cases.map((c) => printSwitchCase(c, indent + 1)).join("\n");
2294
+ return `${pad}switch (${disc}) {
2295
+ ${cases}
2296
+ ${pad}}`;
2297
+ }
2298
+ case "ForOfStatement": {
2299
+ const iter = printExpression(stmt.iterable, indent);
2300
+ const body = `{
2301
+ ${printBlock(stmt.body.body, indent + 1)}
2302
+ ${pad}}`;
2303
+ return `${pad}for (let ${stmt.item} of ${iter}) ${body}`;
2304
+ }
2305
+ case "ForClassicStatement": {
2306
+ const init = stmt.init ? printStatement(stmt.init, 0).trimStart() : "";
2307
+ const test = stmt.test ? printExpression(stmt.test, indent) : "";
2308
+ const update = stmt.update ? printExpression(stmt.update, indent) : "";
2309
+ const body = `{
2310
+ ${printBlock(stmt.body.body, indent + 1)}
2311
+ ${pad}}`;
2312
+ return `${pad}for (${init}; ${test}; ${update}) ${body}`;
2313
+ }
2314
+ case "WhileStatement": {
2315
+ const test = printExpression(stmt.test, indent);
2316
+ const body = `{
2317
+ ${printBlock(stmt.body.body, indent + 1)}
2318
+ ${pad}}`;
2319
+ return `${pad}while (${test}) ${body}`;
2320
+ }
2321
+ case "DoWhileStatement": {
2322
+ const test = printExpression(stmt.test, indent);
2323
+ const body = `{
2324
+ ${printBlock(stmt.body.body, indent + 1)}
2325
+ ${pad}}`;
2326
+ return `${pad}do ${body} while (${test})`;
2327
+ }
2328
+ case "ForInStatement": {
2329
+ const iter = printExpression(stmt.iterable, indent);
2330
+ const body = `{
2331
+ ${printBlock(stmt.body.body, indent + 1)}
2332
+ ${pad}}`;
2333
+ return `${pad}for (let ${stmt.item} in ${iter}) ${body}`;
2334
+ }
2335
+ case "DestructureStatement": {
2336
+ const open = stmt.patternKind === "array" ? "[" : "{";
2337
+ const close = stmt.patternKind === "array" ? "]" : "}";
2338
+ const parts = stmt.bindings.map((b) => {
2339
+ const lead = b.rest ? "..." : "";
2340
+ const keyed = b.sourceKey ? `${b.sourceKey}: ${b.name}` : b.name || "";
2341
+ const def = b.defaultValue ? ` = ${printExpression(b.defaultValue, indent)}` : "";
2342
+ return `${lead}${keyed}${def}`;
2343
+ });
2344
+ const expr = printExpression(stmt.expression, indent);
2345
+ return `${pad}let ${open}${parts.join(", ")}${close} = ${expr}`;
2346
+ }
2347
+ case "BreakStatement":
2348
+ return `${pad}break`;
2349
+ case "ContinueStatement":
2350
+ return `${pad}continue`;
2351
+ case "ThrowStatement":
2352
+ return `${pad}throw ${printExpression(stmt.argument, indent)}`;
2353
+ case "TryStatement": {
2354
+ const block = `{
2355
+ ${printBlock(stmt.block.body, indent + 1)}
2356
+ ${pad}}`;
2357
+ let out = `${pad}try ${block}`;
2358
+ if (stmt.catchBlock) {
2359
+ const catchHead = stmt.catchParam ? ` (${stmt.catchParam})` : "";
2360
+ const catchBody = `{
2361
+ ${printBlock(stmt.catchBlock.body, indent + 1)}
2362
+ ${pad}}`;
2363
+ out += ` catch${catchHead} ${catchBody}`;
2364
+ }
2365
+ if (stmt.finallyBlock) {
2366
+ const finBody = `{
2367
+ ${printBlock(stmt.finallyBlock.body, indent + 1)}
2368
+ ${pad}}`;
2369
+ out += ` finally ${finBody}`;
2370
+ }
2371
+ return out;
2372
+ }
2373
+ }
2374
+ }
2375
+ function printDeclParam(p) {
2376
+ if (p.defaultValue) {
2377
+ return `${p.name} = ${printExpression(p.defaultValue, 0)}`;
2378
+ }
2379
+ return p.name;
2380
+ }
2381
+ function printTrigger(t) {
2382
+ if (t.kind === "lifecycle") return `"${t.name}"`;
2383
+ if (t.kind === "every") return `"every(${t.intervalMs})"`;
2384
+ if (t.kind === "state") return `$${t.name}`;
2385
+ return "";
2386
+ }
2387
+ function printBlock(stmts, indent) {
2388
+ return stmts.map((s) => printStatement(s, indent)).join("\n");
2389
+ }
2390
+ function printExpression(expr, indent) {
2391
+ switch (expr.kind) {
2392
+ case "Literal":
2393
+ return printLiteral(expr.value);
2394
+ case "Identifier":
2395
+ return expr.name;
2396
+ case "StateRef":
2397
+ return `$${expr.name}`;
2398
+ case "Array": {
2399
+ if (expr.elements.length === 0) return "[]";
2400
+ const items = expr.elements.map((e) => printExpression(e, indent));
2401
+ const inline = `[${items.join(", ")}]`;
2402
+ if (inline.length <= 80 && !items.some((s) => s.includes("\n"))) return inline;
2403
+ const pad = INDENT.repeat(indent + 1);
2404
+ return `[
2405
+ ${items.map((s) => `${pad}${s}`).join(",\n")}
2406
+ ${INDENT.repeat(indent)}]`;
2407
+ }
2408
+ case "Object": {
2409
+ if (expr.properties.length === 0) return "{}";
2410
+ const items = expr.properties.map((p) => printObjectProp(p, indent));
2411
+ const inline = `{ ${items.join(", ")} }`;
2412
+ if (inline.length <= 80 && !items.some((s) => s.includes("\n"))) return inline;
2413
+ const pad = INDENT.repeat(indent + 1);
2414
+ return `{
2415
+ ${items.map((s) => `${pad}${s}`).join(",\n")}
2416
+ ${INDENT.repeat(indent)}}`;
2417
+ }
2418
+ case "Member": {
2419
+ const obj = printExpression(expr.object, indent);
2420
+ const dot = expr.optional ? "?." : ".";
2421
+ if (expr.property) return `${obj}${dot}${expr.property}`;
2422
+ if (expr.computed) {
2423
+ const inner = printExpression(expr.computed, indent);
2424
+ return expr.optional ? `${obj}?.[${inner}]` : `${obj}[${inner}]`;
2425
+ }
2426
+ return obj;
2427
+ }
2428
+ case "Unary":
2429
+ return `${expr.operator}${printExpression(expr.argument, indent)}`;
2430
+ case "Binary":
2431
+ return `${printExpression(expr.left, indent)} ${expr.operator} ${printExpression(expr.right, indent)}`;
2432
+ case "Ternary":
2433
+ return `${printExpression(expr.test, indent)} ? ${printExpression(expr.consequent, indent)} : ${printExpression(expr.alternate, indent)}`;
2434
+ case "Call":
2435
+ return printCall(expr.callee, expr.arguments, indent);
2436
+ case "MethodCall": {
2437
+ const target = printExpression(expr.object, indent);
2438
+ const sep = expr.optional ? "?." : ".";
2439
+ return printCall(`${target}${sep}${expr.method}`, expr.arguments, indent);
2440
+ }
2441
+ case "Invoke": {
2442
+ const callee = printExpression(expr.callee, indent);
2443
+ const sep = expr.optional ? "?." : "";
2444
+ return printCall(`${callee}${sep}`, expr.arguments, indent);
2445
+ }
2446
+ case "New": {
2447
+ const callee = printExpression(expr.callee, indent);
2448
+ return `new ${printCall(callee, expr.arguments, indent)}`;
2449
+ }
2450
+ case "BuiltinCall":
2451
+ return printCall(`@${expr.name}`, expr.arguments, indent);
2452
+ case "Template":
2453
+ return printTemplate(expr.quasis, expr.expressions, indent);
2454
+ case "Spread":
2455
+ return `...${printExpression(expr.argument, indent)}`;
2456
+ case "Lambda": {
2457
+ const params = expr.params.map((p) => {
2458
+ const prefix = p.rest ? "..." : "";
2459
+ return p.defaultValue ? `${prefix}${p.name} = ${printExpression(p.defaultValue, indent)}` : `${prefix}${p.name}`;
2460
+ }).join(", ");
2461
+ const head = expr.params.length === 1 && !expr.params[0].defaultValue && !expr.params[0].rest ? expr.params[0].name : `(${params})`;
2462
+ return `${head} => ${printExpression(expr.body, indent)}`;
2463
+ }
2464
+ case "Block":
2465
+ return `{
2466
+ ${printBlock(expr.body, indent + 1)}
2467
+ ${INDENT.repeat(indent)}}`;
2468
+ }
2469
+ }
2470
+ function printCall(callee, args, indent) {
2471
+ if (args.length === 0) return `${callee}()`;
2472
+ const parts = args.map((a) => printExpression(a, indent));
2473
+ const inline = `${callee}(${parts.join(", ")})`;
2474
+ if (inline.length <= 80 && !parts.some((s) => s.includes("\n"))) return inline;
2475
+ const pad = INDENT.repeat(indent + 1);
2476
+ return `${callee}(
2477
+ ${parts.map((s) => `${pad}${s}`).join(",\n")}
2478
+ ${INDENT.repeat(indent)})`;
2479
+ }
2480
+ function printSwitchCase(c, indent) {
2481
+ const pad = INDENT.repeat(indent);
2482
+ const body = c.body.map((s) => printStatement(s, indent + 1)).join("\n");
2483
+ if (c.test === null) {
2484
+ return `${pad}default:
2485
+ ${body}
2486
+ ${printStatement({ kind: "ExpressionStatement", expression: { kind: "Identifier", name: "break" } }, indent + 1)}`;
2487
+ }
2488
+ return `${pad}case ${printExpression(c.test, indent)}:
2489
+ ${body}
2490
+ ${INDENT.repeat(indent + 1)}break`;
2491
+ }
2492
+ function printObjectProp(prop, indent) {
2493
+ if (prop.spread) return `...${printExpression(prop.value, indent)}`;
2494
+ const value = printExpression(prop.value, indent);
2495
+ if (prop.value.kind === "Identifier" && prop.value.name === prop.key && SAFE_IDENT.test(prop.key)) {
2496
+ return prop.key;
2497
+ }
2498
+ const key = SAFE_IDENT.test(prop.key) ? prop.key : printStringLiteral(prop.key);
2499
+ return `${key}: ${value}`;
2500
+ }
2501
+ function printLiteral(value) {
2502
+ if (value === null) return "null";
2503
+ if (typeof value === "string") return printStringLiteral(value);
2504
+ if (typeof value === "boolean") return value ? "true" : "false";
2505
+ return String(value);
2506
+ }
2507
+ function printStringLiteral(value) {
2508
+ if (NEEDS_DOUBLE_QUOTE.test(value)) {
2509
+ const escaped = value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
2510
+ return `"${escaped}"`;
2511
+ }
2512
+ return `"${value}"`;
2513
+ }
2514
+ function printTemplate(quasis, expressions, indent) {
2515
+ const parts = [];
2516
+ for (let i = 0; i < quasis.length; i += 1) {
2517
+ parts.push(quasis[i] ?? "");
2518
+ if (i < expressions.length) {
2519
+ parts.push("${");
2520
+ parts.push(printExpression(expressions[i], indent));
2521
+ parts.push("}");
2522
+ }
2523
+ }
2524
+ return `\`${parts.join("")}\``;
2525
+ }
2526
+ function linkProgram(entrySource, entryPath, resolver) {
2527
+ const modules = /* @__PURE__ */ new Map();
2528
+ const order = [];
2529
+ const visiting = /* @__PURE__ */ new Set();
2530
+ const diagnostics = [];
2531
+ let nextId = 0;
2532
+ const fail = (path, line, column, message) => {
2533
+ diagnostics.push({
2534
+ line,
2535
+ column,
2536
+ message: path === entryPath ? message : `${path}: ${message}`,
2537
+ severity: "error"
2538
+ });
2539
+ };
2540
+ function load(path, sourceOverride) {
2541
+ const existing = modules.get(path);
2542
+ if (existing) return existing;
2543
+ if (visiting.has(path)) return void 0;
2544
+ visiting.add(path);
2545
+ let src;
2546
+ if (sourceOverride !== null) {
2547
+ src = sourceOverride;
2548
+ } else {
2549
+ try {
2550
+ src = resolver.load(path);
2551
+ } catch {
2552
+ visiting.delete(path);
2553
+ fail(entryPath, 0, 0, `Failed to load imported module "${path}".`);
2554
+ return void 0;
2555
+ }
2556
+ }
2557
+ const program = parse(src);
2558
+ const rec = {
2559
+ id: nextId++,
2560
+ path,
2561
+ program,
2562
+ edges: [],
2563
+ declaredPlain: /* @__PURE__ */ new Set(),
2564
+ declaredState: /* @__PURE__ */ new Set(),
2565
+ exportedPlain: /* @__PURE__ */ new Set(),
2566
+ exportedState: /* @__PURE__ */ new Set(),
2567
+ renamePlain: /* @__PURE__ */ new Map(),
2568
+ renameState: /* @__PURE__ */ new Map()
2569
+ };
2570
+ modules.set(path, rec);
2571
+ buildSymbolTable(rec);
2572
+ for (const stmt of program.statements) {
2573
+ if (stmt.kind !== "Import") continue;
2574
+ const resolved = resolver.resolve(stmt.source, path);
2575
+ rec.edges.push({ stmt, resolvedPath: resolved });
2576
+ if (resolved === null) {
2577
+ fail(path, stmt.loc?.line ?? 0, stmt.loc?.column ?? 0, `Cannot resolve import "${stmt.source}".`);
2578
+ continue;
2579
+ }
2580
+ load(resolved, null);
2581
+ }
2582
+ visiting.delete(path);
2583
+ order.push(path);
2584
+ return rec;
2585
+ }
2586
+ load(entryPath, entrySource);
2587
+ for (const rec of modules.values()) {
2588
+ if (rec.path === entryPath) continue;
2589
+ for (const name of rec.declaredPlain) rec.renamePlain.set(name, `__a${rec.id}_${name}`);
2590
+ for (const name of rec.declaredState) rec.renameState.set(name, `__a${rec.id}_${name}`);
2591
+ }
2592
+ for (const rec of modules.values()) {
2593
+ for (const { stmt, resolvedPath } of rec.edges) {
2594
+ if (resolvedPath === null) continue;
2595
+ const src = modules.get(resolvedPath);
2596
+ if (!src) continue;
2597
+ for (const spec of stmt.specifiers) {
2598
+ const line = stmt.loc?.line ?? 0;
2599
+ const column = stmt.loc?.column ?? 0;
2600
+ if (spec.isState) {
2601
+ if (!src.exportedState.has(spec.imported)) {
2602
+ fail(rec.path, line, column, `"${stmt.source}" does not export \`$${spec.imported}\`.`);
2603
+ continue;
2604
+ }
2605
+ rec.renameState.set(spec.local, src.renameState.get(spec.imported) ?? `__a${src.id}_${spec.imported}`);
2606
+ } else {
2607
+ if (!src.exportedPlain.has(spec.imported)) {
2608
+ fail(rec.path, line, column, `"${stmt.source}" does not export \`${spec.imported}\`.`);
2609
+ continue;
2610
+ }
2611
+ rec.renamePlain.set(spec.local, src.renamePlain.get(spec.imported) ?? `__a${src.id}_${spec.imported}`);
2612
+ }
2613
+ }
2614
+ }
2615
+ }
2616
+ const merged = [];
2617
+ for (const path of order) {
2618
+ const rec = modules.get(path);
2619
+ const renamer = makeRenamer(rec);
2620
+ for (const stmt of rec.program.statements) {
2621
+ if (stmt.kind === "Import") continue;
2622
+ renamer.renameTopLevel(stmt);
2623
+ stripExported(stmt);
2624
+ if (stmt.kind === "EffectDeclaration" && rec.path !== entryPath) {
2625
+ stmt.name = `__effect_a${rec.id}_${stmt.name.replace(/^__effect_/, "")}`;
2626
+ }
2627
+ merged.push(stmt);
2628
+ }
2629
+ }
2630
+ const entryRec = modules.get(entryPath);
2631
+ return {
2632
+ program: { statements: merged, errors: entryRec ? entryRec.program.errors : [] },
2633
+ diagnostics,
2634
+ dependencies: order.filter((p) => p !== entryPath)
2635
+ };
2636
+ }
2637
+ function buildSymbolTable(rec) {
2638
+ for (const stmt of rec.program.statements) {
2639
+ switch (stmt.kind) {
2640
+ case "Assignment":
2641
+ if (stmt.isState) {
2642
+ rec.declaredState.add(stmt.identifier);
2643
+ if (stmt.exported) rec.exportedState.add(stmt.identifier);
2644
+ } else {
2645
+ rec.declaredPlain.add(stmt.identifier);
2646
+ if (stmt.exported) rec.exportedPlain.add(stmt.identifier);
2647
+ }
2648
+ break;
2649
+ case "ComponentDeclaration":
2650
+ case "ActionDeclaration":
2651
+ rec.declaredPlain.add(stmt.name);
2652
+ if (stmt.exported) rec.exportedPlain.add(stmt.name);
2653
+ break;
2654
+ case "HookDeclaration":
2655
+ rec.declaredState.add(stmt.name);
2656
+ if (stmt.exported) rec.exportedState.add(stmt.name);
2657
+ break;
2658
+ case "DestructureStatement":
2659
+ for (const b of stmt.bindings) if (b.name) rec.declaredPlain.add(b.name);
2660
+ break;
2661
+ }
2662
+ }
2663
+ }
2664
+ function stripExported(stmt) {
2665
+ if (stmt.kind === "Assignment" || stmt.kind === "ComponentDeclaration" || stmt.kind === "ActionDeclaration" || stmt.kind === "HookDeclaration") {
2666
+ delete stmt.exported;
2667
+ }
2668
+ }
2669
+ function makeRenamer(rec) {
2670
+ const shadow = [];
2671
+ const shadowed = (name) => {
2672
+ for (const set of shadow) if (set.has(name)) return true;
2673
+ return false;
2674
+ };
2675
+ const rPlain = (name) => shadowed(name) ? name : rec.renamePlain.get(name) ?? name;
2676
+ const rState = (name) => rec.renameState.get(name) ?? name;
2677
+ const push = (names) => {
2678
+ shadow.push(new Set(names));
2679
+ };
2680
+ const pop = () => {
2681
+ shadow.pop();
2682
+ };
2683
+ const patternNames = (p) => p.bindings.map((b) => b.name).filter((n) => !!n);
2684
+ const paramNames = (params) => {
2685
+ const out = [];
2686
+ for (const p of params) {
2687
+ if (p.name) out.push(p.name);
2688
+ if (p.pattern) out.push(...patternNames(p.pattern));
2689
+ }
2690
+ return out;
2691
+ };
2692
+ const renameParamDefaults = (params) => {
2693
+ for (const p of params) if (p.defaultValue) renameExpr(p.defaultValue);
2694
+ };
2695
+ function renameExpr(expr) {
2696
+ switch (expr.kind) {
2697
+ case "Literal":
2698
+ return;
2699
+ case "Identifier":
2700
+ expr.name = rPlain(expr.name);
2701
+ return;
2702
+ case "StateRef":
2703
+ expr.name = rState(expr.name);
2704
+ return;
2705
+ case "Array":
2706
+ for (const el2 of expr.elements) renameExpr(el2);
2707
+ return;
2708
+ case "Object":
2709
+ for (const prop of expr.properties) {
2710
+ if (prop.computedKey) renameExpr(prop.computedKey);
2711
+ renameExpr(prop.value);
2712
+ }
2713
+ return;
2714
+ case "Member":
2715
+ renameExpr(expr.object);
2716
+ if (expr.computed) renameExpr(expr.computed);
2717
+ return;
2718
+ case "Unary":
2719
+ renameExpr(expr.argument);
2720
+ return;
2721
+ case "Binary":
2722
+ renameExpr(expr.left);
2723
+ renameExpr(expr.right);
2724
+ return;
2725
+ case "Ternary":
2726
+ renameExpr(expr.test);
2727
+ renameExpr(expr.consequent);
2728
+ renameExpr(expr.alternate);
2729
+ return;
2730
+ case "Call":
2731
+ expr.callee = rPlain(expr.callee);
2732
+ for (const a of expr.arguments) renameExpr(a);
2733
+ return;
2734
+ case "MethodCall":
2735
+ renameExpr(expr.object);
2736
+ for (const a of expr.arguments) renameExpr(a);
2737
+ return;
2738
+ case "Invoke":
2739
+ renameExpr(expr.callee);
2740
+ for (const a of expr.arguments) renameExpr(a);
2741
+ return;
2742
+ case "BuiltinCall":
2743
+ for (const a of expr.arguments) renameExpr(a);
2744
+ return;
2745
+ case "New":
2746
+ renameExpr(expr.callee);
2747
+ for (const a of expr.arguments) renameExpr(a);
2748
+ return;
2749
+ case "Template":
2750
+ for (const e of expr.expressions) renameExpr(e);
2751
+ return;
2752
+ case "Spread":
2753
+ renameExpr(expr.argument);
2754
+ return;
2755
+ case "Lambda":
2756
+ push(paramNames(expr.params));
2757
+ renameParamDefaults(expr.params);
2758
+ renameExpr(expr.body);
2759
+ pop();
2760
+ return;
2761
+ case "Block":
2762
+ renameBlock(expr);
2763
+ return;
2764
+ }
2765
+ }
2766
+ function renameBlock(block) {
2767
+ push([]);
2768
+ const scope = shadow[shadow.length - 1];
2769
+ for (const stmt of block.body) {
2770
+ renameStatement(stmt, false);
2771
+ addBlockLocals(stmt, scope);
2772
+ }
2773
+ pop();
2774
+ }
2775
+ function addBlockLocals(stmt, scope) {
2776
+ if (stmt.kind === "DestructureStatement") {
2777
+ for (const b of stmt.bindings) if (b.name) scope.add(b.name);
2778
+ } else if (stmt.kind === "ComponentDeclaration" || stmt.kind === "ActionDeclaration") {
2779
+ scope.add(stmt.name);
2780
+ }
2781
+ }
2782
+ function renameTopLevel(stmt) {
2783
+ if (stmt.kind === "DestructureStatement") {
2784
+ renameExpr(stmt.expression);
2785
+ for (const b of stmt.bindings) {
2786
+ if (b.defaultValue) renameExpr(b.defaultValue);
2787
+ b.name = rPlain(b.name);
2788
+ }
2789
+ return;
2790
+ }
2791
+ renameStatement(stmt, true);
2792
+ }
2793
+ function renameStatement(stmt, topLevel) {
2794
+ switch (stmt.kind) {
2795
+ case "Import":
2796
+ return;
2797
+ case "Assignment":
2798
+ stmt.identifier = stmt.isState ? rState(stmt.identifier) : rPlain(stmt.identifier);
2799
+ renameExpr(stmt.expression);
2800
+ return;
2801
+ case "ComponentDeclaration":
2802
+ case "ActionDeclaration":
2803
+ stmt.name = rPlain(stmt.name);
2804
+ push(paramNames(stmt.params));
2805
+ renameParamDefaults(stmt.params);
2806
+ renameBlock(stmt.body);
2807
+ pop();
2808
+ return;
2809
+ case "HookDeclaration":
2810
+ stmt.name = rState(stmt.name);
2811
+ push(paramNames(stmt.params));
2812
+ renameParamDefaults(stmt.params);
2813
+ renameBlock(stmt.body);
2814
+ pop();
2815
+ return;
2816
+ case "EffectDeclaration":
2817
+ for (const t of stmt.triggers) if (t.kind === "state") t.name = rState(t.name);
2818
+ renameBlock(stmt.body);
2819
+ return;
2820
+ case "Await":
2821
+ renameExpr(stmt.argument);
2822
+ return;
2823
+ case "Return":
2824
+ if (stmt.argument) renameExpr(stmt.argument);
2825
+ return;
2826
+ case "ExpressionStatement":
2827
+ renameExpr(stmt.expression);
2828
+ return;
2829
+ case "IfStatement":
2830
+ renameExpr(stmt.test);
2831
+ renameBlock(stmt.consequent);
2832
+ if (stmt.alternate) {
2833
+ if (stmt.alternate.kind === "IfStatement") renameStatement(stmt.alternate, false);
2834
+ else renameBlock(stmt.alternate);
2835
+ }
2836
+ return;
2837
+ case "SwitchStatement":
2838
+ renameExpr(stmt.discriminant);
2839
+ for (const c of stmt.cases) {
2840
+ if (c.test) renameExpr(c.test);
2841
+ for (const s of c.body) renameStatement(s, false);
2842
+ }
2843
+ return;
2844
+ case "ForOfStatement": {
2845
+ renameExpr(stmt.iterable);
2846
+ const names = [stmt.item];
2847
+ if (stmt.index) names.push(stmt.index);
2848
+ if (stmt.destructure) names.push(...stmt.destructure);
2849
+ push(names);
2850
+ renameBlock(stmt.body);
2851
+ pop();
2852
+ return;
2853
+ }
2854
+ case "ForInStatement":
2855
+ renameExpr(stmt.iterable);
2856
+ push([stmt.item]);
2857
+ renameBlock(stmt.body);
2858
+ pop();
2859
+ return;
2860
+ case "ForClassicStatement": {
2861
+ const initNames = [];
2862
+ if (stmt.init && stmt.init.kind === "Assignment" && stmt.init.identifier) {
2863
+ initNames.push(stmt.init.identifier);
2864
+ }
2865
+ push(initNames);
2866
+ if (stmt.init) renameStatement(stmt.init, false);
2867
+ if (stmt.test) renameExpr(stmt.test);
2868
+ if (stmt.update) renameExpr(stmt.update);
2869
+ renameBlock(stmt.body);
2870
+ pop();
2871
+ return;
2872
+ }
2873
+ case "WhileStatement":
2874
+ case "DoWhileStatement":
2875
+ renameExpr(stmt.test);
2876
+ renameBlock(stmt.body);
2877
+ return;
2878
+ case "DestructureStatement":
2879
+ renameExpr(stmt.expression);
2880
+ for (const b of stmt.bindings) if (b.defaultValue) renameExpr(b.defaultValue);
2881
+ if (topLevel) for (const b of stmt.bindings) b.name = rPlain(b.name);
2882
+ return;
2883
+ case "ThrowStatement":
2884
+ renameExpr(stmt.argument);
2885
+ return;
2886
+ case "TryStatement":
2887
+ renameBlock(stmt.block);
2888
+ if (stmt.catchBlock) {
2889
+ push(stmt.catchParam ? [stmt.catchParam] : []);
2890
+ renameBlock(stmt.catchBlock);
2891
+ pop();
2892
+ }
2893
+ if (stmt.finallyBlock) renameBlock(stmt.finallyBlock);
2894
+ return;
2895
+ case "BreakStatement":
2896
+ case "ContinueStatement":
2897
+ return;
2898
+ }
2899
+ }
2900
+ return { renameTopLevel };
2901
+ }
2902
+ function isUrl(spec) {
2903
+ return /^[a-z][a-z0-9+.-]*:\/\//i.test(spec);
2904
+ }
2905
+ function normalizeSegments(parts) {
2906
+ const out = [];
2907
+ for (const part of parts) {
2908
+ if (part === "" || part === ".") continue;
2909
+ if (part === "..") out.pop();
2910
+ else out.push(part);
2911
+ }
2912
+ return out.join("/");
2913
+ }
2914
+ function dirOf(path) {
2915
+ const slash = path.lastIndexOf("/");
2916
+ return slash < 0 ? "" : path.slice(0, slash);
2917
+ }
2918
+ function resolveSpecifier(spec, importerPath) {
2919
+ if (isUrl(spec)) {
2920
+ try {
2921
+ return new URL(spec).href;
2922
+ } catch {
2923
+ return null;
2924
+ }
2925
+ }
2926
+ if (isUrl(importerPath)) {
2927
+ try {
2928
+ return new URL(spec, importerPath).href;
2929
+ } catch {
2930
+ return null;
2931
+ }
2932
+ }
2933
+ if (spec.startsWith("/")) {
2934
+ return normalizeSegments(spec.split("/"));
2935
+ }
2936
+ if (spec.startsWith("./") || spec.startsWith("../")) {
2937
+ return normalizeSegments(`${dirOf(importerPath)}/${spec}`.split("/"));
2938
+ }
2939
+ return null;
2940
+ }
2941
+ function createMemoryResolver(files) {
2942
+ return {
2943
+ resolve: (spec, importer) => resolveSpecifier(spec, importer),
2944
+ load: (path) => {
2945
+ const src = files[path];
2946
+ if (src === void 0) throw new Error(`not found: ${path}`);
2947
+ return src;
2948
+ }
2949
+ };
2950
+ }
2951
+ async function defaultFetch(url) {
2952
+ if (typeof fetch !== "function") {
2953
+ throw new Error("global fetch is unavailable; cannot load URL imports");
2954
+ }
2955
+ const res = await fetch(url);
2956
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
2957
+ return res.text();
2958
+ }
2959
+ async function linkProject(options) {
2960
+ const { entry, files } = options;
2961
+ const fetchImpl = options.fetch ?? defaultFetch;
2962
+ const fetchDiagnostics = [];
2963
+ const sources = { ...files };
2964
+ const seen = /* @__PURE__ */ new Set();
2965
+ async function walk(path) {
2966
+ if (seen.has(path)) return;
2967
+ seen.add(path);
2968
+ if (sources[path] === void 0) {
2969
+ if (isUrl(path)) {
2970
+ try {
2971
+ sources[path] = await fetchImpl(path);
2972
+ } catch (err) {
2973
+ fetchDiagnostics.push({
2974
+ line: 0,
2975
+ column: 0,
2976
+ message: `Failed to fetch module "${path}": ${err.message ?? err}`,
2977
+ severity: "error"
2978
+ });
2979
+ return;
2980
+ }
2981
+ } else {
2982
+ return;
2983
+ }
2984
+ }
2985
+ let program;
2986
+ try {
2987
+ program = parse(sources[path]);
2988
+ } catch {
2989
+ return;
2990
+ }
2991
+ const children = [];
2992
+ for (const stmt of program.statements) {
2993
+ if (stmt.kind !== "Import") continue;
2994
+ const resolved = resolveSpecifier(stmt.source, path);
2995
+ if (resolved !== null) children.push(walk(resolved));
2996
+ }
2997
+ await Promise.all(children);
2998
+ }
2999
+ if (sources[entry] === void 0) {
3000
+ return {
3001
+ program: { statements: [], errors: [] },
3002
+ source: "",
3003
+ diagnostics: [
3004
+ { line: 0, column: 0, message: `Entry module "${entry}" was not found.`, severity: "error" }
3005
+ ],
3006
+ dependencies: []
3007
+ };
3008
+ }
3009
+ await walk(entry);
3010
+ const linked = linkProgram(sources[entry], entry, createMemoryResolver(sources));
3011
+ let source;
3012
+ try {
3013
+ source = printProgram(linked.program);
3014
+ } catch {
3015
+ source = sources[entry];
3016
+ }
3017
+ return {
3018
+ program: linked.program,
3019
+ source,
3020
+ diagnostics: [...fetchDiagnostics, ...linked.diagnostics],
3021
+ dependencies: linked.dependencies
3022
+ };
3023
+ }
2191
3024
  function applyDelta(source, ops) {
2192
3025
  const warnings = [];
2193
3026
  const stateUpdates = {};
@@ -28802,6 +29635,7 @@ const ATTRIBUTE_THEME = "theme";
28802
29635
  const ATTRIBUTE_STREAMING = "streaming";
28803
29636
  const ATTRIBUTE_RESPONSE = "response";
28804
29637
  const ATTRIBUTE_SHOW_ERRORS = "showerrors";
29638
+ const ATTRIBUTE_SRC = "src";
28805
29639
  const STATE_ROUTE = "route";
28806
29640
  function buildRouteObject(router) {
28807
29641
  const path = router.getPath();
@@ -28925,6 +29759,25 @@ class AktionElement extends HTMLElement {
28925
29759
  */
28926
29760
  __publicField(this, "forceFullRender", false);
28927
29761
  __publicField(this, "parseErrors", []);
29762
+ /**
29763
+ * Diagnostics raised while loading a program from the `src` attribute
29764
+ * (fetch / link failures, unresolved imports). Tracked separately from
29765
+ * `parseErrors` so they survive the `replan()` that mounting the linked
29766
+ * program triggers, and are merged into the error banner + `error` event.
29767
+ */
29768
+ __publicField(this, "srcDiagnostics", []);
29769
+ /**
29770
+ * Monotonic token guarding overlapping `src` loads. A rapid `src` change
29771
+ * (or a reconnect mid-fetch) bumps the token so a stale in-flight load
29772
+ * resolves into a no-op instead of clobbering the current program.
29773
+ */
29774
+ __publicField(this, "srcLoadToken", 0);
29775
+ /**
29776
+ * True once `connectedCallback` has run at least once. Lets
29777
+ * `attributeChangedCallback` distinguish the initial attribute upgrade
29778
+ * (handled by `connectedCallback`) from a genuine later `src` change.
29779
+ */
29780
+ __publicField(this, "hasConnected", false);
28928
29781
  /**
28929
29782
  * Token keys most recently applied by an in-script `$theme({...})`
28930
29783
  * declaration. We remember them so the next render can clear stale
@@ -29023,10 +29876,12 @@ class AktionElement extends HTMLElement {
29023
29876
  ATTRIBUTE_THEME,
29024
29877
  ATTRIBUTE_STREAMING,
29025
29878
  ATTRIBUTE_RESPONSE,
29026
- ATTRIBUTE_SHOW_ERRORS
29879
+ ATTRIBUTE_SHOW_ERRORS,
29880
+ ATTRIBUTE_SRC
29027
29881
  ];
29028
29882
  }
29029
29883
  connectedCallback() {
29884
+ this.hasConnected = true;
29030
29885
  ensureFontAwesomeLoaded(this.root);
29031
29886
  this.registerWithDevtools();
29032
29887
  this.applyThemeFromAttribute();
@@ -29036,6 +29891,11 @@ class AktionElement extends HTMLElement {
29036
29891
  this.setResponse(responseAttr);
29037
29892
  return;
29038
29893
  }
29894
+ const srcAttr = this.getAttribute(ATTRIBUTE_SRC);
29895
+ if (srcAttr && !this.currentResponse) {
29896
+ void this.loadFromSrc(srcAttr);
29897
+ return;
29898
+ }
29039
29899
  if (!this.currentResponse) {
29040
29900
  const fallback = (this.textContent ?? "").trim();
29041
29901
  if (fallback) {
@@ -29070,6 +29930,9 @@ class AktionElement extends HTMLElement {
29070
29930
  const next = value ?? "";
29071
29931
  if (next !== this.currentResponse) this.setResponse(next);
29072
29932
  }
29933
+ if (name === ATTRIBUTE_SRC) {
29934
+ if (this.hasConnected && value) void this.loadFromSrc(value);
29935
+ }
29073
29936
  }
29074
29937
  /**
29075
29938
  * Register HTTP interceptors used by the Aktion 0.5 HTTP layer (§22.1 of
@@ -29091,6 +29954,7 @@ class AktionElement extends HTMLElement {
29091
29954
  this.state.rebind([]);
29092
29955
  this.renderer.reset();
29093
29956
  this.parseErrors = [];
29957
+ this.srcDiagnostics = [];
29094
29958
  this.scheduleRender();
29095
29959
  }
29096
29960
  /**
@@ -29156,6 +30020,7 @@ class AktionElement extends HTMLElement {
29156
30020
  this.state.rebind([]);
29157
30021
  this.renderer.reset();
29158
30022
  this.parseErrors = [];
30023
+ this.srcDiagnostics = [];
29159
30024
  this.state.hydrate(payload.state);
29160
30025
  this.scheduleRender();
29161
30026
  }
@@ -29185,6 +30050,7 @@ class AktionElement extends HTMLElement {
29185
30050
  this.state.rebind([]);
29186
30051
  this.renderer.reset();
29187
30052
  this.parseErrors = [];
30053
+ this.srcDiagnostics = [];
29188
30054
  if (state) this.state.hydrate(state);
29189
30055
  this.scheduleRender();
29190
30056
  }
@@ -29195,6 +30061,88 @@ class AktionElement extends HTMLElement {
29195
30061
  get sourceId() {
29196
30062
  return this.compiledSourceId;
29197
30063
  }
30064
+ /** Current `src` attribute value, or `null` when none is set. */
30065
+ get src() {
30066
+ return this.getAttribute(ATTRIBUTE_SRC);
30067
+ }
30068
+ set src(value) {
30069
+ if (value === null) this.removeAttribute(ATTRIBUTE_SRC);
30070
+ else this.setAttribute(ATTRIBUTE_SRC, value);
30071
+ }
30072
+ /**
30073
+ * Load the program from an external `.aktion` file referenced by the `src`
30074
+ * attribute. The entry is fetched relative to the document, linked through
30075
+ * the in-browser project linker (so an entry that `import`s other modules
30076
+ * resolves and fetches its whole graph), and mounted as a compiled program.
30077
+ *
30078
+ * A monotonic token guards against overlapping loads: a rapid `src` change
30079
+ * or a reconnect mid-fetch bumps the token, so a stale in-flight load
30080
+ * resolves into a no-op instead of clobbering the current program. Fetch /
30081
+ * link failures and unresolved imports surface through the same error banner
30082
+ * and `error` event as parse errors.
30083
+ */
30084
+ async loadFromSrc(src) {
30085
+ const token = this.srcLoadToken += 1;
30086
+ this.srcDiagnostics = [];
30087
+ let entryUrl;
30088
+ try {
30089
+ const base = typeof document !== "undefined" ? document.baseURI : void 0;
30090
+ entryUrl = new URL(src, base).href;
30091
+ } catch {
30092
+ this.reportSrcError(`Invalid src "${src}".`);
30093
+ return;
30094
+ }
30095
+ let entryText;
30096
+ try {
30097
+ if (typeof fetch !== "function") throw new Error("global fetch is unavailable");
30098
+ const response = await fetch(entryUrl);
30099
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
30100
+ entryText = await response.text();
30101
+ } catch (err) {
30102
+ if (this.isStaleSrcLoad(token)) return;
30103
+ this.reportSrcError(`Failed to load "${src}": ${errorMessage(err)}`);
30104
+ return;
30105
+ }
30106
+ if (this.isStaleSrcLoad(token)) return;
30107
+ let result;
30108
+ try {
30109
+ result = await linkProject({ entry: entryUrl, files: { [entryUrl]: entryText } });
30110
+ } catch (err) {
30111
+ if (this.isStaleSrcLoad(token)) return;
30112
+ this.reportSrcError(`Failed to link "${src}": ${errorMessage(err)}`);
30113
+ return;
30114
+ }
30115
+ if (this.isStaleSrcLoad(token)) return;
30116
+ this.mountCompiled(
30117
+ defineCompiledProgram({
30118
+ __aktionCompiled: COMPILED_PROGRAM_VERSION,
30119
+ program: result.program,
30120
+ source: result.source,
30121
+ path: entryUrl
30122
+ })
30123
+ );
30124
+ this.srcDiagnostics = result.diagnostics.filter((d) => d.severity !== "warning").map((d) => d.line > 0 ? `Line ${d.line}: ${d.message}` : d.message);
30125
+ }
30126
+ /** A `src` load is stale if a newer one started or the element detached. */
30127
+ isStaleSrcLoad(token) {
30128
+ return token !== this.srcLoadToken || !this.isConnected;
30129
+ }
30130
+ /**
30131
+ * Surface a `src`-loading failure: record it, refresh the banner, and
30132
+ * bubble an `error` event so host pages can react (mirrors how parse
30133
+ * errors are reported).
30134
+ */
30135
+ reportSrcError(message) {
30136
+ if (!this.srcDiagnostics.includes(message)) {
30137
+ this.srcDiagnostics = [...this.srcDiagnostics, message];
30138
+ }
30139
+ this.updateErrorBanner();
30140
+ this.dispatchEvent(new CustomEvent("error", {
30141
+ detail: { errors: [{ line: 0, column: 0, message }] },
30142
+ bubbles: true,
30143
+ composed: true
30144
+ }));
30145
+ }
29198
30146
  /** Append a streaming chunk and re-render. */
29199
30147
  appendChunk(chunk) {
29200
30148
  if (chunk === null || chunk === void 0) return;
@@ -29239,6 +30187,7 @@ class AktionElement extends HTMLElement {
29239
30187
  this.renderer.reset();
29240
30188
  this.programDirty = true;
29241
30189
  this.parseErrors = [];
30190
+ this.srcDiagnostics = [];
29242
30191
  this.errorEl.hidden = true;
29243
30192
  this.errorEl.replaceChildren();
29244
30193
  this.rootEl.replaceChildren();
@@ -29623,16 +30572,17 @@ class AktionElement extends HTMLElement {
29623
30572
  }
29624
30573
  }
29625
30574
  updateErrorBanner() {
29626
- if (!this.showErrors || this.streaming || this.parseErrors.length === 0) {
30575
+ const messages = [...this.parseErrors, ...this.srcDiagnostics];
30576
+ if (!this.showErrors || this.streaming || messages.length === 0) {
29627
30577
  this.errorEl.hidden = true;
29628
30578
  this.errorEl.replaceChildren();
29629
30579
  return;
29630
30580
  }
29631
30581
  this.errorEl.hidden = false;
29632
30582
  const title = document.createElement("div");
29633
- title.textContent = `${this.parseErrors.length} parse issue${this.parseErrors.length === 1 ? "" : "s"} (rendered partial UI):`;
30583
+ title.textContent = `${messages.length} parse issue${messages.length === 1 ? "" : "s"} (rendered partial UI):`;
29634
30584
  const list = document.createElement("ul");
29635
- for (const message of this.parseErrors.slice(0, 5)) {
30585
+ for (const message of messages.slice(0, 5)) {
29636
30586
  const li = document.createElement("li");
29637
30587
  li.textContent = message;
29638
30588
  list.append(li);
@@ -29685,6 +30635,10 @@ function parseBooleanAttribute(value) {
29685
30635
  if (normalized === ATTRIBUTE_SHOW_ERRORS) return true;
29686
30636
  return false;
29687
30637
  }
30638
+ function errorMessage(err) {
30639
+ if (err instanceof Error && err.message) return err.message;
30640
+ return String(err);
30641
+ }
29688
30642
  function defineElement() {
29689
30643
  if (!customElements.get(AktionElement.tagName)) {
29690
30644
  customElements.define(AktionElement.tagName, AktionElement);