kerfjs 5.0.0-beta.122 → 5.0.0-beta.124

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.
Files changed (54) hide show
  1. package/CHANGELOG.md +235 -0
  2. package/ai/cursorrules +17 -7
  3. package/ai/manifest.json +13 -7
  4. package/ai/skill.md +18 -9
  5. package/dist/actions.js +1 -1
  6. package/dist/array-signal.js +1 -1
  7. package/dist/async.d.ts +7 -3
  8. package/dist/async.js +16 -2
  9. package/dist/async.js.map +1 -1
  10. package/dist/chunk-KOEGJCIS.js +65 -0
  11. package/dist/chunk-KOEGJCIS.js.map +1 -0
  12. package/dist/{chunk-3C6F6NM4.js → chunk-KUHXPPJ4.js} +1 -1
  13. package/dist/{chunk-3C6F6NM4.js.map → chunk-KUHXPPJ4.js.map} +1 -1
  14. package/dist/{chunk-YVBK73GU.js → chunk-MFRXN2G4.js} +16 -12
  15. package/dist/chunk-MFRXN2G4.js.map +1 -0
  16. package/dist/chunk-N4VHHOCM.js +27 -0
  17. package/dist/chunk-N4VHHOCM.js.map +1 -0
  18. package/dist/{chunk-BI4HGICV.js → chunk-OWNZCCJX.js} +3 -3
  19. package/dist/{chunk-BI4HGICV.js.map → chunk-OWNZCCJX.js.map} +1 -1
  20. package/dist/{chunk-H7WTRM6F.js → chunk-QOAB2ESQ.js} +2 -2
  21. package/dist/{chunk-H7WTRM6F.js.map → chunk-QOAB2ESQ.js.map} +1 -1
  22. package/dist/{chunk-VX3RCRGG.js → chunk-XL35DIZ2.js} +7 -7
  23. package/dist/chunk-XL35DIZ2.js.map +1 -0
  24. package/dist/{chunk-JN7EJM3B.js → chunk-ZZI5NJIV.js} +2 -2
  25. package/dist/{chunk-JN7EJM3B.js.map → chunk-ZZI5NJIV.js.map} +1 -1
  26. package/dist/dev.d.ts +18 -5
  27. package/dist/dev.js +84 -5
  28. package/dist/dev.js.map +1 -1
  29. package/dist/html.js +2 -2
  30. package/dist/index.d.ts +90 -10
  31. package/dist/index.js +25 -6
  32. package/dist/index.js.map +1 -1
  33. package/dist/jsx-runtime.js +1 -1
  34. package/dist/list.js +3 -3
  35. package/dist/overlay.d.ts +9 -9
  36. package/dist/overlay.js +4 -4
  37. package/dist/overlay.js.map +1 -1
  38. package/dist/remount.js +2 -2
  39. package/dist/router.d.ts +3 -1
  40. package/dist/router.js +18 -9
  41. package/dist/router.js.map +1 -1
  42. package/dist/scope.js +3 -3
  43. package/dist/testing.js +1 -1
  44. package/dist/timing.js +1 -1
  45. package/llms.txt +3 -1
  46. package/package.json +2 -2
  47. package/setup/cli.mjs +3 -2
  48. package/setup/index.d.mts +2 -1
  49. package/setup/index.mjs +112 -75
  50. package/setup/state.schema.json +1 -1
  51. package/dist/chunk-IHMDBBUJ.js +0 -20
  52. package/dist/chunk-IHMDBBUJ.js.map +0 -1
  53. package/dist/chunk-VX3RCRGG.js.map +0 -1
  54. package/dist/chunk-YVBK73GU.js.map +0 -1
