what-core 0.5.6 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/render.js CHANGED
@@ -2,21 +2,151 @@
2
2
  // Solid-style rendering: components run once, signals create individual DOM effects.
3
3
  // No VDOM diffing — direct DOM manipulation with surgical signal-driven updates.
4
4
 
5
- import { effect, untrack, createRoot, signal } from './reactive.js';
6
- import { createDOM, disposeTree } from './dom.js';
5
+ import { effect, untrack, createRoot, signal, __DEV__ } from './reactive.js';
6
+ import { createDOM, disposeTree, getCurrentComponent, getComponentStack } from './dom.js';
7
7
 
8
8
  export { effect, untrack };
9
9
 
10
+ // --- _$createComponent(Component, props, children) ---
11
+ // Internal compiler target for component instantiation. The compiler emits calls
12
+ // to this function instead of h() — keeping h() out of compiled output entirely.
13
+ // Merges children into props and delegates to createDOM which calls createComponent.
14
+
15
+ export function _$createComponent(Component, props, children) {
16
+ if (children && children.length > 0) {
17
+ const mergedChildren = children.length === 1 ? children[0] : children;
18
+ props = props ? { ...props, children: mergedChildren } : { children: mergedChildren };
19
+ }
20
+ // Build a VNode-like object and pass to createDOM which handles component execution
21
+ return createDOM({ tag: Component, props: props || {}, children: children || [], key: null, _vnode: true });
22
+ }
23
+
24
+ // --- URL Sanitization for DOM attributes ---
25
+ // Rejects javascript:, data:, vbscript: protocols (case-insensitive, trimmed).
26
+
27
+ const URL_ATTRS = new Set(['href', 'src', 'action', 'formaction', 'formAction']);
28
+
29
+ function isSafeUrl(url) {
30
+ if (typeof url !== 'string') return true; // non-string values are not URL-injection risks
31
+ const normalized = url.trim().replace(/[\s\x00-\x1f]/g, '').toLowerCase();
32
+ if (normalized.startsWith('javascript:')) return false;
33
+ if (normalized.startsWith('data:')) return false;
34
+ if (normalized.startsWith('vbscript:')) return false;
35
+ return true;
36
+ }
37
+
10
38
  // --- template(html) ---
11
39
  // Pre-parse HTML string into a <template> element. Returns a factory function
12
40
  // that clones the DOM tree via cloneNode(true) — 2-5x faster than createElement chains.
