keits 0.0.4 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/README.md +93 -79
  2. package/dist/dev/api.js +8 -3
  3. package/dist/dev/forms.js +6 -4
  4. package/dist/dev/index.js +26 -35
  5. package/dist/dev/router.js +24 -7
  6. package/dist/dev/shared/{computed-3UO-KiH1.js → computed-DrF8O8b4.js} +1 -1
  7. package/dist/dev/shared/{element-CQPqagu1.js → element-DXwmUAnz.js} +30 -76
  8. package/dist/dev/shared/{graph-D6-x_CWC.js → graph-SIvYLXSv.js} +62 -3
  9. package/dist/dev/shared/hydrate-C8cOsDDH.js +588 -0
  10. package/dist/dev/shared/mount-CDB2HgN5.js +23 -0
  11. package/dist/dev/shared/namespaces-Cz82B0Pr.js +84 -0
  12. package/dist/dev/shared/{owner-Dmge21OW.js → owner-BuwIoI4j.js} +12 -2
  13. package/dist/dev/shared/render-context-k2uu_dM_.js +34 -0
  14. package/dist/dev/shared/render-effect-Uk9dDmuU.js +32 -0
  15. package/dist/dev/shared/{resource-CbXVATvq.js → resource-DlgzdtcG.js} +24 -33
  16. package/dist/dev/shared/{signal-BOXkY-Iv.js → signal-B3xOKbVm.js} +1 -1
  17. package/dist/dev/shared/{store-BzUN1qE5.js → store-0vEg2bQV.js} +7 -3
  18. package/dist/dev/shared/unsafe-keys-CB1P22No.js +8 -0
  19. package/dist/dev/static.js +76 -0
  20. package/dist/dev/svg.js +2 -1
  21. package/dist/dev/testing.js +216 -0
  22. package/dist/dev/vite.js +141 -0
  23. package/dist/prod/api.js +76 -71
  24. package/dist/prod/forms.js +63 -60
  25. package/dist/prod/index.js +56 -64
  26. package/dist/prod/router.js +86 -73
  27. package/dist/prod/shared/{computed-CAPpOLCY.js → computed-BjqJ6Pps.js} +1 -1
  28. package/dist/prod/shared/element-DCit4-3e.js +129 -0
  29. package/dist/prod/shared/{graph-C_aA46c6.js → graph-CR2WKbwr.js} +107 -63
  30. package/dist/prod/shared/hydrate-kKnJbkV7.js +480 -0
  31. package/dist/prod/shared/mount-DbeKIoyD.js +18 -0
  32. package/dist/prod/shared/namespaces-BSRrBJIU.js +71 -0
  33. package/dist/prod/shared/owner-DBi3odT4.js +67 -0
  34. package/dist/prod/shared/render-context-DF8lr1uu.js +30 -0
  35. package/dist/prod/shared/render-effect-UFDi2Pfh.js +25 -0
  36. package/dist/prod/shared/resource-Ch5tVseZ.js +91 -0
  37. package/dist/prod/shared/signal-BDMlfa0Z.js +16 -0
  38. package/dist/prod/shared/store-CvW0DbmK.js +110 -0
  39. package/dist/prod/shared/unsafe-keys-C5PMlerl.js +7 -0
  40. package/dist/prod/static.js +48 -0
  41. package/dist/prod/svg.js +3 -2
  42. package/dist/prod/testing.js +144 -0
  43. package/dist/prod/vite.js +106 -0
  44. package/dist/types/async/render-context.d.ts +10 -0
  45. package/dist/types/core/effect.d.ts +1 -0
  46. package/dist/types/core/graph.d.ts +11 -0
  47. package/dist/types/core/owner.d.ts +1 -0
  48. package/dist/types/core/unsafe-keys.d.ts +2 -0
  49. package/dist/types/dom/hooks.d.ts +4 -0
  50. package/dist/types/dom/types.d.ts +5 -0
  51. package/dist/types/router/index.d.ts +1 -0
  52. package/dist/types/router/match.d.ts +1 -0
  53. package/dist/types/router/types.d.ts +1 -0
  54. package/dist/types/static/head.d.ts +36 -0
  55. package/dist/types/static/hydrate.d.ts +3 -0
  56. package/dist/types/static/index.d.ts +4 -0
  57. package/dist/types/static/island.d.ts +14 -0
  58. package/dist/types/static/json.d.ts +1 -0
  59. package/dist/types/static/render.d.ts +11 -0
  60. package/dist/types/static/server-dom.d.ts +100 -0
  61. package/dist/types/testing/index.d.ts +62 -0
  62. package/dist/types/vite/index.d.ts +24 -0
  63. package/package.json +34 -7
  64. package/dist/dev/shared/render-effect-kOGnLNbL.js +0 -26
  65. package/dist/prod/shared/element-DGyQ01Vs.js +0 -164
  66. package/dist/prod/shared/owner-6BFHIPR9.js +0 -59
  67. package/dist/prod/shared/render-effect-DjaUT3Cn.js +0 -23
  68. package/dist/prod/shared/resource-CNC2DBO3.js +0 -109
  69. package/dist/prod/shared/signal-DGrl3r9T.js +0 -16
  70. package/dist/prod/shared/store-Dcscpk_h.js +0 -109
