data
Version:
reactive data for typescript — $() wraps values, chainable operators derive views, render binds to the DOM. work proportional to the path that changed.
1,358 lines (1,354 loc) • 134 kB
JavaScript
var __defProp = Object.defineProperty;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __esm = (fn, res) => function __init() {
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
// utils.ts
var isArray, noop;
var init_utils = __esm({
"utils.ts"() {
({ isArray } = Array);
noop = () => {
};
}
});
// core.ts
function iter2(arr, fn) {
for (let i = 0; i < arr.length; i++) fn(arr[i++], arr[i]);
}
function iter3(arr, fn) {
for (let i = 0; i < arr.length; i++) fn(arr[i++], arr[i++], arr[i]);
}
function create(views, name, res) {
views.set(name, new WeakRef(res));
return res;
}
function connect(p, a, b) {
if (isArray(a)) {
const sink = new ArrSink(p, a);
p.sinks.add(new WeakRef(sink));
return a;
}
if (typeof a === "object" && typeof b === "string") {
const sink = new PropSink(p, a, b);
p.sinks.add(new WeakRef(sink));
return a;
}
if (typeof a === "object" && typeof b === "function") {
const sink = new FunctionSink(p, a, b);
p.sinks.add(new WeakRef(sink));
return a;
}
if (typeof a === "function") throw new Error(
"connect(fn) isn't supported: a bare function can't act as a sink. Use connect(anchor, fn) to receive change records (the anchor object keeps the subscription alive past GC), connect([]) to collect events into an array, or connect(obj, 'prop') to mirror the value onto a property."
);
p.sinks.add(new WeakRef(a));
return a;
}
function firstKey(v) {
if (v == null || typeof v !== "object") return "0";
if (isArray(v)) return "0";
for (const k in v) return k;
return "0";
}
function lastKey(v) {
if (v == null || typeof v !== "object") return "0";
if (isArray(v)) return String(Math.max(0, v.length - 1));
let last = "0";
for (const k in v) last = k;
return last;
}
function raf(p) {
let pending;
let scheduled = false;
const schedule = (cb) => typeof globalThis.requestAnimationFrame === "function" ? globalThis.requestAnimationFrame(cb) : setTimeout(cb, 16);
const writer = (v) => {
pending = v;
if (scheduled) return;
scheduled = true;
schedule(() => {
if (!scheduled) return;
scheduled = false;
p.res.update(pending, p.key);
});
};
writer.flush = () => {
if (!scheduled) return;
scheduled = false;
p.res.update(pending, p.key);
};
return writer;
}
var value, view, Symbols, sclone, Operators, $, _devtoolsRoots, _devtoolsInternalRoots, Value, Operator, View, Sink, LinkedView, ArrSink, lifetimes, PropSink, FunctionSink, ViewProxy;
var init_core = __esm({
"core.ts"() {
init_utils();
value = /* @__PURE__ */ Symbol("value");
view = /* @__PURE__ */ Symbol("view");
Symbols = { value, view };
sclone = (d) => d === void 0 ? void 0 : d[view] ? d[view].value : structuredClone(d);
Operators = {};
$ = (v) => new ViewProxy(View.value(v));
$.random = (o) => crypto.randomUUID();
_devtoolsRoots = /* @__PURE__ */ new Set();
_devtoolsInternalRoots = /* @__PURE__ */ new WeakSet();
Value = class {
constructor() {
this.view = new View(this);
}
// Entry points from ViewProxy.set / .insert(...) / deleteProperty. They
// dispatch on key-path length to the correct depth-suffixed verb. Setting a
// proxy to another proxy is forbidden here because the resulting cycle is
// ambiguous (copy or link?) — the caller must use a linked value instead
// (see LinkedView).
update(value2, key) {
if (value2 instanceof ViewProxy) throw new Error("cannot set value to another data, use a linked value instead");
key.length === 0 ? this.XU0(value2) : key.length === 1 ? this.BU1([key[0], value2]) : this.BU2([key, value2]);
}
insert(value2, key, at) {
if (value2 instanceof ViewProxy) throw new Error("cannot set value to another data, use a linked value instead");
at = at === void 0 ? at : `${at}`;
key.length === 0 ? this.BI0([at, value2]) : this.BI2([key, value2, at]);
}
remove(key) {
key.length === 0 ? this.XR0() : key.length === 1 ? this.BR1([key[0]]) : this.BR2([key]);
}
// Idempotent: a Value already at undefined emits nothing. Returns false so
// callers can short-circuit when nothing happened (used by Sink chains that
// skip propagation on no-ops).
XR0() {
if (this.view.value === void 0) return false;
const value2 = this.view.value;
this.view.value = void 0;
this.view.XR0(value2);
}
// BR1A: array-aware remove-at-name. Each name is treated as a positional
// index; surviving rows shift down. The downstream BR1 carries the original
// (pre-shift) name so sinks can identify which element left, but the
// underlying array is already spliced by the time the View dispatches.
//
// Splice only if this operator owns its view.value — when the value is a
// reference shared with the upstream (the common case for pass-through
// operators like tap, which point view.value at p.value via XU0),
// upstream has already spliced the array and re-splicing here shifts
// every survivor one position further than intended.
BR1A(R1) {
const owns = this.view.value !== this.p?.value;
const NR1 = [];
for (let i = 0; i < R1.length; i++) {
const name = R1[i];
const value2 = this.view.value?.[name];
if (owns) this.view.value.splice(name, 1);
NR1.push(name);
NR1.push(value2);
}
this.view.BR1(NR1);
}
// BR1: object remove-at-name. Routes to BR1A when the underlying value is
// an array so we get splice semantics and downstream V1 propagation. Skips
// already-undefined slots so a remove is a true no-op rather than emitting
// a phantom event.
BR1(R1) {
if (isArray(this.view.value)) return this.BR1A(R1);
const NR1 = [];
for (let i = 0; i < R1.length; i++) {
const name = R1[i];
const value2 = this.view.value?.[name];
if (value2 === void 0) continue;
delete this.view.value[name];
NR1.push(name);
NR1.push(value2);
}
this.view.BR1(NR1);
}
BR2(R2) {
const NR2 = [];
loop1: for (let i = 0; i < R2.length; i++) {
const key = R2[i];
const [last, ...path] = key.slice().reverse();
let vo = this.view.value;
if (typeof vo !== "object") return;
while (path.length) {
const n = path.pop();
if (typeof vo !== "object") continue loop1;
vo = vo[n];
}
if (vo[last] === void 0) continue loop1;
const value2 = vo[last];
if (isArray(vo)) {
vo.splice(last, 1);
} else {
delete vo[last];
}
NR2.push(key, value2);
}
this.view.BR2(NR2);
}
// Reference-equality short-circuit: if the caller passed the same object we
// already hold, skip the entire dispatch. Operators that mutate in place
// and re-emit (e.g. between, sort) rely on this — they swap the live
// reference for a copy first to avoid this guard suppressing real changes.
XU0(value2) {
if (this.view.value === value2) return;
this.view.value = value2;
this.view.XU0();
}
// BU1 doubles as an upsert: keys whose previous value was undefined become
// BI0 events, keys with an existing value become BU1, and identical values
// are dropped entirely. Splitting the two avoids forcing every BU1 sink to
// re-derive whether the row is new or a refresh.
BU1(U1) {
const NU1 = [];
const NI0 = [];
if (typeof this.view.value !== "object") this.view.value = {};
for (let i = 0; i < U1.length; i++) {
const name = U1[i++];
const value2 = U1[i];
if (this.view.value?.[name] === value2) continue;
this.view.value?.[name] === void 0 ? NI0.push(name, value2) : NU1.push(name, value2);
this.view.value[name] = value2;
}
this.view.BU1(NU1);
this.view.BI0(NI0);
}
// Deep update along a key path. We auto-create intermediate objects so a
// user can write `proxy.a.b.c = 1` without first ensuring `a.b` exists; the
// alternative would force callers to reproduce immutable-update boilerplate
// for what's logically one assignment. `key.slice().reverse()` then `pop()`
// is just a cheap way to walk the path forward without mutating the caller's
// key array.
BU2(U2) {
if (typeof this.view.value !== "object") this.view.value = {};
for (let i = 0; i < U2.length; i++) {
const key = U2[i++];
const value2 = U2[i];
const [last, ...path] = key.slice().reverse();
let vo = this.view.value;
while (path.length) {
const n = path.pop();
vo = typeof vo[n] === "object" ? vo[n] : vo[n] = {};
}
if (vo[last] === value2) continue;
vo[last] = value2;
}
this.view.BU2(U2);
}
// BI0: object insert. If `at` is omitted we mint a random key — this lets
// `arr.insert(row)` work without the caller managing IDs. Routes to BI0A
// for arrays so insert-at-position carries shift semantics.
BI0(I0) {
if (isArray(this.view.value)) return this.BI0A(I0);
if (typeof this.view.value !== "object") this.view.value = {};
for (let i = 0; i < I0.length; i++) {
const at = I0[i++] ??= "" + $.random(this.view.value);
const value2 = I0[i];
if (this.view.value?.[at] === value2) continue;
this.view.value[at] = value2;
}
this.view.BI0(I0);
}
// BI0A: array insert-at-position. Undefined `at` means "push to end" and
// we record the resulting index back into I0 so downstream sinks know
// where the row landed. Defined `at` means splice — surviving elements at
// that position and beyond shift up.
//
// Splice only if this operator owns its view.value (same shared-ref
// guard as BR1A / BMV1 — see comment on BR1A).
BI0A(I0) {
const owns = this.view.value !== this.p?.value;
for (let i = 0; i < I0.length; i += 2) {
const at = I0[i];
const value2 = I0[i + 1];
if (at === void 0) {
if (owns) I0[i] = "" + (this.view.value.push(value2) - 1);
else I0[i] = "" + (this.view.value.length - 1);
} else if (owns) {
this.view.value.splice(at, 0, value2);
}
}
this.view.BI0(I0);
}
// Move-at-depth-1 verb. Each [from, to] pair moves the element at
// index `from` to index `to`; rows in between rotate by one. Carried as a
// single 'move' for change-stream consumers that want move semantics rather
// than N value-update events. (DOMSink itself treats a move as a no-op: it
// renders rows index-keyed, so Value.BMV1's positional child refresh below
// already updates each slot's content — see render/index.ts BMV1.)
//
// Splice only if this operator owns its view.value (same shared-ref
// guard as BR1A / BI0A — see comment on BR1A).
BMV1(M1) {
if (this.view.value !== this.p?.value) {
for (let i = 0; i < M1.length; i += 2) {
const from = +M1[i];
const to = +M1[i + 1];
const [v] = this.view.value.splice(from, 1);
this.view.value.splice(to, 0, v);
}
}
this.view.BMV1(M1);
}
BI2(I2) {
if (typeof this.view.value !== "object") this.view.value = {};
for (let i = 0; i < I2.length; i++) {
const key = I2[i++];
const value2 = I2[i++];
const path = key.slice().reverse();
let vo = this.view.value;
while (path.length) {
const n = path.pop();
vo = typeof vo[n] === "object" ? vo[n] : vo[n] = {};
}
if (isArray(vo)) {
if (I2[i] === void 0)
I2[i] ??= "" + (vo.push(value2) - 1);
else
vo.splice(I2[i], 0, value2);
} else {
const at = I2[i] ??= "" + $.random(vo);
vo[at] = value2;
}
}
this.view.BI2(I2);
}
};
Operator = class extends Value {
};
View = class _View {
constructor(res) {
this.res = res;
this.key = [];
this.sinks = /* @__PURE__ */ new Set();
this.views = /* @__PURE__ */ new Map();
this.p = void 0;
this.name = void 0;
this.value = void 0;
}
// Child views are produced lazily when ViewProxy.get sees a property access.
// A child stays attached to its parent's key (so writes route correctly) but
// owns its own value snapshot — kept in sync by the parent's dispatch logic
// calling child.XU0() / XR0() on every notification that crosses its key.
static child(p, name) {
const view2 = new _View(p.res);
view2.p = p;
view2.key = [...p.key, name];
view2.name = name;
view2.XU0(p.value?.[name]);
return view2;
}
// Two distinct entry points unified behind one factory: $(plain) builds a
// fresh Value-backed View; $(otherProxy) builds a LinkedView that forwards
// every read/write to the linked source. The branch matters for set/get
// semantics — see LinkedView below.
static value(value2) {
if (value2 instanceof ViewProxy) {
return new LinkedView(value2);
} else {
const res = new Value();
res.XU0(value2);
_devtoolsRoots.add(new WeakRef(res.view));
return res.view;
}
}
// XR0 cascades a clear: every named child loses its value too, but only if
// the corresponding key actually disappeared (the second half of the OR
// covers the case where a child is currently undefined and stays that way —
// we still want its sinks to know).
XR0(value2) {
if (this.p) this.value = void 0;
this.each((name, child) => {
if (child.value !== value2?.[name] || child.value !== void 0)
child.XR0(value2?.[name]);
});
this.sink((sink) => sink.XR0(value2, this));
}
// Splice-aware fan-out for object removes. For object sources we route each
// R1 to the named child as an XR0 (a single key disappeared, named children
// at other keys are unaffected). For array sources we instead refresh every
// child whose index ≥ the smallest removed index — those rows just got
// shifted to a different value. Sinks then see either the array-aware
// BR1A (with shift semantics) or BR1 (treat as named delete) depending on
// what they implement; the prototype check stops a sink that inherits the
// default Value.BR1A from masquerading as array-aware.
BR1(R1) {
if (!R1.length) return;
const arr = isArray(this.value);
if (!arr) {
for (let i = 0; i < R1.length; i += 2)
this.get_named(R1[i])?.XR0(R1[i + 1]);
} else if (this.views.size) {
let offset = Infinity;
for (let i = 0; i < R1.length; i += 2) {
if (R1[i] < offset) offset = R1[i];
if (!offset) break;
}
this.V1(offset);
}
this.fanout(arr ? "BR1A" : void 0, "BR1", R1);
}
BR2(R2) {
for (let i = 0; i < R2.length; i++) {
const [name, ...rest] = R2[i++];
const value2 = R2[i];
rest.length === 1 ? this.get_named(name)?.BR1([rest[0], value2]) : this.get_named(name)?.BR2([rest, value2]);
}
this.sink((sink) => sink.BR2(R2, this));
}
// Whole-value replacement. For child views this means: any name still
// present in the new value gets a refresh (XU0), any name that vanished
// gets a clear (XR0). The `if (this.p)` re-reads our slice from the parent
// because XU0 on the parent already mutated `p.value`; we just mirror it.
XU0() {
if (this.p) this.value = this.p.value?.[this.name];
this.each((name, child) => {
if (this.value?.[name] !== void 0)
child.XU0();
else {
if (child.value !== void 0)
child.XR0(child.value);
}
});
this.sink((sink) => sink.XU0(this.value, this));
}
BU1(U1) {
if (!U1.length) return;
if (this.p) this.value = this.p.value?.[this.name];
for (let i = 0; i < U1.length; i++) this.get_named(U1[i++])?.XU0();
this.sink((sink) => sink.BU1(U1, this));
}
BU2(U2) {
if (this.p) this.value = this.p.value?.[this.name];
for (let i = 0; i < U2.length; i++) {
const [name, ...rest] = U2[i++];
const value2 = U2[i];
rest.length === 1 ? this.get_named(name)?.BU1([rest[0], value2]) : this.get_named(name)?.BU2([rest, value2]);
}
this.sink((sink) => sink.BU2(U2, this));
}
BI0(I0) {
if (!I0.length) return;
if (this.p) this.value = this.p.value?.[this.name];
if (isArray(this.value)) return this.BI0A(I0);
for (let i = 0; i < I0.length; i++) this.get_named(I0[i++])?.XU0();
this.sink((sink) => sink.BI0(I0, this));
}
// Array insert: every existing index ≥ the smallest insert position has
// shifted up, so refresh those children once before fanning out to sinks.
// The prototype check guards against a sink that only inherits the default
// BI0A from Value being treated as array-aware.
BI0A(I0) {
if (this.views.size) {
let offset = Infinity;
for (let i = 0; i < I0.length; i += 2) {
if (I0[i] < offset) offset = I0[i];
}
this.V1(offset);
}
this.fanout("BI0A", "BI0", I0);
}
// Hole remove / hole fill — the positional-stable counterparts of BR1A/BI0A.
// A sparse producer (between/intersect/union/except over an ARRAY) marks an
// excluded slot `undefined` WITHOUT splicing: the array length is unchanged
// and survivors do NOT shift. BR1A/BI0A would wrongly splice downstream
// (ghost rows / dropped survivors — the array-positional desync). Instead the
// producer emits BH1/BF0: we refresh only the touched children (no V1 shift)
// and route to a sink's BH1/BF0 if it has one. A sink WITHOUT them (an
// aggregate, say — position-agnostic) falls back to BR1/BI0, which is correct:
// it just drops/adds the row. Operator positional sinks (RowOperator, a
// downstream sparse op, sort) implement BH1/BF0 to mirror the hole instead
// of shifting. The DOMSink ALSO implements them (index-keyed _remove_at/
// _create_at, see render/index.ts) so a sparse producer can be bound straight
// to a row template without phantom holes — the V1 content refresh we fire
// here (get_named(k).XU0()) sets the touched child's value BEFORE the sink's
// BH1/BF0 runs, and because the DOMSink keys nodes by index that refresh is
// not double-applied (closed ISSUES.md C4). BH1/BF0 live on View only — never
// on Value — so a plain Value sink never inherits one and always takes the
// BR1/BI0 fallback.
BH1(R1) {
if (!R1.length) return;
for (let i = 0; i < R1.length; i += 2) this.get_named(R1[i])?.XU0();
this.fanout("BH1", "BR1", R1);
}
BF0(I0) {
if (!I0.length) return;
for (let i = 0; i < I0.length; i += 2) this.get_named(I0[i])?.XU0();
this.fanout("BF0", "BI0", I0);
}
BI2(I2) {
if (this.p) this.value = this.p.value?.[this.name];
for (let i = 0; i < I2.length; ) {
const [name, ...rest] = I2[i++];
const value2 = I2[i++];
const at = I2[i++];
rest.length ? this.get_named(name)?.BI2([rest, value2, at]) : this.get_named(name)?.BI0([at, value2]);
}
this.sink((sink) => sink.BI2(I2, this));
}
// Apply a batched [from, to] rotation to named children whose key falls
// inside any affected range, refreshing each from the (already moved)
// parent value. Sinks that don't implement BMV1 fall back to BU1 over the
// affected positions so they refresh content reactively.
BMV1(M1) {
if (!M1.length) return;
if (this.p) this.value = this.p.value?.[this.name];
if (this.views.size) {
let lo = Infinity, hi = -Infinity;
for (let i = 0; i < M1.length; i += 2) {
const a = +M1[i], b = +M1[i + 1];
if (a < lo) lo = a;
if (b < lo) lo = b;
if (a > hi) hi = a;
if (b > hi) hi = b;
}
for (let j = lo; j <= hi; j++) {
const child = this.get_named(`${j}`);
if (child && child.value !== this.value[j]) child.XU0();
}
}
for (const x of this.sinks) {
const sink = x.deref();
if (!sink) {
this.sinks.delete(x);
continue;
}
if (sink.BMV1 && sink.BMV1 !== Value.prototype.BMV1) {
sink.BMV1(M1, this);
} else {
const NU1 = [];
for (let i = 0; i < M1.length; i += 2) {
const a = +M1[i], b = +M1[i + 1];
const lo = a < b ? a : b;
const hi = a < b ? b : a;
for (let j = lo; j <= hi; j++) NU1.push("" + j, this.value[j]);
}
if (NU1.length) sink.BU1(NU1, this);
}
}
}
// After an array splice every index from `offset` onward may now hold a
// different element. Walk all named children in that range and refresh
// those whose snapshot diverged. Off-by-one (`length+1`) intentional: a
// child created at the now-empty tail needs an XU0 to clear itself.
V1(offset) {
for (let i = offset; i < this.value.length + 1; i++) {
const child = this.get_named(`${i}`);
if (child && child.value !== this.value[i]) child.XU0();
}
}
// Iteration helpers all double as sweepers: a WeakRef whose target was GC'd
// is removed from the collection on the fly, so dead subscribers don't
// accumulate. `sink(fn)` is the standard fan-out; `some_sink(fn)` is the
// operator-dedup helper used by createOperator and ViewProxy.apply.
some_sink(fn) {
let n;
for (const x of this.sinks) {
const sink = x.deref?.();
if (!sink) {
this.sinks.delete(x);
continue;
}
if (n = fn(sink)) return n;
}
}
sink(fn) {
for (const x of this.sinks) {
const sink = x.deref?.();
if (!sink) {
this.sinks.delete(x);
continue;
}
fn(sink);
}
}
// Array-aware fan-out: dispatch `verb` to each sink that has its OWN
// implementation, else fall back to `fallback`. The four array-positional
// dispatch sites (BR1→BR1A, BI0A, BH1, BF0) collapse onto this. "Has its own"
// means: for BR1A/BI0A — distinct from Value.prototype's default (Value
// defines those, so a bare Value sink must NOT masquerade as array-aware);
// for BH1/BF0 — merely present (Value defines neither, so `proto` is undefined
// and any method counts). A sink without `verb` takes `fallback` (BR1/BI0),
// which is correct for position-agnostic sinks (aggregates, length). Pass
// `verb = undefined` to force the fallback (object BR1 — no array variant).
// `verb`/`fallback` are constant string literals at each call site, so V8
// specializes `sink[verb]` back to a fixed-offset access after inlining.
fanout(verb, fallback, payload) {
const proto = verb && Value.prototype[verb];
for (const x of this.sinks) {
const sink = x.deref?.();
if (!sink) {
this.sinks.delete(x);
continue;
}
const m = verb && sink[verb];
m && (proto === void 0 || m !== proto) ? m.call(sink, payload, this) : sink[fallback](payload, this);
}
}
each(fn) {
for (const [name, ref] of this.views) {
const res = ref.deref?.();
if (!res) {
this.views.delete(name);
continue;
}
fn(name, res);
}
}
get_or_create_named(name) {
return this.views.get(name)?.deref?.() ?? create(
this.views,
name,
_View.child(this, name)
);
}
get_named(name) {
const res = this.views.get(name)?.deref?.();
if (!res) this.views.delete(name);
return res;
}
disconnect(sink) {
for (const x of this.sinks) {
const s = x.deref?.();
if (s === sink) {
this.sinks.delete(x);
break;
}
if (!s) {
this.sinks.delete(x);
continue;
}
}
}
connect(sink) {
this.sinks.add(new WeakRef(sink));
}
};
Sink = class {
};
LinkedView = class extends View {
constructor(p) {
super();
this.src = p[Symbols.view];
this.update(this.src);
}
update(value2, key = []) {
if (key.length) {
return this.src.res.update(value2, key);
}
if (value2 instanceof ViewProxy) value2 = value2[Symbols.view];
if (!(value2 instanceof View))
throw new Error("cannot set linked value to non-reactive source");
this.src.disconnect(this);
this.src = value2;
this.src.connect(this);
this.XU0();
}
insert(...args) {
return this.src.res.insert(...args);
}
remove(...args) {
return this.src.res.remove(...args);
}
// `value` and `res` are read-through to the source — the LinkedView itself
// never holds data, it's a transparent forwarder.
get value() {
return this.src.value;
}
set value(v) {
}
get res() {
return this;
}
set res(v) {
}
};
ArrSink = class {
constructor(p, arr) {
this.p = p;
this.arr = arr;
const refs = lifetimes.get(arr) ?? /* @__PURE__ */ new Set();
refs.add(this);
lifetimes.set(arr, refs);
this.update([], p.value);
}
update = (key, value2) => this.arr.push({ type: "update", key, value: sclone(value2) });
remove = (key, value2) => this.arr.push({ type: "remove", key, value: sclone(value2) });
insert = (key, value2, at) => this.arr.push({ type: "insert", key, value: sclone(value2), at });
XU0(value2) {
this.update([], value2);
}
BU1(U1) {
iter2(U1, (name, value2) => this.update([name], value2));
}
BU2(U2) {
iter2(U2, (key, value2) => this.update(key, value2));
}
BI0(I0) {
iter2(I0, (at, value2) => this.insert([], value2, at));
}
BI2(I0) {
iter3(I0, (key, value2, at) => this.insert(key, value2, at));
}
XR0(value2) {
this.remove([], value2);
}
BR1(R1) {
iter2(R1, (name, value2) => this.remove([name], value2));
}
BR2(R2) {
iter2(R2, (key, value2) => this.remove(key, value2));
}
move = (from, to) => this.arr.push({ type: "move", from, to });
BMV1(M1) {
iter2(M1, (from, to) => this.move(+from, +to));
}
R0(value2) {
this.arr.push({ type: "remove", key: [], value: sclone(value2) });
}
R1(name, value2) {
this.arr.push({ type: "remove", key: [name], value: sclone(value2) });
}
R2(key, value2) {
this.arr.push({ type: "remove", key, value: sclone(value2) });
}
U0(value2) {
this.arr.push({ type: "update", key: [], value: sclone(value2) });
}
U1(name, value2) {
this.arr.push({ type: "update", key: [name], value: sclone(value2) });
}
U2(key, value2) {
this.arr.push({ type: "update", key, value: sclone(value2) });
}
I0(value2, at) {
this.arr.push({ type: "insert", value: sclone(value2), at });
}
I1(name, value2, at) {
this.arr.push({ type: "insert", key: [name], value: sclone(value2), at });
}
I2(key, value2, at) {
this.arr.push({ type: "insert", key, value: sclone(value2), at });
}
};
lifetimes = /* @__PURE__ */ new WeakMap();
PropSink = class extends Sink {
p;
obj;
prop;
constructor(p, obj, prop) {
super();
this.p = p;
this.obj = obj;
this.prop = prop;
this.obj[prop] = p.value;
const refs = lifetimes.get(obj) ?? /* @__PURE__ */ new Set();
refs.add(this);
lifetimes.set(obj, refs);
}
XU0(value2) {
this.obj[this.prop] = value2;
}
XR0() {
this.XU0(this.p.value);
}
BU1() {
this.XU0(this.p.value);
}
BR1() {
this.XU0(this.p.value);
}
BI0() {
this.XU0(this.p.value);
}
BU2() {
this.XU0(this.p.value);
}
BR2() {
this.XU0(this.p.value);
}
BI2() {
this.XU0(this.p.value);
}
BMV1() {
this.XU0(this.p.value);
}
};
FunctionSink = class extends Sink {
constructor(p, obj, fn) {
super();
this.fn = fn;
const refs = lifetimes.get(obj) ?? /* @__PURE__ */ new Set();
refs.add(this);
lifetimes.set(obj, refs);
fn({ type: "update", key: [], value: sclone(p.value) });
}
XU0(value2) {
this.fn({ type: "update", key: [], value: sclone(value2) });
}
XR0(value2) {
this.fn({ type: "remove", key: [], value: sclone(value2) });
}
BU1(U1) {
iter2(U1, (name, value2) => this.fn({ type: "update", key: [name], value: sclone(value2) }));
}
BU2(U2) {
iter2(U2, (key, value2) => this.fn({ type: "update", key, value: sclone(value2) }));
}
BI0(I0) {
iter2(I0, (at, value2) => this.fn({ type: "insert", key: [], value: sclone(value2), at }));
}
BI2(I2) {
iter3(I2, (key, value2, at) => this.fn({ type: "insert", key, value: sclone(value2), at }));
}
BR1(R1) {
iter2(R1, (name, value2) => this.fn({ type: "remove", key: [name], value: sclone(value2) }));
}
BR2(R2) {
iter2(R2, (key, value2) => this.fn({ type: "remove", key, value: sclone(value2) }));
}
BMV1(M1) {
iter2(M1, (from, to) => this.fn({ type: "move", from: +from, to: +to }));
}
};
ViewProxy = class _ViewProxy {
view;
constructor(view2) {
this.view = view2;
return new Proxy(noop, this);
}
deleteProperty(target, name) {
const { res, key } = this.view;
const path = name === Symbols.value ? key : [...key, "" + name];
res.remove(path);
return true;
}
set(t, name, value2) {
const { res, key } = this.view;
const path = name === Symbols.value ? key : [...key, name];
res.update(value2, path);
return true;
}
// Special-cased property reads:
// Symbol.toPrimitive — used by template literals and arithmetic. `hint`
// is "string" | "number" | "default"; truthy hint means string context.
// Symbol.iterator — lets `for (const x of proxy)` walk numeric indices.
// Symbols.reactive — branding so foreign code can detect ViewProxies.
// Symbols.view — internal: the underlying View object.
// Symbols.value — the raw snapshot. Reading proxy.value would create
// a child view named "value" instead — that's the
// canonical gotcha noted in CLAUDE.md.
get(t, name) {
if (name === Symbol.toPrimitive) return (hint) => hint ? this.view.value?.toString() : +this.view.value;
if (name === Symbol.iterator) return this.iterator;
if (name === Symbols.reactive) return true;
if (name === Symbols.view) return this.view;
if (name === Symbols.value) return this.view.value;
return new _ViewProxy(this.view.get_or_create_named(name));
}
// `proxy.filter(fn)` arrives here as: get → child view named "filter" →
// apply. The child view's `name` tells us which operator to construct.
// `connect`, `update`, `insert`, `remove` are handled directly without
// going through the operator dispatch table.
apply(t, m, args) {
const { p, name: type } = this.view;
if (!p) throw new Error("cannot invoke a root value!");
if (type === "then" && typeof args[0] === "function") {
const [onFulfilled, onRejected] = args;
try {
onFulfilled(p.value);
} catch (e) {
if (typeof onRejected === "function") onRejected(e);
}
return;
}
if (type === "connect") return connect(p, ...args);
if (type === "raf") return raf(p);
if (type === "patch") {
const { res, key } = p;
const pairs = args[0];
if (!key.length) return res.BU1(pairs);
const U2 = [];
for (let i = 0; i < pairs.length; i += 2) U2.push([...key, pairs[i]], pairs[i + 1]);
return res.BU2(U2);
}
if (type === "first") return new _ViewProxy(p.get_or_create_named(firstKey(p.value)));
if (type === "last") return new _ViewProxy(p.get_or_create_named(lastKey(p.value)));
const OperatorClass = Operators[type]?.(...args);
if (OperatorClass) {
let sink = p.some_sink((sink2) => sink2 instanceof OperatorClass && sink2.matches?.(...args) ? sink2 : void 0);
if (!sink) {
p.sinks.add(new WeakRef(sink = new OperatorClass(p, ...args)));
}
return new _ViewProxy(sink.view);
}
const [value2, at] = args;
if (type === "remove") return this.view.res.remove(p.key);
if (type === "update") return this.view.res.update(value2, p.key);
if (type === "insert") return this.view.res.insert(value2, p.key, at);
throw new Error(`Unknown operator '${type}'. Chainable operators (.filter, .between, .length, etc.) register when you import from 'data' (the default entry) or 'data/full' (adds JSX). You're seeing this because the dispatch table is empty \u2014 likely an import from 'data/lean' (the registration-free core). Switch to 'data', or register the operators you need onto the exported 'Operators' table yourself.`);
}
getPrototypeOf(target) {
return _ViewProxy.prototype;
}
// Open-ended counter — relies on the consumer to break out (typically
// `.slice()` or destructuring with a fixed length). The reactive view
// doesn't know its own length without resolving `value` first.
*iterator(i = 0) {
while (true) {
yield this[i++];
}
}
};
}
});
// devtools/walk.ts
function* iterRoots(opts) {
const includeInternal = opts && opts.internal;
for (const ref of _devtoolsRoots) {
const v = ref.deref();
if (!v) {
_devtoolsRoots.delete(ref);
continue;
}
if (!includeInternal && _devtoolsInternalRoots.has(v)) continue;
yield v;
}
}
function classify(sink) {
if (sink instanceof Operator) return "operator";
if (sink && typeof sink === "object") {
if ("parent" in sink && sink.constructor?.name === "DOMSink") return "dom";
const n = sink.constructor?.name;
if (n === "ArrSink" || n === "PropSink" || n === "FunctionSink") return "connect";
}
return "sink";
}
function summarize(value2) {
if (value2 === null || value2 === void 0) return value2;
const t = typeof value2;
if (t === "string") return value2.length > 80 ? value2.slice(0, 77) + "..." : value2;
if (t === "number" || t === "boolean" || t === "bigint" || t === "symbol") return value2;
if (Array.isArray(value2)) return `Array(${value2.length})`;
if (t === "function") return `Function(${value2.name || "anonymous"})`;
if (t === "object") return `{ keys: ${Object.keys(value2).length} }`;
return String(value2);
}
function ancestorOf(child, root, maxDepth = 32) {
if (!child || !root) return false;
if (child === root) return true;
let n = child, d = 0;
while (n && d < maxDepth) {
if (n === root) return true;
n = n.p;
d++;
}
return false;
}
function walk(view2, opts) {
opts = opts || {};
return walkImpl(view2, opts.seen || /* @__PURE__ */ new WeakSet(), opts);
}
function walkImpl(view2, seen, opts) {
if (seen.has(view2)) {
return { key: [...view2.key], kind: "cycle", children: [], sinks: [] };
}
seen.add(view2);
if ("src" in view2 && view2.src && view2.src !== view2) {
return {
key: [...view2.key],
name: view2.name,
kind: "linked-alias",
aliasOf: view2.src.key ? [...view2.src.key] : [],
children: [],
sinks: []
};
}
const node = {
key: [...view2.key],
name: view2.name,
kind: view2.p ? "child" : "root",
value: summarize(view2.value),
children: [],
sinks: []
};
view2.each?.((_name, child) => {
const c = walkImpl(child, seen, opts);
if (c.picked || c.pickedAncestor) node.pickedAncestor = true;
node.children.push(c);
});
view2.sink?.((s) => {
if (s instanceof Operator) {
const opNode = walkImpl(s.view, seen, opts);
opNode.kind = "operator";
opNode.ctor = s.constructor.name;
if (opts.pickedSink === s) opNode.picked = true;
if (opNode.picked || opNode.pickedAncestor) node.pickedAncestor = true;
node.sinks.push(opNode);
} else {
const sinkNode = {
key: [...view2.key],
kind: classify(s),
ctor: s.constructor?.name || "anonymous",
children: [],
sinks: []
};
if (opts.pickedSink === s) {
sinkNode.picked = true;
node.pickedAncestor = true;
}
node.sinks.push(sinkNode);
}
});
return node;
}
var init_walk = __esm({
"devtools/walk.ts"() {
init_core();
}
});
// devtools/panel/index.ts
var panel_exports = {};
__export(panel_exports, {
getShell: () => getShell,
mount: () => mount,
unmount: () => unmount
});
function mount(rootProxy) {
if (typeof document === "undefined") return null;
if (current) return current;
if (!rootProxy) {
const first = iterRoots().next().value;
if (first) rootProxy = new ViewProxy(first);
}
if (rootProxy) {
if (pollTimer) {
clearTimeout(pollTimer);
pollTimer = null;
}
current = mountPanel({ rootProxy });
return current;
}
if (!pollTimer) {
let tries = 0;
const tick = () => {
pollTimer = null;
if (current) return;
const r = iterRoots().next().value;
if (r) {
current = mountPanel({ rootProxy: new ViewProxy(r) });
return;
}
if (++tries < 100) pollTimer = setTimeout(tick, 50);
};
pollTimer = setTimeout(tick, 0);
}
return null;
}
function unmount() {
if (pollTimer) {
clearTimeout(pollTimer);
pollTimer = null;
}
if (!current) return;
try {
current.destroy();
} catch {
}
current = null;
}
function getShell() {
return current;
}
function mountPanel({ rootProxy }) {
const host = document.createElement("div");
host.className = "__ripple_panel_host";
document.body.appendChild(host);
const root = host.attachShadow({ mode: "closed" });
root.appendChild(makeStyle());
const dock = el("aside", "dock");
root.appendChild(dock);
const DOCK_WIDTH_KEY = "data-devtools-dock-width";
const DOCK_MIN = 320;
const dockMax = () => Math.max(DOCK_MIN, window.innerWidth - 60);
const savedWidth = (() => {
const raw = parseInt(localStorage.getItem(DOCK_WIDTH_KEY) || "", 10);
return Number.isFinite(raw) ? Math.max(DOCK_MIN, Math.min(dockMax(), raw)) : null;
})();
if (savedWidth != null) dock.style.width = savedWidth + "px";
const dockResize = el("div", "dock-resize");
dockResize.title = "drag to resize the dock";
dock.appendChild(dockResize);
let dockResizeDrag = null;
dockResize.addEventListener("pointerdown", (e) => {
dockResizeDrag = { startX: e.clientX, startW: dock.getBoundingClientRect().width };
try {
dockResize.setPointerCapture(e.pointerId);
} catch {
}
dockResize.classList.add("dragging");
e.preventDefault();
});
dockResize.addEventListener("pointermove", (e) => {
if (!dockResizeDrag) return;
const dx = e.clientX - dockResizeDrag.startX;
const w = Math.max(DOCK_MIN, Math.min(dockMax(), dockResizeDrag.startW - dx));
dock.style.width = w + "px";
});
const endDockResize = (e) => {
if (!dockResizeDrag) return;
dockResizeDrag = null;
dockResize.classList.remove("dragging");
try {
dockResize.releasePointerCapture(e.pointerId);
} catch {
}
localStorage.setItem(DOCK_WIDTH_KEY, String(Math.round(dock.getBoundingClientRect().width)));
};
dockResize.addEventListener("pointerup", endDockResize);
dockResize.addEventListener("pointercancel", endDockResize);
const header = el("div", "dock-header");
header.append(
el("span", "brand", { text: "data devtools" }),
(() => {
const tools = el("div", "tools");
const hover = mkBtn("\u2299", "arm Alt-hover (or hold Alt)");
const pick = mkBtn("\u25CE", "pick a DOM element to find its view");
const close = mkBtn("\u2715", "close panel");
tools.append(hover, pick, close);
hover.addEventListener("click", () => altHover.toggleArm());
pick.addEventListener("click", () => domPicker.toggleArm());
close.addEventListener("click", () => destroy());
tools.dataset.role = "tools";
return tools;
})()
);
dock.appendChild(header);
const toolbar2 = el("div", "dock-toolbar2");
const layoutLabel = el("span", "layout-pick-label", { text: "layout:" });
const seg = el("div", "seg");
const treeBtn = el("button", "", { text: "Tree" });
const dagBtn = el("button", "active", { text: "DAG" });
seg.append(treeBtn, dagBtn);
toolbar2.append(layoutLabel, seg);
dock.appendChild(toolbar2);
let layout = "dag";
const setLayout = (next) => {
layout = next;
treeBtn.classList.toggle("active", next === "tree");
dagBtn.classList.toggle("active", next === "dag");
dagView = { scale: null, tx: null, ty: null };
rerenderGraph();
};
treeBtn.addEventListener("click", () => setLayout("tree"));
dagBtn.addEventListener("click", () => setLayout("dag"));
const dockBody = el("div", "dock-body");
dock.appendChild(dockBody);
const graphPane = el("div", "graph-pane");
dockBody.appendChild(graphPane);
let selectedView = null;
let focusedPath = null;
let hideSinks = true;
let heatmapMode = false;
let dagView = { scale: null, tx: null, ty: null };
const heat = /* @__PURE__ */ new Map();
let heatDispose = null;
let heatTick = null;
const startHeatmap = () => {
if (heatDispose) return;
heatDispose = $.trace(rootProxy, {
log: false,
onEvent: (e) => {
const k = (e.key || []).join(".") || "<root>";
heat.set(k, performance.now());
if (e.key && e.key.length) {
for (let i = e.key.length - 1; i >= 0; i--) {
const ak = e.key.slice(0, i).join(".") || "<root>";
if (!heat.has(ak) || heat.get(ak) < performance.now() - 100) heat.set(ak, performance.now());
}
}
scheduleRewalk();
}
});
heatTick = setInterval(() => {
if (layout === "dag") rerenderGraph();
}, 500);
};
const stopHeatmap = () => {
if (heatDispose) {
heatDispose();
heatDispose = null;
}
if (heatTick) {
clearInterval(heatTick);
heatTick = null;
}
heat.clear();
};
let rwQueued = false;
const scheduleRewalk = () => {
if (rwQueued) return;
rwQueued = true;
requestAnimationFrame(() => {
rwQueued = false;
rerenderGraph();
refreshInspector();
});
};
const TERMINAL_KINDS = /* @__PURE__ */ new Set(["dom", "connect", "linked-alias"]);
const summarizeValue = (v) => {
if (v === null || v === void 0) return v;
const t = typeof v;
if (t === "string") return v.length > 80 ? v.slice(0, 77) + "\u2026" : v;
if (Array.isArray(v)) return `Array(${v.length})`;
if (t === "object") return `{ keys: ${Object.keys(v).length} }`;
return String(v);
};
const classifyLocal = (s) => {
const n = s?.constructor?.name;
if (n === "DOMSink") return "dom";
if (n === "ArrSink" || n === "PropSink" || n === "FunctionSink") return "connect";
return "sink";
};
function walkGraph(rootProxy2) {
const rv = rootProxy2?.[view];
if (!rv) return null;
const seen = /* @__PURE__ */ new WeakSet();
const walk2 = (v, parent) => {
if (seen.has(v)) {
return { key: [...v.key], kind: "cycle", children: [], sinks: [], _view: v, _parent: parent };
}
seen.add(v);
if ("src" in v && v.src && v.src !== v) {
return {
key: [...v.key],
name: v.name,
kind: "linked-alias",
aliasOf: v.src.key ? [...v.src.key] : [],
children: [],
sinks: [],
_view: v,
_parent: parent
};
}
const node = {
key: [...v.key],
name: v.name,
kind: v.p ? "child" : "root",
value: summarizeValue(v.value),
children: [],
sinks: [],
_view: v,
_parent: parent
};
v.each?.((_n, child) => node.children.push(walk2(child, node)));
v.sink?.((s) => {
if (s && typeof s === "object" && s.view) {
const opNode = walk2(s.view, node);
opNode.kind = "operator";
opNode.ctor = s.constructor.name;
node.sinks.push(opNode);
} else if (s && typeof s === "object") {
node.sinks.push({
key: [...v.key],
kind: classifyLocal(s),
ctor: s.constructor?.name || "anonymous",
children: [],
sinks: [],
_sink: s,
_parent: node
});
}
});
return node;
};
return walk2(rv, null);
}
function buildChain(node) {
const segments = [];
let cur = node;
while (cur) {
segments.unshift(cur);
cur = cur._parent;
}
if (segments.length === 0) return "?";
let s = "";
for (let i = 0; i < segments.length; i++) {
const seg2 = segments[i];
if (i === 0) s += seg2.name || "root";
else if (seg2.kind === "operator") s += `.${methodOfCtor(seg2.ctor)}()`;
else if (seg2.kind === "child") s += `.${seg2.name ?? "?"}`;
else if (seg2.kind === "linked-alias") s += `~>${(seg2.aliasOf || []).join(".") || "root"}`;
else if (seg2.kind === "cycle") s += "\u21BB";
else s += `[${seg2.kind}]`;
}
return s;
}
function formatLiveValue(v, maxLen = 220) {
if (v === void 0) return "undefined";
if (v === null) return "null";
const t = typeof v;
if (t === "string") {
const trimmed = v.length > maxLen ? v.slice(0, maxLen) + "\u2026" : v;
return JSON.stringify(trimmed);
}
if (t === "number" || t === "bigint" || t === "boolean") return String(v);
if (Array.isArray(v)) {
if (v.length === 0) return "[]";
const previews = v.slice(0, 4).map((x) => " " + formatLiveValue(x, 60));
return `Array(${v.length}) [
${previews.join(",\n")}${v.length > 4 ? ",\n \u2026" : ""}
]`;
}
if (t === "object") {
const keys = Object.keys(v);
if (keys.length === 0) return "{}";
const previews = keys.slice(0, 4).map((k) => ` ${k}: ${formatLiveValue(v[k], 60)}`);
return `{
${previews.join(",\n")}${keys.length > 4 ? ",\n \u2026" : ""}
}`;
}
return String(v);
}
function valueTypeLabel(v) {
if (v === void 0) return "undefined";
if (v === null) return "null";
if (Array.isArray(v)) return `Array(${v.length})`;
const t = typeof v;
if (t === "object") return `Object \xB7 ${Object.keys(v).length} key${Object.keys(v).length === 1 ? "" : "s"}`;
return t[0].toUpperCase() + t.slice(1);
}
function propSinkDomTarget(s) {
if (!s || s.constructor?.name !== "PropSink") return null;
const obj = s.obj;
if (!obj) return null;
if (obj.parent && obj.parent.nodeType) {
const ctor = obj.constructor?.name || "";
let label;
switch (ctor) {
case "Text":
label = "textContent";
break;
case "Attr":
label = `[${obj.name}]`;
break;
case "Class":
label = `.${obj.name}`;
break;
case "ID":
label = "#id";
break;
case "Style":
label = `style.${obj.name}`;
break;
default:
label = `${ctor || "prop"}.${s.prop}`;
}
return { el: obj.parent, kind: ctor.toLowerCase() || "prop", label };
}
if (obj.nodeType) return { el: obj, kind: "prop", label: `.${s.prop}` };
return null;
}
function collectB