41
+ // INTERNAL: Used by the compiler. Not intended for direct use by application code.
42
+ // Exported as both `template` (for compiler output) and `_template` (to signal internal use).
43
+
44
+ // Table child elements that need special parent wrapping for innerHTML parsing.
45
+ // Browsers auto-correct bare <tr>, <td>, etc. when orphaned — wrapping prevents silent drops.
46
+ const TABLE_WRAPPERS = {
47
+ tr: { depth: 2, wrap: '<table><tbody>', unwrap: '</tbody></table>' },
48
+ td: { depth: 3, wrap: '<table><tbody><tr>', unwrap: '</tr></tbody></table>' },
49
+ th: { depth: 3, wrap: '<table><tbody><tr>', unwrap: '</tr></tbody></table>' },
50
+ thead: { depth: 1, wrap: '<table>', unwrap: '</table>' },
51
+ tbody: { depth: 1, wrap: '<table>', unwrap: '</table>' },
52
+ tfoot: { depth: 1, wrap: '<table>', unwrap: '</table>' },
53
+ colgroup: { depth: 1, wrap: '<table>', unwrap: '</table>' },
54
+ col: { depth: 1, wrap: '<table>', unwrap: '</table>' },
55
+ caption: { depth: 1, wrap: '<table>', unwrap: '</table>' },
56
+ };
57
+
58
+ // SVG element tags that must be created in an SVG namespace context.
59
+ const SVG_ELEMENTS = new Set([
60
+ 'svg', 'path', 'circle', 'rect', 'line', 'polyline', 'polygon', 'ellipse',
61
+ 'g', 'defs', 'use', 'text', 'tspan', 'foreignObject', 'clipPath', 'mask',
62
+ 'pattern', 'linearGradient', 'radialGradient', 'stop', 'marker', 'symbol',
63
+ 'image', 'animate', 'animateTransform', 'animateMotion', 'set',
64
+ 'filter', 'feGaussianBlur', 'feOffset', 'feMerge', 'feMergeNode',
65
+ 'feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite',
66
+ 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap',
67
+ 'feFlood', 'feImage', 'feMorphology', 'feSpecularLighting',
68
+ 'feTile', 'feTurbulence', 'feDistantLight', 'fePointLight', 'feSpotLight',
69
+ ]);
70
+
71
+ function getLeadingTag(html) {
72
+ const m = html.match(/^<([a-zA-Z][a-zA-Z0-9]*)/);
73
+ return m ? m[1] : '';
74
+ }
75
+
76
+ // Internal implementation — no warnings. Used by compiler via _$template.
77
+ function _$templateImpl(html) {
78
+ const trimmed = html.trim();
79
+ const tag = getLeadingTag(trimmed);
80
+
81
+ // SVG namespace: parse inside an SVG container then extract
82
+ if (SVG_ELEMENTS.has(tag)) {
83
+ return svgTemplate(trimmed);
84
+ }
85
+
86
+ // Table element wrapping: parse inside proper table parent then extract
87
+ const tableInfo = TABLE_WRAPPERS[tag];
88
+ if (tableInfo) {
89
+ const t = document.createElement('template');
90
+ t.innerHTML = tableInfo.wrap + trimmed + tableInfo.unwrap;
91
+ // Navigate down through the wrapper to reach the actual element
92
+ return () => {
93
+ let node = t.content.firstChild;
94
+ for (let i = 0; i < tableInfo.depth; i++) {
95
+ node = node.firstChild;
96
+ }
97
+ return node.cloneNode(true);
98
+ };
99
+ }
13
100
 
14
- export function template(html) {
15
101
  const t = document.createElement('template');
16
- t.innerHTML = html.trim();
102
+ t.innerHTML = trimmed;
17
103
  return () => t.content.firstChild.cloneNode(true);
18
104
  }
19
105
 
106
+ // Public export — warns in dev mode that this is a compiler internal.
107
+ // Application code should use JSX, which the compiler transforms into _$template calls.
108
+ let _templateWarned = false;
109
+ export function template(html) {
110
+ if (__DEV__ && !_templateWarned) {
111
+ _templateWarned = true;
112
+ console.warn(
113
+ '[what] template() is a compiler internal. Use JSX instead. ' +
114
+ 'Direct calls with user input can lead to XSS vulnerabilities.'
115
+ );
116
+ }
117
+ return _$templateImpl(html);
118
+ }
119
+
120
+ // Compiler-internal alias — preferred name for compiled output (no warning)
121
+ export { _$templateImpl as _$template };
122
+
123
+ // Legacy alias kept for backwards compat
124
+ export { template as _template };
125
+
126
+ // --- svgTemplate(html) ---
127
+ // Parse SVG content inside an SVG namespace container. Without this, innerHTML on a
128
+ // <template> element creates HTML-namespace nodes, making SVG elements invisible.
129
+ // If the HTML is a complete <svg> tag, it is parsed inside a temporary <div> so the
130
+ // browser uses the correct SVG namespace. For inner SVG elements (path, circle, etc.),
131
+ // they are wrapped in an <svg> container for parsing and then extracted.
132
+
133
+ export function svgTemplate(html) {
134
+ const trimmed = html.trim();
135
+ const tag = getLeadingTag(trimmed);
136
+
137
+ if (tag === 'svg') {
138
+ // Complete <svg> element — parse in a div (browsers handle the namespace)
139
+ const t = document.createElement('template');
140
+ t.innerHTML = trimmed;
141
+ return () => t.content.firstChild.cloneNode(true);
142
+ }
143
+
144
+ // Inner SVG element (path, circle, g, etc.) — wrap in <svg> for namespace context
145
+ const t = document.createElement('template');
146
+ t.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg">${trimmed}</svg>`;
147
+ return () => t.content.firstChild.firstChild.cloneNode(true);
148
+ }
149
+
20
150
  // --- insert(parent, child, marker?) ---
21
151
  // Reactive child insertion. Handles all child types:
22
152
  // - string/number → text node
@@ -95,6 +225,16 @@ function sameNodeArray(a, b) {
95
225
  }
96
226
 
97
227
  function reconcileInsert(parent, value, current, marker) {
228
+ // Guard: parent must be a node that supports child operations.
229
+ // This catches cases where a stale DOM reference (e.g., a comment node from
230
+ // shifted childNodes indices) is mistakenly passed as the parent.
231
+ if (!parent || typeof parent.insertBefore !== 'function') {
232
+ if (__DEV__) {
233
+ console.warn('[what] reconcileInsert called with invalid parent:', parent);
234
+ }
235
+ return current;
236
+ }
237
+
98
238
  const targetMarker = marker || null;
99
239
 
100
240
  if (value == null || typeof value === 'boolean') {
@@ -190,11 +330,15 @@ function reconcileList(parent, endMarker, oldItems, newItems, mappedNodes, dispo
190
330
  const oldLen = oldItems.length;
191
331
 
192
332
  if (newLen === 0) {
193
- // Fast path: clear all
333
+ // Fast path: clear all — remove only this list's nodes, not all parent content
194
334
  if (oldLen > 0) {
195
- for (let i = 0; i < oldLen; i++) disposeFns[i]?.();
196
- parent.textContent = '';
197
- parent.appendChild(endMarker);
335
+ for (let i = 0; i < oldLen; i++) {
336
+ disposeFns[i]?.();
337
+ if (mappedNodes[i]?.parentNode === parent) {
338
+ disposeTree(mappedNodes[i]);
339
+ parent.removeChild(mappedNodes[i]);
340
+ }
341
+ }
198
342
  mappedNodes.length = 0;
199
343
  disposeFns.length = 0;
200
344
  }
@@ -427,11 +571,15 @@ function reconcileKeyed(parent, endMarker, oldItems, newItems, mappedNodes, disp
427
571
  // --- Fast path: clear all ---
428
572
  if (newLen === 0) {
429
573
  if (oldLen > 0) {
430
- // Skip individual disposal: per-row effects only subscribe to their item signal,
431
- // which is also being discarded. Both become unreachable → GC collects them.
432
- // Bulk DOM removal: clear parent, re-add marker.
433
- parent.textContent = '';
434
- parent.appendChild(endMarker);
574
+ // Call dispose functions to run cleanup callbacks (onCleanup, effect cleanups).
575
+ // Without this, cleanup callbacks leak.
576
+ for (let i = 0; i < oldLen; i++) {
577
+ disposeFns[i]?.();
578
+ if (mappedNodes[i]?.parentNode === parent) {
579
+ disposeTree(mappedNodes[i]);
580
+ parent.removeChild(mappedNodes[i]);
581
+ }
582
+ }
435
583
  mappedNodes.length = 0;
436
584
  disposeFns.length = 0;
437
585
  if (keyedState) keyedState.clear();
@@ -710,6 +858,23 @@ export function spread(el, props) {
710
858
  }
711
859
 
712
860
  export function setProp(el, key, value) {
861
+ // Ref handling — assign element to ref object/callback (defense in depth)
862
+ if (key === 'ref') {
863
+ if (typeof value === 'function') value(el);
864
+ else if (value && typeof value === 'object') value.current = el;
865
+ return;
866
+ }
867
+
868
+ // Sanitize URL attributes — reject dangerous protocols
869
+ if (URL_ATTRS.has(key) || URL_ATTRS.has(key.toLowerCase())) {
870
+ if (!isSafeUrl(value)) {
871
+ if (typeof console !== 'undefined') {
872
+ console.warn(`[what] Blocked unsafe URL in "${key}" attribute: ${value}`);
873
+ }
874
+ return;
875
+ }
876
+ }
877
+
713
878
  if (key === 'class' || key === 'className') {
714
879
  el.className = value || '';
715
880
  } else if (key === 'dangerouslySetInnerHTML') {
@@ -718,7 +883,13 @@ export function setProp(el, key, value) {
718
883
  if (value && typeof value === 'object' && '__html' in value) {
719
884
  el.innerHTML = value.__html ?? '';
720
885
  } else {
721
- el.innerHTML = value ?? '';
886
+ // Plain string innerHTML is rejected for security — use { __html: string } form
887
+ if (typeof console !== 'undefined' && value != null && value !== '') {
888
+ console.warn(
889
+ '[what] Plain string innerHTML is not allowed. Use { __html: "..." } or dangerouslySetInnerHTML={{ __html: "..." }} instead.'
890
+ );
891
+ }
892
+ // Ignored — do not set innerHTML from plain string
722
893
  }
723
894
  } else if (key === 'style') {
724
895
  if (typeof value === 'string') {
@@ -784,3 +955,280 @@ export function classList(el, classes) {
784
955
  }
785
956
  });
786
957
  }
958
+
959
+ // =========================================================================
960
+ // DOM Hydration
961
+ // =========================================================================
962
+ // Reuses server-rendered DOM instead of creating new nodes.
963
+ // After hydration is complete, switches to normal rendering for updates.
964
+
965
+ let _isHydrating = false;
966
+ let _hydrationCursor = null;
967
+
968
+ export function isHydrating() {
969
+ return _isHydrating;
970
+ }
971
+
972
+ /**
973
+ * hydrate(vnode, container)
974
+ * Walk existing DOM nodes in `container`, match them against the vnode tree,
975
+ * attach reactive bindings, and skip cloneNode. Once done, switch to normal rendering.
976
+ */
977
+ export function hydrate(vnode, container) {
978
+ _isHydrating = true;
979
+ _hydrationCursor = { parent: container, index: 0 };
980
+
981
+ try {
982
+ const result = hydrateNode(vnode, container);
983
+ return result;
984
+ } finally {
985
+ _isHydrating = false;
986
+ _hydrationCursor = null;
987
+ }
988
+ }
989
+
990
+ /**
991
+ * Claim the next DOM node from the hydration cursor.
992
+ * Returns the existing DOM node or null if none available.
993
+ */
994
+ function claimNode(parent) {
995
+ const children = parent.childNodes;
996
+ while (_hydrationCursor.index < children.length) {
997
+ const node = children[_hydrationCursor.index];
998
+ // Skip hydration comment markers
999
+ if (node.nodeType === 8) { // Comment node
1000
+ const text = node.textContent;
1001
+ if (text === '$' || text === '/$' || text === '[]' || text === '/[]') {
1002
+ _hydrationCursor.index++;
1003
+ continue;
1004
+ }
1005
+ }
1006
+ _hydrationCursor.index++;
1007
+ return node;
1008
+ }
1009
+ return null;
1010
+ }
1011
+
1012
+ function isDevMode() {
1013
+ return typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production';
1014
+ }
1015
+
1016
+ function hydrateNode(vnode, parent) {
1017
+ if (vnode == null || typeof vnode === 'boolean') {
1018
+ return null;
1019
+ }
1020
+
1021
+ // Text node
1022
+ if (typeof vnode === 'string' || typeof vnode === 'number') {
1023
+ const existing = claimNode(parent);
1024
+ const text = String(vnode);
1025
+
1026
+ if (existing && existing.nodeType === 3) {
1027
+ // Reuse text node — check for mismatch in dev
1028
+ if (isDevMode() && existing.textContent !== text) {
1029
+ console.warn(
1030
+ `[what] Hydration mismatch: expected text "${text}", got "${existing.textContent}"`
1031
+ );
1032
+ existing.textContent = text;
1033
+ }
1034
+ return existing;
1035
+ }
1036
+
1037
+ // Mismatch: expected text node, got element or nothing
1038
+ if (isDevMode()) {
1039
+ console.warn(
1040
+ `[what] Hydration mismatch: expected text node "${text}", got ${existing ? existing.nodeName : 'nothing'}. Falling back to client render.`
1041
+ );
1042
+ }
1043
+ const textNode = document.createTextNode(text);
1044
+ if (existing) {
1045
+ parent.replaceChild(textNode, existing);
1046
+ } else {
1047
+ parent.appendChild(textNode);
1048
+ }
1049
+ return textNode;
1050
+ }
1051
+
1052
+ // Reactive function child — attach effect to existing node
1053
+ if (typeof vnode === 'function') {
1054
+ // Unwrap to get the initial value for hydration
1055
+ const initialValue = vnode();
1056
+ let current = hydrateNode(initialValue, parent);
1057
+
1058
+ // Set up reactive effect for future updates (normal rendering path)
1059
+ effect(() => {
1060
+ const value = vnode();
1061
+ // After hydration, this runs as normal insert
1062
+ if (!_isHydrating) {
1063
+ current = reconcileInsert(parent, value, current, null);
1064
+ }
1065
+ });
1066
+ return current;
1067
+ }
1068
+
1069
+ // Array — hydrate each child
1070
+ if (Array.isArray(vnode)) {
1071
+ const nodes = [];
1072
+ for (const child of vnode) {
1073
+ const node = hydrateNode(child, parent);
1074
+ if (node) nodes.push(node);
1075
+ }
1076
+ return nodes.length === 1 ? nodes[0] : nodes;
1077
+ }
1078
+
1079
+ // VNode — component or element
1080
+ if (typeof vnode === 'object' && vnode._vnode) {
1081
+ // Component — route through component context so hooks work during hydration
1082
+ if (typeof vnode.tag === 'function') {
1083
+ const componentStack = getComponentStack();
1084
+ const Component = vnode.tag;
1085
+ const props = vnode.props || {};
1086
+ const children = vnode.children || [];
1087
+
1088
+ // Set up component context (mirrors createComponent in dom.js)
1089
+ const ctx = {
1090
+ hooks: [],
1091
+ hookIndex: 0,
1092
+ effects: [],
1093
+ cleanups: [],
1094
+ mounted: false,
1095
+ disposed: false,
1096
+ Component,
1097
+ _parentCtx: componentStack[componentStack.length - 1] || null,
1098
+ _errorBoundary: null,
1099
+ };
1100
+
1101
+ // Push context so hooks can access it
1102
+ componentStack.push(ctx);
1103
+
1104
+ let result;
1105
+ try {
1106
+ const propsChildren = children.length === 0 ? undefined
1107
+ : children.length === 1 ? children[0] : children;
1108
+ result = Component({ ...props, children: propsChildren });
1109
+ } catch (error) {
1110
+ componentStack.pop();
1111
+ console.error('[what] Error in component during hydration:', Component.name || 'Anonymous', error);
1112
+ return null;
1113
+ }
1114
+
1115
+ componentStack.pop();
1116
+ ctx.mounted = true;
1117
+
1118
+ // Run onMount callbacks after hydration
1119
+ if (ctx._mountCallbacks) {
1120
+ queueMicrotask(() => {
1121
+ if (ctx.disposed) return;
1122
+ for (const fn of ctx._mountCallbacks) {
1123
+ try { fn(); } catch (e) { console.error('[what] onMount error:', e); }
1124
+ }
1125
+ });
1126
+ }
1127
+
1128
+ return hydrateNode(result, parent);
1129
+ }
1130
+
1131
+ // Element — claim existing DOM element
1132
+ const existing = claimNode(parent);
1133
+ const expectedTag = vnode.tag.toUpperCase();
1134
+
1135
+ if (existing && existing.nodeType === 1 && existing.nodeName === expectedTag) {
1136
+ // Match! Reuse this element. Apply props/bindings.
1137
+ hydrateElementProps(existing, vnode.props || {});
1138
+
1139
+ // Hydrate children
1140
+ const savedCursor = _hydrationCursor;
1141
+ _hydrationCursor = { parent: existing, index: 0 };
1142
+
1143
+ const rawInner = vnode.props?.dangerouslySetInnerHTML?.__html;
1144
+ if (rawInner == null) {
1145
+ for (const child of vnode.children) {
1146
+ hydrateNode(child, existing);
1147
+ }
1148
+ }
1149
+
1150
+ _hydrationCursor = savedCursor;
1151
+ return existing;
1152
+ }
1153
+
1154
+ // Mismatch — fall back to client render for this subtree
1155
+ if (isDevMode()) {
1156
+ console.warn(
1157
+ `[what] Hydration mismatch: expected <${vnode.tag}>, got ${existing ? existing.nodeName : 'nothing'}. Falling back to client render.`
1158
+ );
1159
+ }
1160
+
1161
+ // Create the element from scratch
1162
+ const newEl = document.createElement(vnode.tag);
1163
+ for (const key in vnode.props || {}) {
1164
+ if (key === 'children' || key === 'key') continue;
1165
+ setProp(newEl, key, vnode.props[key]);
1166
+ }
1167
+ for (const child of vnode.children) {
1168
+ reconcileInsert(newEl, child, null, null);
1169
+ }
1170
+ if (existing) {
1171
+ parent.replaceChild(newEl, existing);
1172
+ } else {
1173
+ parent.appendChild(newEl);
1174
+ }
1175
+ return newEl;
1176
+ }
1177
+
1178
+ // DOM node — use directly
1179
+ if (isDomNode(vnode)) {
1180
+ return vnode;
1181
+ }
1182
+
1183
+ // Fallback — create text node
1184
+ const textNode = document.createTextNode(String(vnode));
1185
+ parent.appendChild(textNode);
1186
+ return textNode;
1187
+ }
1188
+
1189
+ /**
1190
+ * Apply props to an existing hydrated element.
1191
+ * Attaches event handlers and reactive bindings without re-creating the element.
1192
+ */
1193
+ function hydrateElementProps(el, props) {
1194
+ for (const key in props) {
1195
+ if (key === 'children' || key === 'key' || key === 'ref') continue;
1196
+ if (key === 'dangerouslySetInnerHTML' || key === 'innerHTML') continue;
1197
+
1198
+ const value = props[key];
1199
+
1200
+ // Event handlers — always attach (they don't exist in SSR HTML)
1201
+ if (key.startsWith('on') && key.length > 2) {
1202
+ const event = key.slice(2).toLowerCase();
1203
+ el.addEventListener(event, value);
1204
+ continue;
1205
+ }
1206
+
1207
+ // Delegated events ($$click etc.)
1208
+ if (key.startsWith('$$')) {
1209
+ el[key] = value;
1210
+ continue;
1211
+ }
1212
+
1213
+ // Reactive props — set up effects
1214
+ if (typeof value === 'function' && !key.startsWith('on')) {
1215
+ if (key === 'class' || key === 'className') {
1216
+ effect(() => { el.className = value() || ''; });
1217
+ } else if (key === 'style' && typeof value() === 'object') {
1218
+ effect(() => {
1219
+ const styles = value();
1220
+ for (const prop in styles) {
1221
+ el.style[prop] = styles[prop] ?? '';
1222
+ }
1223
+ });
1224
+ } else {
1225
+ effect(() => { setProp(el, key, value()); });
1226
+ }
1227
+ continue;
1228
+ }
1229
+
1230
+ // Static props — skip attributes already set from SSR
1231
+ // Only attach non-serializable props or ones that may differ
1232
+ if (key === 'data-hk') continue;
1233
+ }
1234
+ }