@@ -0,0 +1,23 @@
1
+ import { n as createRoot } from "./owner-BuwIoI4j.js";
2
+ import { a as hooks, n as insert } from "./namespaces-Cz82B0Pr.js";
3
+ // src/dom/mount.ts
4
+ function mount(app, target) {
5
+ if (target === null) throw new Error("[keits] mount(): the target element was not found (null).");
6
+ const start = hooks.marker();
7
+ const end = hooks.marker();
8
+ target.append(start, end);
9
+ const dispose = createRoot((dispose) => {
10
+ insert(target, app(), end);
11
+ return dispose;
12
+ });
13
+ return () => {
14
+ dispose();
15
+ let node = start;
16
+ while (node !== null) {
17
+ const next = node === end ? null : node.nextSibling;
18
+ node.remove();
19
+ node = next;
20
+ }
21
+ };
22
+ }
23
+ export { mount as t };
@@ -0,0 +1,84 @@
1
+ import { t as renderEffect } from "./render-effect-Uk9dDmuU.js";
2
+ // src/dom/hooks.ts
3
+ var defaultHooks = {
4
+ element: (tag, namespace) => namespace === null ? document.createElement(tag) : document.createElementNS(namespace, tag),
5
+ text: (value) => document.createTextNode(value),
6
+ marker: () => document.createComment(""),
7
+ fragment: () => document.createDocumentFragment()
8
+ };
9
+ var claimPauses = 0;
10
+ function withoutClaims(fn) {
11
+ claimPauses++;
12
+ try {
13
+ return fn();
14
+ } finally {
15
+ claimPauses--;
16
+ }
17
+ }
18
+ function claimsPaused() {
19
+ return claimPauses > 0;
20
+ }
21
+ var hooks = defaultHooks;
22
+ function setHooks(next) {
23
+ const previous = hooks;
24
+ hooks = next;
25
+ return previous;
26
+ }
27
+ // src/dom/insert.ts
28
+ function insert(parent, child, before = null) {
29
+ if (child === null || child === void 0 || typeof child === "boolean") return;
30
+ if (typeof child === "function") return insertDynamic(parent, child, before);
31
+ if (isChildArray(child)) {
32
+ for (const item of child) insert(parent, item, before);
33
+ return;
34
+ }
35
+ if (typeof child === "object") {
36
+ if (!child.nodeType) throw new Error("[keits] A child is a plain object, not text or an element. If it came from an API, check its type (see parse), or write String(value).");
37
+ parent.insertBefore(child, before);
38
+ return;
39
+ }
40
+ parent.insertBefore(hooks.text(String(child)), before);
41
+ }
42
+ function isChildArray(value) {
43
+ return Array.isArray(value);
44
+ }
45
+ function isTextValue(value) {
46
+ return value === null || typeof value !== "object" && typeof value !== "function";
47
+ }
48
+ function toText(value) {
49
+ return value === null || value === void 0 || typeof value === "boolean" ? "" : String(value);
50
+ }
51
+ function insertDynamic(parent, fn, before) {
52
+ const text = hooks.text("");
53
+ parent.insertBefore(text, before);
54
+ let start = null;
55
+ let end = null;
56
+ renderEffect(() => {
57
+ const value = fn();
58
+ if (start === null || end === null) {
59
+ if (isTextValue(value)) {
60
+ const next = toText(value);
61
+ if (text.data !== next) text.data = next;
62
+ return;
63
+ }
64
+ start = hooks.marker();
65
+ end = hooks.marker();
66
+ text.before(start);
67
+ text.after(end);
68
+ text.remove();
69
+ }
70
+ clearRange(start, end);
71
+ insert(end.parentNode, value, end);
72
+ });
73
+ }
74
+ function clearRange(start, end) {
75
+ let node = start.nextSibling;
76
+ while (node !== null && node !== end) {
77
+ const next = node.nextSibling;
78
+ node.remove();
79
+ node = next;
80
+ }
81
+ }
82
+ // src/dom/namespaces.ts
83
+ var SVG_NS = "http://www.w3.org/2000/svg";
84
+ export { hooks as a, defaultHooks as i, insert as n, setHooks as o, claimsPaused as r, withoutClaims as s, SVG_NS as t };
@@ -1,4 +1,4 @@
1
- import { _ as withStaticRender, c as handleError, i as batch, n as addMount, o as dispose, p as runWithOwner$1, r as adopt, s as getOwner$1, t as addCleanup } from "./graph-D6-x_CWC.js";
1
+ import { _ as runWithOwner$1, c as getOwner$1, i as batch, l as giveKey, n as addMount, o as dispose, r as adopt, t as addCleanup, u as handleError, w as withStaticRender } from "./graph-SIvYLXSv.js";
2
2
  // src/core/owner.ts
