jq79 0.7.14 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -14,6 +14,7 @@ export type ReactiveDeepData<T> = T & {
14
14
  $effect: (run: () => void, options?: EffectOptions) => Unsubscribe;
15
15
  $dispose: () => void;
16
16
  };
17
+ export declare const $raw: <T>(value: T) => T;
17
18
  type TrieNode = {
18
19
  children: Map<string, TrieNode> | null;
19
20
  own: Effect | null;
@@ -42,6 +43,7 @@ export type Effect = {
42
43
  read: Set<Set<Effect>> | null;
43
44
  };
44
45
  export declare const $batch: <T>(fn: () => T) => T;
46
+ export declare const $tick: () => Promise<void>;
45
47
  export declare const ALSO_WAKEN_BY: unique symbol;
46
48
  export declare const OWNER: unique symbol;
47
49
  export declare const $reactive: <T extends Record<string, any>>(data: T) => ReactiveDeepData<T>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jq79",
3
- "version": "0.7.14",
3
+ "version": "0.8.0",
4
4
  "description": "Mini reactive component library: single-file .html components, Svelte-style setup scripts, fine-grained proxy reactivity. No compiler, no bundler, no dependencies — works from any static host.",
5
5
  "keywords": [
6
6
  "reactive",
package/src/jq79.ts CHANGED
@@ -1,7 +1,7 @@
1
1
 
2
2
  import { $, $$, $create, sanitizeHTML, allowedHosts } from "./dom"
3
3
  import type { AllowUrl, QueryAll, QueryOne } from "./dom"
4
- import { $reactive, $toRaw, $computed, $batch, untracked, createEffectScope, ALSO_WAKEN_BY, OWNER } from "./reactive"
4
+ import { $reactive, $toRaw, $raw, $computed, $batch, $tick, untracked, createEffectScope, ALSO_WAKEN_BY, OWNER } from "./reactive"
5
5
  import type { ReactiveDeepData, EffectScope } from "./reactive"
6
6
  import { transformSetupScript, transformFactoryScript, parsePropsPattern, parseFactoryProps, preloadSpecifiers, type PropDecl } from "./transform"
7
7
  import {
@@ -14,7 +14,7 @@ import {
14
14
 
15
15
  export { $, $$, $create } from "./dom"
16
16
  export type { QueryOne, QueryAll } from "./dom"
17
- export { $reactive, $toRaw, $computed, $batch } from "./reactive"
17
+ export { $reactive, $toRaw, $raw, $computed, $batch, $tick } from "./reactive"
18
18
  export type { Computed } from "./reactive"
19
19
 
20
20
  // the package version, substituted at build time (tsup/vitest `define`, read
@@ -475,6 +475,33 @@ const runExpr = (expr: string, scope: Record<string, any>, extras?: Record<strin
475
475
  }
476
476
  }
477
477
 
478
+ const NO_PARAMS: string[] = []
479
+
480
+ // evalExpr for an expression with no extras whose key was built once, ahead of
481
+ // time - by a compiled skeleton, which knows every expression it will evaluate
482
+ // when the plan is made. The key is the same string exprKey builds; building it
483
+ // per evaluation is a concatenation, and a fresh string whose hash the Map
484
+ // lookup then has to compute. Holding the key rather than the entry keeps a
485
+ // demotion (which replaces the entry) visible on the next evaluation
486
+ const evalKeyed = (key: string, expr: string, scope: Record<string, any>): any => {
487
+ try {
488
+ const { fn, scoped } = entryFor(key, expr, NO_PARAMS)
489
+ if (!fn) return undefined
490
+ if (!scoped) return fn(scope, resolveName)
491
+ try {
492
+ return fn(scope, resolveName)
493
+ } catch (error) {
494
+ if (!(error instanceof ReferenceError)) throw error
495
+ const fallback = demoteToWith(key, expr, NO_PARAMS)
496
+ if (!fallback) throw error
497
+ return fallback(scope, resolveName)
498
+ }
499
+ } catch (error) {
500
+ reportExprError(expr, scope, error)
501
+ return undefined
502
+ }
503
+ }
504
+
478
505
  const evalExpr = (expr: string, scope: Record<string, any>, extras?: Record<string, any>): any => {
479
506
  try {
480
507
  return runExpr(expr, scope, extras)
@@ -524,6 +551,36 @@ const renderText = (parts: TextPart[], scope: Record<string, any>): string => {
524
551
  }
525
552
 
526
553
 
554
+ // an interpolated text node's effect, for both render paths. The write is
555
+ // guarded: an effect woken by a sibling's change recomputes the same string it
556
+ // already wrote, and assigning it back is a DOM mutation the browser has to
557
+ // take seriously. With cachedSetters the guard compares against the last
558
+ // string written instead of reading textContent back off the node
559
+ const bindText = (textNode: Text, parts: TextPart[], scope: Record<string, any>, fx: EffectScope) => {
560
+ if (!debugFlags.cachedSetters) {
561
+ fx.effect(() => {
562
+ const text = renderText(parts, scope)
563
+ if (textNode.textContent !== text) textNode.textContent = text
564
+ })
565
+ return
566
+ }
567
+ let last = textNode.data
568
+ fx.effect(() => {
569
+ const text = renderText(parts, scope)
570
+ if (text !== last) textNode.data = last = text
571
+ })
572
+ }
573
+
574
+ // splitText per distinct text, not per instance: a :each row's "{{ row.label }}"
575
+ // is one string rendered a thousand times, and splitting it is a regex pass.
576
+ // The parts are never mutated, so one array serves every instance
577
+ const textPartsCache = new Map<string, TextPart[]>()
578
+ const textParts = (text: string): TextPart[] => {
579
+ if (!debugFlags.cachedSetters) return splitText(text)
580
+ let parts = textPartsCache.get(text)
581
+ if (!parts) textPartsCache.set(text, (parts = splitText(text)))
582
+ return parts
583
+ }
527
584
  type ConditionalBranch = { expr?: string; node: TemplateNode }
528
585
 
529
586
 
@@ -533,6 +590,11 @@ type ConditionalBranch = { expr?: string; node: TemplateNode }
533
590
  // that function is then invoked with the event - so both a handler reference
534
591
  // and an inline arrow/statement work. Modifiers after dots: .prevent .stop
535
592
  // .self (runtime guards) and .once .capture (addEventListener options)
593
+ const runHandler = (el: Element, expr: string, scope: Record<string, any>, event: Event) => {
594
+ const handler = evalHandler(expr, scope, { $event: event })
595
+ if (typeof handler === "function") handler.call(el, event)
596
+ }
597
+
536
598
  const bindEvent = (el: Element, attr: string, expr: string, scope: Record<string, any>) => {
537
599
  const [name, ...modifiers] = attr.slice(1).split(".")
538
600
  const mods = new Set(modifiers)
@@ -542,8 +604,11 @@ const bindEvent = (el: Element, attr: string, expr: string, scope: Record<string
542
604
  if (mods.has("prevent")) event.preventDefault()
543
605
  if (mods.has("stop")) event.stopPropagation()
544
606
 
545
- const handler = evalHandler(expr, scope, { $event: event })
546
- if (typeof handler === "function") handler.call(el, event)
607
+ // in a batch: every effect the handler's writes woke runs once, after it
608
+ // returns, against the state it left - not once per write against the
609
+ // states in between (RECORD/2026-11-17.closing-the-gap-with-svelte.md, A)
610
+ if (debugFlags.batchHandlers) $batch(() => runHandler(el, expr, scope, event))
611
+ else runHandler(el, expr, scope, event)
547
612
  }, { once: mods.has("once"), capture: mods.has("capture") })
548
613
  }
549
614
 
@@ -572,10 +637,12 @@ const wireTagEvent = (instance: Component79, attr: string, expr: string, scope:
572
637
  // deps. Today that is contained - cross-store deps are never notified,
573
638
  // and the creation effect's definition guard no-ops a spurious wake - but
574
639
  // "what a handler reads is nobody's dependency" shouldn't hinge on either
575
- untracked(() => {
640
+ const run = () => {
576
641
  const handler = evalHandler(expr, scope, { $event: event })
577
642
  if (typeof handler === "function") handler(event)
578
- })
643
+ }
644
+ // batched like an element handler (see bindEvent)
645
+ untracked(debugFlags.batchHandlers ? () => $batch(run) : run)
579
646
  }
580
647
  instance.on(name, listener)
581
648
  }
@@ -1450,6 +1517,63 @@ const classNames = (value: any): string[] => {
1450
1517
  return []
1451
1518
  }
1452
1519
 
1520
+ // classNames into `out`, for the one caller that runs per row per wake: the
1521
+ // object form - the benchmark's, and the common one - walked with for...in
1522
+ // instead of Object.entries + flatMap, and a single name taken whole instead
1523
+ // of through the split. Same names, same order as classNames
1524
+ const collectClassNames = (value: any, out: string[]) => {
1525
+ if (typeof value === "string") {
1526
+ if (value && !/\s/.test(value)) out.push(value)
1527
+ else if (value) for (const name of value.split(/\s+/)) { if (name) out.push(name) }
1528
+ } else if (Array.isArray(value)) {
1529
+ for (const entry of value) collectClassNames(entry, out)
1530
+ } else if (value !== null && typeof value === "object") {
1531
+ for (const name in value) if (value[name]) collectClassNames(name, out)
1532
+ }
1533
+ }
1534
+
1535
+ const sameNames = (a: string[], b: string[]): boolean => {
1536
+ if (a.length !== b.length) return false
1537
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false
1538
+ return true
1539
+ }
1540
+
1541
+ // the :class effect, for both render paths. Only classes this binding added
1542
+ // are ever removed, so the static list survives every re-run, even when the
1543
+ // expression names one of its classes and then drops it (class="btn"
1544
+ // :class="{ btn: cond }" keeps btn on false).
1545
+ //
1546
+ // With cachedSetters a re-run that names the same classes as the last one
1547
+ // touches no DOM at all - select1k wakes 1,000 of these to change two - and a
1548
+ // change adds and removes only the difference. The one thing it gives up: a
1549
+ // bound class some other code removed is not put back until the binding's own
1550
+ // value changes (RECORD/2026-11-17.closing-the-gap-with-svelte.md, B)
1551
+ const bindClass = (
1552
+ el: Element,
1553
+ classExpr: string | undefined,
1554
+ toggles: [string, string][] | null,
1555
+ staticClasses: Set<string>,
1556
+ scope: Record<string, any>,
1557
+ fx: EffectScope,
1558
+ ) => {
1559
+ let bound: string[] = []
1560
+ fx.effect(() => {
1561
+ const next: string[] = []
1562
+ if (classExpr !== undefined) collectClassNames(evalExpr(classExpr, scope), next)
1563
+ if (toggles) for (const [name, expr] of toggles) if (evalExpr(expr, scope)) collectClassNames(name, next)
1564
+ if (!debugFlags.cachedSetters) {
1565
+ bound.forEach(name => {
1566
+ if (!next.includes(name) && !staticClasses.has(name)) el.classList.remove(name)
1567
+ })
1568
+ el.classList.add(...next)
1569
+ } else if (!sameNames(bound, next)) {
1570
+ for (const name of bound) if (!next.includes(name) && !staticClasses.has(name)) el.classList.remove(name)
1571
+ for (const name of next) if (!bound.includes(name)) el.classList.add(name)
1572
+ }
1573
+ bound = next
1574
+ })
1575
+ }
1576
+
1453
1577
  // what :html.allowed accepts, normalized to an AllowUrl predicate: host
1454
1578
  // patterns (a comma-separated string or an array - see allowedHosts in
1455
1579
  // ./dom) or a function (url: URL, tag, attr) => boolean. Anything else -
@@ -1638,7 +1762,7 @@ const applyAttr = (el: Element, name: string, value: any) => {
1638
1762
  // rebuild: a page that renders wrong is a bug report either way, but one whose
1639
1763
  // reporter can say "it goes away with cloning off" is a bug report that names
1640
1764
  // the file
1641
- const debugFlags: DebugFlags = { cloneSkeletons: true, scopedNames: true }
1765
+ const debugFlags: DebugFlags = { cloneSkeletons: true, scopedNames: true, batchHandlers: true, cachedSetters: true, compileSkeletons: true }
1642
1766
 
1643
1767
  // What `Component79.debug()` can switch. One flag today; the shape is an object
1644
1768
  // so the next one does not change the call
@@ -1653,6 +1777,26 @@ export type DebugFlags = {
1653
1777
  // was, which is what makes the two forms comparable on one build - both in
1654
1778
  // tests/expressions.test.ts and in `npm run benchmark:ab -- --flags`
1655
1779
  scopedNames: boolean
1780
+
1781
+ // run every @event handler - on an element or a component tag - inside
1782
+ // $batch, so its writes wake each effect once, after it returns. Off means
1783
+ // each write runs what it woke before the next line of the handler, as it
1784
+ // always did (RECORD/2026-11-17.closing-the-gap-with-svelte.md, A)
1785
+ batchHandlers: boolean
1786
+
1787
+ // :class and {{ }} compare against the last value they wrote, and touch the
1788
+ // DOM only for what changed; {{ }} text is split once per distinct string.
1789
+ // Off means every re-run diffs classList and reads textContent back, as
1790
+ // before (RECORD/2026-11-17.closing-the-gap-with-svelte.md, B)
1791
+ cachedSetters: boolean
1792
+
1793
+ // turn a skeleton plan into a function, built once per plan shape, instead
1794
+ // of interpreting its ops for every instance. Needs cloneSkeletons (there is
1795
+ // no plan without it) and cachedSetters (the setters it writes out are that
1796
+ // flag's). Off means renderFromSkeleton walks the ops, as before
1797
+ // (RECORD/2026-11-17.closing-the-gap-with-svelte.md, E1)
1798
+ compileSkeletons: boolean
1799
+
1656
1800
  }
1657
1801
 
1658
1802
  // the control attributes a skeleton knows how to fill. The rest of
@@ -1723,7 +1867,17 @@ type SkeletonOp =
1723
1867
  | { kind: "checked"; path: number[]; expr: string }
1724
1868
  | { kind: "selected"; path: number[]; expr: string }
1725
1869
 
1726
- type SkeletonPlan = { skeleton: Element; ops: SkeletonOp[] }
1870
+ type SkeletonPlan = {
1871
+ skeleton: Element
1872
+ ops: SkeletonOp[]
1873
+ // the plan compiled into a function (compileSkeletons): undefined until the
1874
+ // first render that wants it, null where it could not be built (safe mode
1875
+ // with nothing precompiled for it), and the interpreter takes over
1876
+ factory?: SkeletonFactory | null
1877
+ // what the factory is handed beside the ops: the exprKey of each op's
1878
+ // single expression, built once per plan rather than once per evaluation
1879
+ keys?: string[]
1880
+ }
1727
1881
 
1728
1882
  // mirrors renderNode's own order: the attribute walk (events and attribute
1729
1883
  // bindings as they appear), then :class, then the children. Effects run in
@@ -1852,9 +2006,179 @@ const atPath = (root: Node, path: number[]): Node => {
1852
2006
  return at
1853
2007
  }
1854
2008
 
2009
+ // ---------------------------------------------------------------------------
2010
+ // compiled skeletons (compileSkeletons)
2011
+ //
2012
+ // renderFromSkeleton interprets a plan: for every op of every instance it
2013
+ // walks childNodes down the op's path and dispatches on its kind. Both are
2014
+ // known the moment the plan exists, so this turns the plan into a function
2015
+ // that does neither - the paths become firstChild/nextSibling chains that
2016
+ // share their prefixes, the dispatch is gone, and the bindings a row is made
2017
+ // of (text, :class) are written out inline with their keys built once. One
2018
+ // effect per binding, exactly as interpreted: same effects, same order, same
2019
+ // writes. RECORD/2026-11-17.closing-the-gap-with-svelte.md, E1
2020
+ //
2021
+ // The text holds no user code. Every expression, attribute name and class is
2022
+ // read off the ops array it is handed (`o`), so the body is a function of the
2023
+ // plan's *shape*: two definitions with the same shape share one function, and
2024
+ // the body is the kind of [params, body] pair precompile could emit for safe
2025
+ // mode. Today it does not, so under safe mode makeFunction throws, the plan is
2026
+ // marked uncompilable, and the interpreter renders it - as it always has.
2027
+ // ---------------------------------------------------------------------------
2028
+
2029
+ type SkeletonFactory = (
2030
+ root: Element, scope: Record<string, any>, fx: EffectScope,
2031
+ ops: SkeletonOp[], keys: string[], h: typeof SKELETON_HELPERS,
2032
+ ) => void
2033
+
2034
+ const SKELETON_PARAMS = ["r", "s", "fx", "o", "K", "h"]
2035
+
2036
+ // what a compiled skeleton calls for everything it does not write out itself
2037
+ const SKELETON_HELPERS = {
2038
+ ev: evalKeyed,
2039
+ evalExpr,
2040
+ bindText,
2041
+ bindEvent,
2042
+ renderText,
2043
+ bindClassNames: (el: Element, bound: string[], next: string[], statics: Set<string>) => {
2044
+ for (const name of bound) if (!next.includes(name) && !statics.has(name)) el.classList.remove(name)
2045
+ for (const name of next) if (!bound.includes(name)) el.classList.add(name)
2046
+ },
2047
+ collectClassNames: (value: any, out: string[]) => collectClassNames(value, out),
2048
+ sameNames: (a: string[], b: string[]) => sameNames(a, b),
2049
+ applyAttr: (el: Element, name: string, value: any) => applyAttr(el, name, value),
2050
+ sanitizeHTML: (html: string) => sanitizeHTML(html),
2051
+ }
2052
+
2053
+ const skeletonFactories = new Map<string, SkeletonFactory | null>()
2054
+
2055
+ const skeletonBody = (ops: SkeletonOp[]): string => {
2056
+ const lines: string[] = []
2057
+ // path -> the variable holding that node. Siblings are reached from the
2058
+ // nearest earlier sibling already resolved, so a row's cells cost one
2059
+ // nextSibling each rather than a walk from their parent's first child
2060
+ const vars = new Map<string, string>([["", "r"]])
2061
+ let count = 0
2062
+ const nodeAt = (path: number[]): string => {
2063
+ const key = path.join(".")
2064
+ const known = vars.get(key)
2065
+ if (known) return known
2066
+ const parent = path.slice(0, -1)
2067
+ const index = path[path.length - 1]
2068
+ // from the nearest earlier sibling already held, else from the parent's
2069
+ // first child: either way, one nextSibling per node in between
2070
+ let expr = `${nodeAt(parent)}.firstChild`
2071
+ let hops = index
2072
+ for (let j = index - 1; j >= 0; j--) {
2073
+ const sibling = vars.get([...parent, j].join("."))
2074
+ if (sibling) { expr = sibling; hops = index - j; break }
2075
+ }
2076
+ for (let k = 0; k < hops; k++) expr += ".nextSibling"
2077
+ const name = `n${count++}`
2078
+ lines.push(`const ${name} = ${expr}`)
2079
+ vars.set(key, name)
2080
+ return name
2081
+ }
2082
+
2083
+ // a binding is its declarations (`pre`, run once per instance) and the
2084
+ // statement that re-renders it (`run`), each binding in a block with its own
2085
+ // effect. Sharing one effect between a row's bindings was built and measured
2086
+ // slower (RECORD/2026-11-17.closing-the-gap-with-svelte.md, E2)
2087
+ const bind = (pre: string, run: string) => lines.push(`{ ${pre}; fx.effect(() => { ${run} }) }`)
2088
+
2089
+ ops.forEach((op, i) => {
2090
+ const node = nodeAt(op.path)
2091
+ const o = `o[${i}]`
2092
+ if (op.kind === "text") {
2093
+ const [only] = op.parts
2094
+ if (op.parts.length === 1 && typeof only !== "string") {
2095
+ // bindText's cachedSetters arm, with the key held and renderText's
2096
+ // one-part case written out
2097
+ bind(
2098
+ `const t${i} = ${node}, e${i} = ${o}.parts[0].expr, k${i} = K[${i}]; let last${i} = t${i}.data`,
2099
+ `{ const v = h.ev(k${i}, e${i}, s); const x = v == null ? "" : String(v); if (x !== last${i}) t${i}.data = last${i} = x }`,
2100
+ )
2101
+ } else {
2102
+ bind(
2103
+ `const t${i} = ${node}, p${i} = ${o}.parts; let last${i} = t${i}.data`,
2104
+ `{ const x = h.renderText(p${i}, s); if (x !== last${i}) t${i}.data = last${i} = x }`,
2105
+ )
2106
+ }
2107
+ } else if (op.kind === "event") {
2108
+ lines.push(`h.bindEvent(${node}, ${o}.attr, ${o}.expr, s)`)
2109
+ } else if (op.kind === "attr") {
2110
+ bind(`const el${i} = ${node}, c${i} = ${o}`, `h.applyAttr(el${i}, c${i}.name, h.ev(K[${i}], c${i}.expr, s))`)
2111
+ } else if (op.kind === "class") {
2112
+ // bindClass's cachedSetters arm
2113
+ bind(
2114
+ `const el${i} = ${node}, c${i} = ${o}, k${i} = K[${i}]; let b${i} = []`,
2115
+ `{ const next = []; ` +
2116
+ `if (c${i}.classExpr !== undefined) h.collectClassNames(h.ev(k${i}, c${i}.classExpr, s), next); ` +
2117
+ `if (c${i}.toggles) for (const [n, e] of c${i}.toggles) if (h.evalExpr(e, s)) h.collectClassNames(n, next); ` +
2118
+ `if (!h.sameNames(b${i}, next)) h.bindClassNames(el${i}, b${i}, next, c${i}.staticClasses); b${i} = next }`,
2119
+ )
2120
+ } else if (op.kind === "textContent") {
2121
+ bind(
2122
+ `const el${i} = ${node}, c${i} = ${o}`,
2123
+ `{ const x = String(h.ev(K[${i}], c${i}.expr, s) ?? ""); if (el${i}.textContent !== x) el${i}.textContent = x }`,
2124
+ )
2125
+ } else if (op.kind === "html") {
2126
+ bind(`const el${i} = ${node}, c${i} = ${o}`, `el${i}.innerHTML = h.sanitizeHTML(String(h.ev(K[${i}], c${i}.expr, s) ?? ""))`)
2127
+ } else if (op.kind === "value") {
2128
+ bind(`const el${i} = ${node}, c${i} = ${o}`, `{ const x = String(h.ev(K[${i}], c${i}.expr, s) ?? ""); if (el${i}.value !== x) el${i}.value = x }`)
2129
+ } else if (op.kind === "checked") {
2130
+ bind(`const el${i} = ${node}, c${i} = ${o}`, `{ const x = !!h.ev(K[${i}], c${i}.expr, s); if (el${i}.checked !== x) el${i}.checked = x }`)
2131
+ } else if (op.kind === "selected") {
2132
+ bind(`const el${i} = ${node}, c${i} = ${o}`, `{ const x = !!h.ev(K[${i}], c${i}.expr, s); if (el${i}.selected !== x) el${i}.selected = x }`)
2133
+ } else {
2134
+ const unhandled: never = op
2135
+ void unhandled
2136
+ }
2137
+ })
2138
+ return `"use strict"\n${lines.join("\n")}`
2139
+ }
2140
+
2141
+ // the expression each op evaluates through a held key (h.ev), or "" for the
2142
+ // ones that go through a helper with their own lookup
2143
+ const skeletonKeys = (ops: SkeletonOp[]): string[] => ops.map(op => {
2144
+ if (op.kind === "text") {
2145
+ const [only] = op.parts
2146
+ return op.parts.length === 1 && typeof only !== "string" ? exprKey(only.expr, NO_PARAMS) : ""
2147
+ }
2148
+ if (op.kind === "class") return op.classExpr !== undefined ? exprKey(op.classExpr, NO_PARAMS) : ""
2149
+ if (op.kind === "event") return ""
2150
+ return exprKey(op.expr, NO_PARAMS)
2151
+ })
2152
+
2153
+ const compileSkeleton = (plan: SkeletonPlan): SkeletonFactory | null => {
2154
+ const body = skeletonBody(plan.ops)
2155
+ let factory = skeletonFactories.get(body)
2156
+ if (factory === undefined) {
2157
+ try {
2158
+ factory = makeFunction(SKELETON_PARAMS, body) as SkeletonFactory
2159
+ } catch {
2160
+ // safe mode, and nothing precompiled for this shape: the interpreter
2161
+ // renders this plan from now on. Not cached by shape, so another plan of
2162
+ // the same shape asks again - a precompiled script may have arrived
2163
+ return null
2164
+ }
2165
+ skeletonFactories.set(body, factory)
2166
+ }
2167
+ plan.keys = skeletonKeys(plan.ops)
2168
+ return factory
2169
+ }
2170
+
1855
2171
  const renderFromSkeleton = (plan: SkeletonPlan, scope: Record<string, any>, fx: EffectScope): Node => {
1856
2172
  const root = plan.skeleton.cloneNode(true) as Element
1857
2173
 
2174
+ if (debugFlags.compileSkeletons && debugFlags.cachedSetters) {
2175
+ if (plan.factory === undefined) plan.factory = compileSkeleton(plan)
2176
+ if (plan.factory) {
2177
+ plan.factory(root, scope, fx, plan.ops, plan.keys!, SKELETON_HELPERS)
2178
+ return root
2179
+ }
2180
+ }
2181
+
1858
2182
  // ordered by how often a row actually carries the kind, not by when it was
1859
2183
  // added: this chain runs once per op per instance, so the four holes a
1860
2184
  // benchmark row is made of are matched before the five a form is
@@ -1862,12 +2186,7 @@ const renderFromSkeleton = (plan: SkeletonPlan, scope: Record<string, any>, fx:
1862
2186
  const target = op.path.length === 0 ? root : atPath(root, op.path)
1863
2187
 
1864
2188
  if (op.kind === "text") {
1865
- const textNode = target as Text
1866
- const parts = op.parts
1867
- fx.effect(() => {
1868
- const text = renderText(parts, scope)
1869
- if (textNode.textContent !== text) textNode.textContent = text
1870
- })
2189
+ bindText(target as Text, op.parts, scope, fx)
1871
2190
  } else if (op.kind === "event") {
1872
2191
  bindEvent(target as Element, op.attr, op.expr, scope)
1873
2192
  } else if (op.kind === "attr") {
@@ -1875,20 +2194,7 @@ const renderFromSkeleton = (plan: SkeletonPlan, scope: Record<string, any>, fx:
1875
2194
  const { name, expr } = op
1876
2195
  fx.effect(() => applyAttr(el, name, evalExpr(expr, scope)))
1877
2196
  } else if (op.kind === "class") {
1878
- const el = target as Element
1879
- const { classExpr, toggles, staticClasses } = op
1880
- let bound: string[] = []
1881
- fx.effect(() => {
1882
- const next = classExpr !== undefined ? classNames(evalExpr(classExpr, scope)) : []
1883
- toggles?.forEach(([name, expr]) => {
1884
- if (evalExpr(expr, scope)) next.push(...classNames(name))
1885
- })
1886
- bound.forEach(name => {
1887
- if (!next.includes(name) && !staticClasses.has(name)) el.classList.remove(name)
1888
- })
1889
- el.classList.add(...next)
1890
- bound = next
1891
- })
2197
+ bindClass(target as Element, op.classExpr, op.toggles, op.staticClasses, scope, fx)
1892
2198
  } else if (op.kind === "textContent") {
1893
2199
  const el = target as Element
1894
2200
  const { expr } = op
@@ -2101,20 +2407,7 @@ const renderNode = (node: TemplateNode, outerScope: Record<string, any>, fx: Eff
2101
2407
  if (key.startsWith(":class.")) (classToggles ??= []).push([key.slice(":class.".length), node.attrs[key]])
2102
2408
  }
2103
2409
  if (classExpr !== undefined || classToggles) {
2104
- const staticClasses = new Set(classNames(node.attrs.class ?? ""))
2105
- let bound: string[] = []
2106
-
2107
- fx.effect(() => {
2108
- const next = classExpr !== undefined ? classNames(evalExpr(classExpr, scope)) : []
2109
- classToggles?.forEach(([name, expr]) => {
2110
- if (evalExpr(expr, scope)) next.push(...classNames(name))
2111
- })
2112
- bound.forEach(name => {
2113
- if (!next.includes(name) && !staticClasses.has(name)) el.classList.remove(name)
2114
- })
2115
- el.classList.add(...next)
2116
- bound = next
2117
- })
2410
+ bindClass(el, classExpr, classToggles, new Set(classNames(node.attrs.class ?? "")), scope, fx)
2118
2411
  }
2119
2412
 
2120
2413
  // :text="expr" sets textContent reactively, replacing any children.
@@ -3147,11 +3440,7 @@ const renderNodes = <T extends ParentNode>(
3147
3440
  // same string it already wrote, and assigning it back is a DOM mutation
3148
3441
  // the browser has to take seriously
3149
3442
  if (node.includes("{{")) {
3150
- const parts = splitText(node)
3151
- fx.effect(() => {
3152
- const text = renderText(parts, scope)
3153
- if (textNode.textContent !== text) textNode.textContent = text
3154
- })
3443
+ bindText(textNode, textParts(node), scope, fx)
3155
3444
  }
3156
3445
  fragment.appendChild(textNode)
3157
3446
  i++
@@ -5552,7 +5841,7 @@ let settleQueued = false
5552
5841
  // declaration) shadows them. Their names, in this order, are also
5553
5842
  // SETUP_HELPER_NAMES (source.ts) - what precompile compiles scripts with, so
5554
5843
  // the two change together
5555
- const SETUP_HELPERS: Record<string, any> = { $, $$, $create, $reactive, $toRaw, $batch, Component79, C79: Component79 }
5844
+ const SETUP_HELPERS: Record<string, any> = { $, $$, $create, $reactive, $toRaw, $raw, $batch, $tick, Component79, C79: Component79 }
5556
5845
 
5557
5846
  // the hot-reload handshake. jq79/dev serves a classic script that sets the flag
5558
5847
  // below; classic scripts run before deferred module ones, so the flag is always
package/src/reactive.ts CHANGED
@@ -37,10 +37,28 @@ export type ReactiveDeepData<T> = T & {
37
37
  const getByPath = (obj: Record<string, any>, dotKey: string): any =>
38
38
  dotKey.split(".").reduce((acc, key) => (acc == null ? undefined : acc[key]), obj)
39
39
 
40
+ // what $raw marked: plain data the store holds as it is, unwrapped - so the
41
+ // same as a class instance, below. Keyed by the object itself, so the mark
42
+ // travels with it into every store it is handed to (a prop, a child's store)
43
+ const RAW_VALUES = new WeakSet<object>()
44
+
45
+ // holds `value` as plain data no store will ever wrap: reading it, or anything
46
+ // inside it, records no dependency and goes through no proxy, and changing it
47
+ // in place notifies nobody. What stays reactive is the variable or key holding
48
+ // it - assigning a new value there notifies, and the new value is held raw too
49
+ // when it replaces a raw one, so `data = data.map(...)` keeps the list raw.
50
+ // Svelte's $state.raw (RECORD/2026-11-17.closing-the-gap-with-svelte.md, D)
51
+ export const $raw = <T>(value: T): T => {
52
+ const raw = $toRaw(value)
53
+ if (raw !== null && typeof raw === "object" && !isStore(raw)) RAW_VALUES.add(raw as object)
54
+ return raw
55
+ }
56
+
40
57
  // only plain objects and arrays get deep-wrapped by the reactive store;
41
58
  // class instances (Component79, Date, DOM nodes, ...) pass through untouched
42
59
  // so their identity, prototypes and internals stay intact
43
60
  const isPlainData = (value: object): boolean => {
61
+ if (RAW_VALUES.has(value)) return false
44
62
  if (Array.isArray(value)) return true
45
63
  const proto = Object.getPrototypeOf(value)
46
64
  return proto === Object.prototype || proto === null
@@ -307,6 +325,14 @@ export const $batch = <T>(fn: () => T): T => {
307
325
  }
308
326
  }
309
327
 
328
+ // resolves once every effect pending when it was called has run. A batch -
329
+ // explicit, or the one every event handler runs in - is synchronous: it opens
330
+ // and flushes inside one call stack, so by the time any promise callback runs
331
+ // it has flushed. A resolved promise is therefore already "after the flush",
332
+ // and `await $tick()` is the documented way to say it rather than an
333
+ // accident of `await` (RECORD/2026-11-17.closing-the-gap-with-svelte.md, A)
334
+ export const $tick = (): Promise<void> => Promise.resolve()
335
+
310
336
  // A write outside any $batch runs the effects it woke right away, as it always
311
337
  // has - but what *their* writes wake waits until all of them have run, and then
312
338
  // runs once, as a $batch would. Without it a write that two $computed derive
@@ -993,6 +1019,10 @@ export const $reactive = <T extends Record<string, any>>(data: T): ReactiveDeepD
993
1019
  // always announces itself - the sweep is its whole point
994
1020
  if (!isNewKey && Object.is(target[key], stored) && (stored === null || typeof stored !== "object")) return true
995
1021
  const previous = target[key]
1022
+ // a raw value's replacement is raw: the mark is on the key's contents,
1023
+ // the way the author wrote it (`let data = $raw([])`), not on one array
1024
+ if (previous !== null && typeof previous === "object" && RAW_VALUES.has(previous) &&
1025
+ stored !== null && typeof stored === "object" && !isStore(stored)) RAW_VALUES.add(stored)
996
1026
  target[key] = stored
997
1027
  tombstones?.delete(key) // the key exists again: no claim needed
998
1028
  if (isStore(stored)) bridge(stored, dotKey)
@@ -1313,7 +1343,9 @@ export type Computed<T> = ReactiveDeepData<{ readonly value: T }>
1313
1343
 
1314
1344
  export const $computed = <T>(get: () => T): Computed<T> => {
1315
1345
  const box = $reactive({ value: undefined as T })
1346
+ let self: Effect | null = null
1316
1347
  box.$effect(() => {
1348
+ self ??= activeEffect
1317
1349
  let value: T
1318
1350
  try {
1319
1351
  value = get()
@@ -1329,5 +1361,20 @@ export const $computed = <T>(get: () => T): Computed<T> => {
1329
1361
  console.warn(`jq79: a $computed is read-only - the write to ${String(key)} was ignored`)
1330
1362
  return true
1331
1363
  }
1332
- return new Proxy(box, { set: refuse, deleteProperty: refuse, defineProperty: refuse }) as Computed<T>
1364
+ // read while a batch holds it pending - something it depends on was written
1365
+ // and it has not recomputed yet - it recomputes now, rather than hand back
1366
+ // the value from before the write. Without this, every event handler (which
1367
+ // runs in a batch) that writes and then reads what it derives would read the
1368
+ // old value. Its own run reading itself is left alone, as is a computed
1369
+ // nobody woke: `batched` is null or lacks it, and the read is a Map lookup
1370
+ const read = (target: typeof box, key: string | symbol) => {
1371
+ const owner = key === "value" && self && activeEffect !== self ? batched?.get(self) : undefined
1372
+ if (owner) {
1373
+ batched!.delete(self!)
1374
+ // as the flush would: not if it was disposed while it waited
1375
+ if (owner.has(self!)) self!.run()
1376
+ }
1377
+ return (target as any)[key]
1378
+ }
1379
+ return new Proxy(box, { get: read, set: refuse, deleteProperty: refuse, defineProperty: refuse }) as Computed<T>
1333
1380
  }
package/src/source.ts CHANGED
@@ -374,7 +374,7 @@ export const declaredPropNames = (
374
374
  // $emit, $updateModel and $slots, then $importAll. They are positional parameters, so the order is part of what
375
375
  // precompile has to reproduce; change one side and precompiled scripts stop
376
376
  // matching, which tests/precompile.test.ts and `npm run check:precompile` catch
377
- export const SETUP_HELPER_NAMES = ["$", "$$", "$create", "$reactive", "$toRaw", "$batch", "Component79", "C79"]
377
+ export const SETUP_HELPER_NAMES = ["$", "$$", "$create", "$reactive", "$toRaw", "$raw", "$batch", "$tick", "Component79", "C79"]
378
378
  export const INSTANCE_HELPER_NAMES = ["$mounted", "$destroyed", "$attached", "$detached", "$computed", "$self", "$$self", "$emit", "$updateModel", "$slots", "$importAll"]
379
379
 
380
380
  // the global a precompiled script leaves its functions on, for the runtime to