aktion-runtime 0.5.11 → 0.5.13

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
@@ -707,11 +707,11 @@ function parseEffectDep(ctx, triggers, setRateLimit) {
707
707
  ctx.consume();
708
708
  let name = head.value;
709
709
  while (ctx.peek().type === "Punctuation" && ctx.peek().value === ".") {
710
- const prop = ctx.peek(1);
711
- if (prop.type !== "Identifier" && prop.type !== "Keyword") break;
710
+ const prop2 = ctx.peek(1);
711
+ if (prop2.type !== "Identifier" && prop2.type !== "Keyword") break;
712
712
  ctx.consume();
713
713
  ctx.consume();
714
- name += "." + prop.value;
714
+ name += "." + prop2.value;
715
715
  }
716
716
  triggers.push({ kind: "state", name });
717
717
  return;
@@ -2147,9 +2147,9 @@ function parseObjectProps(ctx) {
2147
2147
  ctx.expect("Punctuation", ":");
2148
2148
  value = parseExpression(ctx);
2149
2149
  }
2150
- const prop = { key, value };
2151
- if (computedKey) prop.computedKey = computedKey;
2152
- props.push(prop);
2150
+ const prop2 = { key, value };
2151
+ if (computedKey) prop2.computedKey = computedKey;
2152
+ props.push(prop2);
2153
2153
  skipWhitespace(ctx);
2154
2154
  if (ctx.peek().type === "Punctuation" && ctx.peek().value === ",") {
2155
2155
  ctx.consume();
@@ -2489,13 +2489,13 @@ ${printStatement({ kind: "ExpressionStatement", expression: { kind: "Identifier"
2489
2489
  ${body}
2490
2490
  ${INDENT.repeat(indent + 1)}break`;
2491
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;
2492
+ function printObjectProp(prop2, indent) {
2493
+ if (prop2.spread) return `...${printExpression(prop2.value, indent)}`;
2494
+ const value = printExpression(prop2.value, indent);
2495
+ if (prop2.value.kind === "Identifier" && prop2.value.name === prop2.key && SAFE_IDENT.test(prop2.key)) {
2496
+ return prop2.key;
2497
2497
  }
2498
- const key = SAFE_IDENT.test(prop.key) ? prop.key : printStringLiteral(prop.key);
2498
+ const key = SAFE_IDENT.test(prop2.key) ? prop2.key : printStringLiteral(prop2.key);
2499
2499
  return `${key}: ${value}`;
2500
2500
  }
2501
2501
  function printLiteral(value) {
@@ -2706,9 +2706,9 @@ function makeRenamer(rec) {
2706
2706
  for (const el2 of expr.elements) renameExpr(el2);
2707
2707
  return;
2708
2708
  case "Object":
2709
- for (const prop of expr.properties) {
2710
- if (prop.computedKey) renameExpr(prop.computedKey);
2711
- renameExpr(prop.value);
2709
+ for (const prop2 of expr.properties) {
2710
+ if (prop2.computedKey) renameExpr(prop2.computedKey);
2711
+ renameExpr(prop2.value);
2712
2712
  }
2713
2713
  return;
2714
2714
  case "Member":
@@ -3929,8 +3929,8 @@ function resolveBorder(v) {
3929
3929
  const c = color(b);
3930
3930
  return c ? [["border", `1px solid ${c}`]] : [];
3931
3931
  }
3932
- function pair(prop, value) {
3933
- return value ? [[prop, value]] : [];
3932
+ function pair(prop2, value) {
3933
+ return value ? [[prop2, value]] : [];
3934
3934
  }
3935
3935
  function applyResponsive(sx, classes) {
3936
3936
  const handled = /* @__PURE__ */ new Set();
@@ -4114,8 +4114,8 @@ function collectArbitraryStateClasses(sx, classes) {
4114
4114
  }
4115
4115
  function resolveStateDecls(obj) {
4116
4116
  const out = [];
4117
- const push = (prop, value) => {
4118
- if (value) out.push([prop, value]);
4117
+ const push = (prop2, value) => {
4118
+ if (value) out.push([prop2, value]);
4119
4119
  };
4120
4120
  const transforms = [];
4121
4121
  push("background", bg(obj.bg));
@@ -4297,8 +4297,8 @@ function assertOnePositionalMax(specs) {
4297
4297
  }
4298
4298
  }
4299
4299
  }
4300
- function propExpectsObject(prop) {
4301
- return /\bobject\b|\bRecord\b|\{|\bany\b/i.test(prop.type);
4300
+ function propExpectsObject(prop2) {
4301
+ return /\bobject\b|\bRecord\b|\{|\bany\b/i.test(prop2.type);
4302
4302
  }
4303
4303
  function knownPropNames(spec) {
4304
4304
  const names = /* @__PURE__ */ new Set();
@@ -4368,8 +4368,8 @@ function callArgShapes(args) {
4368
4368
  }
4369
4369
  function mapPositionalArgs(spec, args) {
4370
4370
  const out = {};
4371
- spec.props.forEach((prop, index) => {
4372
- if (index < args.length) out[prop.name] = args[index];
4371
+ spec.props.forEach((prop2, index) => {
4372
+ if (index < args.length) out[prop2.name] = args[index];
4373
4373
  });
4374
4374
  return out;
4375
4375
  }
@@ -4505,7 +4505,7 @@ function walkExpression(expr, library, out) {
4505
4505
  for (const e of expr.elements) walkExpression(e, library, out);
4506
4506
  return;
4507
4507
  case "Object":
4508
- for (const prop of expr.properties) walkExpression(prop.value, library, out);
4508
+ for (const prop2 of expr.properties) walkExpression(prop2.value, library, out);
4509
4509
  return;
4510
4510
  case "Template":
4511
4511
  for (const e of expr.expressions) walkExpression(e, library, out);
@@ -4602,21 +4602,21 @@ function validateCall(expr, library, out) {
4602
4602
  });
4603
4603
  }
4604
4604
  positionalArgs.forEach((arg, n) => {
4605
- const prop = slotForNthPositional(spec, n);
4606
- if (!prop) return;
4607
- if (prop.enum && arg.kind === "Literal" && typeof arg.value === "string") {
4605
+ const prop2 = slotForNthPositional(spec, n);
4606
+ if (!prop2) return;
4607
+ if (prop2.enum && arg.kind === "Literal" && typeof arg.value === "string") {
4608
4608
  const value = arg.value;
4609
- if (!prop.enum.includes(value) && !prop.enum.includes(canonicalSizeToken(value))) {
4609
+ if (!prop2.enum.includes(value) && !prop2.enum.includes(canonicalSizeToken(value))) {
4610
4610
  out.push({
4611
- message: `<${expr.callee}> ${prop.name}="${value}" — must be one of ${prop.enum.map((v) => `"${v}"`).join(", ")}.`,
4611
+ message: `<${expr.callee}> ${prop2.name}="${value}" — must be one of ${prop2.enum.map((v) => `"${v}"`).join(", ")}.`,
4612
4612
  line: arg.loc?.line ?? expr.loc?.line ?? 0,
4613
4613
  column: arg.loc?.column ?? expr.loc?.column ?? 0
4614
4614
  });
4615
4615
  }
4616
4616
  }
4617
- if (arg.kind === "Object" && !propExpectsObject(prop)) {
4617
+ if (arg.kind === "Object" && !propExpectsObject(prop2)) {
4618
4618
  out.push({
4619
- message: `<${expr.callee}> — object passed positionally for "${prop.name}" (${prop.type}). Use named props from: ${spec.props.map((p) => p.name).join(", ")}.`,
4619
+ message: `<${expr.callee}> — object passed positionally for "${prop2.name}" (${prop2.type}). Use named props from: ${spec.props.map((p) => p.name).join(", ")}.`,
4620
4620
  line: arg.loc?.line ?? expr.loc?.line ?? 0,
4621
4621
  column: arg.loc?.column ?? expr.loc?.column ?? 0
4622
4622
  });
@@ -4624,12 +4624,12 @@ function validateCall(expr, library, out) {
4624
4624
  });
4625
4625
  const namedEntries = [];
4626
4626
  if (trailingObj) {
4627
- for (const prop of trailingObj.properties) {
4628
- if (prop.spread) continue;
4627
+ for (const prop2 of trailingObj.properties) {
4628
+ if (prop2.spread) continue;
4629
4629
  namedEntries.push({
4630
- name: prop.key,
4631
- value: prop.value,
4632
- loc: prop.value.loc ?? trailingObj.loc
4630
+ name: prop2.key,
4631
+ value: prop2.value,
4632
+ loc: prop2.value.loc ?? trailingObj.loc
4633
4633
  });
4634
4634
  }
4635
4635
  }
@@ -4643,14 +4643,14 @@ function validateCall(expr, library, out) {
4643
4643
  });
4644
4644
  continue;
4645
4645
  }
4646
- const prop = spec.props.find(
4646
+ const prop2 = spec.props.find(
4647
4647
  (p) => p.name === entry.name || (p.aliases?.includes(entry.name) ?? false)
4648
4648
  );
4649
- if (prop?.enum && entry.value.kind === "Literal" && typeof entry.value.value === "string") {
4649
+ if (prop2?.enum && entry.value.kind === "Literal" && typeof entry.value.value === "string") {
4650
4650
  const value = entry.value.value;
4651
- if (!prop.enum.includes(value) && !prop.enum.includes(canonicalSizeToken(value))) {
4651
+ if (!prop2.enum.includes(value) && !prop2.enum.includes(canonicalSizeToken(value))) {
4652
4652
  out.push({
4653
- message: `<${expr.callee}> ${entry.name}="${value}" — must be one of ${prop.enum.map((v) => `"${v}"`).join(", ")}.`,
4653
+ message: `<${expr.callee}> ${entry.name}="${value}" — must be one of ${prop2.enum.map((v) => `"${v}"`).join(", ")}.`,
4654
4654
  line: entry.loc?.line ?? expr.loc?.line ?? 0,
4655
4655
  column: entry.loc?.column ?? expr.loc?.column ?? 0
4656
4656
  });
@@ -4663,12 +4663,12 @@ const THEME_METADATA_KEYS$1 = /* @__PURE__ */ new Set(["name", "direction"]);
4663
4663
  function validateThemeCall(expr, out) {
4664
4664
  const arg = expr.arguments[0];
4665
4665
  if (!arg || arg.kind !== "Object") return;
4666
- for (const prop of arg.properties) {
4667
- if (prop.spread) continue;
4668
- if (STRUCTURED_THEME_GROUPS$1.has(prop.key)) continue;
4669
- if (THEME_METADATA_KEYS$1.has(prop.key)) continue;
4670
- const suggestion = suggestStructuredKey(prop.key);
4671
- const message = prop.key.startsWith("--") ? `$theme({"${prop.key}": ...}) — free-form CSS variable keys are removed in Aktion 0.5. Use the structured form: $theme({ colors: {...}, radius: {...}, font: {...} }).` : `$theme({${prop.key}: ...}) — legacy flat-shape token is removed in Aktion 0.5. Use ${suggestion}.`;
4666
+ for (const prop2 of arg.properties) {
4667
+ if (prop2.spread) continue;
4668
+ if (STRUCTURED_THEME_GROUPS$1.has(prop2.key)) continue;
4669
+ if (THEME_METADATA_KEYS$1.has(prop2.key)) continue;
4670
+ const suggestion = suggestStructuredKey(prop2.key);
4671
+ const message = prop2.key.startsWith("--") ? `$theme({"${prop2.key}": ...}) — free-form CSS variable keys are removed in Aktion 0.5. Use the structured form: $theme({ colors: {...}, radius: {...}, font: {...} }).` : `$theme({${prop2.key}: ...}) — legacy flat-shape token is removed in Aktion 0.5. Use ${suggestion}.`;
4672
4672
  out.push({
4673
4673
  message,
4674
4674
  line: expr.loc?.line ?? 0,
@@ -4794,6 +4794,20 @@ const builtinCatalog = [
4794
4794
  signature: "$sse({ url, event })",
4795
4795
  summary: 'Reactive Server-Sent Events stream — { status, connected, last, messages, close }. EventSource reconnects natively (status reads "connecting" while it does).'
4796
4796
  },
4797
+ {
4798
+ name: "script",
4799
+ sigil: "$script",
4800
+ category: "data",
4801
+ signature: "$script({ src, global? })",
4802
+ summary: "Load an external UMD/ESM script or stylesheet once → reactive { ready, loading, error, value }. `global` reads window[global] into `value` (e.g. window.Stripe). De-duplicated per src across the app; gate a third-party widget on `.ready`."
4803
+ },
4804
+ {
4805
+ name: "head",
4806
+ sigil: "$head",
4807
+ category: "app",
4808
+ signature: "$head({ title, meta, og, twitter, link, jsonLd })",
4809
+ summary: "Reactive document head: title, meta description, canonical/alternate links, Open Graph + Twitter cards, JSON-LD, <html> attrs. Per-route calls compose; renderToString emits the resolved <head> so SSR pages are crawlable."
4810
+ },
4797
4811
  // App / routing / theming / events.
4798
4812
  {
4799
4813
  name: "app",
@@ -4856,6 +4870,14 @@ const builtinCatalog = [
4856
4870
  summary: "Imperative toasts: $toast.show/.success/.error/.dismiss; reactive .items.",
4857
4871
  namespace: true
4858
4872
  },
4873
+ {
4874
+ name: "dom",
4875
+ sigil: "$dom",
4876
+ category: "namespace",
4877
+ signature: "$dom",
4878
+ summary: "Managed DOM-observer namespace: $dom.onResize(node, cb) / .onIntersect(node, cb, opts?) / .onMutation(node, cb, opts?) (auto-disposed on replan) and .measure(node) → { rect, scroll, viewport }. Pair with Mount/OnMount node refs.",
4879
+ namespace: true
4880
+ },
4859
4881
  {
4860
4882
  name: "i18n",
4861
4883
  sigil: "$i18n",
@@ -4870,6 +4892,314 @@ new Set(
4870
4892
  Object.freeze(
4871
4893
  Object.fromEntries(builtinCatalog.map((b) => [b.name, b]))
4872
4894
  );
4895
+ const method = (name, signature, summary) => ({
4896
+ name,
4897
+ kind: "method",
4898
+ signature,
4899
+ summary
4900
+ });
4901
+ const prop = (name, summary) => ({
4902
+ name,
4903
+ kind: "property",
4904
+ signature: name,
4905
+ summary
4906
+ });
4907
+ const utilMembers = [
4908
+ // Aggregation
4909
+ method("count", "count(items)", "Number of items in an array."),
4910
+ method("sum", "sum(items)", "Sum of the numeric values."),
4911
+ method("avg", "avg(items)", "Arithmetic mean of the values."),
4912
+ method("min", "min(items)", "Smallest numeric value."),
4913
+ method("max", "max(items)", "Largest numeric value."),
4914
+ method("first", "first(items)", "First element, or null when empty."),
4915
+ method("last", "last(items)", "Last element, or null when empty."),
4916
+ // Reshaping
4917
+ method("filter", "filter(items, field?, op?, value?)", "Keep items where field matches. Operators: == != > < >= <= contains startsWith endsWith."),
4918
+ method("find", "find(items, field?, op?, value?)", "First item matching the comparator, or null."),
4919
+ method("sort", "sort(items, field?, direction?)", 'Sort by field, "asc" (default) or "desc".'),
4920
+ method("groupBy", "groupBy(items, field?)", "Group items into an object keyed by the field value."),
4921
+ method("slice", "slice(items, start?, end?)", "Subarray between start and end indices."),
4922
+ method("unique", "unique(items, field?)", "De-duplicate an array (optionally by a field)."),
4923
+ method("reverse", "reverse(items)", "Reversed copy of the array."),
4924
+ method("range", "range(start, end, step?)", "Array of numbers from start to end (inclusive)."),
4925
+ method("repeat", "repeat(value, n)", "Array with the value repeated n times."),
4926
+ method("pick", "pick(obj, keys)", "Object containing only the listed keys."),
4927
+ method("omit", "omit(obj, keys)", "Object without the listed keys."),
4928
+ method("chunk", "chunk(items, size)", "Split an array into chunks of the given size."),
4929
+ method("flatten", "flatten(items, depth?)", "Flatten nested arrays to the given depth (default 1)."),
4930
+ method("zip", "zip(...arrays)", "Combine arrays element-wise into tuples."),
4931
+ method("partition", "partition(items, field?, op?, value?)", "Split into [pass, fail] by a comparator."),
4932
+ method("keyBy", "keyBy(items, field?)", "Index an array into an object keyed by a field."),
4933
+ method("cloneDeep", "cloneDeep(value)", "Deep-clone a value (arrays / objects / dates)."),
4934
+ method("merge", "merge(target, ...sources)", "Deep-merge source objects onto a clone of the target."),
4935
+ // Formatting
4936
+ method("format", "format(value, mode?, options?)", 'Locale number format: "number" | "currency" | "percent" | "compact".'),
4937
+ method("formatDate", "formatDate(value, format?)", 'Format a date — a token pattern (MMM D, YYYY-MM-DD) or "relative"/"date"/"time"/"datetime"/"iso".'),
4938
+ method("plural", "plural(count, singular, plural?)", "Count + correctly pluralised noun: `3 items` / `1 item`."),
4939
+ method("capitalize", "capitalize(text)", "Capitalise the first letter."),
4940
+ method("lowercase", "lowercase(text)", "Lowercase the whole string."),
4941
+ method("uppercase", "uppercase(text)", "Uppercase the whole string."),
4942
+ method("titlecase", "titlecase(text)", "Title-case each word."),
4943
+ method("case", "case(text, kind?)", 'Recase: "camel" | "pascal" | "snake" | "kebab".'),
4944
+ // Date / time
4945
+ method("now", "now()", "Current time as epoch milliseconds."),
4946
+ method("today", "today()", "Start of today as an ISO string."),
4947
+ method("addDays", "addDays(date, days)", "Date shifted by n days (ISO)."),
4948
+ method("addHours", "addHours(date, hours)", "Date shifted by n hours (ISO)."),
4949
+ method("diffDays", "diffDays(start, end)", "Whole days between two dates."),
4950
+ method("startOfWeek", "startOfWeek(date)", "Start of the week containing the date (ISO)."),
4951
+ method("endOfMonth", "endOfMonth(date)", "End of the month containing the date (ISO)."),
4952
+ // String / regex
4953
+ method("join", "join(items, sep?)", "Join an array into a string with a separator."),
4954
+ method("split", "split(text, sep?)", "Split a string into an array on a separator."),
4955
+ method("trim", "trim(text)", "Trim surrounding whitespace."),
4956
+ method("replace", "replace(text, search, replacement?)", "Replace every occurrence of a substring."),
4957
+ method("substring", "substring(text, start, end?)", "Substring between two indices."),
4958
+ method("startsWith", "startsWith(text, prefix)", "True when the text starts with the prefix."),
4959
+ method("endsWith", "endsWith(text, suffix)", "True when the text ends with the suffix."),
4960
+ method("contains", "contains(text, needle)", "True when the text contains the needle."),
4961
+ method("match", "match(text, pattern)", "Test the text against a regular-expression pattern."),
4962
+ // Math
4963
+ method("round", "round(value, decimals?)", "Round to n decimal places."),
4964
+ method("floor", "floor(value)", "Round down to an integer."),
4965
+ method("ceil", "ceil(value)", "Round up to an integer."),
4966
+ method("abs", "abs(value)", "Absolute value."),
4967
+ method("clamp", "clamp(value, min, max)", "Constrain a number to a [min, max] range."),
4968
+ method("pow", "pow(base, exp)", "Exponentiation (base^exp)."),
4969
+ method("sqrt", "sqrt(value)", "Square root."),
4970
+ method("random", "random()", "Pseudo-random number in [0, 1)."),
4971
+ method("log", "log(value)", "Natural logarithm."),
4972
+ // Formatting / misc convenience
4973
+ method("slugify", "slugify(text)", 'URL-safe slug: "Hello World" → "hello-world".'),
4974
+ method("truncate", "truncate(text, length?, ellipsis?)", "Cut text to n chars with an ellipsis."),
4975
+ method("initials", "initials(name, max?)", "Up-to-`max` initials from a full name."),
4976
+ method("currency", "currency(value, code?, locale?)", "Locale currency string."),
4977
+ method("percent", "percent(value, decimals?)", 'Locale percent string (0.42 → "42%").'),
4978
+ method("bytes", "bytes(value)", 'Human-readable byte size (1536 → "1.5 KB").'),
4979
+ method("relativeTime", "relativeTime(value)", '"3 minutes ago" / "in 2 days" via Intl.'),
4980
+ method("copy", "copy(text)", "Copy to the clipboard — async; resolves true only when the write succeeds (`await $util.copy(x)`)."),
4981
+ method("sleep", "sleep(ms?)", "Awaitable pause: `await $util.sleep(ms)` (capped at 60s)."),
4982
+ method("uuid", "uuid()", "Random UUID v4 string."),
4983
+ method("debounceFn", "debounceFn(fn, wait?)", "Wrap a function so it fires `wait` ms after the LAST call."),
4984
+ method("throttleFn", "throttleFn(fn, wait?)", "Wrap a function to fire at most once per `wait` ms (leading + one trailing)."),
4985
+ // Computed + program hooks
4986
+ method("derived", "derived(fn)", "Computed reactive value — recomputes from the atoms the lambda reads."),
4987
+ method("onError", "onError(fn)", "Program-level error sink — fires with { error, source } when an action throws."),
4988
+ method("onNavigate", "onNavigate(fn)", "Navigation guard: return false to block, a path string to redirect, anything else to allow."),
4989
+ method("onRequest", "onRequest(fn)", "HTTP request interceptor — a partial return merges over every outgoing request."),
4990
+ method("onResponse", "onResponse(fn)", "HTTP response interceptor — replace the response or `await retry()`."),
4991
+ method("invalidate", "invalidate(keys)", "Refetch every cached $query whose key contains one of the substrings."),
4992
+ // Reactive environment (listeners attach lazily on first read)
4993
+ prop("scroll", 'Reactive scroll: .x / .y / .progress (0–1) / .direction ("up"|"down").'),
4994
+ prop("viewport", "Reactive viewport: .width / .height."),
4995
+ prop("breakpoint", 'Reactive breakpoint: .active ("base"|"sm"|"md"|"lg"|"xl") + boolean .sm/.md/.lg/.xl.'),
4996
+ prop("media", "Reactive media flags: .prefersDark / .prefersReducedMotion / .online / .pointer / .portrait."),
4997
+ prop("mouse", "Reactive pointer position: .x / .y."),
4998
+ // URL + query-param state
4999
+ prop("url", "Reactive URL snapshot: .path / .params / .query / .hash + .navigate(to)."),
5000
+ method("url.setQuery", "url.setQuery(key, value)", 'Write a query param in place (null/"" drops it) — shareable filter/tab state.'),
5001
+ method("url.removeQuery", "url.removeQuery(key)", "Drop a query param from the URL."),
5002
+ // Styling helpers ($util.style)
5003
+ { name: "style", kind: "namespace", signature: "style", summary: "Safe styling helpers: .cx / .gradient / .alpha / .clamp / .token / .toStyle." },
5004
+ method("style.cx", "style.cx(...args)", "clsx-style class composer — strings, arrays, { name: cond } objects."),
5005
+ method("style.gradient", "style.gradient(stops, angle?)", "Safe linear-gradient() from color stops + angle."),
5006
+ method("style.alpha", "style.alpha(color, amount)", "color-mix transparency: token or color at 0–1 alpha."),
5007
+ method("style.clamp", "style.clamp(min, preferred, max)", "Responsive clamp(min, preferred, max) size."),
5008
+ method("style.token", "style.token(path)", 'Resolve a theme token path to its CSS var: "colors.primary" → var(--rui-color-primary).'),
5009
+ method("style.toStyle", "style.toStyle(obj)", "Serialise a CSS-declarations object to a sanitised style string."),
5010
+ // Validators ($util.rules)
5011
+ { name: "rules", kind: "namespace", signature: "rules", summary: "Composable validators — compose per field; run with .validate / .validateAll or hand to $form." },
5012
+ method("rules.required", "rules.required(message?)", "Non-empty value."),
5013
+ method("rules.email", "rules.email(message?)", "Valid email address."),
5014
+ method("rules.url", "rules.url(message?)", "Valid http(s) URL."),
5015
+ method("rules.min", "rules.min(n, message?)", "Number ≥ n."),
5016
+ method("rules.max", "rules.max(n, message?)", "Number ≤ n."),
5017
+ method("rules.minLength", "rules.minLength(n, message?)", "String length ≥ n."),
5018
+ method("rules.maxLength", "rules.maxLength(n, message?)", "String length ≤ n."),
5019
+ method("rules.pattern", "rules.pattern(re, message?)", "Match a regular expression."),
5020
+ method("rules.oneOf", "rules.oneOf(options, message?)", "Value is in the allowed list."),
5021
+ method("rules.matches", "rules.matches(other, message?)", "Equals another value (password confirmation)."),
5022
+ method("rules.custom", "rules.custom(fn, message?)", "Custom sync rule — return true/null (valid), false, or an error string."),
5023
+ method("rules.asyncCustom", "rules.asyncCustom(fn, message?)", "Async rule (Promise) — server-side checks; $form awaits it before submitting."),
5024
+ method("rules.validate", "rules.validate(value, validators)", "Run validators — first error message or null (a Promise when an async rule is hit)."),
5025
+ method("rules.validateAll", "rules.validateAll(values, schema)", "Validate an object against { field: [validators] } → { field: message }."),
5026
+ // Device / platform
5027
+ method("vibrate", "vibrate(pattern?)", "Haptic pulse (ms or pattern array) on supporting devices."),
5028
+ method("share", "share(data)", "Native share sheet (Web Share API) — resolves true on share."),
5029
+ method("readClipboard", "readClipboard()", "Read clipboard text (async, permission-gated)."),
5030
+ method("geolocate", "geolocate(options?)", "Resolve { lat, lng, accuracy } via the Geolocation API."),
5031
+ method("isOnline", "isOnline()", "Current navigator.onLine flag."),
5032
+ method("deviceType", "deviceType()", '"mobile" | "tablet" | "desktop" heuristic.'),
5033
+ method("worker", "worker(fn, ...args)", "Run a closure-free function in a Web Worker; resolves its return value."),
5034
+ method("registerServiceWorker", "registerServiceWorker(url, scope?)", "Register a service worker for PWA/offline."),
5035
+ method("webManifest", "webManifest(config)", "Build a sanitised web-app manifest (name, icons, themeColor…)."),
5036
+ method("nativeShell", "nativeShell()", 'Detect the wrapper: capacitor/cordova/tauri/electron/react-native or "web".'),
5037
+ method("isNativeApp", "isNativeApp()", "True when running inside a native shell.")
5038
+ ];
5039
+ const storageBackendMembers = (prefix, label) => [
5040
+ method(`${prefix}set`, `${prefix}set(key, value, options?)`, `${label} write.`),
5041
+ method(`${prefix}get`, `${prefix}get(key)`, `${label} read. Returns null when missing.`),
5042
+ method(`${prefix}remove`, `${prefix}remove(key, options?)`, `Delete a key from ${label.toLowerCase()}.`),
5043
+ method(`${prefix}clear`, `${prefix}clear()`, `Wipe every ${label.toLowerCase()} entry.`)
5044
+ ];
5045
+ const storageMembers = [
5046
+ ...storageBackendMembers("", "localStorage (default namespace)"),
5047
+ { name: "local", kind: "namespace", signature: "local", summary: "localStorage backend — set/get/remove/clear." },
5048
+ ...storageBackendMembers("local.", "localStorage"),
5049
+ { name: "session", kind: "namespace", signature: "session", summary: "sessionStorage backend (per-tab) — set/get/remove/clear." },
5050
+ ...storageBackendMembers("session.", "Per-tab sessionStorage"),
5051
+ { name: "cookies", kind: "namespace", signature: "cookies", summary: "Document cookies — set/get/remove/clear (options: expires, maxAge, path, domain, secure, sameSite)." },
5052
+ method("cookies.set", "cookies.set(key, value, options?)", "Set a cookie. Options: expires, maxAge, path, domain, secure, sameSite."),
5053
+ method("cookies.get", "cookies.get(key)", "Read a cookie value."),
5054
+ method("cookies.remove", "cookies.remove(key, options?)", "Delete a cookie. Path/domain must match the original set call."),
5055
+ method("cookies.clear", "cookies.clear()", "Clear every cookie on this document.")
5056
+ ];
5057
+ const consoleMembers = [
5058
+ method("log", "log(...args)", "Log a message at the default level."),
5059
+ method("error", "error(...args)", "Log an error."),
5060
+ method("warn", "warn(...args)", "Log a warning."),
5061
+ method("info", "info(...args)", "Log an informational message."),
5062
+ method("debug", "debug(...args)", "Log a verbose debug message.")
5063
+ ];
5064
+ const toastMembers = [
5065
+ method("show", "show(message, options?)", "Show a toast; returns its id. Options: { title?, tone?, duration? }."),
5066
+ method("success", "success(message, options?)", '`show` with tone "success".'),
5067
+ method("error", "error(message, options?)", '`show` with tone "danger".'),
5068
+ method("info", "info(message, options?)", '`show` with tone "info".'),
5069
+ method("warning", "warning(message, options?)", '`show` with tone "warning".'),
5070
+ method("dismiss", "dismiss(id)", "Remove a single toast by id."),
5071
+ method("clear", "clear()", "Remove every toast."),
5072
+ prop("items", "Reactive list of live toasts (newest last). Treat as read-only.")
5073
+ ];
5074
+ const domMembers = [
5075
+ method("onResize", "onResize(node, callback)", "Observe element size with a ResizeObserver; callback gets { width, height, entry }. Returns a disposer; auto-disposed on replan."),
5076
+ method("onIntersect", "onIntersect(node, callback, options?)", "Observe viewport intersection with an IntersectionObserver; callback gets the entry. Options: { root?, rootMargin?, threshold? }."),
5077
+ method("onMutation", "onMutation(node, callback, options?)", "Observe DOM mutations with a MutationObserver. Options: { childList?, attributes?, subtree?, characterData? }."),
5078
+ method("measure", "measure(node)", "One-shot read → { rect, scroll, viewport } (getBoundingClientRect + scroll offsets + window size).")
5079
+ ];
5080
+ const namespaceCatalog = [
5081
+ { name: "util", sigil: "$util", summary: "Runtime helper + reactive-environment namespace.", members: utilMembers },
5082
+ { name: "storage", sigil: "$storage", summary: "Browser storage namespace (local / session / cookies).", members: storageMembers },
5083
+ { name: "console", sigil: "$console", summary: "Console namespace forwarding to the browser console.", members: consoleMembers },
5084
+ { name: "toast", sigil: "$toast", summary: "Imperative toast namespace.", members: toastMembers },
5085
+ { name: "dom", sigil: "$dom", summary: "Managed DOM-observer namespace (resize / intersection / mutation / measure).", members: domMembers }
5086
+ ];
5087
+ Object.freeze(
5088
+ Object.fromEntries(namespaceCatalog.map((n) => [n.name, n]))
5089
+ );
5090
+ const httpResourceMembers = [
5091
+ prop("data", "Parsed response body — `null` until the request resolves."),
5092
+ prop("error", "`null` on success; `{ status, body }` on a non-2xx; the thrown error on network failure."),
5093
+ prop("status", "HTTP status code of the last response, e.g. `200`."),
5094
+ prop("loading", "`true` while a request is in flight."),
5095
+ prop("headers", "Response headers as a plain object."),
5096
+ prop("lastUpdated", "Epoch-ms of the last successful response."),
5097
+ method("refetch", "refetch()", "Re-issue the original request."),
5098
+ method("cancel", "cancel()", "Abort the in-flight request."),
5099
+ prop("onDone", "Settable callback fired each time the request settles (success or error).")
5100
+ ];
5101
+ const queryResourceMembers = [
5102
+ ...httpResourceMembers,
5103
+ method("loadMore", "loadMore()", "Fetch the next page (infinite mode)."),
5104
+ prop("hasMore", "`true` while more pages are available (infinite mode)."),
5105
+ prop("loadingMore", "`true` while a `loadMore()` page is in flight."),
5106
+ prop("pages", "Raw page bodies loaded so far (infinite mode); `.data` is the flattened items.")
5107
+ ];
5108
+ const mutationResourceMembers = [
5109
+ method("mutate", "mutate(overrides?)", "Fire the request; overrides shallow-merge over the config. `optimistic` applies instantly and rolls back on failure."),
5110
+ prop("data", "Response body of the last successful mutation."),
5111
+ prop("error", "`null` on success; error details on failure."),
5112
+ prop("loading", "`true` while the mutation request is in flight."),
5113
+ prop("status", "HTTP status code of the last response."),
5114
+ prop("onDone", "Settable callback fired when the mutation settles.")
5115
+ ];
5116
+ const socketResourceMembers = [
5117
+ prop("status", 'Connection lifecycle: "connecting" | "open" | "closed".'),
5118
+ prop("connected", '`true` while status is "open".'),
5119
+ prop("last", "Most recent message (JSON auto-parsed), or null."),
5120
+ prop("messages", "Buffered messages, newest last (capped to bufferSize)."),
5121
+ prop("attempts", "Reconnect attempts in the current streak (resets on success)."),
5122
+ prop("error", "Last socket error event, if any."),
5123
+ method("send", "send(data)", "Send a message (objects JSON-stringified). Queues while connecting; flushes on open."),
5124
+ method("close", "close()", "Close for good — disables auto-reconnect.")
5125
+ ];
5126
+ const sseResourceMembers = [
5127
+ prop("status", '"connecting" | "open" | "closed" (EventSource retries natively).'),
5128
+ prop("connected", "`true` while the stream is open."),
5129
+ prop("last", "Most recent event payload (JSON auto-parsed)."),
5130
+ prop("messages", "Buffered events, newest last (capped to bufferSize)."),
5131
+ prop("error", "Last stream error, if any."),
5132
+ method("close", "close()", "Close the stream.")
5133
+ ];
5134
+ const formResourceMembers = [
5135
+ prop("values", "Reactive field values — two-way bind with an input's `value`."),
5136
+ prop("errors", "Per-field error messages (set after validate/touch/submit)."),
5137
+ prop("touched", "Per-field booleans — true once the user has interacted."),
5138
+ prop("dirty", "`true` once any value differs from the clean snapshot."),
5139
+ prop("valid", "`true` when the last validation pass found no errors."),
5140
+ prop("submitting", "`true` from submit() until an async onSubmit settles."),
5141
+ prop("validating", "`true` while async rules ($util.rules.asyncCustom) are in flight."),
5142
+ method("field", "field(name)", "Controlled prop bag: { value, error, name, onChange, onBlur } — spread onto an input."),
5143
+ method("touch", "touch(name)", "Mark a field touched + validate it (wire to `onBlur`)."),
5144
+ method("setField", "setField(name, value)", "Set one field value (clears its error)."),
5145
+ method("setValues", "setValues(values)", "Merge several field values at once."),
5146
+ method("validate", "validate()", "Validate every field → boolean (a Promise when async rules exist)."),
5147
+ method("validateField", "validateField(name)", "Validate one field → message | null (Promise for async rules)."),
5148
+ method("submit", "submit()", "Touch all → validate → onSubmit(values) when valid. Alias: handleSubmit()."),
5149
+ method("handleSubmit", "handleSubmit()", "Alias of submit()."),
5150
+ method("reset", "reset()", "Restore initial values; clears errors/touched/dirty.")
5151
+ ];
5152
+ const scriptResourceMembers = [
5153
+ prop("ready", "`true` once the external script / stylesheet has loaded successfully."),
5154
+ prop("loading", "`true` while the resource is still downloading."),
5155
+ prop("error", "The load error, or `null` on success."),
5156
+ prop("value", "The resolved value — `window[global]` for a script with a `global` (e.g. window.Stripe), else `true`. `null` until ready.")
5157
+ ];
5158
+ const storeResourceMembers = [
5159
+ method("undo", "undo()", "Undo the last change (`history: true|depth` stores)."),
5160
+ method("redo", "redo()", "Redo the last undone change."),
5161
+ prop("canUndo", "Reactive — `true` when an undo step is available."),
5162
+ prop("canRedo", "Reactive — `true` when a redo step is available."),
5163
+ method("clearHistory", "clearHistory()", "Drop the undo/redo stacks.")
5164
+ ];
5165
+ const factoryResourceCatalog = [
5166
+ { factory: "http", summary: "Reactive HTTP resource bag.", members: httpResourceMembers },
5167
+ { factory: "query", summary: "Cached query bag (HTTP + pagination).", members: queryResourceMembers },
5168
+ { factory: "mutation", summary: "Deferred mutation bag (fires on .mutate()).", members: mutationResourceMembers },
5169
+ { factory: "socket", summary: "Reactive WebSocket bag.", members: socketResourceMembers },
5170
+ { factory: "sse", summary: "Reactive Server-Sent Events bag.", members: sseResourceMembers },
5171
+ { factory: "script", summary: "External script / stylesheet load bag.", members: scriptResourceMembers },
5172
+ { factory: "form", summary: "Managed form engine bag.", members: formResourceMembers },
5173
+ { factory: "store", summary: "Global store handle (built-in history methods).", members: storeResourceMembers }
5174
+ ];
5175
+ Object.freeze(
5176
+ Object.fromEntries(factoryResourceCatalog.map((f) => [f.factory, f]))
5177
+ );
5178
+ const factoryResourceNames = new Set(
5179
+ factoryResourceCatalog.map((f) => f.factory)
5180
+ );
5181
+ const cfg = (name, type, summary) => ({ name, type, summary });
5182
+ const httpConfigKeys = [
5183
+ cfg("url", "string", "Absolute request URL."),
5184
+ cfg("method", 'enum: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS"', "HTTP method. Defaults to GET."),
5185
+ cfg("query", "object", "Object serialised into the URL querystring (`?k=v`)."),
5186
+ cfg("headers", "object", "Request headers as a plain object."),
5187
+ cfg("body", "object", "Request body. Objects are JSON-encoded automatically."),
5188
+ cfg("credentials", 'enum: "omit" | "same-origin" | "include"', "Fetch credentials mode."),
5189
+ cfg("mode", 'enum: "cors" | "no-cors" | "same-origin"', "Fetch request mode."),
5190
+ cfg("cache", 'enum: "default" | "no-store" | "reload" | "no-cache" | "force-cache"', "Fetch cache mode."),
5191
+ cfg("gql", "string", "GraphQL query — POSTs { query, variables }; `.data` is the unwrapped GraphQL data."),
5192
+ cfg("variables", "object", "GraphQL variables paired with `gql`.")
5193
+ ];
5194
+ [
5195
+ ...httpConfigKeys,
5196
+ cfg("key", "string", "Cache key — identical keys share one in-flight request + cached bag."),
5197
+ cfg("ttl", "number", "Milliseconds before cached data is considered stale and auto-refetched."),
5198
+ cfg("refetchInterval", "number", "Poll interval in ms (live dashboards)."),
5199
+ cfg("refetchOnFocus", "boolean", "Refetch when the tab regains focus."),
5200
+ cfg("refetchOnReconnect", "boolean", "Refetch when the network reconnects."),
5201
+ cfg("infinite", "object", "Pagination config: { param?, start?, limit?, mode?, select? } → .loadMore()/.hasMore.")
5202
+ ];
4873
5203
  const GRID_COLUMNS = 12;
4874
5204
  const FLEX_ALIGN = {
4875
5205
  start: "flex-start",
@@ -4898,15 +5228,15 @@ function applyDirectionWithReverse(value, reverse) {
4898
5228
  if (value.endsWith("-reverse")) return value;
4899
5229
  return `${value}-reverse`;
4900
5230
  }
4901
- function emitResponsiveSpacingVars(styleParts, prop, cssPrefix) {
5231
+ function emitResponsiveSpacingVars(styleParts, prop2, cssPrefix) {
4902
5232
  for (const bp of RESPONSIVE_BREAKPOINTS) {
4903
- const v = prop.values[bp];
5233
+ const v = prop2.values[bp];
4904
5234
  if (v) styleParts.push(`${cssPrefix}-${bp}:${spacingCssValue(v) || `var(--rui-spacing-${v}, ${v})`}`);
4905
5235
  }
4906
5236
  }
4907
- function emitResponsiveFlexVars(styleParts, prop, cssPrefix, mapper) {
5237
+ function emitResponsiveFlexVars(styleParts, prop2, cssPrefix, mapper) {
4908
5238
  for (const bp of RESPONSIVE_BREAKPOINTS) {
4909
- const v = prop.values[bp];
5239
+ const v = prop2.values[bp];
4910
5240
  if (v) styleParts.push(`${cssPrefix}-${bp}:${mapper(String(v))}`);
4911
5241
  }
4912
5242
  }
@@ -6672,7 +7002,7 @@ function renderMarkdown(value) {
6672
7002
  let result = s.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, (_match, alt, rawSrc) => {
6673
7003
  const src = sanitiseImageSrc(rawSrc);
6674
7004
  if (!src) return `<span class="rui-markdown-image-fallback">${alt}</span>`;
6675
- return `<img class="rui-markdown-image" src="${escapeAttr(src)}" alt="${alt}" loading="lazy">`;
7005
+ return `<img class="rui-markdown-image" src="${escapeAttr$1(src)}" alt="${alt}" loading="lazy">`;
6676
7006
  }).replace(/`([^`]+)`/g, "<code>$1</code>").replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>").replace(/\*([^*]+)\*/g, "<em>$1</em>").replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_match, label, rawHref) => {
6677
7007
  const href = sanitizeMarkdownHref(rawHref);
6678
7008
  return `<a class="rui-link" href="${href}" target="_blank" rel="noopener noreferrer">${label}</a>`;
@@ -6692,16 +7022,16 @@ function sanitizeMarkdownHref(raw) {
6692
7022
  if (!trimmed) return "#";
6693
7023
  if (trimmed.startsWith("//")) return "#";
6694
7024
  if (trimmed.startsWith("#") || trimmed.startsWith("/") || trimmed.startsWith("?")) {
6695
- return escapeAttr(trimmed);
7025
+ return escapeAttr$1(trimmed);
6696
7026
  }
6697
7027
  const schemeMatch = /^([a-zA-Z][a-zA-Z0-9+.-]*):/.exec(trimmed);
6698
- if (!schemeMatch) return escapeAttr(trimmed);
7028
+ if (!schemeMatch) return escapeAttr$1(trimmed);
6699
7029
  const scheme = schemeMatch[1].toLowerCase();
6700
7030
  const allowed = /* @__PURE__ */ new Set(["http", "https", "mailto", "tel"]);
6701
7031
  if (!allowed.has(scheme)) return "#";
6702
- return escapeAttr(trimmed);
7032
+ return escapeAttr$1(trimmed);
6703
7033
  }
6704
- function escapeAttr(value) {
7034
+ function escapeAttr$1(value) {
6705
7035
  return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/'/g, "&#39;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
6706
7036
  }
6707
7037
  function renderAvatar(src, name, size2) {
@@ -7091,8 +7421,8 @@ const OnMouse = {
7091
7421
  if (asBoolean$1(props.draggable)) wrapper.setAttribute("draggable", "true");
7092
7422
  wrapper.append(renderChildAsNode(helpers, props.child));
7093
7423
  const passive = props.passiveScroll === void 0 ? true : asBoolean$1(props.passiveScroll);
7094
- for (const { prop, event } of MOUSE_EVENT_MAP) {
7095
- const handler = props[prop];
7424
+ for (const { prop: prop2, event } of MOUSE_EVENT_MAP) {
7425
+ const handler = props[prop2];
7096
7426
  if (handler == null) continue;
7097
7427
  const isScrollEvent = event === "scroll" || event === "wheel";
7098
7428
  const options = isScrollEvent ? { passive } : {};
@@ -7122,8 +7452,8 @@ const OnKeyboard = {
7122
7452
  const focusable = props.focusable === void 0 ? true : asBoolean$1(props.focusable);
7123
7453
  const wrapper = transparentWrapper("rui-on-keyboard", focusable ? { tabindex: "0" } : {});
7124
7454
  wrapper.append(renderChildAsNode(helpers, props.child));
7125
- for (const { prop, event } of KEYBOARD_EVENT_MAP) {
7126
- const handler = props[prop];
7455
+ for (const { prop: prop2, event } of KEYBOARD_EVENT_MAP) {
7456
+ const handler = props[prop2];
7127
7457
  if (handler == null) continue;
7128
7458
  wrapper.addEventListener(event, (ev) => {
7129
7459
  helpers.invoke(handler, ev);
@@ -15574,31 +15904,33 @@ const VirtualList = {
15574
15904
  windowEl.style.right = "0";
15575
15905
  scrollEl.style.maxHeight = `${Math.min(Math.max(total, 1), 12) * itemHeight}px`;
15576
15906
  scrollEl.style.overflow = "auto";
15577
- const renderSlice = (startIndex) => {
15578
- windowEl.replaceChildren();
15579
- const viewHeight = scrollEl.clientHeight || itemHeight * 12;
15907
+ const renderSlice = (winNode, scroller) => {
15908
+ winNode.replaceChildren();
15909
+ const viewHeight = scroller.clientHeight || itemHeight * 12;
15580
15910
  const visible = Math.ceil(viewHeight / itemHeight) + 2;
15581
- const start = Math.max(0, startIndex);
15911
+ const scrollTop = Number.isFinite(scroller.scrollTop) ? scroller.scrollTop : 0;
15912
+ const start = Math.max(0, Math.floor(scrollTop / itemHeight));
15582
15913
  const end = Math.min(total, start + visible);
15583
- windowEl.style.transform = `translateY(${start * itemHeight}px)`;
15914
+ winNode.style.transform = `translateY(${start * itemHeight}px)`;
15584
15915
  for (let i = start; i < end; i++) {
15585
15916
  const entry = rawItems[i];
15586
15917
  if (props.renderItem) {
15587
- windowEl.append(helpers.renderNode(entry ?? props.renderItem));
15918
+ winNode.append(helpers.renderNode(entry ?? props.renderItem));
15588
15919
  } else if (entry && typeof entry === "object" && entry.__kind) {
15589
- windowEl.append(helpers.renderNode(entry));
15920
+ winNode.append(helpers.renderNode(entry));
15590
15921
  } else {
15591
15922
  const row = el("div", { class: "rui-virtual-list-item", style: `height:${itemHeight}px` });
15592
15923
  row.append(el("span", {}, [asString$1(entry)]));
15593
- windowEl.append(row);
15924
+ winNode.append(row);
15594
15925
  }
15595
15926
  }
15596
15927
  };
15597
- scrollEl.onscroll = () => {
15598
- const start = Math.floor(scrollEl.scrollTop / itemHeight);
15599
- renderSlice(start);
15928
+ scrollEl.onscroll = (ev) => {
15929
+ const liveScroller = ev?.currentTarget ?? ev?.target ?? scrollEl;
15930
+ const liveWindow = liveScroller.querySelector(".rui-virtual-list-window");
15931
+ if (liveWindow) renderSlice(liveWindow, liveScroller);
15600
15932
  };
15601
- renderSlice(0);
15933
+ renderSlice(windowEl, scrollEl);
15602
15934
  scrollEl.append(spacer, windowEl);
15603
15935
  viewport.append(scrollEl);
15604
15936
  return viewport;
@@ -16406,6 +16738,175 @@ const Styles = {
16406
16738
  return node;
16407
16739
  }
16408
16740
  };
16741
+ function asRecord$4(value) {
16742
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
16743
+ }
16744
+ function shallowEqual$1(a, b) {
16745
+ if (a === null) return false;
16746
+ const ak = Object.keys(a);
16747
+ const bk = Object.keys(b);
16748
+ if (ak.length !== bk.length) return false;
16749
+ for (const key of ak) {
16750
+ if (!Object.is(a[key], b[key])) return false;
16751
+ }
16752
+ return true;
16753
+ }
16754
+ function defer(run) {
16755
+ if (typeof queueMicrotask === "function") queueMicrotask(run);
16756
+ else void Promise.resolve().then(run);
16757
+ }
16758
+ const HOST_TAGS = /* @__PURE__ */ new Set([
16759
+ "div",
16760
+ "span",
16761
+ "section",
16762
+ "article",
16763
+ "aside",
16764
+ "figure",
16765
+ "canvas",
16766
+ "p",
16767
+ "pre",
16768
+ "form"
16769
+ ]);
16770
+ function resolveHostTag(input) {
16771
+ const name = asString$1(input).trim().toLowerCase();
16772
+ return HOST_TAGS.has(name) ? name : "div";
16773
+ }
16774
+ const Mount = {
16775
+ name: "Mount",
16776
+ description: "First-class host for an imperative / third-party widget that owns its own DOM (chart, map, editor, payment element, captcha, video SDK). Aktion creates the host element; `setup(node, props)` runs once after it attaches and returns an instance handle, `update(instance, props)` runs when `props` change (shallow-compared), and `cleanup(instance)` runs on unmount. The host is preserved across re-renders so the widget is never rebuilt. Apply layout with `sx`.",
16777
+ props: [
16778
+ { name: "setup", type: "callable", required: true, description: "`(node, props) => instance` — runs once after the host attaches; return value is the instance handle passed to `update`/`cleanup`." },
16779
+ { name: "update", type: "callable", optional: true, description: "`(instance, props) => void` — runs when `props` change (shallow-compared)." },
16780
+ { name: "cleanup", type: "callable", optional: true, description: "`(instance) => void` — runs when the component leaves the tree (destroy/teardown)." },
16781
+ { name: "props", type: "object", optional: true, description: "Reactive prop bag handed to `setup`/`update`. Bind `$state` here to drive the widget." },
16782
+ { name: "tag", type: "string", optional: true, enum: ["div", "span", "section", "article", "aside", "figure", "canvas", "p", "pre", "form"], description: 'Host element tag (default "div").' }
16783
+ ],
16784
+ render: (_node, props, helpers) => {
16785
+ const host = el(resolveHostTag(props.tag), {
16786
+ class: "rui-mount",
16787
+ "data-rui-preserve": ""
16788
+ });
16789
+ const widgetProps = asRecord$4(props.props);
16790
+ const slot = helpers.useInstanceState("rui-mount", {
16791
+ started: false,
16792
+ instance: void 0,
16793
+ props: widgetProps,
16794
+ prevProps: null
16795
+ });
16796
+ const state = slot.get();
16797
+ state.prevProps = state.props;
16798
+ state.props = widgetProps;
16799
+ if (!state.started) {
16800
+ state.started = true;
16801
+ defer(() => {
16802
+ try {
16803
+ state.instance = typeof props.setup === "function" ? props.setup(host, state.props) : void 0;
16804
+ } catch (err) {
16805
+ console.error("[aktion] Mount setup threw", err);
16806
+ }
16807
+ if (props.cleanup != null) {
16808
+ helpers.registerDisposer(() => {
16809
+ defer(() => {
16810
+ try {
16811
+ if (typeof props.cleanup === "function") {
16812
+ props.cleanup(state.instance);
16813
+ }
16814
+ } catch (err) {
16815
+ console.error("[aktion] Mount cleanup threw", err);
16816
+ }
16817
+ });
16818
+ }, "rui-mount-cleanup");
16819
+ }
16820
+ });
16821
+ return host;
16822
+ }
16823
+ if (state.instance !== void 0 && typeof props.update === "function" && !shallowEqual$1(state.prevProps, widgetProps)) {
16824
+ const update = props.update;
16825
+ const instance = state.instance;
16826
+ defer(() => {
16827
+ try {
16828
+ update(instance, widgetProps);
16829
+ } catch (err) {
16830
+ console.error("[aktion] Mount update threw", err);
16831
+ }
16832
+ });
16833
+ }
16834
+ return host;
16835
+ }
16836
+ };
16837
+ const CUSTOM_ELEMENT_RE = /^[a-z][a-z0-9]*(-[a-z0-9]+)+$/;
16838
+ function resolveCustomTag(input) {
16839
+ const name = asString$1(input).trim().toLowerCase();
16840
+ return CUSTOM_ELEMENT_RE.test(name) ? name : "div";
16841
+ }
16842
+ function applyAttributes(node, attributes) {
16843
+ for (const [key, value] of Object.entries(attributes)) {
16844
+ if (/^on/i.test(key)) continue;
16845
+ if (value === null || value === void 0 || value === false) {
16846
+ node.removeAttribute(key);
16847
+ continue;
16848
+ }
16849
+ node.setAttribute(key, value === true ? "" : String(value));
16850
+ }
16851
+ }
16852
+ function applyProperties(node, properties) {
16853
+ const target = node;
16854
+ for (const [key, value] of Object.entries(properties)) {
16855
+ try {
16856
+ target[key] = value;
16857
+ } catch {
16858
+ }
16859
+ }
16860
+ }
16861
+ const WebComponent = {
16862
+ name: "WebComponent",
16863
+ description: "Render and hydrate any native custom element / web component with reactive `attributes`, JS `properties`, and `on` event hooks. Use to drop a third-party web component (`<stripe-pricing-table>`, `<model-viewer>`, a design-system element) into an Aktion app. The element is preserved across re-renders; attribute changes flow through reactively and listeners stay current. Invalid (hyphen-less) tag names fall back to a `div`.",
16864
+ props: [
16865
+ { name: "tag", type: "string", positional: true, required: true, description: 'Custom-element tag name (must contain a hyphen, e.g. "stripe-pricing-table").' },
16866
+ { name: "attributes", type: "object", optional: true, aliases: ["attrs"], description: "Reactive attribute map. `$state` values update the element on change; `on*` keys are ignored." },
16867
+ { name: "properties", type: "object", optional: true, aliases: ["props"], description: "JS properties assigned on the element (for components that take rich, non-string props)." },
16868
+ { name: "on", type: "object", optional: true, aliases: ["events"], description: "Event map `{ eventName: handler }` bound once to the live element (handlers stay current across re-renders)." },
16869
+ { name: "children", type: "Node[]", optional: true, description: "Light-DOM child nodes / text to slot inside the element." }
16870
+ ],
16871
+ render: (_node, props, helpers) => {
16872
+ const tag = resolveCustomTag(props.tag);
16873
+ const node = el(tag, {
16874
+ class: "rui-web-component",
16875
+ "data-rui-preserve": ""
16876
+ });
16877
+ applyAttributes(node, asRecord$4(props.attributes));
16878
+ applyProperties(node, asRecord$4(props.properties));
16879
+ const children = Array.isArray(props.children) ? props.children : props.children != null ? [props.children] : [];
16880
+ for (const child of children) {
16881
+ if (child == null) continue;
16882
+ node.append(typeof child === "string" ? document.createTextNode(child) : helpers.renderNode(child));
16883
+ }
16884
+ const handlers = asRecord$4(props.on);
16885
+ const slot = helpers.useInstanceState("rui-web-component", {
16886
+ bound: false,
16887
+ handlers,
16888
+ node: null
16889
+ });
16890
+ const state = slot.get();
16891
+ state.handlers = handlers;
16892
+ if (!state.bound) {
16893
+ state.bound = true;
16894
+ defer(() => {
16895
+ state.node = node;
16896
+ for (const eventName of Object.keys(handlers)) {
16897
+ node.addEventListener(eventName, (event) => {
16898
+ const fn = state.handlers[eventName];
16899
+ if (typeof fn === "function") helpers.invoke(fn, event);
16900
+ });
16901
+ }
16902
+ });
16903
+ } else if (state.node) {
16904
+ applyAttributes(state.node, asRecord$4(props.attributes));
16905
+ applyProperties(state.node, asRecord$4(props.properties));
16906
+ }
16907
+ return node;
16908
+ }
16909
+ };
16409
16910
  const GradientText = {
16410
16911
  name: "GradientText",
16411
16912
  description: 'Inline text painted with a brand gradient. Use inside a Display/Heading title to emphasise a phrase: `Display(["Build in ", GradientText("record time")])`. `gradient` selects a named theme gradient (brand|accent|warm|cool|success|danger).',
@@ -16992,14 +17493,14 @@ function startBackdropEngine(canvas, helpers) {
16992
17493
  return { count, type, speed, link, size: size2, colors: colors.length > 0 ? colors : BACKDROP_PALETTE };
16993
17494
  };
16994
17495
  const seed = () => {
16995
- const cfg = readConfig();
16996
- particles = Array.from({ length: cfg.count }, (_unused, i) => ({
17496
+ const cfg2 = readConfig();
17497
+ particles = Array.from({ length: cfg2.count }, (_unused, i) => ({
16997
17498
  x: Math.random() * w,
16998
17499
  y: Math.random() * h,
16999
17500
  vx: (Math.random() - 0.5) * 0.5 * dpr,
17000
17501
  vy: (Math.random() - 0.5) * 0.5 * dpr,
17001
- r: (Math.random() * (cfg.size - 0.5) + 0.5) * dpr,
17002
- c: cfg.colors[i % cfg.colors.length],
17502
+ r: (Math.random() * (cfg2.size - 0.5) + 0.5) * dpr,
17503
+ c: cfg2.colors[i % cfg2.colors.length],
17003
17504
  phase: Math.random() * Math.PI * 2
17004
17505
  }));
17005
17506
  };
@@ -17014,8 +17515,8 @@ function startBackdropEngine(canvas, helpers) {
17014
17515
  seed();
17015
17516
  };
17016
17517
  const drawFrame = () => {
17017
- const cfg = readConfig();
17018
- const sig = `${cfg.count}|${cfg.type}|${cfg.colors.join(",")}`;
17518
+ const cfg2 = readConfig();
17519
+ const sig = `${cfg2.count}|${cfg2.type}|${cfg2.colors.join(",")}`;
17019
17520
  if (sig !== signature) {
17020
17521
  signature = sig;
17021
17522
  seed();
@@ -17024,9 +17525,9 @@ function startBackdropEngine(canvas, helpers) {
17024
17525
  if (canvas.height !== h) canvas.height = h;
17025
17526
  ctx.clearRect(0, 0, w, h);
17026
17527
  tick += 1;
17027
- const sp = cfg.speed;
17528
+ const sp = cfg2.speed;
17028
17529
  for (const p of particles) {
17029
- switch (cfg.type) {
17530
+ switch (cfg2.type) {
17030
17531
  case "drift":
17031
17532
  p.x += p.vx * 0.5 * sp;
17032
17533
  p.y += p.vy * 0.5 * sp;
@@ -17066,7 +17567,7 @@ function startBackdropEngine(canvas, helpers) {
17066
17567
  }
17067
17568
  ctx.beginPath();
17068
17569
  ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2);
17069
- if (cfg.type === "bubbles") {
17570
+ if (cfg2.type === "bubbles") {
17070
17571
  ctx.strokeStyle = p.c;
17071
17572
  ctx.lineWidth = dpr;
17072
17573
  ctx.stroke();
@@ -17078,8 +17579,8 @@ function startBackdropEngine(canvas, helpers) {
17078
17579
  ctx.fill();
17079
17580
  }
17080
17581
  }
17081
- if (cfg.type === "network") {
17082
- const link = cfg.link * dpr;
17582
+ if (cfg2.type === "network") {
17583
+ const link = cfg2.link * dpr;
17083
17584
  for (let i = 0; i < particles.length; i += 1) {
17084
17585
  for (let j = i + 1; j < particles.length; j += 1) {
17085
17586
  const a = particles[i];
@@ -17155,7 +17656,7 @@ const Backdrop = {
17155
17656
  ].filter(Boolean).join(";");
17156
17657
  root.append(el("div", { class: "rui-backdrop-blob", style }));
17157
17658
  });
17158
- const count = Math.max(0, Math.min(120, Math.round(asNumber(props.particles || 50, 0))));
17659
+ const count = Math.max(0, Math.min(120, Math.round(asNumber(props.particles, 0))));
17159
17660
  if (count > 0) {
17160
17661
  const typeRaw = asString$1(props.type, "network");
17161
17662
  const palette = asArray(props.particleColors).map((c) => safeCssColor(asString$1(c), "")).filter(Boolean).slice(0, 8);
@@ -18938,29 +19439,29 @@ function readGcalEvents(raw) {
18938
19439
  }
18939
19440
  return { chips, dots };
18940
19441
  }
18941
- function buildCalendarInto(root, year, month, cfg) {
19442
+ function buildCalendarInto(root, year, month, cfg2) {
18942
19443
  const liveRootOf = (event) => (event.currentTarget ?? event.target)?.closest(".rui-gcal") ?? root;
18943
19444
  const navigateTo = (event, y, m) => {
18944
19445
  const live = liveRootOf(event);
18945
- const prev = cfg.viewSlot.get();
18946
- cfg.viewSlot.set({
19446
+ const prev = cfg2.viewSlot.get();
19447
+ cfg2.viewSlot.set({
18947
19448
  propsYear: prev?.propsYear ?? y,
18948
19449
  propsMonth: prev?.propsMonth ?? m,
18949
19450
  year: y,
18950
19451
  month: m
18951
19452
  });
18952
- buildCalendarInto(live, y, m, cfg);
18953
- cfg.helpers.invoke(cfg.onNavigate, y, m);
19453
+ buildCalendarInto(live, y, m, cfg2);
19454
+ cfg2.helpers.invoke(cfg2.onNavigate, y, m);
18954
19455
  };
18955
19456
  const navigateBy = (event, delta) => {
18956
- const current = cfg.viewSlot.get();
19457
+ const current = cfg2.viewSlot.get();
18957
19458
  const baseYear = current?.year ?? year;
18958
19459
  const baseMonth = current?.month ?? month;
18959
19460
  const shifted = new Date(baseYear, baseMonth + delta, 1);
18960
19461
  navigateTo(event, shifted.getFullYear(), shifted.getMonth());
18961
19462
  };
18962
19463
  const toolbar = el("div", { class: "rui-gcal-toolbar" });
18963
- if (cfg.navigable) {
19464
+ if (cfg2.navigable) {
18964
19465
  const todayBtn = el("button", { type: "button", class: "rui-gcal-today" }, ["Today"]);
18965
19466
  todayBtn.onclick = (event) => {
18966
19467
  const now = /* @__PURE__ */ new Date();
@@ -18981,7 +19482,7 @@ function buildCalendarInto(root, year, month, cfg) {
18981
19482
  toolbar.append(el("span", { class: "rui-gcal-title" }, [`${MONTH_NAMES[month]} ${year}`]));
18982
19483
  const grid = el("div", { class: "rui-gcal-grid", role: "grid" });
18983
19484
  for (let i = 0; i < 7; i += 1) {
18984
- grid.append(el("div", { class: "rui-gcal-weekday", role: "columnheader" }, [WEEKDAY_LABELS[(cfg.firstDay + i) % 7]]));
19485
+ grid.append(el("div", { class: "rui-gcal-weekday", role: "columnheader" }, [WEEKDAY_LABELS[(cfg2.firstDay + i) % 7]]));
18985
19486
  }
18986
19487
  grid.onkeydown = (event) => {
18987
19488
  const key = event.key;
@@ -19004,7 +19505,7 @@ function buildCalendarInto(root, year, month, cfg) {
19004
19505
  };
19005
19506
  const firstOfMonth = new Date(year, month, 1);
19006
19507
  const daysInMonth = new Date(year, month + 1, 0).getDate();
19007
- const lead = (firstOfMonth.getDay() - cfg.firstDay + 7) % 7;
19508
+ const lead = (firstOfMonth.getDay() - cfg2.firstDay + 7) % 7;
19008
19509
  const totalCells = Math.ceil((lead + daysInMonth) / 7) * 7;
19009
19510
  const start = new Date(year, month, 1 - lead);
19010
19511
  for (let i = 0; i < totalCells; i += 1) {
@@ -19016,16 +19517,16 @@ function buildCalendarInto(root, year, month, cfg) {
19016
19517
  class: "rui-gcal-day",
19017
19518
  role: "gridcell",
19018
19519
  "data-in-month": inMonth ? "true" : "false",
19019
- "data-today": iso === cfg.todayIso ? "true" : null,
19020
- "data-selected": cfg.selected && iso === cfg.selected ? "true" : null,
19520
+ "data-today": iso === cfg2.todayIso ? "true" : null,
19521
+ "data-selected": cfg2.selected && iso === cfg2.selected ? "true" : null,
19021
19522
  "data-iso": iso,
19022
19523
  // Human-readable for screen readers ("June 10, 2026", not the ISO).
19023
19524
  "aria-label": `${MONTH_NAMES[date.getMonth()]} ${date.getDate()}, ${date.getFullYear()}`,
19024
- "aria-pressed": cfg.selected && iso === cfg.selected ? "true" : "false"
19525
+ "aria-pressed": cfg2.selected && iso === cfg2.selected ? "true" : "false"
19025
19526
  });
19026
19527
  cell.append(el("span", { class: "rui-gcal-daynum" }, [String(date.getDate())]));
19027
- const chipEvents = cfg.chips.get(iso) ?? [];
19028
- const dotCount = cfg.dots.get(iso) ?? 0;
19528
+ const chipEvents = cfg2.chips.get(iso) ?? [];
19529
+ const dotCount = cfg2.dots.get(iso) ?? 0;
19029
19530
  if (chipEvents.length > 0 || dotCount > 0) {
19030
19531
  const eventsEl = el("div", { class: "rui-gcal-events" });
19031
19532
  const visible = chipEvents.slice(0, 2);
@@ -19055,8 +19556,8 @@ function buildCalendarInto(root, year, month, cfg) {
19055
19556
  const liveCell = origin?.closest?.(".rui-gcal-day");
19056
19557
  liveCell?.setAttribute("data-selected", "true");
19057
19558
  liveCell?.setAttribute("aria-pressed", "true");
19058
- if (cfg.selRef) cfg.helpers.setState(cfg.selRef, iso);
19059
- cfg.helpers.invoke(cfg.onSelect, iso);
19559
+ if (cfg2.selRef) cfg2.helpers.setState(cfg2.selRef, iso);
19560
+ cfg2.helpers.invoke(cfg2.onSelect, iso);
19060
19561
  };
19061
19562
  grid.append(cell);
19062
19563
  }
@@ -19087,7 +19588,7 @@ const Calendar = {
19087
19588
  const view = followProps ? { propsYear, propsMonth, year: propsYear, month: propsMonth } : stored;
19088
19589
  viewSlot.set(view);
19089
19590
  const { chips, dots } = readGcalEvents(props.events);
19090
- const cfg = {
19591
+ const cfg2 = {
19091
19592
  todayIso: isoOf(now.getFullYear(), now.getMonth(), now.getDate()),
19092
19593
  selected: asString$1(props.selected),
19093
19594
  chips,
@@ -19101,7 +19602,7 @@ const Calendar = {
19101
19602
  viewSlot
19102
19603
  };
19103
19604
  const root = el("div", { class: "rui-gcal" });
19104
- buildCalendarInto(root, view.year, view.month, cfg);
19605
+ buildCalendarInto(root, view.year, view.month, cfg2);
19105
19606
  return root;
19106
19607
  }
19107
19608
  };
@@ -20115,7 +20616,10 @@ const components = [
20115
20616
  SignaturePad,
20116
20617
  // Escape hatches for raw HTML / CSS — last-resort primitives
20117
20618
  HTMLTag,
20118
- Styles
20619
+ Styles,
20620
+ // Imperative / third-party widget interop
20621
+ Mount,
20622
+ WebComponent
20119
20623
  ];
20120
20624
  const componentGroups = [
20121
20625
  {
@@ -20512,6 +21016,16 @@ const componentGroups = [
20512
21016
  "- `Link(label_or_child, { to?, href?, external?, variant? })` is the anchor primitive — accepts either a plain string label or a wrapped component. Use `to` for client-side router navigation and `href` (with `external: true`) for outbound links."
20513
21017
  ]
20514
21018
  },
21019
+ {
21020
+ name: "Interop",
21021
+ components: ["Mount", "WebComponent"],
21022
+ notes: [
21023
+ "- Interop primitives are the bridge to imperative / third-party libraries that own their own DOM. Reach for them ONLY when a real widget (chart, map, editor, payment element, captcha) cannot be expressed with built-in components.",
21024
+ '- `Mount({ setup, update?, cleanup?, props?, tag?, sx? })` is the managed imperative-component host. `setup(node, props)` runs once after the host attaches and returns an instance handle; `update(instance, props)` runs when the (shallow-compared) `props` bag changes; `cleanup(instance)` runs on unmount. Aktion owns + preserves the host element so the widget is never rebuilt mid-session. Example: `Mount({ sx: { h: "320px" }, setup: (node, p) => new Chart(node, p.config), update: (c, p) => { c.data = p.data; c.update() }, cleanup: c => c.destroy(), props: { config: $cfg, data: $series } })`.',
21025
+ '- `WebComponent(tag, { attributes?, properties?, on?, children? })` renders + hydrates a native custom element. `attributes` is reactive (re-applies on `$state` change); `properties` assigns rich JS props; `on` binds event listeners that stay current across renders. Example: `WebComponent("stripe-pricing-table", { attributes: { "pricing-table-id": $id, "publishable-key": $pk }, on: { checkout: e => route.navigate("/thanks") } })`.',
21026
+ "- Pair these with the `$script({ src, global? })` loader (gate a widget on its SDK being ready) and the `$dom` observer namespace (`$dom.onResize`/`onIntersect`/`measure`) for layout-aware widgets."
21027
+ ]
21028
+ },
20515
21029
  {
20516
21030
  name: "Escape hatches",
20517
21031
  components: ["HTMLTag", "Styles"],
@@ -20528,6 +21042,8 @@ const defaultLibrary = {
20528
21042
  components,
20529
21043
  componentGroups
20530
21044
  };
21045
+ [...factoryResourceNames].join("|");
21046
+ [...factoryResourceNames].join("|");
20531
21047
  const isThemeNode = (value) => {
20532
21048
  return Boolean(
20533
21049
  value && typeof value === "object" && value.kind === "Theme"
@@ -20908,21 +21424,21 @@ function invalidateQueries(ctx, keys) {
20908
21424
  }
20909
21425
  }
20910
21426
  function buildRequestFromConfig(config) {
20911
- const cfg = config && typeof config === "object" && !Array.isArray(config) ? config : {};
20912
- const url = typeof cfg.url === "string" ? cfg.url : "";
20913
- const isGraphQL = typeof cfg.gql === "string" && cfg.gql.trim().length > 0;
20914
- const method = isGraphQL ? "POST" : typeof cfg.method === "string" ? cfg.method.toUpperCase() : "GET";
21427
+ const cfg2 = config && typeof config === "object" && !Array.isArray(config) ? config : {};
21428
+ const url = typeof cfg2.url === "string" ? cfg2.url : "";
21429
+ const isGraphQL = typeof cfg2.gql === "string" && cfg2.gql.trim().length > 0;
21430
+ const method2 = isGraphQL ? "POST" : typeof cfg2.method === "string" ? cfg2.method.toUpperCase() : "GET";
20915
21431
  const headers = {};
20916
- if (cfg.headers && typeof cfg.headers === "object" && !Array.isArray(cfg.headers)) {
20917
- for (const [k, v] of Object.entries(cfg.headers)) {
21432
+ if (cfg2.headers && typeof cfg2.headers === "object" && !Array.isArray(cfg2.headers)) {
21433
+ for (const [k, v] of Object.entries(cfg2.headers)) {
20918
21434
  if (v == null) continue;
20919
21435
  headers[k] = String(v);
20920
21436
  }
20921
21437
  }
20922
21438
  let finalUrl = url;
20923
- if (cfg.query && typeof cfg.query === "object" && !Array.isArray(cfg.query)) {
21439
+ if (cfg2.query && typeof cfg2.query === "object" && !Array.isArray(cfg2.query)) {
20924
21440
  const params = new URLSearchParams();
20925
- for (const [k, v] of Object.entries(cfg.query)) {
21441
+ for (const [k, v] of Object.entries(cfg2.query)) {
20926
21442
  if (v == null) continue;
20927
21443
  params.append(k, String(v));
20928
21444
  }
@@ -20930,18 +21446,18 @@ function buildRequestFromConfig(config) {
20930
21446
  if (qs) finalUrl += (finalUrl.includes("?") ? "&" : "?") + qs;
20931
21447
  }
20932
21448
  const init = {};
20933
- for (const [k, v] of Object.entries(cfg)) {
21449
+ for (const [k, v] of Object.entries(cfg2)) {
20934
21450
  if (RESERVED_CONFIG_KEYS.has(k)) continue;
20935
21451
  init[k] = v;
20936
21452
  }
20937
21453
  const req = {
20938
21454
  url: finalUrl,
20939
- method,
21455
+ method: method2,
20940
21456
  headers,
20941
- body: isGraphQL ? { query: cfg.gql, variables: asRecord$1(cfg.variables) } : cfg.body
21457
+ body: isGraphQL ? { query: cfg2.gql, variables: asRecord$3(cfg2.variables) } : cfg2.body
20942
21458
  };
20943
21459
  if (Object.keys(init).length > 0) req.init = init;
20944
- if (cfg.signal instanceof AbortSignal) req.signal = cfg.signal;
21460
+ if (cfg2.signal instanceof AbortSignal) req.signal = cfg2.signal;
20945
21461
  return req;
20946
21462
  }
20947
21463
  function createHttpResource(config, ctx) {
@@ -20994,8 +21510,8 @@ function createHttpResource(config, ctx) {
20994
21510
  const response = await ctx.http.request(req);
20995
21511
  if (runId !== generation) return;
20996
21512
  const ok = response.status >= 200 && response.status < 300;
20997
- const isGraphQL = typeof asRecord$1(config).gql === "string";
20998
- const gqlBody = isGraphQL ? asRecord$1(response.body) : null;
21513
+ const isGraphQL = typeof asRecord$3(config).gql === "string";
21514
+ const gqlBody = isGraphQL ? asRecord$3(response.body) : null;
20999
21515
  const gqlErrors = gqlBody && Array.isArray(gqlBody.errors) && gqlBody.errors.length > 0 ? gqlBody.errors : null;
21000
21516
  if (ok && !gqlErrors) {
21001
21517
  resource.data = isGraphQL ? gqlBody.data : response.body;
@@ -21030,48 +21546,48 @@ function createHttpResource(config, ctx) {
21030
21546
  void run();
21031
21547
  return resource;
21032
21548
  }
21033
- function asRecord$1(value) {
21549
+ function asRecord$3(value) {
21034
21550
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
21035
21551
  }
21036
21552
  function asBoolean(value) {
21037
21553
  return value === true || value === "true";
21038
21554
  }
21039
- function deriveQueryKey(cfg) {
21040
- const method = typeof cfg.method === "string" ? cfg.method.toUpperCase() : "GET";
21041
- const url = typeof cfg.url === "string" ? cfg.url : "";
21555
+ function deriveQueryKey(cfg2) {
21556
+ const method2 = typeof cfg2.method === "string" ? cfg2.method.toUpperCase() : "GET";
21557
+ const url = typeof cfg2.url === "string" ? cfg2.url : "";
21042
21558
  let q = "null";
21043
21559
  let b = "null";
21044
21560
  try {
21045
- q = JSON.stringify(cfg.query ?? null);
21561
+ q = JSON.stringify(cfg2.query ?? null);
21046
21562
  } catch {
21047
21563
  }
21048
21564
  try {
21049
- b = JSON.stringify(cfg.body ?? null);
21565
+ b = JSON.stringify(cfg2.body ?? null);
21050
21566
  } catch {
21051
21567
  }
21052
21568
  let g = "null";
21053
- if (typeof cfg.gql === "string") {
21569
+ if (typeof cfg2.gql === "string") {
21054
21570
  let v = "null";
21055
21571
  try {
21056
- v = JSON.stringify(cfg.variables ?? null);
21572
+ v = JSON.stringify(cfg2.variables ?? null);
21057
21573
  } catch {
21058
21574
  }
21059
- g = `${cfg.gql}|${v}`;
21575
+ g = `${cfg2.gql}|${v}`;
21060
21576
  }
21061
- return `${method} ${url} ${q} ${b} ${g}`;
21577
+ return `${method2} ${url} ${q} ${b} ${g}`;
21062
21578
  }
21063
21579
  function createQueryResource(config, ctx) {
21064
- const cfg = asRecord$1(config);
21065
- if (cfg.infinite && typeof cfg.infinite === "object") {
21066
- const key2 = cfg.key != null ? String(cfg.key) : deriveQueryKey(cfg);
21580
+ const cfg2 = asRecord$3(config);
21581
+ if (cfg2.infinite && typeof cfg2.infinite === "object") {
21582
+ const key2 = cfg2.key != null ? String(cfg2.key) : deriveQueryKey(cfg2);
21067
21583
  const cached = ctx.queryCache.get(key2);
21068
21584
  if (cached) return cached;
21069
- const resource2 = createInfiniteQueryResource(cfg, ctx);
21585
+ const resource2 = createInfiniteQueryResource(cfg2, ctx);
21070
21586
  ctx.queryCache.set(key2, resource2);
21071
21587
  return resource2;
21072
21588
  }
21073
- const ttl = typeof cfg.ttl === "number" ? cfg.ttl : 0;
21074
- const key = cfg.key != null ? String(cfg.key) : deriveQueryKey(cfg);
21589
+ const ttl = typeof cfg2.ttl === "number" ? cfg2.ttl : 0;
21590
+ const key = cfg2.key != null ? String(cfg2.key) : deriveQueryKey(cfg2);
21075
21591
  const cache = ctx.queryCache;
21076
21592
  const existing = cache.get(key);
21077
21593
  if (existing) {
@@ -21081,27 +21597,27 @@ function createQueryResource(config, ctx) {
21081
21597
  return existing;
21082
21598
  }
21083
21599
  const httpConfig = {};
21084
- for (const [k, v] of Object.entries(cfg)) {
21600
+ for (const [k, v] of Object.entries(cfg2)) {
21085
21601
  if (k === "key" || k === "ttl" || k === "refetchInterval" || k === "refetchOnFocus" || k === "refetchOnReconnect") continue;
21086
21602
  httpConfig[k] = v;
21087
21603
  }
21088
21604
  const resource = createHttpResource(httpConfig, ctx);
21089
21605
  cache.set(key, resource);
21090
- const interval = typeof cfg.refetchInterval === "number" ? cfg.refetchInterval : 0;
21606
+ const interval = typeof cfg2.refetchInterval === "number" ? cfg2.refetchInterval : 0;
21091
21607
  if (interval > 0) {
21092
21608
  const id = setInterval(() => {
21093
21609
  if (!resource.loading) void resource.refetch();
21094
21610
  }, Math.max(250, interval));
21095
21611
  ctx.disposers.push(() => clearInterval(id));
21096
21612
  }
21097
- if (asBoolean(cfg.refetchOnFocus) && typeof window !== "undefined") {
21613
+ if (asBoolean(cfg2.refetchOnFocus) && typeof window !== "undefined") {
21098
21614
  const onFocus = () => {
21099
21615
  if (!resource.loading) void resource.refetch();
21100
21616
  };
21101
21617
  window.addEventListener("focus", onFocus);
21102
21618
  ctx.disposers.push(() => window.removeEventListener("focus", onFocus));
21103
21619
  }
21104
- if (asBoolean(cfg.refetchOnReconnect) && typeof window !== "undefined") {
21620
+ if (asBoolean(cfg2.refetchOnReconnect) && typeof window !== "undefined") {
21105
21621
  const onOnline = () => {
21106
21622
  if (!resource.loading) void resource.refetch();
21107
21623
  };
@@ -21110,8 +21626,8 @@ function createQueryResource(config, ctx) {
21110
21626
  }
21111
21627
  return resource;
21112
21628
  }
21113
- function createInfiniteQueryResource(cfg, ctx) {
21114
- const opts = asRecord$1(cfg.infinite);
21629
+ function createInfiniteQueryResource(cfg2, ctx) {
21630
+ const opts = asRecord$3(cfg2.infinite);
21115
21631
  const param = typeof opts.param === "string" ? opts.param : "page";
21116
21632
  const limit = typeof opts.limit === "number" && opts.limit > 0 ? opts.limit : 20;
21117
21633
  const start = typeof opts.start === "number" ? opts.start : opts.mode === "offset" ? 0 : 1;
@@ -21122,7 +21638,7 @@ function createInfiniteQueryResource(cfg, ctx) {
21122
21638
  let pageIndex = start;
21123
21639
  let inFlight = false;
21124
21640
  const baseConfig = {};
21125
- for (const [k, v] of Object.entries(cfg)) {
21641
+ for (const [k, v] of Object.entries(cfg2)) {
21126
21642
  if (k === "key" || k === "ttl" || k === "infinite") continue;
21127
21643
  baseConfig[k] = v;
21128
21644
  }
@@ -21179,7 +21695,7 @@ function createInfiniteQueryResource(cfg, ctx) {
21179
21695
  const pageValue = pageIndex;
21180
21696
  const merged = {
21181
21697
  ...baseConfig,
21182
- query: { ...asRecord$1(baseConfig.query), [param]: pageValue, limit }
21698
+ query: { ...asRecord$3(baseConfig.query), [param]: pageValue, limit }
21183
21699
  };
21184
21700
  const req = buildRequestFromConfig(merged);
21185
21701
  req.url = ctx.http.resolveUrl(req.url);
@@ -21214,7 +21730,7 @@ function createInfiniteQueryResource(cfg, ctx) {
21214
21730
  return resource;
21215
21731
  }
21216
21732
  function createMutationResource(baseConfig, ctx) {
21217
- const base = asRecord$1(baseConfig);
21733
+ const base = asRecord$3(baseConfig);
21218
21734
  let generation = 0;
21219
21735
  let controller = null;
21220
21736
  const notify = () => ctx.notify?.();
@@ -21252,7 +21768,7 @@ function createMutationResource(baseConfig, ctx) {
21252
21768
  ctx.notify?.();
21253
21769
  };
21254
21770
  try {
21255
- optimistic(asRecord$1(overrides));
21771
+ optimistic(asRecord$3(overrides));
21256
21772
  } catch {
21257
21773
  }
21258
21774
  }
@@ -21265,7 +21781,7 @@ function createMutationResource(baseConfig, ctx) {
21265
21781
  return void 0;
21266
21782
  }
21267
21783
  try {
21268
- const merged = { method: "POST", ...base, ...asRecord$1(overrides) };
21784
+ const merged = { method: "POST", ...base, ...asRecord$3(overrides) };
21269
21785
  const req = buildRequestFromConfig(merged);
21270
21786
  req.url = ctx.http.resolveUrl(req.url);
21271
21787
  req.signal = localController.signal;
@@ -21310,7 +21826,7 @@ function createMutationResource(baseConfig, ctx) {
21310
21826
  });
21311
21827
  return resource;
21312
21828
  }
21313
- function asRecord(value) {
21829
+ function asRecord$2(value) {
21314
21830
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
21315
21831
  }
21316
21832
  function parseMaybeJson(raw) {
@@ -21325,11 +21841,11 @@ const SEND_QUEUE_LIMIT = 100;
21325
21841
  const RECONNECT_BASE_MS = 500;
21326
21842
  const RECONNECT_MAX_MS = 15e3;
21327
21843
  function createSocketResource(config, ctx) {
21328
- const cfg = asRecord(config);
21329
- const url = typeof cfg.url === "string" ? cfg.url : "";
21330
- const bufferSize = typeof cfg.bufferSize === "number" && cfg.bufferSize > 0 ? Math.floor(cfg.bufferSize) : 50;
21331
- const onMessage = typeof cfg.onMessage === "function" ? cfg.onMessage : null;
21332
- const maxAttempts = cfg.reconnect === true ? Infinity : typeof cfg.reconnect === "number" && cfg.reconnect > 0 ? Math.floor(cfg.reconnect) : 0;
21844
+ const cfg2 = asRecord$2(config);
21845
+ const url = typeof cfg2.url === "string" ? cfg2.url : "";
21846
+ const bufferSize = typeof cfg2.bufferSize === "number" && cfg2.bufferSize > 0 ? Math.floor(cfg2.bufferSize) : 50;
21847
+ const onMessage = typeof cfg2.onMessage === "function" ? cfg2.onMessage : null;
21848
+ const maxAttempts = cfg2.reconnect === true ? Infinity : typeof cfg2.reconnect === "number" && cfg2.reconnect > 0 ? Math.floor(cfg2.reconnect) : 0;
21333
21849
  const notify = () => ctx.notify?.();
21334
21850
  const resource = {
21335
21851
  connected: false,
@@ -21378,7 +21894,7 @@ function createSocketResource(config, ctx) {
21378
21894
  const connect = () => {
21379
21895
  let socket;
21380
21896
  try {
21381
- socket = cfg.protocols != null ? new WebSocket(url, cfg.protocols) : new WebSocket(url);
21897
+ socket = cfg2.protocols != null ? new WebSocket(url, cfg2.protocols) : new WebSocket(url);
21382
21898
  } catch (err) {
21383
21899
  resource.error = err;
21384
21900
  setStatus("closed");
@@ -21453,11 +21969,11 @@ function createSocketResource(config, ctx) {
21453
21969
  return resource;
21454
21970
  }
21455
21971
  function createSseResource(config, ctx) {
21456
- const cfg = asRecord(config);
21457
- const url = typeof cfg.url === "string" ? cfg.url : "";
21458
- const bufferSize = typeof cfg.bufferSize === "number" && cfg.bufferSize > 0 ? Math.floor(cfg.bufferSize) : 50;
21459
- const eventName = typeof cfg.event === "string" && cfg.event ? cfg.event : "message";
21460
- const onMessage = typeof cfg.onMessage === "function" ? cfg.onMessage : null;
21972
+ const cfg2 = asRecord$2(config);
21973
+ const url = typeof cfg2.url === "string" ? cfg2.url : "";
21974
+ const bufferSize = typeof cfg2.bufferSize === "number" && cfg2.bufferSize > 0 ? Math.floor(cfg2.bufferSize) : 50;
21975
+ const eventName = typeof cfg2.event === "string" && cfg2.event ? cfg2.event : "message";
21976
+ const onMessage = typeof cfg2.onMessage === "function" ? cfg2.onMessage : null;
21461
21977
  const notify = () => ctx.notify?.();
21462
21978
  const resource = {
21463
21979
  connected: false,
@@ -21474,7 +21990,7 @@ function createSseResource(config, ctx) {
21474
21990
  }
21475
21991
  let source = null;
21476
21992
  try {
21477
- source = new EventSource(url, { withCredentials: cfg.withCredentials === true });
21993
+ source = new EventSource(url, { withCredentials: cfg2.withCredentials === true });
21478
21994
  } catch (err) {
21479
21995
  resource.error = err;
21480
21996
  return resource;
@@ -21522,6 +22038,415 @@ function createSseResource(config, ctx) {
21522
22038
  });
21523
22039
  return resource;
21524
22040
  }
22041
+ function asRecord$1(value) {
22042
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
22043
+ }
22044
+ const scriptLoads = /* @__PURE__ */ new Map();
22045
+ function looksLikeStylesheet(src, as) {
22046
+ if (as === "style" || as === "stylesheet" || as === "css") return true;
22047
+ return /\.css(\?|#|$)/i.test(src);
22048
+ }
22049
+ function loadStylesheet(src, attributes) {
22050
+ return new Promise((resolve, reject) => {
22051
+ const link = document.createElement("link");
22052
+ link.rel = "stylesheet";
22053
+ link.href = src;
22054
+ for (const [key, val] of Object.entries(attributes)) {
22055
+ if (val == null || /^on/i.test(key)) continue;
22056
+ link.setAttribute(key, val === true ? "" : String(val));
22057
+ }
22058
+ link.addEventListener("load", () => resolve(true));
22059
+ link.addEventListener("error", () => reject(new Error(`[aktion] $script failed to load stylesheet: ${src}`)));
22060
+ document.head.appendChild(link);
22061
+ });
22062
+ }
22063
+ function loadScript(src, config) {
22064
+ return new Promise((resolve, reject) => {
22065
+ const readValue = () => {
22066
+ if (!config.global) return true;
22067
+ const w = globalThis;
22068
+ return w[config.global] ?? true;
22069
+ };
22070
+ const script = document.createElement("script");
22071
+ script.src = src;
22072
+ script.async = true;
22073
+ if (config.type) script.type = config.type;
22074
+ for (const [key, val] of Object.entries(config.attributes)) {
22075
+ if (val == null || /^on/i.test(key)) continue;
22076
+ script.setAttribute(key, val === true ? "" : String(val));
22077
+ }
22078
+ script.addEventListener("load", () => resolve(readValue()));
22079
+ script.addEventListener("error", () => reject(new Error(`[aktion] $script failed to load: ${src}`)));
22080
+ document.head.appendChild(script);
22081
+ });
22082
+ }
22083
+ function createScriptResource(config, ctx) {
22084
+ const cfg2 = asRecord$1(config);
22085
+ const src = typeof cfg2.src === "string" ? cfg2.src : "";
22086
+ const global = typeof cfg2.global === "string" ? cfg2.global : void 0;
22087
+ const type = typeof cfg2.type === "string" ? cfg2.type : void 0;
22088
+ const as = typeof cfg2.as === "string" ? cfg2.as.toLowerCase() : "";
22089
+ const attributes = asRecord$1(cfg2.attributes);
22090
+ const notify = () => ctx.notify?.();
22091
+ const resource = { ready: false, loading: false, error: null, value: null };
22092
+ if (!src) {
22093
+ resource.error = new Error("[aktion] $script requires a `src`.");
22094
+ return resource;
22095
+ }
22096
+ if (typeof document === "undefined" || typeof document.createElement !== "function") {
22097
+ return resource;
22098
+ }
22099
+ let load = scriptLoads.get(src);
22100
+ if (!load) {
22101
+ const promise = looksLikeStylesheet(src, as) ? loadStylesheet(src, attributes) : loadScript(src, { global, type, attributes });
22102
+ load = { promise, settled: false, value: null, error: null };
22103
+ promise.then(
22104
+ (value) => {
22105
+ load.settled = true;
22106
+ load.value = value;
22107
+ },
22108
+ (error) => {
22109
+ load.settled = true;
22110
+ load.error = error;
22111
+ }
22112
+ );
22113
+ scriptLoads.set(src, load);
22114
+ }
22115
+ if (load.settled) {
22116
+ if (load.error != null) {
22117
+ resource.error = load.error;
22118
+ } else {
22119
+ resource.ready = true;
22120
+ resource.value = global ? globalThis[global] ?? load.value : load.value;
22121
+ }
22122
+ return resource;
22123
+ }
22124
+ resource.loading = true;
22125
+ let live = true;
22126
+ load.promise.then(
22127
+ (value) => {
22128
+ if (!live) return;
22129
+ resource.loading = false;
22130
+ resource.ready = true;
22131
+ resource.value = global ? globalThis[global] ?? value : value;
22132
+ notify();
22133
+ },
22134
+ (error) => {
22135
+ if (!live) return;
22136
+ resource.loading = false;
22137
+ resource.error = error;
22138
+ notify();
22139
+ }
22140
+ );
22141
+ ctx.disposers.push(() => {
22142
+ live = false;
22143
+ });
22144
+ return resource;
22145
+ }
22146
+ const noopDisposer = () => {
22147
+ };
22148
+ function asElement(node) {
22149
+ return node instanceof Element ? node : null;
22150
+ }
22151
+ function asCallback(callback) {
22152
+ return typeof callback === "function" ? callback : null;
22153
+ }
22154
+ function createDomManager(ctx) {
22155
+ const notify = () => ctx.notify?.();
22156
+ const track = (stop) => {
22157
+ let done = false;
22158
+ const dispose = () => {
22159
+ if (done) return;
22160
+ done = true;
22161
+ try {
22162
+ stop();
22163
+ } catch {
22164
+ }
22165
+ };
22166
+ ctx.disposers.push(dispose);
22167
+ return dispose;
22168
+ };
22169
+ return {
22170
+ onResize(node, callback) {
22171
+ const el2 = asElement(node);
22172
+ const cb = asCallback(callback);
22173
+ if (!el2 || !cb || typeof ResizeObserver === "undefined") return noopDisposer;
22174
+ const observer = new ResizeObserver((entries) => {
22175
+ for (const entry of entries) {
22176
+ const box = entry.contentRect;
22177
+ try {
22178
+ cb({ width: box.width, height: box.height, entry });
22179
+ } catch {
22180
+ }
22181
+ }
22182
+ notify();
22183
+ });
22184
+ observer.observe(el2);
22185
+ return track(() => observer.disconnect());
22186
+ },
22187
+ onIntersect(node, callback, options) {
22188
+ const el2 = asElement(node);
22189
+ const cb = asCallback(callback);
22190
+ if (!el2 || !cb || typeof IntersectionObserver === "undefined") return noopDisposer;
22191
+ const observer = new IntersectionObserver((entries) => {
22192
+ for (const entry of entries) {
22193
+ try {
22194
+ cb(entry);
22195
+ } catch {
22196
+ }
22197
+ }
22198
+ notify();
22199
+ }, asRecord$1(options));
22200
+ observer.observe(el2);
22201
+ return track(() => observer.disconnect());
22202
+ },
22203
+ onMutation(node, callback, options) {
22204
+ const el2 = asElement(node);
22205
+ const cb = asCallback(callback);
22206
+ if (!el2 || !cb || typeof MutationObserver === "undefined") return noopDisposer;
22207
+ const opts = asRecord$1(options);
22208
+ const observer = new MutationObserver((mutations) => {
22209
+ try {
22210
+ cb(mutations);
22211
+ } catch {
22212
+ }
22213
+ notify();
22214
+ });
22215
+ observer.observe(el2, {
22216
+ childList: opts.childList !== false,
22217
+ attributes: opts.attributes !== false,
22218
+ subtree: opts.subtree === true,
22219
+ characterData: opts.characterData === true
22220
+ });
22221
+ return track(() => observer.disconnect());
22222
+ },
22223
+ measure(node) {
22224
+ const el2 = asElement(node);
22225
+ if (!el2) return null;
22226
+ const rect = typeof el2.getBoundingClientRect === "function" ? el2.getBoundingClientRect() : { width: 0, height: 0, top: 0, left: 0, right: 0, bottom: 0 };
22227
+ const html = el2;
22228
+ return {
22229
+ rect,
22230
+ scroll: {
22231
+ top: html.scrollTop ?? 0,
22232
+ left: html.scrollLeft ?? 0,
22233
+ width: html.scrollWidth ?? 0,
22234
+ height: html.scrollHeight ?? 0
22235
+ },
22236
+ viewport: {
22237
+ width: typeof window !== "undefined" ? window.innerWidth : 0,
22238
+ height: typeof window !== "undefined" ? window.innerHeight : 0
22239
+ }
22240
+ };
22241
+ }
22242
+ };
22243
+ }
22244
+ function asRecord(value) {
22245
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
22246
+ }
22247
+ function escapeAttr(value) {
22248
+ return String(value ?? "").replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
22249
+ }
22250
+ function escapeText(value) {
22251
+ return String(value ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
22252
+ }
22253
+ function resolveConfig(config) {
22254
+ const cfg2 = asRecord(config);
22255
+ const out = { meta: {}, og: {}, twitter: {}, link: [], jsonLd: [], htmlAttrs: {} };
22256
+ if (typeof cfg2.title === "string") {
22257
+ const template = typeof cfg2.titleTemplate === "string" ? cfg2.titleTemplate : "";
22258
+ out.title = template ? template.replace("%s", cfg2.title) : cfg2.title;
22259
+ }
22260
+ const meta = asRecord(cfg2.meta);
22261
+ for (const [k, v] of Object.entries(meta)) {
22262
+ if (v != null) out.meta[k] = String(v);
22263
+ }
22264
+ const og = asRecord(cfg2.og);
22265
+ for (const [k, v] of Object.entries(og)) {
22266
+ if (v != null) out.og[k] = String(v);
22267
+ }
22268
+ const twitter = asRecord(cfg2.twitter);
22269
+ for (const [k, v] of Object.entries(twitter)) {
22270
+ if (v != null) out.twitter[k] = String(v);
22271
+ }
22272
+ const links = Array.isArray(cfg2.link) ? cfg2.link : cfg2.link != null ? [cfg2.link] : [];
22273
+ for (const entry of links) {
22274
+ const rec = asRecord(entry);
22275
+ const link = {};
22276
+ for (const [k, v] of Object.entries(rec)) {
22277
+ if (v != null) link[k] = String(v);
22278
+ }
22279
+ if (Object.keys(link).length > 0) out.link.push(link);
22280
+ }
22281
+ if (cfg2.jsonLd != null) {
22282
+ const entries = Array.isArray(cfg2.jsonLd) ? cfg2.jsonLd : [cfg2.jsonLd];
22283
+ for (const entry of entries) {
22284
+ if (entry && typeof entry === "object") {
22285
+ const obj = entry;
22286
+ out.jsonLd.push("@context" in obj ? obj : { "@context": "https://schema.org", ...obj });
22287
+ }
22288
+ }
22289
+ }
22290
+ if (typeof cfg2.base === "string") out.base = cfg2.base;
22291
+ else if (cfg2.base && typeof cfg2.base === "object") {
22292
+ const href = cfg2.base.href;
22293
+ if (typeof href === "string") out.base = href;
22294
+ }
22295
+ const htmlAttrs = asRecord(cfg2.htmlAttrs);
22296
+ for (const [k, v] of Object.entries(htmlAttrs)) {
22297
+ if (v != null) out.htmlAttrs[k] = String(v);
22298
+ }
22299
+ return out;
22300
+ }
22301
+ function mergeDirectives(list) {
22302
+ const merged = { meta: {}, og: {}, twitter: {}, link: [], jsonLd: [], htmlAttrs: {} };
22303
+ const linkSeen = /* @__PURE__ */ new Set();
22304
+ for (const d of list) {
22305
+ if (d.title != null) merged.title = d.title;
22306
+ Object.assign(merged.meta, d.meta);
22307
+ Object.assign(merged.og, d.og);
22308
+ Object.assign(merged.twitter, d.twitter);
22309
+ Object.assign(merged.htmlAttrs, d.htmlAttrs);
22310
+ if (d.base != null) merged.base = d.base;
22311
+ for (const link of d.link) {
22312
+ const id = `${link.rel ?? ""}|${link.href ?? ""}|${link.hreflang ?? ""}`;
22313
+ if (linkSeen.has(id)) continue;
22314
+ linkSeen.add(id);
22315
+ merged.link.push(link);
22316
+ }
22317
+ for (const entry of d.jsonLd) merged.jsonLd.push(entry);
22318
+ }
22319
+ return merged;
22320
+ }
22321
+ function serializeDirective(head) {
22322
+ const parts = [];
22323
+ if (head.title != null) parts.push(`<title>${escapeText(head.title)}</title>`);
22324
+ for (const [name, content] of Object.entries(head.meta)) {
22325
+ if (name.toLowerCase() === "charset") parts.push(`<meta charset="${escapeAttr(content)}">`);
22326
+ else parts.push(`<meta name="${escapeAttr(name)}" content="${escapeAttr(content)}">`);
22327
+ }
22328
+ for (const [key, content] of Object.entries(head.og)) {
22329
+ const property = key.startsWith("og:") ? key : `og:${key}`;
22330
+ parts.push(`<meta property="${escapeAttr(property)}" content="${escapeAttr(content)}">`);
22331
+ }
22332
+ for (const [key, content] of Object.entries(head.twitter)) {
22333
+ const name = key.startsWith("twitter:") ? key : `twitter:${key}`;
22334
+ parts.push(`<meta name="${escapeAttr(name)}" content="${escapeAttr(content)}">`);
22335
+ }
22336
+ if (head.base) parts.push(`<base href="${escapeAttr(head.base)}">`);
22337
+ for (const link of head.link) {
22338
+ const attrs = Object.entries(link).map(([k, v]) => `${escapeAttr(k)}="${escapeAttr(v)}"`).join(" ");
22339
+ parts.push(`<link ${attrs}>`);
22340
+ }
22341
+ for (const entry of head.jsonLd) {
22342
+ let json2 = "";
22343
+ try {
22344
+ json2 = JSON.stringify(entry);
22345
+ } catch {
22346
+ json2 = "";
22347
+ }
22348
+ if (json2) parts.push(`<script type="application/ld+json">${json2.replace(/</g, "\\u003c")}<\/script>`);
22349
+ }
22350
+ return parts.join("\n");
22351
+ }
22352
+ const MANAGED_ATTR = "data-rui-head";
22353
+ function applyToDom(head) {
22354
+ if (typeof document === "undefined") return;
22355
+ if (head.title != null) document.title = head.title;
22356
+ const root = document.documentElement;
22357
+ if (root) {
22358
+ for (const [k, v] of Object.entries(head.htmlAttrs)) {
22359
+ if (/^on/i.test(k)) continue;
22360
+ root.setAttribute(k, v);
22361
+ }
22362
+ }
22363
+ const headEl = document.head;
22364
+ if (!headEl) return;
22365
+ headEl.querySelectorAll(`[${MANAGED_ATTR}]`).forEach((el2) => el2.remove());
22366
+ const add = (el2) => {
22367
+ el2.setAttribute(MANAGED_ATTR, "");
22368
+ headEl.appendChild(el2);
22369
+ };
22370
+ for (const [name, content] of Object.entries(head.meta)) {
22371
+ const el2 = document.createElement("meta");
22372
+ if (name.toLowerCase() === "charset") el2.setAttribute("charset", content);
22373
+ else {
22374
+ el2.setAttribute("name", name);
22375
+ el2.setAttribute("content", content);
22376
+ }
22377
+ add(el2);
22378
+ }
22379
+ for (const [key, content] of Object.entries(head.og)) {
22380
+ const el2 = document.createElement("meta");
22381
+ el2.setAttribute("property", key.startsWith("og:") ? key : `og:${key}`);
22382
+ el2.setAttribute("content", content);
22383
+ add(el2);
22384
+ }
22385
+ for (const [key, content] of Object.entries(head.twitter)) {
22386
+ const el2 = document.createElement("meta");
22387
+ el2.setAttribute("name", key.startsWith("twitter:") ? key : `twitter:${key}`);
22388
+ el2.setAttribute("content", content);
22389
+ add(el2);
22390
+ }
22391
+ if (head.base) {
22392
+ const el2 = document.createElement("base");
22393
+ el2.setAttribute("href", head.base);
22394
+ add(el2);
22395
+ }
22396
+ for (const link of head.link) {
22397
+ const el2 = document.createElement("link");
22398
+ for (const [k, v] of Object.entries(link)) {
22399
+ if (/^on/i.test(k)) continue;
22400
+ el2.setAttribute(k, v);
22401
+ }
22402
+ add(el2);
22403
+ }
22404
+ for (const entry of head.jsonLd) {
22405
+ const el2 = document.createElement("script");
22406
+ el2.setAttribute("type", "application/ld+json");
22407
+ try {
22408
+ el2.textContent = JSON.stringify(entry);
22409
+ } catch {
22410
+ }
22411
+ add(el2);
22412
+ }
22413
+ }
22414
+ function createHeadManager(ctx) {
22415
+ let pending = [];
22416
+ let scheduled = false;
22417
+ let resolved = { meta: {}, og: {}, twitter: {}, link: [], jsonLd: [], htmlAttrs: {} };
22418
+ const commit = () => {
22419
+ scheduled = false;
22420
+ if (pending.length === 0) return;
22421
+ resolved = mergeDirectives(pending);
22422
+ pending = [];
22423
+ applyToDom(resolved);
22424
+ };
22425
+ ctx.disposers.push(() => {
22426
+ if (typeof document === "undefined" || !document.head) return;
22427
+ document.head.querySelectorAll(`[${MANAGED_ATTR}]`).forEach((el2) => el2.remove());
22428
+ });
22429
+ return {
22430
+ apply(config) {
22431
+ pending.push(resolveConfig(config));
22432
+ if (scheduled) return;
22433
+ scheduled = true;
22434
+ if (typeof queueMicrotask === "function") queueMicrotask(commit);
22435
+ else void Promise.resolve().then(commit);
22436
+ },
22437
+ flush() {
22438
+ commit();
22439
+ },
22440
+ serialize() {
22441
+ if (pending.length > 0) commit();
22442
+ return serializeDirective(resolved);
22443
+ },
22444
+ htmlAttrs() {
22445
+ if (pending.length > 0) commit();
22446
+ return resolved.htmlAttrs;
22447
+ }
22448
+ };
22449
+ }
21525
22450
  function createI18n(config = {}) {
21526
22451
  const translations = sanitiseTranslations(config.translations);
21527
22452
  const defaultLanguage = typeof config.defaultLanguage === "string" ? config.defaultLanguage : "";
@@ -22372,18 +23297,18 @@ const Util = {
22372
23297
  * build time. Unknown/unsafe keys are dropped.
22373
23298
  */
22374
23299
  webManifest: (config) => {
22375
- const cfg = config && typeof config === "object" && !Array.isArray(config) ? config : {};
23300
+ const cfg2 = config && typeof config === "object" && !Array.isArray(config) ? config : {};
22376
23301
  const out = {
22377
- name: typeof cfg.name === "string" ? cfg.name : "App",
22378
- short_name: typeof cfg.shortName === "string" ? cfg.shortName : typeof cfg.name === "string" ? cfg.name : "App",
22379
- start_url: typeof cfg.startUrl === "string" ? cfg.startUrl : "/",
22380
- display: typeof cfg.display === "string" ? cfg.display : "standalone",
22381
- background_color: typeof cfg.backgroundColor === "string" ? cfg.backgroundColor : "#ffffff",
22382
- theme_color: typeof cfg.themeColor === "string" ? cfg.themeColor : "#000000"
23302
+ name: typeof cfg2.name === "string" ? cfg2.name : "App",
23303
+ short_name: typeof cfg2.shortName === "string" ? cfg2.shortName : typeof cfg2.name === "string" ? cfg2.name : "App",
23304
+ start_url: typeof cfg2.startUrl === "string" ? cfg2.startUrl : "/",
23305
+ display: typeof cfg2.display === "string" ? cfg2.display : "standalone",
23306
+ background_color: typeof cfg2.backgroundColor === "string" ? cfg2.backgroundColor : "#ffffff",
23307
+ theme_color: typeof cfg2.themeColor === "string" ? cfg2.themeColor : "#000000"
22383
23308
  };
22384
- if (typeof cfg.description === "string") out.description = cfg.description;
22385
- if (Array.isArray(cfg.icons)) {
22386
- out.icons = cfg.icons.filter((i) => Boolean(i) && typeof i === "object").map((i) => ({ src: String(i.src ?? ""), sizes: String(i.sizes ?? "512x512"), type: String(i.type ?? "image/png") }));
23309
+ if (typeof cfg2.description === "string") out.description = cfg2.description;
23310
+ if (Array.isArray(cfg2.icons)) {
23311
+ out.icons = cfg2.icons.filter((i) => Boolean(i) && typeof i === "object").map((i) => ({ src: String(i.src ?? ""), sizes: String(i.sizes ?? "512x512"), type: String(i.type ?? "image/png") }));
22387
23312
  }
22388
23313
  return out;
22389
23314
  },
@@ -22505,11 +23430,11 @@ const Style = {
22505
23430
  const parts = [];
22506
23431
  for (const [k, v] of Object.entries(obj)) {
22507
23432
  if (v == null || v === false) continue;
22508
- const prop = k.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
22509
- if (!/^[a-z-]+$/.test(prop)) continue;
23433
+ const prop2 = k.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
23434
+ if (!/^[a-z-]+$/.test(prop2)) continue;
22510
23435
  const val = String(v).trim();
22511
23436
  if (/[;{}<>]|expression\s*\(|javascript\s*:|@import/i.test(val)) continue;
22512
- parts.push(`${prop}:${val}`);
23437
+ parts.push(`${prop2}:${val}`);
22513
23438
  }
22514
23439
  return parts.join(";");
22515
23440
  }
@@ -23638,10 +24563,10 @@ const getNativeConsole = () => {
23638
24563
  const g = globalThis;
23639
24564
  return g.console ?? null;
23640
24565
  };
23641
- const forward = (method) => (...args) => {
24566
+ const forward = (method2) => (...args) => {
23642
24567
  const native = getNativeConsole();
23643
24568
  if (!native) return;
23644
- const fn = native[method] ?? native.log;
24569
+ const fn = native[method2] ?? native.log;
23645
24570
  if (typeof fn !== "function") return;
23646
24571
  try {
23647
24572
  fn(...args);
@@ -23649,8 +24574,8 @@ const forward = (method) => (...args) => {
23649
24574
  }
23650
24575
  };
23651
24576
  const consoleNs = METHODS.reduce(
23652
- (acc, method) => {
23653
- acc[method] = forward(method);
24577
+ (acc, method2) => {
24578
+ acc[method2] = forward(method2);
23654
24579
  return acc;
23655
24580
  },
23656
24581
  {}
@@ -23948,11 +24873,19 @@ const RESERVED_STATE_NAMESPACES = {
23948
24873
  console: consoleNs,
23949
24874
  storage
23950
24875
  };
23951
- const RESERVED_CONTEXT_NAMESPACES = /* @__PURE__ */ new Set(["toast"]);
24876
+ const RESERVED_CONTEXT_NAMESPACES = /* @__PURE__ */ new Set(["toast", "dom"]);
23952
24877
  function getToastManager(ctx) {
23953
24878
  if (!ctx.toastManager) ctx.toastManager = createToastManager(ctx);
23954
24879
  return ctx.toastManager;
23955
24880
  }
24881
+ function getDomManager(ctx) {
24882
+ if (!ctx.domManager) ctx.domManager = createDomManager(ctx);
24883
+ return ctx.domManager;
24884
+ }
24885
+ function getHeadManager(ctx) {
24886
+ if (!ctx.headManager) ctx.headManager = createHeadManager(ctx);
24887
+ return ctx.headManager;
24888
+ }
23956
24889
  function getEnvManager(ctx) {
23957
24890
  if (!ctx.envManager) ctx.envManager = createEnvManager(ctx);
23958
24891
  return ctx.envManager;
@@ -24371,7 +25304,7 @@ function isPureLiteralExpression(expr) {
24371
25304
  );
24372
25305
  case "Object":
24373
25306
  return expr.properties.every(
24374
- (prop) => !prop.spread && !prop.computedKey && isPureLiteralExpression(prop.value)
25307
+ (prop2) => !prop2.spread && !prop2.computedKey && isPureLiteralExpression(prop2.value)
24375
25308
  );
24376
25309
  case "Template":
24377
25310
  return expr.expressions.length === 0;
@@ -24491,14 +25424,14 @@ function evaluateRouterCall(args, ctx, loc) {
24491
25424
  }
24492
25425
  const path = readRoutePath(ctx);
24493
25426
  let wildcardArm = null;
24494
- for (const prop of arg.properties) {
24495
- if (prop.spread) continue;
24496
- const pattern = prop.key;
25427
+ for (const prop2 of arg.properties) {
25428
+ if (prop2.spread) continue;
25429
+ const pattern = prop2.key;
24497
25430
  if (pattern === "default" || pattern === "*") {
24498
- wildcardArm = prop;
25431
+ wildcardArm = prop2;
24499
25432
  continue;
24500
25433
  }
24501
- const layoutArm = asLayoutArm(prop.value);
25434
+ const layoutArm = asLayoutArm(prop2.value);
24502
25435
  if (layoutArm) {
24503
25436
  const pm = matchRoutePrefix(pattern, path);
24504
25437
  if (!pm.matched) continue;
@@ -24506,7 +25439,7 @@ function evaluateRouterCall(args, ctx, loc) {
24506
25439
  }
24507
25440
  const result = matchRoute(pattern, path);
24508
25441
  if (!result.matched) continue;
24509
- return runRouterArm(pattern, prop.value, result.params, ctx);
25442
+ return runRouterArm(pattern, prop2.value, result.params, ctx);
24510
25443
  }
24511
25444
  if (wildcardArm) {
24512
25445
  return runRouterArm(null, wildcardArm.value, {}, ctx);
@@ -24518,10 +25451,10 @@ function asLayoutArm(value) {
24518
25451
  if (value.kind !== "Object") return null;
24519
25452
  let layout = null;
24520
25453
  let routes = null;
24521
- for (const prop of value.properties) {
24522
- if (prop.spread) continue;
24523
- if (prop.key === "layout") layout = prop.value;
24524
- else if (prop.key === "routes" && prop.value.kind === "Object") routes = prop.value;
25454
+ for (const prop2 of value.properties) {
25455
+ if (prop2.spread) continue;
25456
+ if (prop2.key === "layout") layout = prop2.value;
25457
+ else if (prop2.key === "routes" && prop2.value.kind === "Object") routes = prop2.value;
24525
25458
  }
24526
25459
  return layout ? { layout, routes } : null;
24527
25460
  }
@@ -24531,26 +25464,26 @@ function runLayoutArm(pattern, arm, params, rest, ctx) {
24531
25464
  let childParams = {};
24532
25465
  if (arm.routes) {
24533
25466
  let childWildcard = null;
24534
- for (const prop of arm.routes.properties) {
24535
- if (prop.spread) continue;
24536
- if (prop.key === "default" || prop.key === "*") {
24537
- childWildcard = prop;
25467
+ for (const prop2 of arm.routes.properties) {
25468
+ if (prop2.spread) continue;
25469
+ if (prop2.key === "default" || prop2.key === "*") {
25470
+ childWildcard = prop2;
24538
25471
  continue;
24539
25472
  }
24540
- const nested = asLayoutArm(prop.value);
25473
+ const nested = asLayoutArm(prop2.value);
24541
25474
  if (nested) {
24542
- const pm = matchRoutePrefix(prop.key, rest);
25475
+ const pm = matchRoutePrefix(prop2.key, rest);
24543
25476
  if (!pm.matched) continue;
24544
- childPattern = prop.key;
25477
+ childPattern = prop2.key;
24545
25478
  childParams = pm.params;
24546
- child = runLayoutArm(prop.key, nested, pm.params, pm.rest, ctx);
25479
+ child = runLayoutArm(prop2.key, nested, pm.params, pm.rest, ctx);
24547
25480
  break;
24548
25481
  }
24549
- const m = matchRoute(prop.key, rest);
25482
+ const m = matchRoute(prop2.key, rest);
24550
25483
  if (!m.matched) continue;
24551
- childPattern = prop.key;
25484
+ childPattern = prop2.key;
24552
25485
  childParams = m.params;
24553
- child = evaluateWithBindings(prop.value, ctx, { params: m.params });
25486
+ child = evaluateWithBindings(prop2.value, ctx, { params: m.params });
24554
25487
  break;
24555
25488
  }
24556
25489
  if (child === null && childPattern === null && childWildcard) {
@@ -24603,9 +25536,9 @@ function evaluateLiteral(expr) {
24603
25536
  }
24604
25537
  case "Object": {
24605
25538
  const obj = {};
24606
- for (const prop of expr.properties) {
24607
- if (prop.spread) continue;
24608
- obj[prop.key] = evaluateLiteral(prop.value);
25539
+ for (const prop2 of expr.properties) {
25540
+ if (prop2.spread) continue;
25541
+ obj[prop2.key] = evaluateLiteral(prop2.value);
24609
25542
  }
24610
25543
  return obj;
24611
25544
  }
@@ -24672,6 +25605,7 @@ function evaluate(expr, ctx) {
24672
25605
  }
24673
25606
  if (RESERVED_CONTEXT_NAMESPACES.has(expr.name)) {
24674
25607
  if (expr.name === "toast") return getToastManager(ctx);
25608
+ if (expr.name === "dom") return getDomManager(ctx);
24675
25609
  }
24676
25610
  if (expr.name === "emit" && ctx.onEmit) {
24677
25611
  const onEmit = ctx.onEmit;
@@ -24701,9 +25635,9 @@ function evaluate(expr, ctx) {
24701
25635
  }
24702
25636
  case "Object": {
24703
25637
  const obj = {};
24704
- for (const prop of expr.properties) {
24705
- if (prop.spread) {
24706
- const value = evaluate(prop.value, ctx);
25638
+ for (const prop2 of expr.properties) {
25639
+ if (prop2.spread) {
25640
+ const value = evaluate(prop2.value, ctx);
24707
25641
  if (value && typeof value === "object" && !Array.isArray(value)) {
24708
25642
  for (const [k, v] of Object.entries(value)) {
24709
25643
  obj[k] = v;
@@ -24711,8 +25645,8 @@ function evaluate(expr, ctx) {
24711
25645
  }
24712
25646
  continue;
24713
25647
  }
24714
- const key = prop.computedKey ? String(evaluate(prop.computedKey, ctx) ?? "") : prop.key;
24715
- obj[key] = evaluate(prop.value, ctx);
25648
+ const key = prop2.computedKey ? String(evaluate(prop2.computedKey, ctx) ?? "") : prop2.key;
25649
+ obj[key] = evaluate(prop2.value, ctx);
24716
25650
  }
24717
25651
  return obj;
24718
25652
  }
@@ -25381,8 +26315,8 @@ function evaluateFormCall(args, ctx, loc) {
25381
26315
  const key = loc ? `${loc.line}:${loc.column}` : `form:${ctx.stores.size}`;
25382
26316
  const cached = ctx.stores.get(key);
25383
26317
  if (cached) return cached;
25384
- const cfg = args[0] ? evaluate(args[0], ctx) : {};
25385
- const config = cfg && typeof cfg === "object" && !Array.isArray(cfg) ? cfg : {};
26318
+ const cfg2 = args[0] ? evaluate(args[0], ctx) : {};
26319
+ const config = cfg2 && typeof cfg2 === "object" && !Array.isArray(cfg2) ? cfg2 : {};
25386
26320
  const initialValues = config.values && typeof config.values === "object" && !Array.isArray(config.values) ? { ...config.values } : {};
25387
26321
  const rules = config.rules && typeof config.rules === "object" && !Array.isArray(config.rules) ? config.rules : {};
25388
26322
  const onSubmit = typeof config.onSubmit === "function" ? config.onSubmit : null;
@@ -25618,6 +26552,15 @@ function evaluateInvoke(expr, ctx) {
25618
26552
  const optsArg = expr.arguments[0];
25619
26553
  return createSseResource(optsArg ? evaluate(optsArg, ctx) : {}, ctx);
25620
26554
  }
26555
+ case "script": {
26556
+ const optsArg = expr.arguments[0];
26557
+ return createScriptResource(optsArg ? evaluate(optsArg, ctx) : {}, ctx);
26558
+ }
26559
+ case "head": {
26560
+ const optsArg = expr.arguments[0];
26561
+ getHeadManager(ctx).apply(optsArg ? evaluate(optsArg, ctx) : {});
26562
+ return null;
26563
+ }
25621
26564
  case "theme": {
25622
26565
  const tokensArg = expr.arguments[0];
25623
26566
  const themeInput = tokensArg ? evaluate(tokensArg, ctx) : null;
@@ -25641,8 +26584,8 @@ function evaluateInvoke(expr, ctx) {
25641
26584
  case "i18n": {
25642
26585
  const configArg = expr.arguments[0];
25643
26586
  const config = configArg ? evaluate(configArg, ctx) : null;
25644
- const cfg = config && typeof config === "object" && !Array.isArray(config) ? config : {};
25645
- return createI18n(cfg);
26587
+ const cfg2 = config && typeof config === "object" && !Array.isArray(config) ? config : {};
26588
+ return createI18n(cfg2);
25646
26589
  }
25647
26590
  case "emit": {
25648
26591
  const eventName = expr.arguments[0] ? String(evaluate(expr.arguments[0], ctx)) : "";
@@ -26105,20 +27048,20 @@ function resolveLibraryCallArgs(ctx, callee, propArgs) {
26105
27048
  if (trailingObjIdx >= 0) {
26106
27049
  const trailingObj = propArgs[trailingObjIdx];
26107
27050
  if (trailingObj.kind === "Object") {
26108
- for (const prop of trailingObj.properties) {
26109
- if (prop.spread) continue;
26110
- const slot = slotByName.get(prop.key);
27051
+ for (const prop2 of trailingObj.properties) {
27052
+ if (prop2.spread) continue;
27053
+ const slot = slotByName.get(prop2.key);
26111
27054
  if (slot === void 0) {
26112
- if (UNIVERSAL_PROP_NAMES.has(prop.key)) {
27055
+ if (UNIVERSAL_PROP_NAMES.has(prop2.key)) {
26113
27056
  if (!universal) universal = {};
26114
- universal[prop.key] = evaluate(prop.value, ctx);
27057
+ universal[prop2.key] = evaluate(prop2.value, ctx);
26115
27058
  }
26116
27059
  continue;
26117
27060
  }
26118
- const value = evaluate(prop.value, ctx);
27061
+ const value = evaluate(prop2.value, ctx);
26119
27062
  slots[slot].value = value;
26120
27063
  slots[slot].filled = true;
26121
- const ref = stateRefForArg(prop.value, ctx);
27064
+ const ref = stateRefForArg(prop2.value, ctx);
26122
27065
  if (ref !== null) slots[slot].meta = { stateRef: ref };
26123
27066
  }
26124
27067
  }
@@ -26165,13 +27108,13 @@ function invokeComponentDecl(decl, args, ctx, loc) {
26165
27108
  const paramNames = new Set(decl.params.map((p) => p.name));
26166
27109
  const objKeys = [];
26167
27110
  let allIdentifierKeys = true;
26168
- for (const prop of trailingObjArg.properties) {
26169
- if (prop.spread) continue;
26170
- objKeys.push(prop.key);
26171
- if (prop.key === "key" || paramNames.has(prop.key)) {
27111
+ for (const prop2 of trailingObjArg.properties) {
27112
+ if (prop2.spread) continue;
27113
+ objKeys.push(prop2.key);
27114
+ if (prop2.key === "key" || paramNames.has(prop2.key)) {
26172
27115
  expandAsNamed = true;
26173
27116
  }
26174
- if (!/^[A-Za-z_$][\w$]*$/.test(prop.key)) allIdentifierKeys = false;
27117
+ if (!/^[A-Za-z_$][\w$]*$/.test(prop2.key)) allIdentifierKeys = false;
26175
27118
  }
26176
27119
  if (!expandAsNamed && allIdentifierKeys && objKeys.length > 0) {
26177
27120
  const positionalBefore = args.length - 1;
@@ -26197,12 +27140,12 @@ function invokeComponentDecl(decl, args, ctx, loc) {
26197
27140
  positionalExprs.push(args[i]);
26198
27141
  }
26199
27142
  if (trailingObjArg && trailingObjArg.kind === "Object") {
26200
- for (const prop of trailingObjArg.properties) {
26201
- if (prop.spread) continue;
26202
- if (prop.key === "key") {
26203
- explicitKeyExpr = prop.value;
27143
+ for (const prop2 of trailingObjArg.properties) {
27144
+ if (prop2.spread) continue;
27145
+ if (prop2.key === "key") {
27146
+ explicitKeyExpr = prop2.value;
26204
27147
  } else {
26205
- named[prop.key] = prop.value;
27148
+ named[prop2.key] = prop2.value;
26206
27149
  }
26207
27150
  }
26208
27151
  }
@@ -27997,11 +28940,25 @@ function replaceNode(oldNode, newNode) {
27997
28940
  return newNode;
27998
28941
  }
27999
28942
  function patchElement(oldEl, newEl) {
28943
+ if (oldEl.hasAttribute("data-rui-preserve") || newEl.hasAttribute("data-rui-preserve")) {
28944
+ syncAttributesAdditive(oldEl, newEl);
28945
+ syncEventHandlers(oldEl, newEl);
28946
+ return;
28947
+ }
28000
28948
  syncAttributes(oldEl, newEl);
28001
28949
  syncEventHandlers(oldEl, newEl);
28002
28950
  reconcileChildren(oldEl, Array.from(newEl.childNodes));
28003
28951
  syncFormState(oldEl, newEl);
28004
28952
  }
28953
+ function syncAttributesAdditive(oldEl, newEl) {
28954
+ const newAttrs = newEl.attributes;
28955
+ for (let i = 0; i < newAttrs.length; i += 1) {
28956
+ const attr = newAttrs[i];
28957
+ if (oldEl.getAttribute(attr.name) !== attr.value) {
28958
+ oldEl.setAttribute(attr.name, attr.value);
28959
+ }
28960
+ }
28961
+ }
28005
28962
  function syncAttributes(oldEl, newEl) {
28006
28963
  const oldAttrs = oldEl.attributes;
28007
28964
  for (let i = oldAttrs.length - 1; i >= 0; i -= 1) {
@@ -28157,6 +29114,7 @@ function buildFullPrompt(library, options) {
28157
29114
  sections.push(fullGlobals());
28158
29115
  sections.push(fullEmitAndWrappers());
28159
29116
  sections.push(fullEscapeHatches());
29117
+ sections.push(fullInteropAndHead());
28160
29118
  sections.push(fullUniversalProps());
28161
29119
  sections.push(fullThemingI18nIcons());
28162
29120
  sections.push(fullUtil());
@@ -28620,6 +29578,46 @@ $app(Column([
28620
29578
  ]))
28621
29579
  \`\`\``;
28622
29580
  }
29581
+ function fullInteropAndHead() {
29582
+ return `## Third-party widgets & document head
29583
+
29584
+ ### Imperative / third-party widget interop
29585
+ For a library that owns its own DOM (chart, map, editor, payment element, captcha) — NOT for normal markup (use components). The host carries \`data-rui-preserve\`, so the reconciler never touches the widget's DOM.
29586
+ - \`Mount({ setup, update?, cleanup?, props?, tag?, sx? })\` — managed imperative host. \`setup(node, props)\` runs once after attach and **returns the instance handle**; \`update(instance, props)\` runs when the (shallow-compared) \`props\` bag changes; \`cleanup(instance)\` runs on unmount. \`props\` is the reactive boundary; \`tag\` sets the host (default \`"div"\`).
29587
+ - \`WebComponent(tag, { attributes?, properties?, on?, children? })\` — render + hydrate a native custom element (tag must contain a hyphen). \`attributes\` is reactive, \`properties\` assigns rich JS props, \`on\` binds listeners that stay current.
29588
+ - \`$script({ src, global?, type?, as?, attributes? })\` — load an external script/stylesheet once (de-duplicated per \`src\`) → reactive \`{ ready, loading, error, value }\`. Gate a widget on \`.ready\`; \`value\` = \`window[global]\`. Stays un-ready under SSR.
29589
+ - \`$dom\` — managed observers, auto-disposed on replan: \`$dom.onResize(node, cb)\`, \`$dom.onIntersect(node, cb, opts?)\`, \`$dom.onMutation(node, cb, opts?)\`, and one-shot \`$dom.measure(node)\` → \`{ rect, scroll, viewport }\`. Pair with an \`OnMount\` / \`Mount\` node ref.
29590
+
29591
+ \`\`\`
29592
+ $chartjs = $script({ src: "https://cdn.jsdelivr.net/npm/chart.js", global: "Chart" })
29593
+ function SalesChart() {
29594
+ if (!$chartjs.ready) return Skeleton({ sx: { h: "320px" } })
29595
+ return Mount({
29596
+ sx: { h: "320px" },
29597
+ setup: (node, p) => new $chartjs.value(node, { type: "bar", data: { datasets: [{ data: p.series }] } }),
29598
+ update: (chart, p) => { chart.data.datasets[0].data = p.series; chart.update() },
29599
+ cleanup: (chart) => chart.destroy(),
29600
+ props: { series: $series }
29601
+ })
29602
+ }
29603
+ \`\`\`
29604
+
29605
+ ### Document head — \`$head({...})\`
29606
+ Reactive head manager: call it from a page component body. Sets the title, meta, canonical/alternate links, Open Graph + Twitter cards, JSON-LD, and \`<html>\` attrs. Reads \`$state\`, so it re-applies on change; per-route calls compose (later wins). \`renderToString\` returns the resolved \`head\` + \`headAttrs\` for crawlable SSR.
29607
+
29608
+ \`\`\`
29609
+ function ProductPage() {
29610
+ $head({
29611
+ title: \`\${$product.name} — Acme\`,
29612
+ meta: { description: $product.summary },
29613
+ og: { title: $product.name, image: $product.image, type: "product" },
29614
+ link: [{ rel: "canonical", href: $canonicalUrl }],
29615
+ jsonLd: { "@type": "Product", name: $product.name }
29616
+ })
29617
+ return Column([ /* … */ ])
29618
+ }
29619
+ \`\`\``;
29620
+ }
28623
29621
  function fullThemingI18nIcons() {
28624
29622
  return `## Theming, i18n & icons
28625
29623
 
@@ -29050,10 +30048,10 @@ function chatFinalVerification() {
29050
30048
  }
29051
30049
  function formatComponentSignature(spec) {
29052
30050
  const positional = findPositionalProp(spec);
29053
- const params = spec.props.map((prop) => {
29054
- const typePart = prop.enum ? prop.enum.map((v) => `"${v}"`).join("|") : prop.type;
29055
- const tag = prop === positional && prop.positional === true ? " (positional)" : "";
29056
- return `${prop.name}${prop.optional ? "?" : ""}: ${typePart}${tag}`;
30051
+ const params = spec.props.map((prop2) => {
30052
+ const typePart = prop2.enum ? prop2.enum.map((v) => `"${v}"`).join("|") : prop2.type;
30053
+ const tag = prop2 === positional && prop2.positional === true ? " (positional)" : "";
30054
+ return `${prop2.name}${prop2.optional ? "?" : ""}: ${typePart}${tag}`;
29057
30055
  }).join(", ");
29058
30056
  return `- ${spec.name}(${params}) — ${spec.description}`;
29059
30057
  }
@@ -38979,7 +39977,7 @@ function installFetchMock(handler) {
38979
39977
  const original = globalThis.fetch;
38980
39978
  const mock = async (input, init) => {
38981
39979
  const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
38982
- const method = (init?.method ?? input?.method ?? "GET").toUpperCase();
39980
+ const method2 = (init?.method ?? input?.method ?? "GET").toUpperCase();
38983
39981
  const headers = {};
38984
39982
  new Headers(init?.headers).forEach((v, k) => {
38985
39983
  headers[k] = v;
@@ -38991,8 +39989,8 @@ function installFetchMock(handler) {
38991
39989
  } catch {
38992
39990
  }
38993
39991
  }
38994
- requests.push({ url, method, headers, body });
38995
- const result = await handler(url, { ...init, method });
39992
+ requests.push({ url, method: method2, headers, body });
39993
+ const result = await handler(url, { ...init, method: method2 });
38996
39994
  return toResponse(result);
38997
39995
  };
38998
39996
  globalThis.fetch = mock;