3
3
  function getOwner() {
4
4
  return getOwner$1();
@@ -15,6 +15,7 @@ function createRoot(fn) {
15
15
  disposed: false,
16
16
  handler: null
17
17
  };
18
+ giveKey(root);
18
19
  const disposeRoot = () => batch(() => dispose(root));
19
20
  return batch(() => {
20
21
  try {
@@ -25,6 +26,15 @@ function createRoot(fn) {
25
26
  }
26
27
  });
27
28
  }
29
+ function keyedRoot(key, hydratable, fn) {
30
+ return createRoot((dispose) => {
31
+ const root = getOwner$1();
32
+ root.key = key;
33
+ root.keyCount = 0;
34
+ if (hydratable) root.hydratable = true;
35
+ return fn(dispose);
36
+ });
37
+ }
28
38
  function onCleanup(fn) {
29
39
  if (!addCleanup(fn) && true) console.warn("[keits] onCleanup was called outside an owner, so it will never run.");
30
40
  }
@@ -59,4 +69,4 @@ function renderStatic(fn) {
59
69
  }
60
70
  }));
61
71
  }
62
- export { onMount as a, onCleanup as i, createRoot as n, renderStatic as o, getOwner as r, runWithOwner as s, catchError as t };
72
+ export { onCleanup as a, runWithOwner as c, keyedRoot as i, createRoot as n, onMount as o, getOwner as r, renderStatic as s, catchError as t };
@@ -0,0 +1,34 @@
1
+ import { _ as runWithOwner, c as getOwner, r as adopt } from "./graph-SIvYLXSv.js";
2
+ // src/core/context.ts
3
+ function createContext(defaultValue, options) {
4
+ const context = { defaultValue };
5
+ if (options?.name !== void 0) context.name = options.name;
6
+ return context;
7
+ }
8
+ function provide(context, value, fn) {
9
+ const provider = {
10
+ kind: 3,
11
+ owner: null,
12
+ children: null,
13
+ cleanups: null,
14
+ disposed: false,
15
+ handler: null,
16
+ context: {
17
+ key: context,
18
+ value
19
+ }
20
+ };
21
+ adopt(provider);
22
+ return runWithOwner(provider, fn);
23
+ }
24
+ function useContext(context) {
25
+ for (let o = getOwner(); o !== null; o = o.owner) if (o.kind === 3 && o.context?.key === context) return o.context.value;
26
+ return context.defaultValue;
27
+ }
28
+ // src/async/render-context.ts
29
+ var RenderContext = createContext(null);
30
+ var hydratedValue = null;
31
+ function setHydratedValue(lookup) {
32
+ hydratedValue = lookup;
33
+ }
34
+ export { provide as a, createContext as i, hydratedValue as n, useContext as o, setHydratedValue as r, RenderContext as t };
@@ -0,0 +1,32 @@
1
+ import { c as getOwner, f as isStaticRender, g as runEffect, i as batch, m as nextKey, r as adopt } from "./graph-SIvYLXSv.js";
2
+ // src/core/effect.ts
3
+ function effect(fn, options) {
4
+ if (isStaticRender()) {
5
+ nextKey();
6
+ return;
7
+ }
8
+ if (getOwner() === null) console.warn(`[keits] effect(${options?.name === void 0 ? "" : `"${options.name}"`}) was created outside a root (createRoot, mount, or a component): nothing will ever dispose it. Create it inside one.`);
9
+ createEffect(fn, options?.name);
10
+ }
11
+ function createEffect(fn, name) {
12
+ const node = {
13
+ kind: 1,
14
+ fn,
15
+ state: 0,
16
+ sources: [],
17
+ flushId: 0,
18
+ flushRuns: 0,
19
+ owner: null,
20
+ children: null,
21
+ cleanups: null,
22
+ disposed: false
23
+ };
24
+ if (name !== void 0) node.name = name;
25
+ adopt(node);
26
+ batch(() => runEffect(node));
27
+ }
28
+ // src/dom/render-effect.ts
29
+ function renderEffect(fn) {
30
+ createEffect(fn);
31
+ }
32
+ export { effect as n, renderEffect as t };
@@ -1,32 +1,7 @@
1
- import { c as handleError, h as untrack, i as batch, p as runWithOwner, r as adopt, s as getOwner, t as addCleanup } from "./graph-D6-x_CWC.js";
2
- import { t as signal } from "./signal-BOXkY-Iv.js";
3
- import { t as renderEffect } from "./render-effect-kOGnLNbL.js";
4
- // src/core/context.ts
5
- function createContext(defaultValue, options) {
6
- const context = { defaultValue };
7
- if (options?.name !== void 0) context.name = options.name;
8
- return context;
9
- }
10
- function provide(context, value, fn) {
11
- const provider = {
12
- kind: 3,
13
- owner: null,
14
- children: null,
15
- cleanups: null,
16
- disposed: false,
17
- handler: null,
18
- context: {
19
- key: context,
20
- value
21
- }
22
- };
23
- adopt(provider);
24
- return runWithOwner(provider, fn);
25
- }
26
- function useContext(context) {
27
- for (let o = getOwner(); o !== null; o = o.owner) if (o.kind === 3 && o.context?.key === context) return o.context.value;
28
- return context.defaultValue;
29
- }
1
+ import { i as createContext, n as hydratedValue, o as useContext, t as RenderContext } from "./render-context-k2uu_dM_.js";
2
+ import { S as untrack, c as getOwner, i as batch, m as nextKey, s as getObserver, t as addCleanup, u as handleError } from "./graph-SIvYLXSv.js";
3
+ import { t as signal } from "./signal-B3xOKbVm.js";
4
+ import { t as renderEffect } from "./render-effect-Uk9dDmuU.js";
30
5
  // src/async/suspense-context.ts