package/ai/skill.md CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: kerf-app
3
3
  description: Build UIs in the kerf reactive framework and its @kerfjs/ui component package (https://github.com/brianwestphal/kerf). Use this skill whenever the user is writing or modifying code that imports `kerfjs` or `@kerfjs/ui`, asks to add a feature to a kerf app, or asks "how do I do X in kerf?". Use it proactively the moment you spot a kerf import in the file you're editing.
4
- kerf-skill-version: 1.28.0
4
+ kerf-skill-version: 1.31.0
5
5
  ---
6
6
 
7
7
  # Building apps with kerf
@@ -98,16 +98,18 @@ match Hot Sheet 2 and Web Awesome: override `--kui-color-*` globally or
98
98
  component properties such as `--kui-state-banner-background` at a tone or
99
99
  instance boundary, for theming only.
100
100
 
101
- For Web Awesome's broader free component set, import the CSS-only
102
- `@kerfjs/ui/webawesome.css` theme once, then import only each Web Awesome
103
- component module the app renders. The theme registers no component JavaScript
104
- and remains overridable through later or scoped `--wa-*` values.
101
+ Scope a subtree to the light or dark palette with a component's
102
+ `scheme="light" | "dark"` prop or Kerf's `.kui-light` / `.kui-dark` /
103
+ `.kui-invert` classes; they need no Web Awesome CSS. Only with the optional
104
+ Web Awesome integration: import the CSS-only `@kerfjs/ui/webawesome.css` theme
105
+ once, then only each Web Awesome component module the app renders. The theme
106
+ registers no component JavaScript and remains overridable through later or
107
+ scoped `--wa-*` values.
105
108
 
106
- `Select` renders pure Web Awesome markup. Import
109
+ `Select` is a form-associated Kerf custom element. Import
107
110
  `@kerfjs/ui/select/register` once in an application entry that uses it; never
108
111
  hide that registration inside another component. Web Awesome is an optional
109
- peer and must remain absent from bundles that use neither Select nor the Web
110
- Awesome theme. The package's
112
+ peer that only the `@kerfjs/ui/webawesome.css` theme touches. The package's
111
113
  full AI contract is at `node_modules/@kerfjs/ui/ai/skill.md`.
112
114
 
113
115
  ## Public API — one import path
@@ -117,7 +119,9 @@ import {
117
119
  signal,
118
120
  computed,
119
121
  effect,
120
- batch, // reactivity
122
+ batch,
123
+ selector,
124
+ setSelector, // reactivity
121
125
  defineStore,
122
126
  resetAllStores, // stores
123
127
  mount,
@@ -146,6 +150,8 @@ if (import.meta.env.DEV) await import("kerfjs/dev");
146
150
  | `computed(fn)` | derived value, read-only |
147
151
  | `effect(fn)` | side effect on signal change; returns disposer |
148
152
  | `batch(fn)` | coalesce multiple writes into one re-run |
153
+ | `selector(source)` | keyed equality at O(1) per change: `selector(selectedId)(row.id).value` is true for the selected row; one subscription instead of one per row |
154
+ | `setSelector(source)` | membership in a `ReadonlySet` signal; a write notifies only the added/removed members (multi-select, expanded rows) |
149
155
  | `defineStore({initial, actions})` | named multi-consumer state |
150
156
  | `resetAllStores()` | reset every store (test teardown) |
151
157
  | `mount(el, render)` | bind reactive render to a DOM element; returns disposer |
@@ -278,6 +284,9 @@ mount(listEl, () => (
278
284
  </ul>
279
285
  ));
280
286
  // selectedId.value = 3 → only the ~2 affected <li> class attrs update.
287
+ // Large list: `const isSelected = selector(selectedId)` (from "kerfjs") and
288
+ // `computed(() => (isSelected(row.id).value ? "sel" : ""))` — one subscription
289
+ // to selectedId instead of one per row, so a selection flip is O(1).
281
290
 
282
291
  // Pattern 6: no build step (CDN / importmap) — the html tagged template
283
292
  // instead of JSX. Same runtime semantics; real HTML attribute names; a hole
package/dist/actions.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { attr } from './chunk-MK42GLPV.js';
2
- import { _delegate, NON_BUBBLING } from './chunk-JN7EJM3B.js';
2
+ import { _delegate, NON_BUBBLING } from './chunk-ZZI5NJIV.js';
3
3
 
4
4
 
5
5
  // src/actions.ts
@@ -1,4 +1,4 @@
1
- export { ARRAY_SIGNAL_BRAND, ArraySignal, arraySignal } from './chunk-H7WTRM6F.js';
1
+ export { ARRAY_SIGNAL_BRAND, ArraySignal, arraySignal } from './chunk-QOAB2ESQ.js';
2
2
 
3
3
 
4
4
 
package/dist/async.d.ts CHANGED
@@ -51,10 +51,14 @@ interface ResourceOptions<T, I = void> {
51
51
  }
52
52
  /**
53
53
  * The fetcher passed to {@link Resource.run}. You own the transport. It receives
54
- * a `report(completed, total)` callback for optional progress — ignore it if you
55
- * don't need progress (a plain `() => Promise<T>` is assignable here).
54
+ * a `report(completed, total)` callback for optional progress and an
55
+ * `AbortSignal` that aborts when a newer run supersedes this one or the
56
+ * resource is `reset()` — never after this run settles. Ignore either if you
57
+ * don't need it (a plain `() => Promise<T>` or `(report) => Promise<T>` is
58
+ * assignable here). The abort rejection of a superseded run is dropped by the
59
+ * stale guard, so it never surfaces as `failed`.
56
60
  */
57
- type ResourceFetcher<T> = (report: (completed: number, total: number) => void) => Promise<T>;
61
+ type ResourceFetcher<T> = (report: (completed: number, total: number) => void, signal: AbortSignal) => Promise<T>;
58
62
  /**
59
63
  * An async-state container. Its `value` is a tracking read; drive UI off
60
64
  * `value.status`. `I` is the run-input type — parametrize it (`resource<T, I>()`)
package/dist/async.js CHANGED
@@ -1,4 +1,4 @@
1
- import { signal } from './chunk-IHMDBBUJ.js';
1
+ import { signal } from './chunk-N4VHHOCM.js';
2
2
 
3
3
 
4
4
  // src/async.ts
@@ -28,12 +28,23 @@ function resource(options = {}) {
28
28
  revision: 0
29
29
  });
30
30
  let generation = 0;
31
+ let controller;
32
+ const supersede = () => {
33
+ controller?.abort();
34
+ controller = void 0;
35
+ };
31
36
  function run(inputOrFetcher, maybeFetcher) {
32
37
  const fetcher = maybeFetcher ?? inputOrFetcher;
33
38
  const input = maybeFetcher === void 0 ? void 0 : inputOrFetcher;
34
39
  const key = cacheKey !== void 0 && maybeFetcher !== void 0 ? cacheKey(input) : void 0;
35
40
  const runningData = cacheKey !== void 0 ? key !== void 0 ? cache.get(key) : void 0 : state.peek().data;
41
+ supersede();
36
42
  const gen = ++generation;
43
+ const own = new AbortController();
44
+ controller = own;
45
+ const settled = () => {
46
+ if (controller === own) controller = void 0;
47
+ };
37
48
  state.value = {
38
49
  status: "running",
39
50
  data: runningData,
@@ -48,6 +59,7 @@ function resource(options = {}) {
48
59
  }
49
60
  };
50
61
  const fail = (error) => {
62
+ settled();
51
63
  if (gen === generation) {
52
64
  state.value = {
53
65
  ...state.peek(),
@@ -61,11 +73,12 @@ function resource(options = {}) {
61
73
  };
62
74
  let pending;
63
75
  try {
64
- pending = fetcher(report);
76
+ pending = fetcher(report, own.signal);
65
77
  } catch (error) {
66
78
  return Promise.resolve(fail(error));
67
79
  }
68
80
  return pending.then((data) => {
81
+ settled();
69
82
  if (gen === generation) {
70
83
  if (key !== void 0) cache.set(key, data);
71
84
  state.value = {
@@ -82,6 +95,7 @@ function resource(options = {}) {
82
95
  }
83
96
  function reset() {
84
97
  generation++;
98
+ supersede();
85
99
  cache.clear();
86
100
  state.value = {
87
101
  status: "idle",
package/dist/async.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/async.ts"],"names":[],"mappings":";;;;AA0IO,SAAS,QAAA,CACd,OAAA,GAAiC,EAAC,EAClB;AAChB,EAAA,MAAM,EAAE,QAAA,EAAU,MAAA,EAAO,GAAI,OAAA;AAC7B,EAAA,MAAM,EAAA,GAA8B,UAAU,M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UACR,IAAA;AAAA,UACA,KAAA,EAAO,MAAA;AAAA,UACP,QAAA,EAAU,MAAA;AAAA,UACV,KAAA;AAAA,UACA,QAAA,EAAU,OAAO,IAAI;AAAA,SACvB;AAAA,MACF;AACA,MAAA,OAAO,IAAA;AAAA,IACT,GAAG,IAAI,CAAA;AAAA,EACT;AAEA,EAAA,SAAS,KAAA,GAAc;AACrB,IAAA,UAAA,EAAA;AACA,IAAA,KAAA,CAAM,KAAA,EAAM;AACZ,IAAA,KAAA,CAAM,KAAA,GAAQ;AAAA,MACZ,MAAA,EAAQ,MAAA;AAAA,MACR,IAAA,EAAM,MAAA;AAAA,MACN,KAAA,EAAO,MAAA;AAAA,MACP,QAAA,EAAU,MAAA;AAAA,MACV,KAAA,EAAO,MAAA;AAAA,MACP,QAAA,EAAU,OAAO,MAAS;AAAA,KAC5B;AAAA,EACF;AAEA,EAAA,OAAO;AAAA,IACL,IAAI,KAAA,GAAQ;AACV,MAAA,OAAO,KAAA,CAAM,KAAA;AAAA,IACf,CAAA;AAAA,IACA,GAAA;AAAA,IACA,KAAA;AAAA,IACA,MAAA,EAAQ,CAAC,CAAA,KAAM,KAAA,CAAM,IAAI,CAAC,CAAA;AAAA,IAC1B,YAAY,MAAM,KAAA,CAAM,IAAA,CAAK,KAAA,CAAM,MAAM,CAAA;AAAA,IACzC,UAAA,EAAY,CAAC,CAAA,KAAM;AACjB,MAAA,IAAI,CAAA,KAAM,MAAA,EAAW,KAAA,CAAM,KAAA,EAAM;AAAA,WAC5B,KAAA,CAAM,OAAO,CAAC,CAAA;AAAA,IACrB;AAAA,GACF;AACF","file":"async.js","sourcesContent":["/**\n * `kerfjs/async` — model async state, with the stale-response guard built in.\n *\n * Every real kerf app reproduces the same shape — `{ status, data, error }` —\n * for loading/error UI, each paired with a hand-rolled generation counter so a\n * slow response can't overwrite a newer one. This subpath blesses exactly that,\n * and no more: you still write the fetch (Node `fetch` for SSR, browser `fetch`\n * client-side), and `.run()` owns the status transitions plus the stale guard.\n *\n * import { resource } from 'kerfjs/async';\n *\n * const users = resource<User[]>();\n * users.run(() => fetch('/api/users').then((r) => r.json()));\n * // render off users.value.status: 'idle' | 'running' | 'completed' | 'failed'\n *\n * Only the LATEST run may resolve the state, so out-of-order responses are\n * dropped automatically. Optional progress: declare the `report` parameter on\n * your fetcher and call it (e.g. from an upload's progress events).\n *\n * Pass an input — `run(input, fetcher)` — to carry which request a run is for\n * through to `value.input` (set for `running`/`completed`/`failed`), so a\n * failure handler can recover the id/params of the run that failed:\n *\n * const diff = resource<Diff, { fileId: string }>();\n * diff.run({ fileId }, (report) => fetchDiff(fileId, report));\n * // on failure: diff.value.status === 'failed' && diff.value.input.fileId\n *\n * For a real SWR-with-cache section, pass `cacheKey` to keep the last value PER\n * input key (switching back to a loaded key paints its cached slice instantly\n * while it revalidates), and read `value.revision` — a counter that bumps only\n * when `data` actually CHANGES (by `equals`, default `Object.is`) — to skip a\n * redundant paint when a poll tick returns identical data:\n *\n * const win = resource<Slice, string>({ cacheKey: (w) => w, equals: sameSlice });\n * win.run(w, () => fetchSlice(w)); // instant cached paint for a revisited w\n */\nimport { signal } from './reactive.js';\n\n/** The lifecycle status of a {@link Resource}. */\nexport type ResourceStatus = 'idle' | 'running' | 'completed' | 'failed';\n\n/** Optional progress for a long-running fetch (uploads, chunked work). */\nexport interface ResourceProgress {\n completed: number;\n total: number;\n}\n\n/** The reactive state a {@link Resource} exposes. */\nexport interface ResourceState<T, I = void> {\n status: ResourceStatus;\n /** The last successful value. Kept across a re-run (stale-while-revalidate) and on failure. */\n data: T | undefined;\n /** The rejection from the most recent failed run. */\n error: unknown;\n /** Latest reported progress while running, or `undefined`. */\n progress: ResourceProgress | undefined;\n /**\n * The input of the LATEST run — the value passed to {@link Resource.run} as\n * `run(input, fetcher)`. Set for `running`, `completed`, AND `failed` (same\n * stale-guard rule as the rest of the state), so an effect can branch on\n * `status === 'failed'` and still know which request failed. `undefined` in\n * `idle`, and for the no-input `run(fetcher)` form.\n */\n input: I | undefined;\n /**\n * A monotonic counter that increments only when `data` actually CHANGES (by\n * the resource's `equals`, default `Object.is`). Compare it against the value\n * you last painted to skip a redundant re-render — e.g. a 30s poll returning\n * identical data leaves `revision` untouched, so you can bail before wiping\n * scroll / sort / hover state. Starts at `0`.\n */\n revision: number;\n}\n\n/** Construction options for {@link resource}. */\nexport interface ResourceOptions<T, I = void> {\n /**\n * Derive a cache key from a run's `input`. When set, the resource keeps the\n * last successful value PER key: starting a run for a key that was loaded\n * before paints its cached slice immediately (still `running`) while the fetch\n * revalidates in the background; a never-loaded key starts with no `data`.\n * Without `cacheKey`, a run keeps the previous run's `data` (single-slot\n * stale-while-revalidate), as before.\n */\n cacheKey?: (input: I) => string;\n /**\n * Equality used to decide whether `data` changed (drives `value.revision`).\n * Default `Object.is`. Pass a structural comparison to dedup a poll that\n * returns a fresh-but-equal object.\n */\n equals?: (a: T, b: T) => boolean;\n}\n\n/**\n * The fetcher passed to {@link Resource.run}. You own the transport. It receives\n * a `report(completed, total)` callback for optional progress — ignore it if you\n * don't need progress (a plain `() => Promise<T>` is assignable here).\n */\nexport type ResourceFetcher<T> = (\n report: (completed: number, total: number) => void,\n) => Promise<T>;\n\n/**\n * An async-state container. Its `value` is a tracking read; drive UI off\n * `value.status`. `I` is the run-input type — parametrize it (`resource<T, I>()`)\n * to carry a typed `run(input, fetcher)` input through to `value.input`.\n */\nexport interface Resource<T, I = void> {\n /** Tracking read of the current {@link ResourceState}. */\n readonly value: ResourceState<T, I>;\n /**\n * Run `fetcher`, driving `idle`/`running` → `completed`/`failed` and guarding\n * against stale responses (only the latest run resolves the state). Never\n * rejects — a failure lands in `value.error`; resolves with the data (or\n * `undefined` on failure) for callers who want to await it.\n */\n run(fetcher: ResourceFetcher<T>): Promise<T | undefined>;\n /**\n * Run `fetcher` for a given `input`, exposing it as `value.input` for the\n * `running`/`completed`/`failed` states of THIS run — so a failure handler can\n * recover which request failed. Same stale guard: only the latest run resolves.\n */\n run(input: I, fetcher: ResourceFetcher<T>): Promise<T | undefined>;\n /** Reset to `idle` (clearing data/error/progress/input, and the per-key cache) and invalidate any in-flight run. */\n reset(): void;\n /**\n * Read-only: the cached value for a `cacheKey` key, or `undefined` if that key\n * isn't cached (or no `cacheKey` was given). Lets a consumer ask \"is this slice\n * cached?\" without running it (which would mutate state).\n */\n cached(key: string): T | undefined;\n /** Read-only: the keys currently in the per-input cache (`.length` is the cache size). */\n cachedKeys(): string[];\n /** Evict the per-input cache — one `key`, or the whole cache when called with no argument. Does NOT change `value`. */\n clearCache(key?: string): void;\n}\n\n/** Create an async-state {@link Resource}. No per-instance framework state — it's a closure over a signal. */\nexport function resource<T, I = void>(\n options: ResourceOptions<T, I> = {},\n): Resource<T, I> {\n const { cacheKey, equals } = options;\n const eq: (a: T, b: T) => boolean = equals ?? Object.is;\n const cache = new Map<string, T>(); // per-key SWR cache (GC-tied to the resource)\n\n // Revision tracking: `revision` bumps only when `data` changes (by `eq`).\n let revision = 0;\n let lastData: T | undefined;\n const changed = (next: T | undefined): boolean =>\n // undefined transitions are handled by reference; two defined values by `eq`.\n lastData === undefined || next === undefined\n ? lastData !== next\n : !eq(lastData, next);\n const commit = (next: T | undefined): number => {\n if (changed(next)) {\n revision++;\n lastData = next;\n }\n return revision;\n };\n\n const state = signal<ResourceState<T, I>>({\n status: 'idle',\n data: undefined,\n error: undefined,\n progress: undefined,\n input: undefined,\n revision: 0,\n });\n // Per-resource run counter (closure-local, not module state) — the stale guard.\n let generation = 0;\n\n function run(\n inputOrFetcher: I | ResourceFetcher<T>,\n maybeFetcher?: ResourceFetcher<T>,\n ): Promise<T | undefined> {\n // Two-arg form is (input, fetcher); one-arg form is (fetcher) with no input.\n // A fetcher is always a function, so `maybeFetcher === undefined` uniquely\n // identifies the one-arg call — even when the input value is itself undefined.\n const fetcher = (maybeFetcher ?? inputOrFetcher) as ResourceFetcher<T>;\n const input = (maybeFetcher === undefined ? undefined : inputOrFetcher) as\n I | undefined;\n const key =\n cacheKey !== undefined && maybeFetcher !== undefined\n ? cacheKey(input as I)\n : undefined;\n\n // What `data` shows while running: the cached slice for this key (per-key\n // SWR), or the previous run's data (single-slot SWR) when no cacheKey.\n const runningData =\n cacheKey !== undefined\n ? key !== undefined\n ? cache.get(key)\n : undefined\n : state.peek().data;\n\n const gen = ++generation;\n state.value = {\n status: 'running',\n data: runningData,\n error: undefined,\n progress: undefined,\n input,\n revision: commit(runningData),\n };\n\n const report = (completed: number, total: number): void => {\n if (gen === generation) {\n state.value = { ...state.peek(), progress: { completed, total } };\n }\n };\n\n const fail = (error: unknown): undefined => {\n if (gen === generation) {\n // Keep `data` (and thus `revision`) on failure — stale-while-error.\n state.value = {\n ...state.peek(),\n status: 'failed',\n error,\n progress: undefined,\n input,\n };\n }\n return undefined;\n };\n\n let pending: Promise<T>;\n try {\n pending = fetcher(report);\n } catch (error: unknown) {\n return Promise.resolve(fail(error));\n }\n\n return pending.then((data) => {\n if (gen === generation) {\n if (key !== undefined) cache.set(key, data);\n state.value = {\n status: 'completed',\n data,\n error: undefined,\n progress: undefined,\n input,\n revision: commit(data),\n };\n }\n return data;\n }, fail);\n }\n\n function reset(): void {\n generation++; // invalidate any in-flight run\n cache.clear();\n state.value = {\n status: 'idle',\n data: undefined,\n error: undefined,\n progress: undefined,\n input: undefined,\n revision: commit(undefined),\n };\n }\n\n return {\n get value() {\n return state.value;\n },\n run,\n reset,\n cached: (k) => cache.get(k),\n cachedKeys: () => Array.from(cache.keys()),\n clearCache: (k) => {\n if (k === undefined) cache.clear();\n else cache.delete(k);\n },\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/async.ts"],"names":[],"mappings":";;;;AAoJO,SAAS,QAAA,CACd,OAAA,GAAiC,EAAC,EAClB;AAChB,EAAA,MAAM,EAAE,QAAA,EAAU,MAAA,EAAO,GAAI,OAAA;AAC7B,EAAA,MAAM,EAAA,GAA8B,UAAU,MAAA,CAAO,EAAA;AACrD,EAAA,MAAM,KAAA,uBAAY,GAAA,EAAe;AAGjC,EA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AACjB,MAAA,IAAI,CAAA,KAAM,MAAA,EAAW,KAAA,CAAM,KAAA,EAAM;AAAA,WAC5B,KAAA,CAAM,OAAO,CAAC,CAAA;AAAA,IACrB;AAAA,GACF;AACF","file":"async.js","sourcesContent":["/**\n * `kerfjs/async` — model async state, with the stale-response guard built in.\n *\n * Every real kerf app reproduces the same shape — `{ status, data, error }` —\n * for loading/error UI, each paired with a hand-rolled generation counter so a\n * slow response can't overwrite a newer one. This subpath blesses exactly that,\n * and no more: you still write the fetch (Node `fetch` for SSR, browser `fetch`\n * client-side), and `.run()` owns the status transitions plus the stale guard.\n *\n * import { resource } from 'kerfjs/async';\n *\n * const users = resource<User[]>();\n * users.run(() => fetch('/api/users').then((r) => r.json()));\n * // render off users.value.status: 'idle' | 'running' | 'completed' | 'failed'\n *\n * Only the LATEST run may resolve the state, so out-of-order responses are\n * dropped automatically. Optional progress: declare the `report` parameter on\n * your fetcher and call it (e.g. from an upload's progress events). Optional\n * cancellation: declare the second `signal` parameter and hand it to `fetch()`\n * (or listen for its `abort` event) — it aborts when a newer run supersedes\n * this one or on `reset()`, and never once this run has settled:\n *\n * users.run((_report, signal) => fetch('/api/users', { signal }).then((r) => r.json()));\n *\n * Pass an input — `run(input, fetcher)` — to carry which request a run is for\n * through to `value.input` (set for `running`/`completed`/`failed`), so a\n * failure handler can recover the id/params of the run that failed:\n *\n * const diff = resource<Diff, { fileId: string }>();\n * diff.run({ fileId }, (report) => fetchDiff(fileId, report));\n * // on failure: diff.value.status === 'failed' && diff.value.input.fileId\n *\n * For a real SWR-with-cache section, pass `cacheKey` to keep the last value PER\n * input key (switching back to a loaded key paints its cached slice instantly\n * while it revalidates), and read `value.revision` — a counter that bumps only\n * when `data` actually CHANGES (by `equals`, default `Object.is`) — to skip a\n * redundant paint when a poll tick returns identical data:\n *\n * const win = resource<Slice, string>({ cacheKey: (w) => w, equals: sameSlice });\n * win.run(w, () => fetchSlice(w)); // instant cached paint for a revisited w\n */\nimport { signal } from './reactive.js';\n\n/** The lifecycle status of a {@link Resource}. */\nexport type ResourceStatus = 'idle' | 'running' | 'completed' | 'failed';\n\n/** Optional progress for a long-running fetch (uploads, chunked work). */\nexport interface ResourceProgress {\n completed: number;\n total: number;\n}\n\n/** The reactive state a {@link Resource} exposes. */\nexport interface ResourceState<T, I = void> {\n status: ResourceStatus;\n /** The last successful value. Kept across a re-run (stale-while-revalidate) and on failure. */\n data: T | undefined;\n /** The rejection from the most recent failed run. */\n error: unknown;\n /** Latest reported progress while running, or `undefined`. */\n progress: ResourceProgress | undefined;\n /**\n * The input of the LATEST run — the value passed to {@link Resource.run} as\n * `run(input, fetcher)`. Set for `running`, `completed`, AND `failed` (same\n * stale-guard rule as the rest of the state), so an effect can branch on\n * `status === 'failed'` and still know which request failed. `undefined` in\n * `idle`, and for the no-input `run(fetcher)` form.\n */\n input: I | undefined;\n /**\n * A monotonic counter that increments only when `data` actually CHANGES (by\n * the resource's `equals`, default `Object.is`). Compare it against the value\n * you last painted to skip a redundant re-render — e.g. a 30s poll returning\n * identical data leaves `revision` untouched, so you can bail before wiping\n * scroll / sort / hover state. Starts at `0`.\n */\n revision: number;\n}\n\n/** Construction options for {@link resource}. */\nexport interface ResourceOptions<T, I = void> {\n /**\n * Derive a cache key from a run's `input`. When set, the resource keeps the\n * last successful value PER key: starting a run for a key that was loaded\n * before paints its cached slice immediately (still `running`) while the fetch\n * revalidates in the background; a never-loaded key starts with no `data`.\n * Without `cacheKey`, a run keeps the previous run's `data` (single-slot\n * stale-while-revalidate), as before.\n */\n cacheKey?: (input: I) => string;\n /**\n * Equality used to decide whether `data` changed (drives `value.revision`).\n * Default `Object.is`. Pass a structural comparison to dedup a poll that\n * returns a fresh-but-equal object.\n */\n equals?: (a: T, b: T) => boolean;\n}\n\n/**\n * The fetcher passed to {@link Resource.run}. You own the transport. It receives\n * a `report(completed, total)` callback for optional progress and an\n * `AbortSignal` that aborts when a newer run supersedes this one or the\n * resource is `reset()` — never after this run settles. Ignore either if you\n * don't need it (a plain `() => Promise<T>` or `(report) => Promise<T>` is\n * assignable here). The abort rejection of a superseded run is dropped by the\n * stale guard, so it never surfaces as `failed`.\n */\nexport type ResourceFetcher<T> = (\n report: (completed: number, total: number) => void,\n signal: AbortSignal,\n) => Promise<T>;\n\n/**\n * An async-state container. Its `value` is a tracking read; drive UI off\n * `value.status`. `I` is the run-input type — parametrize it (`resource<T, I>()`)\n * to carry a typed `run(input, fetcher)` input through to `value.input`.\n */\nexport interface Resource<T, I = void> {\n /** Tracking read of the current {@link ResourceState}. */\n readonly value: ResourceState<T, I>;\n /**\n * Run `fetcher`, driving `idle`/`running` → `completed`/`failed` and guarding\n * against stale responses (only the latest run resolves the state). Never\n * rejects — a failure lands in `value.error`; resolves with the data (or\n * `undefined` on failure) for callers who want to await it.\n */\n run(fetcher: ResourceFetcher<T>): Promise<T | undefined>;\n /**\n * Run `fetcher` for a given `input`, exposing it as `value.input` for the\n * `running`/`completed`/`failed` states of THIS run — so a failure handler can\n * recover which request failed. Same stale guard: only the latest run resolves.\n */\n run(input: I, fetcher: ResourceFetcher<T>): Promise<T | undefined>;\n /** Reset to `idle` (clearing data/error/progress/input, and the per-key cache) and invalidate any in-flight run. */\n reset(): void;\n /**\n * Read-only: the cached value for a `cacheKey` key, or `undefined` if that key\n * isn't cached (or no `cacheKey` was given). Lets a consumer ask \"is this slice\n * cached?\" without running it (which would mutate state).\n */\n cached(key: string): T | undefined;\n /** Read-only: the keys currently in the per-input cache (`.length` is the cache size). */\n cachedKeys(): string[];\n /** Evict the per-input cache — one `key`, or the whole cache when called with no argument. Does NOT change `value`. */\n clearCache(key?: string): void;\n}\n\n/** Create an async-state {@link Resource}. No per-instance framework state — it's a closure over a signal. */\nexport function resource<T, I = void>(\n options: ResourceOptions<T, I> = {},\n): Resource<T, I> {\n const { cacheKey, equals } = options;\n const eq: (a: T, b: T) => boolean = equals ?? Object.is;\n const cache = new Map<string, T>(); // per-key SWR cache (GC-tied to the resource)\n\n // Revision tracking: `revision` bumps only when `data` changes (by `eq`).\n let revision = 0;\n let lastData: T | undefined;\n const changed = (next: T | undefined): boolean =>\n // undefined transitions are handled by reference; two defined values by `eq`.\n lastData === undefined || next === undefined\n ? lastData !== next\n : !eq(lastData, next);\n const commit = (next: T | undefined): number => {\n if (changed(next)) {\n revision++;\n lastData = next;\n }\n return revision;\n };\n\n const state = signal<ResourceState<T, I>>({\n status: 'idle',\n data: undefined,\n error: undefined,\n progress: undefined,\n input: undefined,\n revision: 0,\n });\n // Per-resource run counter (closure-local, not module state) — the stale guard.\n let generation = 0;\n // The LATEST unsettled run's controller; dropped when that run settles, so a\n // later run or reset() never aborts work that already finished.\n let controller: AbortController | undefined;\n const supersede = (): void => {\n controller?.abort();\n controller = undefined;\n };\n\n function run(\n inputOrFetcher: I | ResourceFetcher<T>,\n maybeFetcher?: ResourceFetcher<T>,\n ): Promise<T | undefined> {\n // Two-arg form is (input, fetcher); one-arg form is (fetcher) with no input.\n // A fetcher is always a function, so `maybeFetcher === undefined` uniquely\n // identifies the one-arg call — even when the input value is itself undefined.\n const fetcher = (maybeFetcher ?? inputOrFetcher) as ResourceFetcher<T>;\n const input = (maybeFetcher === undefined ? undefined : inputOrFetcher) as\n I | undefined;\n const key =\n cacheKey !== undefined && maybeFetcher !== undefined\n ? cacheKey(input as I)\n : undefined;\n\n // What `data` shows while running: the cached slice for this key (per-key\n // SWR), or the previous run's data (single-slot SWR) when no cacheKey.\n const runningData =\n cacheKey !== undefined\n ? key !== undefined\n ? cache.get(key)\n : undefined\n : state.peek().data;\n\n supersede();\n const gen = ++generation;\n const own = new AbortController();\n controller = own;\n const settled = (): void => {\n if (controller === own) controller = undefined;\n };\n state.value = {\n status: 'running',\n data: runningData,\n error: undefined,\n progress: undefined,\n input,\n revision: commit(runningData),\n };\n\n const report = (completed: number, total: number): void => {\n if (gen === generation) {\n state.value = { ...state.peek(), progress: { completed, total } };\n }\n };\n\n const fail = (error: unknown): undefined => {\n settled();\n if (gen === generation) {\n // Keep `data` (and thus `revision`) on failure — stale-while-error.\n state.value = {\n ...state.peek(),\n status: 'failed',\n error,\n progress: undefined,\n input,\n };\n }\n return undefined;\n };\n\n let pending: Promise<T>;\n try {\n pending = fetcher(report, own.signal);\n } catch (error: unknown) {\n return Promise.resolve(fail(error));\n }\n\n return pending.then((data) => {\n settled();\n if (gen === generation) {\n if (key !== undefined) cache.set(key, data);\n state.value = {\n status: 'completed',\n data,\n error: undefined,\n progress: undefined,\n input,\n revision: commit(data),\n };\n }\n return data;\n }, fail);\n }\n\n function reset(): void {\n generation++; // invalidate any in-flight run\n supersede(); // …and tell its fetcher to stop\n cache.clear();\n state.value = {\n status: 'idle',\n data: undefined,\n error: undefined,\n progress: undefined,\n input: undefined,\n revision: commit(undefined),\n };\n }\n\n return {\n get value() {\n return state.value;\n },\n run,\n reset,\n cached: (k) => cache.get(k),\n cachedKeys: () => Array.from(cache.keys()),\n clearCache: (k) => {\n if (k === undefined) cache.clear();\n else cache.delete(k);\n },\n };\n}\n"]}
@@ -0,0 +1,65 @@
1
+ import { computed, rawSignal, effect } from './chunk-N4VHHOCM.js';
2
+
3
+ // src/utils/keyed-flags.ts
4
+ function keyedFlags(source, test, follow) {
5
+ const watched = /* @__PURE__ */ new Map();
6
+ let stop;
7
+ const flip = (key, value) => {
8
+ const entry = watched.get(key);
9
+ if (entry) for (const flag of entry.flags) flag.value = value;
10
+ };
11
+ return (key) => {
12
+ const existing = watched.get(key);
13
+ if (existing) return existing.shared;
14
+ let flag;
15
+ const reader = computed(
16
+ () => flag ? flag.value : test(source.value, key),
17
+ {
18
+ watched() {
19
+ flag = rawSignal(test(source.peek(), key));
20
+ let entry = watched.get(key);
21
+ if (!entry)
22
+ watched.set(key, entry = { flags: /* @__PURE__ */ new Set(), shared: reader });
23
+ entry.flags.add(flag);
24
+ if (stop === void 0) stop = follow(flip);
25
+ },
26
+ unwatched() {
27
+ const released = flag;
28
+ flag = void 0;
29
+ const entry = watched.get(key);
30
+ entry.flags.delete(released);
31
+ if (entry.flags.size === 0) watched.delete(key);
32
+ released.value = !released.peek();
33
+ if (watched.size === 0 && stop !== void 0) {
34
+ stop();
35
+ stop = void 0;
36
+ }
37
+ }
38
+ }
39
+ );
40
+ return reader;
41
+ };
42
+ }
43
+
44
+ // src/set-selector.ts
45
+ function setSelector(source) {
46
+ return keyedFlags(
47
+ source,
48
+ (members, key) => members.has(key),
49
+ (flip) => {
50
+ let current = source.peek();
51
+ return effect(() => {
52
+ const next = source.value;
53
+ if (next === current) return;
54
+ const previous = current;
55
+ current = next;
56
+ for (const key of previous) if (!next.has(key)) flip(key, false);
57
+ for (const key of next) if (!previous.has(key)) flip(key, true);
58
+ });
59
+ }
60
+ );
61
+ }
62
+
63
+ export { keyedFlags, setSelector };
64
+
65
+ //# sourceMappingURL=chunk-KOEGJCIS.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utils/keyed-flags.ts","../src/set-selector.ts"],"names":[],"mappings":";;;AAiCO,SAAS,UAAA,CACd,MAAA,EACA,IAAA,EACA,MAAA,EACqC;AACrC,EAAA,MAAM,OAAA,uBAAc,GAAA,EAAmB;AACvC,EAAA,IAAI,IAAA;AAEJ,EAAA,MAAM,IAAA,GAAO,CAAC,GAAA,EAAQ,KAAA,KAAyB;AAC7C,IAAA,MAAM,KAAA,GAAQ,OAAA,CAAQ,GAAA,CAAI,GAAG,CAAA;AAC7B,IAAA,IAAI,OAAO,KAAA,MAAW,IAAA,IAAQ,KAAA,CAAM,KAAA,OAAY,KAAA,GAAQ,KAAA;AAAA,EAC1D,CAAA;AAEA,EAAA,OAAO,CAAC,GAAA,KAAoC;AAC1C,IAAA,MAAM,QAAA,GAAW,OAAA,CAAQ,GAAA,CAAI,GAAG,CAAA;AAChC,IAAA,IAAI,QAAA,SAAiB,QAAA,CAAS,MAAA;AAC9B,IAAA,IAAI,IAAA;AACJ,IAAA,MAAM,MAAA,GAAkC,QAAA;AAAA,MACtC,MAAO,IAAA,GAAO,IAAA,CAAK,QAAQ,IAA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S,GAAA,KAAQ,OAAA,CAAQ,IAAI,GAAG,CAAA;AAAA,IACjC,CAAC,IAAA,KAAS;AACR,MAAA,IAAI,OAAA,GAAU,OAAO,IAAA,EAAK;AAC1B,MAAA,OAAO,OAAO,MAAM;AAClB,QAAA,MAAM,OAAO,MAAA,CAAO,KAAA;AACpB,QAAA,IAAI,SAAS,OAAA,EAAS;AACtB,QAAA,MAAM,QAAA,GAAW,OAAA;AACjB,QAAA,OAAA,GAAU,IAAA;AACV,QAAA,KAAA,MAAW,GAAA,IAAO,QAAA,EAAU,IAAI,CAAC,IAAA,CAAK,IAAI,GAAG,CAAA,EAAG,IAAA,CAAK,GAAA,EAAK,KAAK,CAAA;AAC/D,QAAA,KAAA,MAAW,GAAA,IAAO,IAAA,EAAM,IAAI,CAAC,QAAA,CAAS,IAAI,GAAG,CAAA,EAAG,IAAA,CAAK,GAAA,EAAK,IAAI,CAAA;AAAA,MAChE,CAAC,CAAA;AAAA,IACH;AAAA,GACF;AACF","file":"chunk-KOEGJCIS.js","sourcesContent":["/**\n * The per-key boolean signals behind `selector()` and `setSelector()`\n * (KF-769EW2 / KF-1TFHMP). `test(value, key)` answers the question for one\n * source value; `follow(flip)` subscribes to the source once and calls\n * `flip(key, value)` for each key whose answer changed, returning a stop.\n *\n * Each key is handed out as a `computed` with two modes (KF-4TXB21):\n *\n * - **Unwatched**, it reads `source` directly. Unwatched computeds are lazy,\n * so this costs nothing per source change, and a signal held outside any\n * subscriber (a click handler reading `.value`) is always current.\n * - **Watched**, it reads only a per-key flag that the single `follow`\n * effect flips, so a source change notifies just the keys that changed.\n *\n * A key's flag joins the map when the computed gains its first subscriber\n * and leaves with its last (signals-core `watched` / `unwatched`), and the\n * source subscription runs only while some key is watched. Internal.\n */\nimport {\n computed,\n rawSignal,\n type ReadonlySignal,\n type Signal,\n} from '../reactive.js';\n\ninterface WatchedKey {\n /** The flags `follow` flips: usually one; more when several unshared\n * computeds for one key each gained a subscriber. */\n flags: Set<Signal<boolean>>;\n /** Handed out again for this key while it is watched. */\n shared: ReadonlySignal<boolean>;\n}\n\nexport function keyedFlags<K, S>(\n source: ReadonlySignal<S>,\n test: (value: S, key: K) => boolean,\n follow: (flip: (key: K, value: boolean) => void) => () => void,\n): (key: K) => ReadonlySignal<boolean> {\n const watched = new Map<K, WatchedKey>();\n let stop: (() => void) | undefined;\n\n const flip = (key: K, value: boolean): void => {\n const entry = watched.get(key);\n if (entry) for (const flag of entry.flags) flag.value = value;\n };\n\n return (key: K): ReadonlySignal<boolean> => {\n const existing = watched.get(key);\n if (existing) return existing.shared;\n let flag: Signal<boolean> | undefined;\n const reader: ReadonlySignal<boolean> = computed(\n () => (flag ? flag.value : test(source.value, key)),\n {\n watched() {\n flag = rawSignal(test(source.peek(), key));\n let entry = watched.get(key);\n if (!entry)\n watched.set(key, (entry = { flags: new Set(), shared: reader }));\n entry.flags.add(flag);\n if (stop === undefined) stop = follow(flip);\n },\n unwatched() {\n const released = flag as Signal<boolean>;\n flag = undefined;\n const entry = watched.get(key) as WatchedKey;\n entry.flags.delete(released);\n if (entry.flags.size === 0) watched.delete(key);\n // The computed's last dependency is this flag, which nothing will\n // flip again. Changing it makes the next read re-evaluate, and that\n // read goes back to tracking the source.\n released.value = !released.peek();\n if (watched.size === 0 && stop !== undefined) {\n stop();\n stop = undefined;\n }\n },\n },\n );\n return reader;\n };\n}\n","/**\n * `setSelector(source)` — membership in one set signal, flipping only the\n * members that changed (KF-1TFHMP).\n *\n * `selector()` answers \"is this key THE selected one?\". `setSelector()`\n * answers \"is this key IN the set?\", for multi-select, a tree's expanded\n * rows, fields with errors, or a router's active path prefixes:\n *\n * const checked = signal<ReadonlySet<string>>(new Set());\n * const isChecked = setSelector(checked);\n * <tr class={computed(() => (isChecked(row.id).value ? 'on' : ''))}>\n *\n * One write diffs the previous set against the next, O(|old| + |new|), and\n * notifies only the subscribers of members that were added or removed. A\n * new Set with the same members flips nothing. That pays off when the sets\n * are small next to the number of subscribed keys (a few selected rows of\n * many); for a set that holds most keys, a plain `computed` per row costs\n * about the same.\n *\n * Per-key signals follow their subscribers exactly as `selector()`'s do, and\n * membership is `Set.prototype.has` (SameValueZero).\n */\nimport { effect, type ReadonlySignal } from './reactive.js';\nimport { keyedFlags } from './utils/keyed-flags.js';\n\n/** A set-membership reader returned by {@link setSelector}. */\nexport type SetSelector<K> = (key: K) => ReadonlySignal<boolean>;\n\n/**\n * Create a membership reader over `source`: `setSelector(source)(key).value`\n * is `true` exactly when `source.value.has(key)`, and one source change\n * notifies only the subscribers of members added or removed.\n */\nexport function setSelector<K>(\n source: ReadonlySignal<ReadonlySet<K>>,\n): SetSelector<K> {\n return keyedFlags<K, ReadonlySet<K>>(\n source,\n (members, key) => members.has(key),\n (flip) => {\n let current = source.peek();\n return effect(() => {\n const next = source.value;\n if (next === current) return;\n const previous = current;\n current = next;\n for (const key of previous) if (!next.has(key)) flip(key, false);\n for (const key of next) if (!previous.has(key)) flip(key, true);\n });\n },\n );\n}\n"]}
@@ -11,4 +11,4 @@ function clearDevHooks() {
11
11
 
12
12
  export { clearDevHooks, devHooks, installDevHooks };
13
13
 
14
- //# sourceMappingURL=chunk-3C6F6NM4.js.map
14
+ //# sourceMappingURL=chunk-KUHXPPJ4.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/dev-hooks.ts"],"names":[],"mappings":";AAoKO,IAAM,WAAqB;AAS3B,SAAS,gBAAgB,KAAA,EAAuB;AACrD,EAAA,MAAA,CAAO,MAAA,CAAO,UAAU,KAAK,CAAA;AAC/B;AAOO,SAAS,aAAA,GAAsB;AACpC,EAAA,KAAA,MAAW,GAAA,IAAO,MAAA,CAAO,IAAA,CAAK,QAAQ,CAAA,EAAG;AACvC,IAAA,OAAQ,SAAqC,GAAG,CAAA;AAAA,EAClD;AACF","file":"chunk-3C6F6NM4.js","sourcesContent":["/**\n * The dev-hook registry — kerf's single seam between production code and the\n * opt-in development diagnostics.\n *\n * ## Why this exists\n *\n * kerf used to INFER whether it was running in development, by reading\n * `globalThis.process?.env?.NODE_ENV` through `utils/devMode.ts`. That\n * inference cannot be made correct, and it was wrong in the most common case:\n * bundlers substitute the BARE `process.env.NODE_ENV` token and never create a\n * `globalThis.process` object for browser targets, so the read returned\n * `undefined` and `undefined !== 'production'` resolved to DEVELOPMENT inside\n * production browser bundles.\n *\n * It also could not be fixed by rewriting the expression. Only the\n * *production* answer can be made static: `X && false` folds to a constant for\n * any side-effect-free `X`, while `X && true` does not. So any form that a\n * bundler can eliminate is also a form that treats \"no `process` binding\" as\n * production — which silently disables every warning in the no-build/CDN path\n * and in browser dev bundles.\n *\n * The fix is to stop guessing. Every environment already has a correct,\n * statically-foldable dev flag; what none of them offers is a way to hand that\n * flag to a *library*. So the consumer writes the conditional, in their own\n * code, with their own flag:\n *\n * ```js\n * if (import.meta.env.DEV) await import('kerfjs/dev'); // Vite\n * if (process.env.NODE_ENV !== 'production') await import('kerfjs/dev');\n * ```\n *\n * Because that condition folds to `false` in the consumer's production build,\n * the entire statement is eliminated and the dev chunk is never emitted or\n * fetched. Installation IS the development signal — there is nothing left to\n * detect, and no environment kerf can be wrong about.\n *\n * ## The contract\n *\n * Core modules never import a `dev-*` module. They read a nullable slot off\n * `devHooks` and call through it:\n *\n * ```ts\n * devHooks.listRebind?.(id, marker.parentElement as Element);\n * ```\n *\n * When nothing is installed every slot is `undefined`, so the cost is one\n * property read per call site and the `dev-*` modules are unreachable from the\n * main entry — which is what lets a bundler drop them. This is why the gate\n * lives at the CALL SITE rather than inside each warner: an unconditional call\n * into a self-gating warner keeps the module reachable no matter how the gate\n * is written, so no amount of dead-code elimination can reclaim it.\n *\n * Slots ending in `Enabled` are predicates rather than warnings. They exist for\n * the handful of call sites that must decide whether to do *expensive\n * preparatory work* — capturing the previous render's binding list, allocating\n * a per-render `Map` — before there is anything to warn about. Core must check\n * those before paying the cost, exactly as it checked the old `isOptedIn()`\n * exports.\n *\n * Each opt-in warner keeps its own internal switch check through `devFlag()`;\n * an `enableWarnings()` override wins over the matching `KERF_DEV_WARN_*`\n * environment variable. Installation decides whether the diagnostics are\n * *present*; the opt-in warner decides whether it is *switched on*. Always-on\n * hooks skip that second gate.\n *\n * @see docs/11-dev-warnings.md\n */\n\nimport type { Binding } from './bindings.js';\nimport type { ListBinding } from './list-binding.js';\nimport type { Signal } from './reactive.js';\n\n/** Per-mount / per-store one-shot dedup flag, owned by the caller in core. */\nexport interface WarnOnceContext {\n warned: boolean;\n}\n\nexport interface DevHooks {\n // --- reactive.ts -------------------------------------------------------\n /**\n * Replaces `signal()`'s constructor so writes to never-subscribed signals can\n * warn. Resolved at signal-CREATION time, so signals created before the dev\n * entry is installed stay plain — see `signalsCreatedBeforeInstall`.\n */\n signalFactory?: <T>(value: T) => Signal<T>;\n /**\n * Wraps an `effect()` body so `delegate()` can detect that it is running\n * inside one. Returns the body to actually run. Resolved at effect-CREATION\n * time (the delegate-in-effect switch too), so an effect created before the\n * install or the opt-in is never wrapped.\n */\n wrapEffect?: (fn: () => void | (() => void)) => () => void | (() => void);\n\n // --- delegate.ts -------------------------------------------------------\n delegateInEffect?: (fn: 'delegate' | 'delegateCapture') => void;\n\n // --- store.ts ----------------------------------------------------------\n narrowSet?: (prev: unknown, next: unknown, ctx: WarnOnceContext) => void;\n /** Deep read-only proxy for the `get()` snapshot, so stray writes throw. */\n storeReadonly?: <T extends object>(state: T) => T;\n /** Unwraps a proxy handed back through `set({ ...get() })`. */\n storeToRaw?: <T>(next: T) => T;\n\n // --- mount.ts ----------------------------------------------------------\n /**\n * Attaches the rebuilt-listeners observer to a mount root. Called once per\n * `mount()`, at creation — and it returns `null` when the warning is switched\n * off then — so a mount created before the install or the opt-in is never\n * observed.\n */\n listenerRebuild?: (rootEl: Element) => MutationObserver | null;\n listIdShift?: (id: string) => void;\n parserRepair?: (html: string) => void;\n staleBindingEnabled?: () => boolean;\n staleBinding?: (\n prevWired: readonly Binding[],\n current: readonly Binding[],\n ) => void;\n listInvariantsEnabled?: () => boolean;\n listInvariants?: (\n rootEl: Element,\n bindings: ReadonlyMap<string, ListBinding>,\n expectedCounts?: ReadonlyMap<string, number>,\n ) => void;\n valueOnlyRerender?: (\n prevHtml: string,\n nextHtml: string,\n ctx: WarnOnceContext,\n ) => void;\n listRebind?: (id: string, liveParent: Element) => void;\n eachInMorphSkip?: (id: string, liveParent: Element, rootEl: Element) => void;\n missingRowKey?: (\n rowEl: Element,\n rowHtml: string,\n binding: { warnedMissingKey?: boolean },\n ) => void;\n\n // --- each.ts -----------------------------------------------------------\n staleIndexEnabled?: () => boolean;\n staleIndex?: (id: string) => void;\n duplicateCacheKeys?: (\n id: string,\n segItems: readonly { cacheKey: unknown }[],\n ) => void;\n\n // --- overlay-core.ts ---------------------------------------------------\n /** A surface opened over a modal `<dialog>` could not be made fully usable. */\n overlayBlockedByModal?: (reason: 'hidden' | 'inert') => void;\n\n // --- utils/url-screen.ts -----------------------------------------------\n /**\n * When installed, a screened URL throws instead of warning-and-dropping.\n * A slot rather than a boolean so the check stays uniform with the rest.\n */\n urlScreenThrow?: (message: string) => never;\n}\n\n/**\n * The live slot table. Mutable by design — this is the fourth sanctioned\n * module-level mutable location (Design rule 5), and like `store.ts:REGISTRY`\n * it depends on there being exactly ONE copy at runtime. `tsup`'s\n * `splitting: true` guarantees that: shared modules are promoted into a single\n * chunk that both the main entry and the `kerfjs/dev` entry import.\n */\nexport const devHooks: DevHooks = {};\n\n/**\n * Install (or extend) the dev hooks. Called by the `kerfjs/dev` entry; not part\n * of the public API surface.\n *\n * Merges rather than replaces, so a consumer can install the standard bundle\n * and then override a single slot in a test.\n */\nexport function installDevHooks(hooks: DevHooks): void {\n Object.assign(devHooks, hooks);\n}\n\n/**\n * Remove every installed hook. Exists for test isolation — a suite that asserts\n * the not-installed (production-shaped) path needs to get back to a clean slate\n * without reloading modules.\n */\nexport function clearDevHooks(): void {\n for (const key of Object.keys(devHooks)) {\n delete (devHooks as Record<string, unknown>)[key];\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/dev-hooks.ts"],"names":[],"mappings":";AA2KO,IAAM,WAAqB;AAS3B,SAAS,gBAAgB,KAAA,EAAuB;AACrD,EAAA,MAAA,CAAO,MAAA,CAAO,UAAU,KAAK,CAAA;AAC/B;AAOO,SAAS,aAAA,GAAsB;AACpC,EAAA,KAAA,MAAW,GAAA,IAAO,MAAA,CAAO,IAAA,CAAK,QAAQ,CAAA,EAAG;AACvC,IAAA,OAAQ,SAAqC,GAAG,CAAA;AAAA,EAClD;AACF","file":"chunk-KUHXPPJ4.js","sourcesContent":["/**\n * The dev-hook registry — kerf's single seam between production code and the\n * opt-in development diagnostics.\n *\n * ## Why this exists\n *\n * kerf used to INFER whether it was running in development, by reading\n * `globalThis.process?.env?.NODE_ENV` through `utils/devMode.ts`. That\n * inference cannot be made correct, and it was wrong in the most common case:\n * bundlers substitute the BARE `process.env.NODE_ENV` token and never create a\n * `globalThis.process` object for browser targets, so the read returned\n * `undefined` and `undefined !== 'production'` resolved to DEVELOPMENT inside\n * production browser bundles.\n *\n * It also could not be fixed by rewriting the expression. Only the\n * *production* answer can be made static: `X && false` folds to a constant for\n * any side-effect-free `X`, while `X && true` does not. So any form that a\n * bundler can eliminate is also a form that treats \"no `process` binding\" as\n * production — which silently disables every warning in the no-build/CDN path\n * and in browser dev bundles.\n *\n * The fix is to stop guessing. Every environment already has a correct,\n * statically-foldable dev flag; what none of them offers is a way to hand that\n * flag to a *library*. So the consumer writes the conditional, in their own\n * code, with their own flag:\n *\n * ```js\n * if (import.meta.env.DEV) await import('kerfjs/dev'); // Vite\n * if (process.env.NODE_ENV !== 'production') await import('kerfjs/dev');\n * ```\n *\n * Because that condition folds to `false` in the consumer's production build,\n * the entire statement is eliminated and the dev chunk is never emitted or\n * fetched. Installation IS the development signal — there is nothing left to\n * detect, and no environment kerf can be wrong about.\n *\n * ## The contract\n *\n * Core modules never import a `dev-*` module. They read a nullable slot off\n * `devHooks` and call through it:\n *\n * ```ts\n * devHooks.listRebind?.(id, marker.parentElement as Element);\n * ```\n *\n * When nothing is installed every slot is `undefined`, so the cost is one\n * property read per call site and the `dev-*` modules are unreachable from the\n * main entry — which is what lets a bundler drop them. This is why the gate\n * lives at the CALL SITE rather than inside each warner: an unconditional call\n * into a self-gating warner keeps the module reachable no matter how the gate\n * is written, so no amount of dead-code elimination can reclaim it.\n *\n * Slots ending in `Enabled` are predicates rather than warnings. They exist for\n * the handful of call sites that must decide whether to do *expensive\n * preparatory work* — capturing the previous render's binding list, allocating\n * a per-render `Map` — before there is anything to warn about. Core must check\n * those before paying the cost, exactly as it checked the old `isOptedIn()`\n * exports.\n *\n * Each opt-in warner keeps its own internal switch check through `devFlag()`;\n * an `enableWarnings()` override wins over the matching `KERF_DEV_WARN_*`\n * environment variable. Installation decides whether the diagnostics are\n * *present*; the opt-in warner decides whether it is *switched on*. Always-on\n * hooks skip that second gate.\n *\n * @see docs/11-dev-warnings.md\n */\n\nimport type { Binding } from './bindings.js';\nimport type { ListBinding } from './list-binding.js';\nimport type { Signal } from './reactive.js';\n\n/** Per-mount / per-store one-shot dedup flag, owned by the caller in core. */\nexport interface WarnOnceContext {\n warned: boolean;\n}\n\nexport interface DevHooks {\n // --- reactive.ts -------------------------------------------------------\n /**\n * Replaces `signal()`'s constructor so writes to never-subscribed signals can\n * warn. Resolved at signal-CREATION time, so signals created before the dev\n * entry is installed stay plain — see `signalsCreatedBeforeInstall`.\n */\n signalFactory?: <T>(value: T) => Signal<T>;\n /**\n * Wraps an `effect()` body so `delegate()` can detect that it is running\n * inside one. Returns the body to actually run. Resolved at effect-CREATION\n * time (the delegate-in-effect switch too), so an effect created before the\n * install or the opt-in is never wrapped.\n */\n wrapEffect?: (fn: () => void | (() => void)) => () => void | (() => void);\n /**\n * Wraps a `computed()` body so the selector fan-out warning can count\n * re-evaluations and value changes. Returns the body to actually run.\n * Resolved at computed-CREATION time (the `selectorFanout` switch too), so\n * a computed created before the install or the opt-in is never counted.\n */\n wrapComputed?: <T>(fn: () => T) => () => T;\n\n // --- delegate.ts -------------------------------------------------------\n delegateInEffect?: (fn: 'delegate' | 'delegateCapture') => void;\n\n // --- store.ts ----------------------------------------------------------\n narrowSet?: (prev: unknown, next: unknown, ctx: WarnOnceContext) => void;\n /** Deep read-only proxy for the `get()` snapshot, so stray writes throw. */\n storeReadonly?: <T extends object>(state: T) => T;\n /** Unwraps a proxy handed back through `set({ ...get() })`. */\n storeToRaw?: <T>(next: T) => T;\n\n // --- mount.ts ----------------------------------------------------------\n /**\n * Attaches the rebuilt-listeners observer to a mount root. Called once per\n * `mount()`, at creation — and it returns `null` when the warning is switched\n * off then — so a mount created before the install or the opt-in is never\n * observed.\n */\n listenerRebuild?: (rootEl: Element) => MutationObserver | null;\n listIdShift?: (id: string) => void;\n parserRepair?: (html: string) => void;\n staleBindingEnabled?: () => boolean;\n staleBinding?: (\n prevWired: readonly Binding[],\n current: readonly Binding[],\n ) => void;\n listInvariantsEnabled?: () => boolean;\n listInvariants?: (\n rootEl: Element,\n bindings: ReadonlyMap<string, ListBinding>,\n expectedCounts?: ReadonlyMap<string, number>,\n ) => void;\n valueOnlyRerender?: (\n prevHtml: string,\n nextHtml: string,\n ctx: WarnOnceContext,\n ) => void;\n listRebind?: (id: string, liveParent: Element) => void;\n eachInMorphSkip?: (id: string, liveParent: Element, rootEl: Element) => void;\n missingRowKey?: (\n rowEl: Element,\n rowHtml: string,\n binding: { warnedMissingKey?: boolean },\n ) => void;\n\n // --- each.ts -----------------------------------------------------------\n staleIndexEnabled?: () => boolean;\n staleIndex?: (id: string) => void;\n duplicateCacheKeys?: (\n id: string,\n segItems: readonly { cacheKey: unknown }[],\n ) => void;\n\n // --- overlay-core.ts ---------------------------------------------------\n /** A surface opened over a modal `<dialog>` could not be made fully usable. */\n overlayBlockedByModal?: (reason: 'hidden' | 'inert') => void;\n\n // --- utils/url-screen.ts -----------------------------------------------\n /**\n * When installed, a screened URL throws instead of warning-and-dropping.\n * A slot rather than a boolean so the check stays uniform with the rest.\n */\n urlScreenThrow?: (message: string) => never;\n}\n\n/**\n * The live slot table. Mutable by design — this is the fourth sanctioned\n * module-level mutable location (Design rule 5), and like `store.ts:REGISTRY`\n * it depends on there being exactly ONE copy at runtime. `tsup`'s\n * `splitting: true` guarantees that: shared modules are promoted into a single\n * chunk that both the main entry and the `kerfjs/dev` entry import.\n */\nexport const devHooks: DevHooks = {};\n\n/**\n * Install (or extend) the dev hooks. Called by the `kerfjs/dev` entry; not part\n * of the public API surface.\n *\n * Merges rather than replaces, so a consumer can install the standard bundle\n * and then override a single slot in a test.\n */\nexport function installDevHooks(hooks: DevHooks): void {\n Object.assign(devHooks, hooks);\n}\n\n/**\n * Remove every installed hook. Exists for test isolation — a suite that asserts\n * the not-installed (production-shaped) path needs to get back to a clean slate\n * without reloading modules.\n */\nexport function clearDevHooks(): void {\n for (const key of Object.keys(devHooks)) {\n delete (devHooks as Record<string, unknown>)[key];\n }\n}\n"]}
@@ -1,9 +1,9 @@
1
1
  import { itemVersion } from './chunk-5WRGJZV6.js';
2
2
  import { seedRenderedAttrs, RENDERED_ATTRS, isUserAgentOwnedAttr, hasCustomTag, parseRowTemplate, rowContractError, parseSingleRow, collectTemplateChildren } from './chunk-6LXUC4ZY.js';
3
- import { captureRowBindings, listSafeHtml, boundTextNodeOf, syncFormProp, newBindingContext, wireBindings, disposeRowBindings, isSafeHtml, _setBindingContext, TEXT_MARKER_PREFIX, ROW_TEXT_PREFIX, wireRowBindings, carryOrRewireRowBindings, granularListSafeHtml } from './chunk-VX3RCRGG.js';
4
- import { effect } from './chunk-IHMDBBUJ.js';
3
+ import { captureRowBindings, listSafeHtml, boundTextNodeOf, syncFormProp, newBindingContext, wireBindings, disposeRowBindings, isSafeHtml, _setBindingContext, TEXT_MARKER_PREFIX, ROW_TEXT_PREFIX, wireRowBindings, carryOrRewireRowBindings, granularListSafeHtml } from './chunk-XL35DIZ2.js';
4
+ import { effect } from './chunk-N4VHHOCM.js';
5
5
  import { LIST_MARKER_PREFIX, flattenWithoutListItems, collectLists, isOverlayHost, flatten } from './chunk-4TX6YJDM.js';
6
- import { devHooks } from './chunk-3C6F6NM4.js';
6
+ import { devHooks } from './chunk-KUHXPPJ4.js';
7
7
 
8
8
  // src/list-render-state.ts
9
9
  function deriveListRenderState(bindingCount) {
@@ -211,16 +211,20 @@ function eachSnapshotById(items, render, cacheKey, id, source) {
211
211
  cache = c;
212
212
  }
213
213
  const segItems = new Array(items.length);
214
- const seen = /* @__PURE__ */ new Set();
214
+ const seen = /* @__PURE__ */ new Map();
215
215
  for (let i = 0; i < items.length; i++) {
216
216
  const item = items[i];
217
217
  assertObjectItem(item, i);
218
- if (seen.has(item)) {
218
+ const first = seen.get(item);
219
+ if (first !== void 0) {
219
220
  throw new Error(
220
- `each(): the same object reference appears at multiple indices in items (first seen earlier, again at index ${i}). The per-item HTML cache is keyed on object identity, so duplicate references break the keyed reconciler and can leak DOM nodes on re-render. Use a fresh object per row (e.g. items.map(o => ({ ...o })) before passing to each()).`
221
+ `each(): the same object reference appears at multiple indices in items (first at index ${first}, again at index ${i}). The per-item HTML cache is keyed on object identity, so duplicate references break the keyed reconciler and can leak DOM nodes on re-render. Use a fresh object per row (e.g. items.map(o => ({ ...o })) before passing to each()).` + // KF-7HMTZQ: an arraySignal's push/insert/update renders through the
222
+ // granular path, which skips this O(N) check, so the duplicate may
223
+ // predate this render; say where to look instead of blaming it.
224
+ (source !== void 0 ? " (arraySignal: likely added by an earlier push/insert/update, not this render.)" : "")
221
225
  );
222
226
  }
223
- seen.add(item);
227
+ seen.set(item, i);
224
228
  const k = cacheKey ? cacheKey(item, i) : void 0;
225
229
  const version = itemVersion(item);
226
230
  let html;
@@ -519,8 +523,8 @@ function morphAttributes(fromEl, toEl) {
519
523
  fromEl.setAttributeNS(ns, attr.name, value);
520
524
  }
521
525
  } else if (fromEl.getAttribute(name) !== value) {
522
- fromEl.setAttribute(name, value);
523
526
  syncFormProp(fromEl, name, value, true);
527
+ fromEl.setAttribute(name, value);
524
528
  }
525
529
  }
526
530
  const fromAttrs = fromEl.attributes;
@@ -531,8 +535,8 @@ function morphAttributes(fromEl, toEl) {
531
535
  if (ns !== null) {
532
536
  if (!toEl.hasAttributeNS(ns, name)) fromEl.removeAttributeNS(ns, name);
533
537
  } else if (!toEl.hasAttribute(name) && !isUserAgentOwnedAttr(fromTag, name) && (!rendered || rendered.includes(name))) {
534
- fromEl.removeAttribute(name);
535
538
  syncFormProp(fromEl, name, "", false);
539
+ fromEl.removeAttribute(name);
536
540
  }
537
541
  }
538
542
  if (fromTag.includes("-")) host[RENDERED_ATTRS] = toEl.getAttributeNames();
@@ -604,14 +608,14 @@ function tryAttributeOnlyFastPath(liveNode, oldHtml, newHtml) {
604
608
  const oldValue = oldTag.attrs.get(name);
605
609
  if (oldValue === rawValue) continue;
606
610
  const value = unescapeAttrValue(rawValue);
607
- liveNode.setAttribute(name, value);
608
611
  syncFormProp(liveNode, name, value, true);
612
+ liveNode.setAttribute(name, value);
609
613
  }
610
614
  for (const name of oldTag.attrs.keys()) {
611
615
  if (newTag.attrs.has(name)) continue;
612
616
  if (isUserAgentOwnedAttr(liveTagUpper, name)) continue;
613
- liveNode.removeAttribute(name);
614
617
  syncFormProp(liveNode, name, "", false);
618
+ liveNode.removeAttribute(name);
615
619
  }
616
620
  delete liveNode[RENDERED_ATTRS];
617
621
  return true;
@@ -1859,4 +1863,4 @@ function resultToSegment(result) {
1859
1863
 
1860
1864
  export { captureFocus, each, morph, mount, moveNode, restoreFocus };
1861
1865
 
1862
- //# sourceMappingURL=chunk-YVBK73GU.js.map
1866
+ //# sourceMappingURL=chunk-MFRXN2G4.js.map