31
6
  var SuspenseContext = createContext(null);
32
7
  // src/async/resource.ts
@@ -36,8 +11,11 @@ function resource(first, second, third) {
36
11
  const fetcher = hasSource ? second : (_, info) => first(info);
37
12
  const options = hasSource ? third : second;
38
13
  const owner = getOwner();
39
- const hasInitial = options !== void 0 && "initialValue" in options;
40
- const value = signal(options?.initialValue);
14
+ const key = nextKey();
15
+ const tracker = useContext(RenderContext);
16
+ const hydrated = key !== null && tracker === null ? hydratedValue?.(key) : void 0;
17
+ const hasInitial = hydrated !== void 0 || options !== void 0 && "initialValue" in options;
18
+ const value = signal(hydrated !== void 0 ? hydrated.value : options?.initialValue);
41
19
  const state = signal(hasInitial ? "ready" : "unresolved");
42
20
  const failure = signal(null);
43
21
  let controller = null;
@@ -78,14 +56,17 @@ function resource(first, second, third) {
78
56
  return Promise.resolve();
79
57
  }
80
58
  state.set(untrack(value) === void 0 && untrack(state) !== "ready" ? "pending" : "refreshing");
81
- return Promise.resolve(result).then((data) => {
59
+ const loading = Promise.resolve(result).then((data) => {
82
60
  if (id === version) succeed(data);
83
61
  }, (error) => {
84
62
  if (id === version) fail(error);
85
63
  });
64
+ tracker?.wait(loading);
65
+ return loading;
86
66
  }
87
67
  function succeed(data) {
88
68
  controller = null;
69
+ if (key !== null) tracker?.store(key, data, owner);
89
70
  batch(() => {
90
71
  value.set(() => data);
91
72
  failure.set(null);
@@ -101,8 +82,13 @@ function resource(first, second, third) {
101
82
  });
102
83
  settleWaiters();
103
84
  }
85
+ let skipFirst = hydrated !== void 0;
104
86
  renderEffect(() => {
105
87
  const src = source();
88
+ if (skipFirst) {
89
+ skipFirst = false;
90
+ return;
91
+ }
106
92
  untrack(() => load(src, false));
107
93
  });
108
94
  addCleanup(() => {
@@ -110,7 +96,12 @@ function resource(first, second, third) {
110
96
  controller?.abort();
111
97
  controller = null;
112
98
  });
99
+ let warned = false;
113
100
  const read = () => {
101
+ if (!warned && owner !== null && getObserver() === owner) {
102
+ warned = true;
103
+ console.warn("[keits] A resource is read inside the same `() =>` function that created it. When its data arrives that function runs again and creates a new resource, which loads again: an endless loop. Create the resource in the component body, and read it inside `() =>`.");
104
+ }
114
105
  const current = state();
115
106
  if (current === "errored") throw failure().error;
116
107
  if (current === "pending") {
@@ -151,4 +142,4 @@ function resource(first, second, third) {
151
142
  function isPromiseLike(value) {
152
143
  return typeof value?.then === "function";
153
144
  }
154
- export { useContext as a, provide as i, SuspenseContext as n, createContext as r, resource as t };
145
+ export { SuspenseContext as n, resource as t };
@@ -1,4 +1,4 @@
1
- import { d as notify, m as track } from "./graph-D6-x_CWC.js";
1
+ import { h as notify, x as track } from "./graph-SIvYLXSv.js";
2
2
  // src/core/signal.ts
3
3
  function signal(value, options) {
4
4
  const node = {
@@ -1,4 +1,5 @@
1
- import { d as notify, h as untrack, i as batch, m as track, u as isTracking } from "./graph-D6-x_CWC.js";
1
+ import { t as UNSAFE_KEYS } from "./unsafe-keys-CB1P22No.js";
2
+ import { S as untrack, h as notify, i as batch, p as isTracking, x as track } from "./graph-SIvYLXSv.js";
2
3
  // src/core/store.ts
3
4
  var RAW = Symbol("raw");
4
5
  var SHAPE = Symbol("shape");
@@ -28,7 +29,7 @@ function unwrap(value) {
28
29
  return value;
29
30
  }
30
31
  function isWrappable(value) {
31
- if (value === null || typeof value !== "object") return false;
32
+ if (value === null || typeof value !== "object" || value === Object.prototype) return false;
32
33
  if (Array.isArray(value)) return true;
33
34
  const proto = Object.getPrototypeOf(value);
34
35
  return proto === Object.prototype || proto === null;
@@ -135,7 +136,10 @@ function reconcileInto(target, source, key) {
135
136
  if (raw.length !== source.length) draft.length = source.length;
136
137
  return;
137
138
  }
138
- for (const k of Object.keys(source)) draft[k] = matchAndUpdate(raw[k], source[k], key);
139
+ for (const k of Object.keys(source)) {
140
+ if (UNSAFE_KEYS.has(k)) continue;
141
+ draft[k] = matchAndUpdate(raw[k], source[k], key);
142
+ }
139
143
  for (const k of Object.keys(raw)) if (!Object.hasOwn(source, k)) delete draft[k];
140
144
  }
141
145
  function matchAndUpdate(existing, next, key) {
@@ -0,0 +1,8 @@
1
+ // src/core/unsafe-keys.ts
2
+ /** Keys that reach a prototype instead of a property. Data from an API never needs them. */
3
+ var UNSAFE_KEYS = /* @__PURE__ */ new Set([
4
+ "__proto__",
5
+ "constructor",
6
+ "prototype"
7
+ ]);
8
+ export { UNSAFE_KEYS as t };
@@ -0,0 +1,76 @@
1
+ import { i as head, r as renderToString, t as hydrate } from "./shared/hydrate-C8cOsDDH.js";
2
+ import { c as getOwner, f as isStaticRender } from "./shared/graph-SIvYLXSv.js";
3
+ import { a as onCleanup, n as createRoot } from "./shared/owner-BuwIoI4j.js";
4
+ import { a as hooks, n as insert } from "./shared/namespaces-Cz82B0Pr.js";
5
+ // src/static/island.ts
6
+ function island(name, component, options = {}) {
7
+ const render = (props) => {
8
+ const element = hooks.element("keits-island", null);
9
+ element.setAttribute("data-island", name);
10
+ element.setAttribute("style", "display: contents");
11
+ if (options.when !== void 0 && options.when !== "load") element.setAttribute("data-when", options.when);
12
+ const dispose = createRoot((end) => {
13
+ const root = getOwner();
14
+ if (isStaticRender()) {
15
+ root.hydratable = true;
16
+ if (root.key !== void 0) element.setAttribute("data-key", root.key);
17
+ element.setAttribute("data-props", propsJson(name, props));
18
+ }
19
+ insert(element, component(props));
20
+ return end;
21
+ });
22
+ onCleanup(dispose);
23
+ return element;
24
+ };
25
+ return Object.assign(render, {
26
+ island: name,
27
+ component
28
+ });
29
+ }
30
+ function propsJson(name, props) {
31
+ JSON.stringify(props ?? {}, (key, value) => {
32
+ if (typeof value === "function" || typeof value === "symbol") throw new Error(`[keits/static] Island "${name}": prop "${key}" is a ${typeof value}. Island props travel in the HTML, so they must be JSON.`);
33
+ return value;
34
+ });
35
+ return JSON.stringify(props ?? {});
36
+ }
37
+ function hydrateIslands(islands, root = document) {
38
+ for (const element of root.querySelectorAll("keits-island[data-key]")) {
39
+ if (element.parentElement?.closest("keits-island") != null) continue;
40
+ const name = element.getAttribute("data-island") ?? "";
41
+ const entry = Object.hasOwn(islands, name) ? islands[name] : void 0;
42
+ if (entry === void 0) {
43
+ console.warn(`[keits] hydrateIslands(): no island called "${name}" was given, so it stays static.`);
44
+ continue;
45
+ }
46
+ const start = () => {
47
+ if ("island" in entry) return hydrateIsland(element, entry);
48
+ Promise.resolve(entry()).then((loaded) => hydrateIsland(element, "island" in loaded ? loaded : loaded.default), (error) => setTimeout(() => {
49
+ throw error;
50
+ }));
51
+ };
52
+ when(element, element.getAttribute("data-when") ?? "load", start);
53
+ }
54
+ }
55
+ function hydrateIsland(element, found) {
56
+ const key = element.getAttribute("data-key");
57
+ const props = JSON.parse(element.getAttribute("data-props") ?? "{}");
58
+ element.removeAttribute("data-key");
59
+ element.removeAttribute("data-props");
60
+ hydrate(() => found.component(props), element, key);
61
+ }
62
+ function when(element, moment, start) {
63
+ if (moment === "visible" && typeof IntersectionObserver === "function") {
64
+ const observer = new IntersectionObserver((entries) => {
65
+ if (entries.some((entry) => entry.isIntersecting)) {
66
+ observer.disconnect();
67
+ start();
68
+ }
69
+ });
70
+ for (const child of element.children) observer.observe(child);
71
+ if (element.children.length === 0) start();
72
+ } else if (moment === "idle" && typeof requestIdleCallback === "function") requestIdleCallback(() => start());
73
+ else if (moment === "idle") setTimeout(start, 1);
74
+ else start();
75
+ }
76
+ export { head, hydrate, hydrateIslands, island, renderToString };
package/dist/dev/svg.js CHANGED
@@ -1,4 +1,5 @@
1
- import { r as SVG_NS, t as createFactory } from "./shared/element-CQPqagu1.js";
1
+ import { t as createFactory } from "./shared/element-DXwmUAnz.js";
2
+ import { t as SVG_NS } from "./shared/namespaces-Cz82B0Pr.js";
2
3
  // src/svg/element.ts
3
4
  function svg(tag) {
4
5
  return createFactory(tag, SVG_NS);
@@ -0,0 +1,216 @@
1
+ import { t as mount } from "./shared/mount-CDB2HgN5.js";
2
+ import { n as resetHydrationData, r as renderToString, t as hydrate } from "./shared/hydrate-C8cOsDDH.js";
3
+ // src/testing/index.ts
4
+ /**
5
+ * Testing helpers for keits apps (with Vitest + happy-dom or jsdom). Find things the way a user
6
+ * does, by role, label or text, act like a user, and call cleanup() after each test:
7
+ *
8
+ * afterEach(cleanup);
9
+ * const page = render(() => SignupForm());
10
+ * await user.type(page.getByLabelText("Email"), "kei@example.com");
11
+ * user.click(page.getByRole("button", { name: "Sign up" }));
12
+ */
13
+ var mounted = /* @__PURE__ */ new Set();
14
+ /** Mounts `app` into a fresh element in the document. */
15
+ function render(app) {
16
+ const container = document.body.appendChild(document.createElement("div"));
17
+ return track(container, mount(app, container));
18
+ }
19
+ /**
20
+ * Renders `app` like the server does (waiting for its data), and puts the HTML in the page the way
21
+ * a browser receives it. Then `hydrate()` makes it live, as the browser would.
22
+ */
23
+ async function renderOnServer(app) {
24
+ const result = await renderToString(app, { hydrate: true });
25
+ const container = document.body.appendChild(document.createElement("div"));
26
+ container.innerHTML = result.html;
27
+ document.getElementById("keits-data")?.remove();
28
+ if (result.data !== "") document.body.insertAdjacentHTML("beforeend", result.data);
29
+ resetHydrationData();
30
+ mounted.add(() => container.remove());
31
+ return {
32
+ container,
33
+ html: result.html,
34
+ head: result.head,
35
+ hydrate: () => track(container, hydrate(app, container))
36
+ };
37
+ }
38
+ function track(container, dispose) {
39
+ const unmount = () => {
40
+ if (!mounted.delete(unmount)) return;
41
+ dispose();
42
+ container.remove();
43
+ };
44
+ mounted.add(unmount);
45
+ return {
46
+ container,
47
+ unmount,
48
+ ...within(container)
49
+ };
50
+ }
51
+ /** Disposes everything render() and renderOnServer() made. Call it after each test: `afterEach(cleanup)`. */
52
+ function cleanup() {
53
+ for (const unmount of [...mounted]) unmount();
54
+ mounted.clear();
55
+ document.getElementById("keits-data")?.remove();
56
+ }
57
+ /** Waits until pending promises and timers of 0 ms have run (loaded data shows, effects settle). */
58
+ async function flush() {
59
+ for (let i = 0; i < 3; i++) await new Promise((resolve) => setTimeout(resolve, 0));
60
+ }
61
+ /** Acts like a user would: the events a browser fires, in its order. */
62
+ var user = {
63
+ click(element) {
64
+ element.dispatchEvent(new MouseEvent("click", {
65
+ bubbles: true,
66
+ cancelable: true,
67
+ button: 0
68
+ }));
69
+ },
70
+ /** Types `text` one character at a time (an `input` event each), after the current value. */
71
+ type(element, text) {
72
+ const field = asField(element, "type into");
73
+ field.focus();
74
+ for (const char of text) {
75
+ field.value += char;
76
+ field.dispatchEvent(new Event("input", { bubbles: true }));
77
+ }
78
+ },
79
+ /** Empties a text field. */
80
+ clear(element) {
81
+ const field = asField(element, "clear");
82
+ field.value = "";
83
+ field.dispatchEvent(new Event("input", { bubbles: true }));
84
+ },
85
+ /** Picks an option of a <select> by its value. */
86
+ select(element, value) {
87
+ if (!(element instanceof HTMLSelectElement)) throw new Error(`[keits/testing] user.select() needs a <select>, got <${element.localName}>.`);
88
+ element.value = value;
89
+ element.dispatchEvent(new Event("input", { bubbles: true }));
90
+ element.dispatchEvent(new Event("change", { bubbles: true }));
91
+ },
92
+ /** Ticks or unticks a checkbox, or picks a radio. */
93
+ check(element) {
94
+ if (!(element instanceof HTMLInputElement) || element.type !== "checkbox" && element.type !== "radio") throw new Error(`[keits/testing] user.check() needs a checkbox or radio, got ${describe(element)}.`);
95
+ element.checked = element.type === "radio" ? true : !element.checked;
96
+ element.dispatchEvent(new Event("input", { bubbles: true }));
97
+ element.dispatchEvent(new Event("change", { bubbles: true }));
98
+ },
99
+ /** Leaves a field (what makes keits/forms show its error). */
100
+ blur(element) {
101
+ element.dispatchEvent(new FocusEvent("blur"));
102
+ element.dispatchEvent(new FocusEvent("focusout", { bubbles: true }));
103
+ },
104
+ /** Submits a form (or the form an element is in), like pressing Enter in it. */
105
+ submit(element) {
106
+ const form = element instanceof HTMLFormElement ? element : element.closest("form");
107
+ if (form === null) throw new Error(`[keits/testing] user.submit(): ${describe(element)} is not in a <form>.`);
108
+ form.dispatchEvent(new Event("submit", {
109
+ bubbles: true,
110
+ cancelable: true
111
+ }));
112
+ }
113
+ };
114
+ function asField(element, action) {
115
+ if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) return element;
116
+ throw new Error(`[keits/testing] Can't ${action} ${describe(element)}: it isn't an <input> or <textarea>.`);
117
+ }
118
+ /** The queries, scoped to `root`. */
119
+ function within(root) {
120
+ const all = () => [...root.querySelectorAll("*")];
121
+ const byText = (text) => {
122
+ const matching = all().filter((element) => matches(normalize(element.textContent ?? ""), text));
123
+ return matching.filter((element) => !matching.some((other) => other !== element && element.contains(other)));
124
+ };
125
+ const byRole = (role, options = {}) => all().filter((element) => roleOf(element) === role && (options.name === void 0 || matches(nameOf(element), options.name)));
126
+ const one = (found, what) => {
127
+ if (found.length === 1) return found[0];
128
+ const page = normalize(root.textContent ?? "").slice(0, 200);
129
+ if (found.length === 0) throw new Error(`[keits/testing] Found no element ${what}. The page says: "${page}"`);
130
+ throw new Error(`[keits/testing] Found ${found.length} elements ${what}: ${found.map(describe).join(", ")}. Make the query more specific.`);
131
+ };
132
+ const roleQuery = (role, options) => `with role "${role}"${options?.name === void 0 ? "" : ` named ${String(options.name)}`}`;
133
+ return {
134
+ getByText: (text) => one(byText(text), `with the text ${String(text)}`),
135
+ queryByText: (text) => byText(text)[0] ?? null,
136
+ getAllByText: (text) => {
137
+ const found = byText(text);
138
+ if (found.length === 0) one(found, `with the text ${String(text)}`);
139
+ return found;
140
+ },
141
+ getByRole: (role, options) => one(byRole(role, options), roleQuery(role, options)),
142
+ queryByRole: (role, options) => byRole(role, options)[0] ?? null,
143
+ getAllByRole: (role, options) => {
144
+ const found = byRole(role, options);
145
+ if (found.length === 0) one(found, roleQuery(role, options));
146
+ return found;
147
+ },
148
+ getByLabelText: (text) => one(all().filter((element) => isLabelable(element) && labelsOf(element).some((label) => matches(label, text))), `labelled ${String(text)}`),
149
+ getByTestId: (id) => one(all().filter((element) => element.getAttribute("data-testid") === id), `with data-testid "${id}"`)
150
+ };
151
+ }
152
+ var normalize = (text) => text.replace(/\s+/g, " ").trim();
153
+ var matches = (value, expected) => typeof expected === "string" ? value === expected : expected.test(value);
154
+ var describe = (element) => `<${element.localName}${element.id ? `#${element.id}` : ""}>`;
155
+ var isLabelable = (element) => [
156
+ "input",
157
+ "select",
158
+ "textarea",
159
+ "button"
160
+ ].includes(element.localName);
161
+ /** The texts that name a form control: aria-label, aria-labelledby, its <label>s. */
162
+ function labelsOf(element) {
163
+ const labels = [];
164
+ const aria = element.getAttribute("aria-label");
165
+ if (aria !== null) labels.push(normalize(aria));
166
+ const labelledBy = element.getAttribute("aria-labelledby");
167
+ if (labelledBy !== null) labels.push(normalize(labelledBy.split(/\s+/).map((id) => element.ownerDocument.getElementById(id)?.textContent ?? "").join(" ")));
168
+ if (element.id !== "") for (const label of element.ownerDocument.querySelectorAll(`label[for="${element.id}"]`)) labels.push(normalize(label.textContent ?? ""));
169
+ const wrapping = element.closest("label");
170
+ if (wrapping !== null) labels.push(normalize(wrapping.textContent ?? ""));
171
+ return labels;
172
+ }
173
+ /** What the element is to assistive technology: its role attribute, or what its tag means. */
174
+ function roleOf(element) {
175
+ const explicit = element.getAttribute("role");
176
+ if (explicit !== null) return explicit.split(/\s+/)[0];
177
+ const tag = element.localName;
178
+ if (tag === "input") {
179
+ const type = (element.getAttribute("type") ?? "text").toLowerCase();
180
+ if (type === "checkbox" || type === "radio") return type;
181
+ if (type === "button" || type === "submit" || type === "reset") return "button";
182
+ if (type === "range") return "slider";
183
+ if (type === "number") return "spinbutton";
184
+ if (type === "search") return "searchbox";
185
+ if (type === "hidden") return null;
186
+ return "textbox";
187
+ }
188
+ if (/^h[1-6]$/.test(tag)) return "heading";
189
+ const roles = {
190
+ button: "button",
191
+ textarea: "textbox",
192
+ select: "combobox",
193
+ ul: "list",
194
+ ol: "list",
195
+ li: "listitem",
196
+ nav: "navigation",
197
+ main: "main",
198
+ form: "form",
199
+ dialog: "dialog",
200
+ table: "table",
201
+ tr: "row",
202
+ option: "option"
203
+ };
204
+ if (tag === "a") return element.hasAttribute("href") ? "link" : null;
205
+ if (tag === "img") return element.getAttribute("alt") === "" ? "presentation" : "img";
206
+ return roles[tag] ?? null;
207
+ }
208
+ /** The accessible name, simplified: labels for controls, alt for images, the text for the rest. */
209
+ function nameOf(element) {
210
+ const aria = element.getAttribute("aria-label");
211
+ if (aria !== null) return normalize(aria);
212
+ if (isLabelable(element) && element.localName !== "button") return labelsOf(element)[0] ?? normalize(element.getAttribute("placeholder") ?? "");
213
+ if (element.localName === "img") return normalize(element.getAttribute("alt") ?? "");
214
+ return normalize(element.textContent ?? "");
215
+ }
216
+ export { cleanup, flush, render, renderOnServer, user, within };