@pithyjs/core 0.1.0-beta.17 → 0.1.0-beta.19

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/README.md CHANGED
@@ -301,6 +301,8 @@ The `@for` directive provides keyed, reactive list rendering with:
301
301
  | bindBoundAttributes | attributes | `(root: Element | DocumentFragment, context: Record<string, unknown>, disposers: (() => void)[]) => void` | stable | - |
302
302
  | styleWriter | attributes | `(el: Element) => (text: string) => void` | internal | - |
303
303
  | setStyleProp | attributes | `(el: Element, prop: string, value: string | null, priority?: string) => void` | internal | - |
304
+ | UNCOMPILED | attributes | `Error` | internal | - |
305
+ | writeBound | attributes | `(el: Element, attr: string, expr: string, writeStyle: ((text: string) => void) | null, read: () => unknown) => void` | internal | - |
304
306
  | bindClassDirectives | classes | `(root: Element | DocumentFragment, ctx: Record<string, unknown>, disposers: (() => void)[]) => void` | stable | - |
305
307
  | applyClassGroup | classes | `(el: Element, result: unknown, owned: Set<string>) => void` | internal | - |
306
308
  | bindComponentTags | components | `(root: Element | DocumentFragment, rootCtx: Record<string, unknown>, disposers: (() => void)[]) => void` | stable | - |
@@ -436,6 +438,8 @@ pnpm test -- --watch # Watch mode
436
438
  | bindBoundAttributes | - | - | - | Missing unit, integration, e2e |
437
439
  | styleWriter | - | - | - | Missing unit, integration, e2e |
438
440
  | setStyleProp | - | - | - | Missing unit, integration, e2e |
441
+ | UNCOMPILED | - | - | - | Missing unit, integration, e2e |
442
+ | writeBound | - | - | - | Missing unit, integration, e2e |
439
443
  | bindClassDirectives | - | - | - | Missing unit, integration, e2e |
440
444
  | applyClassGroup | - | - | - | Missing unit, integration, e2e |
441
445
  | bindComponentTags | - | - | - | Missing unit, integration, e2e |
@@ -15,5 +15,8 @@ export declare function bindBoundAttributes(root: Element | DocumentFragment, co
15
15
  export declare function styleWriter(el: Element): (text: string) => void;
16
16
  /** @codexApi {"parent":"pithy.runtime.attributes","name":"setStyleProp","stability":"internal","signature":"(el: Element, prop: string, value: string | null, priority?: string) => void"} */
17
17
  export declare function setStyleProp(el: Element, prop: string, value: string | null, priority?: string): void;
18
- export declare function rejectsScriptSink(el: Element, attr: string, text: string): boolean;
18
+ /** @codexApi {"parent":"pithy.runtime.attributes","name":"UNCOMPILED","stability":"internal","signature":"Error"} */
19
+ export declare const UNCOMPILED: Error;
20
+ /** @codexApi {"parent":"pithy.runtime.attributes","name":"writeBound","stability":"internal","signature":"(el: Element, attr: string, expr: string, writeStyle: ((text: string) => void) | null, read: () => unknown) => void"} */
21
+ export declare function writeBound(el: Element, attr: string, expr: string, writeStyle: ((text: string) => void) | null, read: () => unknown): void;
19
22
  //# sourceMappingURL=bindBoundAttributes.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"bindBoundAttributes.d.ts","sourceRoot":"","sources":["../../../src/compile/binds/bindBoundAttributes.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAMF;;;GAGG;AACH,8NAA8N;AAC9N,wBAAgB,mBAAmB,CACjC,IAAI,EAAE,OAAO,GAAG,gBAAgB,EAChC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAChC,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,GACxB,IAAI,CA4CN;AAsBD,wJAAwJ;AACxJ,wBAAgB,WAAW,CAAC,EAAE,EAAE,OAAO,GAAG,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAY/D;AAED,8LAA8L;AAC9L,wBAAgB,YAAY,CAC1B,EAAE,EAAE,OAAO,EACX,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,MAAM,GAAG,IAAI,EACpB,QAAQ,SAAK,GACZ,IAAI,CAYN;AA2BD,wBAAgB,iBAAiB,CAC/B,EAAE,EAAE,OAAO,EACX,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,GACX,OAAO,CAiBT"}
1
+ {"version":3,"file":"bindBoundAttributes.d.ts","sourceRoot":"","sources":["../../../src/compile/binds/bindBoundAttributes.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAMF;;;GAGG;AACH,8NAA8N;AAC9N,wBAAgB,mBAAmB,CACjC,IAAI,EAAE,OAAO,GAAG,gBAAgB,EAChC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAChC,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,GACxB,IAAI,CA8BN;AAsBD,wJAAwJ;AACxJ,wBAAgB,WAAW,CAAC,EAAE,EAAE,OAAO,GAAG,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAY/D;AAED,8LAA8L;AAC9L,wBAAgB,YAAY,CAC1B,EAAE,EAAE,OAAO,EACX,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,MAAM,GAAG,IAAI,EACpB,QAAQ,SAAK,GACZ,IAAI,CAYN;AA+HD,qHAAqH;AACrH,eAAO,MAAM,UAAU,OAA+C,CAAC;AAEvE,mOAAmO;AACnO,wBAAgB,UAAU,CACxB,EAAE,EAAE,OAAO,EACX,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,EACZ,UAAU,EAAE,CAAC,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC,GAAG,IAAI,EAC3C,IAAI,EAAE,MAAM,OAAO,GAClB,IAAI,CAYN"}
@@ -17,7 +17,9 @@ export function bindBoundAttributes(root, context, disposers) {
17
17
  root.querySelectorAll('*').forEach(el => {
18
18
  // Use element's own __pithyCtx when available (projected slot content
19
19
  // carries the parent component's context via this property).
20
- const elCtx = nodeExpando(el).__pithyCtx || context;
20
+ const elCtx = nodeExpando(el).__pithyForwardCtx ??
21
+ nodeExpando(el).__pithyCtx ??
22
+ context;
21
23
  for (const attr of Array.from(el.attributes)) {
22
24
  if (!attr.name.startsWith('data-bind-') || !isDeclaredDirective(attr))
23
25
  continue;
@@ -28,30 +30,7 @@ export function bindBoundAttributes(root, context, disposers) {
28
30
  el.removeAttribute(attr.name);
29
31
  const writeStyle = attrName === 'style' ? styleWriter(el) : null;
30
32
  const stop = effect(() => {
31
- const value = evaluateExpression(expr, elCtx);
32
- if (writeStyle && typeof value === 'boolean') {
33
- writeStyle('');
34
- }
35
- else if (typeof value === 'boolean') {
36
- if (value) {
37
- el.setAttribute(attrName, '');
38
- }
39
- else {
40
- el.removeAttribute(attrName);
41
- }
42
- }
43
- else {
44
- const text = String(value ?? '');
45
- if (writeStyle) {
46
- writeStyle(text);
47
- }
48
- else if (rejectsScriptSink(el, attrName, text)) {
49
- el.removeAttribute(attrName);
50
- }
51
- else {
52
- el.setAttribute(attrName, text);
53
- }
54
- }
33
+ writeBound(el, attrName, expr, writeStyle, () => evaluateExpression(expr, elCtx));
55
34
  });
56
35
  disposers.push(stop);
57
36
  }
@@ -130,7 +109,7 @@ function hasScheme(url, scheme) {
130
109
  const compact = [...url].filter(c => c > ' ' && c !== '\x7f').join('');
131
110
  return scheme.test(compact);
132
111
  }
133
- export function rejectsScriptSink(el, attr, text) {
112
+ function rejectsScriptSink(el, attr, text) {
134
113
  if (el.localName === 'iframe' && attr === 'srcdoc') {
135
114
  if (import.meta.env?.DEV && text !== '') {
136
115
  console.warn('[PithyJS] A bound [srcdoc] is rejected: its HTML runs with the page origin. Bind [src] to a data:text/html URL, which loads in an opaque origin.');
@@ -148,15 +127,134 @@ export function rejectsScriptSink(el, attr, text) {
148
127
  }
149
128
  return true;
150
129
  }
151
- function evaluateExpression(expr, context) {
130
+ const TEXT_BOOLEAN_ATTR = /^(?:aria-.+|contenteditable|draggable|spellcheck)$/i;
131
+ const FORM_CONTROLS = new Set(['input', 'select', 'textarea']);
132
+ function syncSelect(select) {
133
+ const bound = nodeExpando(select).__selectValue;
134
+ if (!bound)
135
+ return;
136
+ const picks = select.multiple ? bound.picks : null;
137
+ let found = false;
138
+ for (const option of select.querySelectorAll('option')) {
139
+ const match = picks
140
+ ? picks.has(option.value)
141
+ : !found && option.value === bound.text;
142
+ option.toggleAttribute('selected', match);
143
+ if (select.multiple)
144
+ option.selected = match;
145
+ found || (found = match);
146
+ }
147
+ if (!select.multiple)
148
+ select.value = bound.text;
149
+ }
150
+ function syncOption(option) {
151
+ const select = option.closest('select');
152
+ const bound = select && nodeExpando(select).__selectValue;
153
+ if (!select || !bound)
154
+ return;
155
+ if (select.multiple && bound.picks) {
156
+ const match = bound.picks.has(option.value);
157
+ option.toggleAttribute('selected', match);
158
+ option.selected = match;
159
+ }
160
+ else if (option.selected || option.value === bound.text) {
161
+ syncSelect(select);
162
+ }
163
+ }
164
+ function setControlValue(el, text, value) {
165
+ if (el.localName === 'option') {
166
+ syncOption(el);
167
+ return;
168
+ }
169
+ if (!FORM_CONTROLS.has(el.localName))
170
+ return;
171
+ const control = el;
172
+ if (control.type === 'file')
173
+ return;
174
+ if (el.localName === 'select') {
175
+ const picks = Array.isArray(value) ? new Set(value.map(String)) : null;
176
+ nodeExpando(el).__selectValue = { text, picks };
177
+ syncSelect(el);
178
+ return;
179
+ }
180
+ if (el.localName === 'textarea' && el.textContent !== text) {
181
+ el.textContent = text;
182
+ }
183
+ if (control.value !== text)
184
+ control.value = text;
185
+ }
186
+ function writeValue(el, attr, value, writeStyle) {
187
+ if (value == null) {
188
+ if (writeStyle)
189
+ writeStyle('');
190
+ else
191
+ el.removeAttribute(attr);
192
+ if (attr === 'value')
193
+ setControlValue(el, '');
194
+ return;
195
+ }
196
+ if (typeof value === 'boolean' && !TEXT_BOOLEAN_ATTR.test(attr)) {
197
+ if (writeStyle)
198
+ writeStyle('');
199
+ else if (value)
200
+ el.setAttribute(attr, '');
201
+ else
202
+ el.removeAttribute(attr);
203
+ return;
204
+ }
205
+ const text = String(value);
206
+ if (writeStyle) {
207
+ writeStyle(text);
208
+ }
209
+ else if (rejectsScriptSink(el, attr, text)) {
210
+ el.removeAttribute(attr);
211
+ }
212
+ else {
213
+ el.setAttribute(attr, text);
214
+ if (attr === 'value')
215
+ setControlValue(el, text, value);
216
+ }
217
+ }
218
+ /** @codexApi {"parent":"pithy.runtime.attributes","name":"UNCOMPILED","stability":"internal","signature":"Error"} */
219
+ export const UNCOMPILED = new Error('The expression does not compile');
220
+ /** @codexApi {"parent":"pithy.runtime.attributes","name":"writeBound","stability":"internal","signature":"(el: Element, attr: string, expr: string, writeStyle: ((text: string) => void) | null, read: () => unknown) => void"} */
221
+ export function writeBound(el, attr, expr, writeStyle, read) {
152
222
  try {
153
- // eslint-disable-next-line no-new-func -- args-style template expression evaluation is a core framework feature
154
- const compiled = new Function(...Object.keys(context), `return (${expr})`);
155
- return compiled(...Object.values(context));
223
+ writeValue(el, attr, read(), writeStyle);
156
224
  }
157
225
  catch (err) {
158
- console.warn(`[pithy] Failed to evaluate: ${expr}`, err);
159
- return undefined;
226
+ if (import.meta.env?.DEV && err !== UNCOMPILED) {
227
+ console.warn(`[pithy] Failed to evaluate: ${expr}`, err);
228
+ }
229
+ removeBound(el, attr, writeStyle);
160
230
  }
231
+ if (attr === 'multiple' && el.localName === 'select') {
232
+ syncSelect(el);
233
+ }
234
+ }
235
+ function removeBound(el, attr, writeStyle) {
236
+ try {
237
+ if (writeStyle) {
238
+ writeStyle('');
239
+ }
240
+ else {
241
+ const control = el;
242
+ const kept = control.value;
243
+ el.removeAttribute(attr);
244
+ if (attr === 'value' &&
245
+ FORM_CONTROLS.has(el.localName) &&
246
+ control.value !== kept) {
247
+ control.value = kept;
248
+ }
249
+ }
250
+ }
251
+ catch {
252
+ /* ignore */
253
+ }
254
+ }
255
+ function evaluateExpression(expr, context) {
256
+ // eslint-disable-next-line no-new-func -- args-style template expression evaluation is a core framework feature
257
+ const compiled = new Function(...Object.keys(context), `return (${expr})`);
258
+ return compiled(...Object.values(context));
161
259
  }
162
260
  //# sourceMappingURL=bindBoundAttributes.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"bindBoundAttributes.js","sourceRoot":"","sources":["../../../src/compile/binds/bindBoundAttributes.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAA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AC,CAAC;IAC1D,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,SAAS,CAAC,GAAG,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;QAAE,OAAO,KAAK,CAAC;IACjE,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,CAAC;QACzB,OAAO,CAAC,IAAI,CAAC,qBAAqB,IAAI,gBAAgB,IAAI,IAAI,CAAC,CAAC;IAClE,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED,SAAS,kBAAkB,CACzB,IAAY,EACZ,OAAgC;IAEhC,IAAI,CAAC;QACH,gHAAgH;QAChH,MAAM,QAAQ,GAAG,IAAI,QAAQ,CAC3B,GAAG,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,EACvB,WAAW,IAAI,GAAG,CACgB,CAAC;QACrC,OAAO,QAAQ,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC;IAC7C,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,OAAO,CAAC,IAAI,CAAC,+BAA+B,IAAI,EAAE,EAAE,GAAG,CAAC,CAAC;QACzD,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.runtime.attributes\",\n \"title\": \"Bound Attribute Binding System\",\n \"category\": \"runtime\"\n}\n*/\n\nimport { isDeclaredDirective } from './declaredDirective';\nimport { effect } from '@pithyjs/signals';\nimport { nodeExpando, type StyleOwners } from '../nodeExpando';\n\n/**\n * Binds [attr]=\"expression\" bindings like [class]=\"dynamicClass\"\n * using reactive effect evaluation.\n */\n/** @codexApi {\"parent\":\"pithy.runtime.attributes\",\"name\":\"bindBoundAttributes\",\"stability\":\"stable\",\"signature\":\"(root: Element | DocumentFragment, context: Record<string, unknown>, disposers: (() => void)[]) => void\"} */\nexport function bindBoundAttributes(\n root: Element | DocumentFragment,\n context: Record<string, unknown>,\n disposers: (() => void)[]\n): void {\n root.querySelectorAll('*').forEach(el => {\n // Use element's own __pithyCtx when available (projected slot content\n // carries the parent component's context via this property).\n const elCtx = nodeExpando(el).__pithyCtx || context;\n\n for (const attr of Array.from(el.attributes)) {\n if (!attr.name.startsWith('data-bind-') || !isDeclaredDirective(attr))\n continue;\n\n const attrName = attr.name.slice('data-bind-'.length);\n const expr = attr.value;\n\n // Remove data-bind-* attribute after capturing expression to prevent\n // double-processing when component subtrees are inserted into outer DOM\n el.removeAttribute(attr.name);\n\n const writeStyle = attrName === 'style' ? styleWriter(el) : null;\n const stop = effect(() => {\n const value = evaluateExpression(expr, elCtx);\n\n if (writeStyle && typeof value === 'boolean') {\n writeStyle('');\n } else if (typeof value === 'boolean') {\n if (value) {\n el.setAttribute(attrName, '');\n } else {\n el.removeAttribute(attrName);\n }\n } else {\n const text = String(value ?? '');\n if (writeStyle) {\n writeStyle(text);\n } else if (rejectsScriptSink(el, attrName, text)) {\n el.removeAttribute(attrName);\n } else {\n el.setAttribute(attrName, text);\n }\n }\n });\n\n disposers.push(stop);\n }\n });\n}\n\n/**\n * Every binding on one element's `style`. Strings compose in bind order, then\n * each `[style.x]` applies on top, so nothing depends on reading the CSSOM back:\n * a value there cannot show which binding wrote it.\n */\nfunction styleOwners(el: Element): StyleOwners {\n const node = nodeExpando(el);\n return (node.__styleOwners ??= { strings: [], props: new Map() });\n}\n\nfunction renderStyle(el: Element, owners: StyleOwners): void {\n const text = owners.strings.filter(Boolean).join('; ');\n if (text) el.setAttribute('style', text);\n else el.removeAttribute('style');\n const style = (el as Partial<ElementCSSInlineStyle>).style;\n for (const [prop, [value, priority]] of owners.props) {\n style?.setProperty(prop, value, priority);\n }\n}\n\n/** @codexApi {\"parent\":\"pithy.runtime.attributes\",\"name\":\"styleWriter\",\"stability\":\"internal\",\"signature\":\"(el: Element) => (text: string) => void\"} */\nexport function styleWriter(el: Element): (text: string) => void {\n const owners = styleOwners(el);\n if (!owners.strings.length) {\n const style = (el as Partial<ElementCSSInlineStyle>).style;\n for (const prop of owners.props.keys()) style?.removeProperty(prop);\n owners.strings.push(el.getAttribute('style') ?? '');\n }\n const slot = owners.strings.push('') - 1;\n return text => {\n owners.strings[slot] = text;\n renderStyle(el, owners);\n };\n}\n\n/** @codexApi {\"parent\":\"pithy.runtime.attributes\",\"name\":\"setStyleProp\",\"stability\":\"internal\",\"signature\":\"(el: Element, prop: string, value: string | null, priority?: string) => void\"} */\nexport function setStyleProp(\n el: Element,\n prop: string,\n value: string | null,\n priority = ''\n): void {\n const owners = styleOwners(el);\n const style = (el as Partial<ElementCSSInlineStyle>).style;\n owners.props.delete(prop);\n if (value !== null) owners.props.set(prop, [value, priority]);\n if (owners.strings.length) {\n renderStyle(el, owners);\n } else if (value === null) {\n style?.removeProperty(prop);\n } else {\n style?.setProperty(prop, value, priority);\n }\n}\n\nconst LINK_SCHEME_RE = /^(?:javascript|vbscript|data):/i;\n// A data: frame, form target or animated href loads in an opaque origin, so only a link refuses data:.\nconst SCRIPT_SCHEME_RE = /^(?:javascript|vbscript):/i;\nconst LINK_ATTRS = ['href', 'xlink:href'];\nconst LINK_SINK = { attrs: LINK_ATTRS, scheme: LINK_SCHEME_RE };\nconst FORM_ACTION_SINK = { attrs: ['formaction'], scheme: SCRIPT_SCHEME_RE };\nconst URL_SINKS = new Map<string, { attrs: readonly string[]; scheme: RegExp }>(\n [\n ['a', LINK_SINK],\n ['area', LINK_SINK],\n ['set', { attrs: ['to'], scheme: SCRIPT_SCHEME_RE }],\n ['animate', { attrs: ['to', 'from', 'values'], scheme: SCRIPT_SCHEME_RE }],\n ['iframe', { attrs: ['src'], scheme: SCRIPT_SCHEME_RE }],\n ['frame', { attrs: ['src'], scheme: SCRIPT_SCHEME_RE }],\n ['form', { attrs: ['action'], scheme: SCRIPT_SCHEME_RE }],\n ['button', FORM_ACTION_SINK],\n ['input', FORM_ACTION_SINK],\n ]\n);\n\nfunction hasScheme(url: string, scheme: RegExp): boolean {\n const compact = [...url].filter(c => c > ' ' && c !== '\\x7f').join('');\n return scheme.test(compact);\n}\n\nexport function rejectsScriptSink(\n el: Element,\n attr: string,\n text: string\n): boolean {\n if (el.localName === 'iframe' && attr === 'srcdoc') {\n if (import.meta.env?.DEV && text !== '') {\n console.warn(\n '[PithyJS] A bound [srcdoc] is rejected: its HTML runs with the page origin. Bind [src] to a data:text/html URL, which loads in an opaque origin.'\n );\n }\n return true;\n }\n const sink = URL_SINKS.get(el.localName);\n if (!sink?.attrs.includes(attr)) return false;\n const urls = attr === 'values' ? text.split(';') : [text];\n if (!urls.some(url => hasScheme(url, sink.scheme))) return false;\n if (import.meta.env?.DEV) {\n console.warn(`[PithyJS] Unsafe [${attr}] rejected: \"${text}\".`);\n }\n return true;\n}\n\nfunction evaluateExpression(\n expr: string,\n context: Record<string, unknown>\n): unknown {\n try {\n // eslint-disable-next-line no-new-func -- args-style template expression evaluation is a core framework feature\n const compiled = new Function(\n ...Object.keys(context),\n `return (${expr})`\n ) as (...args: unknown[]) => unknown;\n return compiled(...Object.values(context));\n } catch (err) {\n console.warn(`[pithy] Failed to evaluate: ${expr}`, err);\n return undefined;\n }\n}\n"]}
1
+ {"version":3,"file":"bindBoundAttributes.js","sourceRoot":"","sources":["../../../src/compile/binds/bindBoundAttributes.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EAAE,WAAW,EAAoB,MAAM,gBAAgB,CAAC;AAE/D;;;GAGG;AACH,8NAA8N;AAC9N,MAAM,UAAU,mBAAmB,CACjC,IAAgC,EAChC,OAAgC,EAChC,SAAyB;IAEzB,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,EAAE,CAAC,EAAE;QACtC,sEAAsE;QACtE,6DAA6D;QAC7D,MAAM,KAAK,GACT,WAAW,CAAC,EAA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CAAC;AACH,CAAC;AAED,SAAS,WAAW,CAClB,EAAW,EACX,IAAY,EACZ,UAA2C;IAE3C,IAAI,CAAC;QACH,IAAI,UAAU,EAAE,CAAC;YACf,UAAU,CAAC,EAAE,CAAC,CAAC;QACjB,CAAC;aAAM,CAAC;YACN,MAAM,OAAO,GAAG,EAAsB,CAAC;YACvC,MAAM,IAAI,GAAG,OAAO,CAAC,KAAK,CAAC;YAC3B,EAAE,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC;YACzB,IACE,IAAI,KAAK,OAAO;gBAChB,aAAa,CAAC,GAAG,CAAC,EAAE,CAAC,SAAS,CAAC;gBAC/B,OAAO,CAAC,KAAK,KAAK,IAAI,EACtB,CAAC;gBACD,OAAO,CAAC,KAAK,GAAG,IAAI,CAAC;YACvB,CAAC;QACH,CAAC;IACH,CAAC;IAAC,MAAM,CAAC;QACP,YAAY;IACd,CAAC;AACH,CAAC;AAED,SAAS,kBAAkB,CACzB,IAAY,EACZ,OAAgC;IAEhC,gHAAgH;IAChH,MAAM,QAAQ,GAAG,IAAI,QAAQ,CAC3B,GAAG,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,EACvB,WAAW,IAAI,GAAG,CACgB,CAAC;IACrC,OAAO,QAAQ,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC;AAC7C,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.runtime.attributes\",\n \"title\": \"Bound Attribute Binding System\",\n \"category\": \"runtime\"\n}\n*/\n\nimport { isDeclaredDirective } from './declaredDirective';\nimport { effect } from '@pithyjs/signals';\nimport { nodeExpando, type StyleOwners } from '../nodeExpando';\n\n/**\n * Binds [attr]=\"expression\" bindings like [class]=\"dynamicClass\"\n * using reactive effect evaluation.\n */\n/** @codexApi {\"parent\":\"pithy.runtime.attributes\",\"name\":\"bindBoundAttributes\",\"stability\":\"stable\",\"signature\":\"(root: Element | DocumentFragment, context: Record<string, unknown>, disposers: (() => void)[]) => void\"} */\nexport function bindBoundAttributes(\n root: Element | DocumentFragment,\n context: Record<string, unknown>,\n disposers: (() => void)[]\n): void {\n root.querySelectorAll('*').forEach(el => {\n // Use element's own __pithyCtx when available (projected slot content\n // carries the parent component's context via this property).\n const elCtx =\n nodeExpando(el).__pithyForwardCtx ??\n nodeExpando(el).__pithyCtx ??\n context;\n\n for (const attr of Array.from(el.attributes)) {\n if (!attr.name.startsWith('data-bind-') || !isDeclaredDirective(attr))\n continue;\n\n const attrName = attr.name.slice('data-bind-'.length);\n const expr = attr.value;\n\n // Remove data-bind-* attribute after capturing expression to prevent\n // double-processing when component subtrees are inserted into outer DOM\n el.removeAttribute(attr.name);\n\n const writeStyle = attrName === 'style' ? styleWriter(el) : null;\n const stop = effect(() => {\n writeBound(el, attrName, expr, writeStyle, () =>\n evaluateExpression(expr, elCtx)\n );\n });\n\n disposers.push(stop);\n }\n });\n}\n\n/**\n * Every binding on one element's `style`. Strings compose in bind order, then\n * each `[style.x]` applies on top, so nothing depends on reading the CSSOM back:\n * a value there cannot show which binding wrote it.\n */\nfunction styleOwners(el: Element): StyleOwners {\n const node = nodeExpando(el);\n return (node.__styleOwners ??= { strings: [], props: new Map() });\n}\n\nfunction renderStyle(el: Element, owners: StyleOwners): void {\n const text = owners.strings.filter(Boolean).join('; ');\n if (text) el.setAttribute('style', text);\n else el.removeAttribute('style');\n const style = (el as Partial<ElementCSSInlineStyle>).style;\n for (const [prop, [value, priority]] of owners.props) {\n style?.setProperty(prop, value, priority);\n }\n}\n\n/** @codexApi {\"parent\":\"pithy.runtime.attributes\",\"name\":\"styleWriter\",\"stability\":\"internal\",\"signature\":\"(el: Element) => (text: string) => void\"} */\nexport function styleWriter(el: Element): (text: string) => void {\n const owners = styleOwners(el);\n if (!owners.strings.length) {\n const style = (el as Partial<ElementCSSInlineStyle>).style;\n for (const prop of owners.props.keys()) style?.removeProperty(prop);\n owners.strings.push(el.getAttribute('style') ?? '');\n }\n const slot = owners.strings.push('') - 1;\n return text => {\n owners.strings[slot] = text;\n renderStyle(el, owners);\n };\n}\n\n/** @codexApi {\"parent\":\"pithy.runtime.attributes\",\"name\":\"setStyleProp\",\"stability\":\"internal\",\"signature\":\"(el: Element, prop: string, value: string | null, priority?: string) => void\"} */\nexport function setStyleProp(\n el: Element,\n prop: string,\n value: string | null,\n priority = ''\n): void {\n const owners = styleOwners(el);\n const style = (el as Partial<ElementCSSInlineStyle>).style;\n owners.props.delete(prop);\n if (value !== null) owners.props.set(prop, [value, priority]);\n if (owners.strings.length) {\n renderStyle(el, owners);\n } else if (value === null) {\n style?.removeProperty(prop);\n } else {\n style?.setProperty(prop, value, priority);\n }\n}\n\nconst LINK_SCHEME_RE = /^(?:javascript|vbscript|data):/i;\n// A data: frame, form target or animated href loads in an opaque origin, so only a link refuses data:.\nconst SCRIPT_SCHEME_RE = /^(?:javascript|vbscript):/i;\nconst LINK_ATTRS = ['href', 'xlink:href'];\nconst LINK_SINK = { attrs: LINK_ATTRS, scheme: LINK_SCHEME_RE };\nconst FORM_ACTION_SINK = { attrs: ['formaction'], scheme: SCRIPT_SCHEME_RE };\nconst URL_SINKS = new Map<string, { attrs: readonly string[]; scheme: RegExp }>(\n [\n ['a', LINK_SINK],\n ['area', LINK_SINK],\n ['set', { attrs: ['to'], scheme: SCRIPT_SCHEME_RE }],\n ['animate', { attrs: ['to', 'from', 'values'], scheme: SCRIPT_SCHEME_RE }],\n ['iframe', { attrs: ['src'], scheme: SCRIPT_SCHEME_RE }],\n ['frame', { attrs: ['src'], scheme: SCRIPT_SCHEME_RE }],\n ['form', { attrs: ['action'], scheme: SCRIPT_SCHEME_RE }],\n ['button', FORM_ACTION_SINK],\n ['input', FORM_ACTION_SINK],\n ]\n);\n\nfunction hasScheme(url: string, scheme: RegExp): boolean {\n const compact = [...url].filter(c => c > ' ' && c !== '\\x7f').join('');\n return scheme.test(compact);\n}\n\nfunction rejectsScriptSink(el: Element, attr: string, text: string): boolean {\n if (el.localName === 'iframe' && attr === 'srcdoc') {\n if (import.meta.env?.DEV && text !== '') {\n console.warn(\n '[PithyJS] A bound [srcdoc] is rejected: its HTML runs with the page origin. Bind [src] to a data:text/html URL, which loads in an opaque origin.'\n );\n }\n return true;\n }\n const sink = URL_SINKS.get(el.localName);\n if (!sink?.attrs.includes(attr)) return false;\n const urls = attr === 'values' ? text.split(';') : [text];\n if (!urls.some(url => hasScheme(url, sink.scheme))) return false;\n if (import.meta.env?.DEV) {\n console.warn(`[PithyJS] Unsafe [${attr}] rejected: \"${text}\".`);\n }\n return true;\n}\n\nconst TEXT_BOOLEAN_ATTR = /^(?:aria-.+|contenteditable|draggable|spellcheck)$/i;\nconst FORM_CONTROLS = new Set(['input', 'select', 'textarea']);\n\nfunction syncSelect(select: HTMLSelectElement): void {\n const bound = nodeExpando(select).__selectValue;\n if (!bound) return;\n const picks = select.multiple ? bound.picks : null;\n let found = false;\n for (const option of select.querySelectorAll('option')) {\n const match: boolean = picks\n ? picks.has(option.value)\n : !found && option.value === bound.text;\n option.toggleAttribute('selected', match);\n if (select.multiple) option.selected = match;\n found ||= match;\n }\n if (!select.multiple) select.value = bound.text;\n}\n\nfunction syncOption(option: HTMLOptionElement): void {\n const select = option.closest('select');\n const bound = select && nodeExpando(select).__selectValue;\n if (!select || !bound) return;\n if (select.multiple && bound.picks) {\n const match = bound.picks.has(option.value);\n option.toggleAttribute('selected', match);\n option.selected = match;\n } else if (option.selected || option.value === bound.text) {\n syncSelect(select);\n }\n}\n\nfunction setControlValue(el: Element, text: string, value?: unknown): void {\n if (el.localName === 'option') {\n syncOption(el as HTMLOptionElement);\n return;\n }\n if (!FORM_CONTROLS.has(el.localName)) return;\n const control = el as HTMLInputElement;\n if (control.type === 'file') return;\n if (el.localName === 'select') {\n const picks = Array.isArray(value) ? new Set(value.map(String)) : null;\n nodeExpando(el).__selectValue = { text, picks };\n syncSelect(el as HTMLSelectElement);\n return;\n }\n if (el.localName === 'textarea' && el.textContent !== text) {\n el.textContent = text;\n }\n if (control.value !== text) control.value = text;\n}\n\nfunction writeValue(\n el: Element,\n attr: string,\n value: unknown,\n writeStyle: ((text: string) => void) | null\n): void {\n if (value == null) {\n if (writeStyle) writeStyle('');\n else el.removeAttribute(attr);\n if (attr === 'value') setControlValue(el, '');\n return;\n }\n if (typeof value === 'boolean' && !TEXT_BOOLEAN_ATTR.test(attr)) {\n if (writeStyle) writeStyle('');\n else if (value) el.setAttribute(attr, '');\n else el.removeAttribute(attr);\n return;\n }\n const text = String(value);\n if (writeStyle) {\n writeStyle(text);\n } else if (rejectsScriptSink(el, attr, text)) {\n el.removeAttribute(attr);\n } else {\n el.setAttribute(attr, text);\n if (attr === 'value') setControlValue(el, text, value);\n }\n}\n\n/** @codexApi {\"parent\":\"pithy.runtime.attributes\",\"name\":\"UNCOMPILED\",\"stability\":\"internal\",\"signature\":\"Error\"} */\nexport const UNCOMPILED = new Error('The expression does not compile');\n\n/** @codexApi {\"parent\":\"pithy.runtime.attributes\",\"name\":\"writeBound\",\"stability\":\"internal\",\"signature\":\"(el: Element, attr: string, expr: string, writeStyle: ((text: string) => void) | null, read: () => unknown) => void\"} */\nexport function writeBound(\n el: Element,\n attr: string,\n expr: string,\n writeStyle: ((text: string) => void) | null,\n read: () => unknown\n): void {\n try {\n writeValue(el, attr, read(), writeStyle);\n } catch (err) {\n if (import.meta.env?.DEV && err !== UNCOMPILED) {\n console.warn(`[pithy] Failed to evaluate: ${expr}`, err);\n }\n removeBound(el, attr, writeStyle);\n }\n if (attr === 'multiple' && el.localName === 'select') {\n syncSelect(el as HTMLSelectElement);\n }\n}\n\nfunction removeBound(\n el: Element,\n attr: string,\n writeStyle: ((text: string) => void) | null\n): void {\n try {\n if (writeStyle) {\n writeStyle('');\n } else {\n const control = el as HTMLInputElement;\n const kept = control.value;\n el.removeAttribute(attr);\n if (\n attr === 'value' &&\n FORM_CONTROLS.has(el.localName) &&\n control.value !== kept\n ) {\n control.value = kept;\n }\n }\n } catch {\n /* ignore */\n }\n}\n\nfunction evaluateExpression(\n expr: string,\n context: Record<string, unknown>\n): unknown {\n // eslint-disable-next-line no-new-func -- args-style template expression evaluation is a core framework feature\n const compiled = new Function(\n ...Object.keys(context),\n `return (${expr})`\n ) as (...args: unknown[]) => unknown;\n return compiled(...Object.values(context));\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"bindClassDirectives.d.ts","sourceRoot":"","sources":["../../../src/compile/binds/bindClassDirectives.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAUF;;;;;;;;;;GAUG;AACH,uNAAuN;AACvN,wBAAgB,mBAAmB,CACjC,IAAI,EAAE,OAAO,GAAG,gBAAgB,EAChC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC5B,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,GACxB,IAAI,CAiFN;AAED,4KAA4K;AAC5K,wBAAgB,eAAe,CAC7B,EAAE,EAAE,OAAO,EACX,MAAM,EAAE,OAAO,EACf,KAAK,EAAE,GAAG,CAAC,MAAM,CAAC,GACjB,IAAI,CA8BN"}
1
+ {"version":3,"file":"bindClassDirectives.d.ts","sourceRoot":"","sources":["../../../src/compile/binds/bindClassDirectives.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAUF;;;;;;;;;;GAUG;AACH,uNAAuN;AACvN,wBAAgB,mBAAmB,CACjC,IAAI,EAAE,OAAO,GAAG,gBAAgB,EAChC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC5B,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,GACxB,IAAI,CAkFN;AAED,4KAA4K;AAC5K,wBAAgB,eAAe,CAC7B,EAAE,EAAE,OAAO,EACX,MAAM,EAAE,OAAO,EACf,KAAK,EAAE,GAAG,CAAC,MAAM,CAAC,GACjB,IAAI,CA8BN"}
@@ -27,7 +27,7 @@ export function bindClassDirectives(root, ctx, disposers) {
27
27
  root.querySelectorAll('*').forEach(el => {
28
28
  // Use element's own __pithyCtx when available (projected slot content
29
29
  // carries the parent component's context via this property).
30
- const elCtx = nodeExpando(el).__pithyCtx || ctx;
30
+ const elCtx = nodeExpando(el).__pithyForwardCtx ?? nodeExpando(el).__pithyCtx ?? ctx;
31
31
  let declared;
32
32
  for (const attr of Array.from(el.attributes)) {
33
33
  if (!attr.name.startsWith(TOGGLE_PREFIX))
@@ -1 +1 @@
1
- {"version":3,"file":"bindClassDirectives.js","sourceRoot":"","sources":["../../../src/compile/binds/bindClassDirectives.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAAE,aAAa,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AACzE,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAE1E,MAAM,aAAa,GAAG,oBAAoB,CAAC;AAE3C;;;;;;;;;;GAUG;AACH,uNAAuN;AACvN,MAAM,UAAU,mBAAmB,CACjC,IAAgC,EAChC,GAA4B,EAC5B,SAAyB;IAEzB,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,EAAE,CAAC,EAAE;QACtC,sEAAsE;QACtE,6DAA6D;QAC7D,MAAM,KAAK,GAAG,WAAW,CAAC,EAAE,CAAC,CAAC,UAAU,IAAI,GAAG,CAAC;QAEhD,IAAI,QAA8B,CAAC;QACnC,KAAK,MAAM,IAAI,IAAI,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,EAAE,CAAC;YAC7C,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,aAAa,CAAC;gBAAE,SAAS;YACnD,MAAM,OAAO,GAAG,WAAW,CAAC,EAAE,CAAC,CAAC;YAChC,QAAQ,KAAR,QAAQ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,EAAE,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;AACtE,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.runtime.classes\",\n \"title\": \"Class Directive Binding System\",\n \"category\": \"runtime\"\n}\n*/\n\nimport { declaredValue, isDeclaredDirective } from './declaredDirective';\nimport { effect } from '@pithyjs/signals';\nimport { compileExpression } from '../compileExpression';\nimport { nodeExpando } from '../nodeExpando';\nimport { bindStyleProperties, declaredName } from './bindStyleDirectives';\n\nconst TOGGLE_PREFIX = 'data-class-toggle-';\n\n/**\n * Binds class directives like:\n * • [class.active]=\"isActive\"\n * • [classes]=\"{ active: isActive() }\"\n * • [classes]=\"['a', 'b']\"\n * • [classes]=\"'a b'\"\n *\n * @param root - The root node to search for class bindings\n * @param ctx - Context object containing reactive variables and functions\n * @param disposers - Cleanup functions to remove subscriptions\n */\n/** @codexApi {\"parent\":\"pithy.runtime.classes\",\"name\":\"bindClassDirectives\",\"stability\":\"stable\",\"signature\":\"(root: Element | DocumentFragment, ctx: Record<string, unknown>, disposers: (() => void)[]) => void\"} */\nexport function bindClassDirectives(\n root: Element | DocumentFragment,\n ctx: Record<string, unknown>,\n disposers: (() => void)[]\n): void {\n root.querySelectorAll('*').forEach(el => {\n // Use element's own __pithyCtx when available (projected slot content\n // carries the parent component's context via this property).\n const elCtx = nodeExpando(el).__pithyCtx || ctx;\n\n let declared: string[] | undefined;\n for (const attr of Array.from(el.attributes)) {\n if (!attr.name.startsWith(TOGGLE_PREFIX)) continue;\n const expando = nodeExpando(el);\n declared ??= [\n ...(expando.__classToggles ?? []),\n ...Object.keys(expando.__pithyNode?.directives?.classMap ?? {}),\n ];\n const className = declaredName(\n attr.name.slice(TOGGLE_PREFIX.length),\n declared\n );\n if (!className || !isDeclaredDirective(attr)) continue;\n const expression = attr.value;\n\n // Remove directive attribute after capturing to prevent double-processing\n // when component subtrees are inserted into an outer DOM that re-runs binders\n el.removeAttribute(attr.name);\n\n let evaluate: () => unknown;\n\n try {\n evaluate = compileExpression(expression, elCtx);\n } catch (err) {\n console.warn(\n `[PithyJS] ⚠️ Failed to compile [class.${className}]=\"${expression}\"`,\n err\n );\n return;\n }\n\n const stop = effect(() => {\n try {\n const result = evaluate();\n el.classList.toggle(className, !!result);\n } catch {\n /* ignore */\n }\n });\n\n disposers.push(stop);\n }\n\n const classGroupExpr = declaredValue(el, 'data-classes');\n if (classGroupExpr) {\n // Remove directive attribute after capturing to prevent double-processing\n el.removeAttribute('data-classes');\n\n let evaluate: () => unknown;\n\n try {\n evaluate = compileExpression(classGroupExpr, elCtx);\n } catch (err) {\n console.warn(\n `[PithyJS] ⚠️ Failed to compile [classes]=\"${classGroupExpr}\"`,\n err\n );\n return;\n }\n\n const owned = new Set<string>();\n const stop = effect(() => {\n try {\n applyClassGroup(el, evaluate(), owned);\n } catch (err) {\n console.warn('[PithyJS] ⚠️ Failed to evaluate [classes]:', err);\n }\n });\n\n disposers.push(stop);\n }\n\n // After the classes, so the attributes serialise in the build's order.\n bindStyleProperties(el, elCtx, disposers);\n });\n}\n\n/** @codexApi {\"parent\":\"pithy.runtime.classes\",\"name\":\"applyClassGroup\",\"stability\":\"internal\",\"signature\":\"(el: Element, result: unknown, owned: Set<string>) => void\"} */\nexport function applyClassGroup(\n el: Element,\n result: unknown,\n owned: Set<string>\n): void {\n const named = new Map<string, boolean>();\n const name = (classes: string, on: boolean) => {\n for (const c of classes.split(/[\\t\\n\\f\\r ]+/)) if (c) named.set(c, on);\n };\n if (typeof result === 'string') {\n name(result, true);\n } else if (Array.isArray(result)) {\n for (const cls of result) if (typeof cls === 'string') name(cls, true);\n } else if (result && typeof result === 'object') {\n for (const [cls, on] of Object.entries(result)) name(cls, !!on);\n } else if (import.meta.env?.DEV && result) {\n console.warn(\n `[PithyJS] ⚠️ [classes] expects a string, an array or an object, got ${typeof result}; the classes it added are removed.`\n );\n }\n\n // `owned` is this binding's own record, not the element's: a component's\n // root `[classes]` and one forwarded from its tag share the element, and\n // each may only remove the classes it added.\n const previous = new Set(owned);\n owned.clear();\n for (const [c, on] of named) {\n if (!on) el.classList.remove(c);\n else if (previous.has(c) || !el.classList.contains(c)) {\n el.classList.add(c);\n owned.add(c);\n }\n }\n for (const c of previous) if (!named.has(c)) el.classList.remove(c);\n}\n"]}
1
+ {"version":3,"file":"bindClassDirectives.js","sourceRoot":"","sources":["../../../src/compile/binds/bindClassDirectives.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAAE,aAAa,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AACzE,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAE1E,MAAM,aAAa,GAAG,oBAAoB,CAAC;AAE3C;;;;;;;;;;GAUG;AACH,uNAAuN;AACvN,MAAM,UAAU,mBAAmB,CACjC,IAAgC,EAChC,GAA4B,EAC5B,SAAyB;IAEzB,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,EAAE,CAAC,EAAE;QACtC,sEAAsE;QACtE,6DAA6D;QAC7D,MAAM,KAAK,GACT,WAAW,CAAC,EAAE,CAAC,CAAC,iBAAiB,IAAI,WAAW,CAAC,EAAE,CAAC,CAAC,UAAU,IAAI,GAAG,CAAC;QAEzE,IAAI,QAA8B,CAAC;QACnC,KAAK,MAAM,IAAI,IAAI,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,EAAE,CAAC;YAC7C,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,aAAa,CAAC;gBAAE,SAAS;YACnD,MAAM,OAAO,GAAG,WAAW,CAAC,EAAE,CAAC,CAAC;YAChC,QAAQ,KAAR,QAAQ,GAA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,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;AACtE,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.runtime.classes\",\n \"title\": \"Class Directive Binding System\",\n \"category\": \"runtime\"\n}\n*/\n\nimport { declaredValue, isDeclaredDirective } from './declaredDirective';\nimport { effect } from '@pithyjs/signals';\nimport { compileExpression } from '../compileExpression';\nimport { nodeExpando } from '../nodeExpando';\nimport { bindStyleProperties, declaredName } from './bindStyleDirectives';\n\nconst TOGGLE_PREFIX = 'data-class-toggle-';\n\n/**\n * Binds class directives like:\n * • [class.active]=\"isActive\"\n * • [classes]=\"{ active: isActive() }\"\n * • [classes]=\"['a', 'b']\"\n * • [classes]=\"'a b'\"\n *\n * @param root - The root node to search for class bindings\n * @param ctx - Context object containing reactive variables and functions\n * @param disposers - Cleanup functions to remove subscriptions\n */\n/** @codexApi {\"parent\":\"pithy.runtime.classes\",\"name\":\"bindClassDirectives\",\"stability\":\"stable\",\"signature\":\"(root: Element | DocumentFragment, ctx: Record<string, unknown>, disposers: (() => void)[]) => void\"} */\nexport function bindClassDirectives(\n root: Element | DocumentFragment,\n ctx: Record<string, unknown>,\n disposers: (() => void)[]\n): void {\n root.querySelectorAll('*').forEach(el => {\n // Use element's own __pithyCtx when available (projected slot content\n // carries the parent component's context via this property).\n const elCtx =\n nodeExpando(el).__pithyForwardCtx ?? nodeExpando(el).__pithyCtx ?? ctx;\n\n let declared: string[] | undefined;\n for (const attr of Array.from(el.attributes)) {\n if (!attr.name.startsWith(TOGGLE_PREFIX)) continue;\n const expando = nodeExpando(el);\n declared ??= [\n ...(expando.__classToggles ?? []),\n ...Object.keys(expando.__pithyNode?.directives?.classMap ?? {}),\n ];\n const className = declaredName(\n attr.name.slice(TOGGLE_PREFIX.length),\n declared\n );\n if (!className || !isDeclaredDirective(attr)) continue;\n const expression = attr.value;\n\n // Remove directive attribute after capturing to prevent double-processing\n // when component subtrees are inserted into an outer DOM that re-runs binders\n el.removeAttribute(attr.name);\n\n let evaluate: () => unknown;\n\n try {\n evaluate = compileExpression(expression, elCtx);\n } catch (err) {\n console.warn(\n `[PithyJS] ⚠️ Failed to compile [class.${className}]=\"${expression}\"`,\n err\n );\n return;\n }\n\n const stop = effect(() => {\n try {\n const result = evaluate();\n el.classList.toggle(className, !!result);\n } catch {\n /* ignore */\n }\n });\n\n disposers.push(stop);\n }\n\n const classGroupExpr = declaredValue(el, 'data-classes');\n if (classGroupExpr) {\n // Remove directive attribute after capturing to prevent double-processing\n el.removeAttribute('data-classes');\n\n let evaluate: () => unknown;\n\n try {\n evaluate = compileExpression(classGroupExpr, elCtx);\n } catch (err) {\n console.warn(\n `[PithyJS] ⚠️ Failed to compile [classes]=\"${classGroupExpr}\"`,\n err\n );\n return;\n }\n\n const owned = new Set<string>();\n const stop = effect(() => {\n try {\n applyClassGroup(el, evaluate(), owned);\n } catch (err) {\n console.warn('[PithyJS] ⚠️ Failed to evaluate [classes]:', err);\n }\n });\n\n disposers.push(stop);\n }\n\n // After the classes, so the attributes serialise in the build's order.\n bindStyleProperties(el, elCtx, disposers);\n });\n}\n\n/** @codexApi {\"parent\":\"pithy.runtime.classes\",\"name\":\"applyClassGroup\",\"stability\":\"internal\",\"signature\":\"(el: Element, result: unknown, owned: Set<string>) => void\"} */\nexport function applyClassGroup(\n el: Element,\n result: unknown,\n owned: Set<string>\n): void {\n const named = new Map<string, boolean>();\n const name = (classes: string, on: boolean) => {\n for (const c of classes.split(/[\\t\\n\\f\\r ]+/)) if (c) named.set(c, on);\n };\n if (typeof result === 'string') {\n name(result, true);\n } else if (Array.isArray(result)) {\n for (const cls of result) if (typeof cls === 'string') name(cls, true);\n } else if (result && typeof result === 'object') {\n for (const [cls, on] of Object.entries(result)) name(cls, !!on);\n } else if (import.meta.env?.DEV && result) {\n console.warn(\n `[PithyJS] ⚠️ [classes] expects a string, an array or an object, got ${typeof result}; the classes it added are removed.`\n );\n }\n\n // `owned` is this binding's own record, not the element's: a component's\n // root `[classes]` and one forwarded from its tag share the element, and\n // each may only remove the classes it added.\n const previous = new Set(owned);\n owned.clear();\n for (const [c, on] of named) {\n if (!on) el.classList.remove(c);\n else if (previous.has(c) || !el.classList.contains(c)) {\n el.classList.add(c);\n owned.add(c);\n }\n }\n for (const c of previous) if (!named.has(c)) el.classList.remove(c);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"bindComponentsTags.d.ts","sourceRoot":"","sources":["../../../src/compile/binds/bindComponentsTags.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAgDF,qGAAqG;AACrG,wBAAgB,2BAA2B,IAAI,IAAI,CAElD;AAmKD;;;;;;GAMG;AACH,4NAA4N;AAC5N,wBAAgB,iBAAiB,CAC/B,IAAI,EAAE,OAAO,GAAG,gBAAgB,EAChC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAChC,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,GACxB,IAAI,CA8ZN"}
1
+ {"version":3,"file":"bindComponentsTags.d.ts","sourceRoot":"","sources":["../../../src/compile/binds/bindComponentsTags.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAgDF,qGAAqG;AACrG,wBAAgB,2BAA2B,IAAI,IAAI,CAElD;AAmKD;;;;;;GAMG;AACH,4NAA4N;AAC5N,wBAAgB,iBAAiB,CAC/B,IAAI,EAAE,OAAO,GAAG,gBAAgB,EAChC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAChC,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,GACxB,IAAI,CAmaN"}
@@ -14,7 +14,7 @@ import { componentChildDirectiveMessage, componentChildDirectives, nativeTags, }
14
14
  import { collectForwardedAttrs, applyForwardedAttrs } from './forwardedAttrs.js';
15
15
  import { createRoot, untrack } from '@pithyjs/signals';
16
16
  import { watchStaleRowProp } from './staleRowProps.js';
17
- import { nodeExpando } from '../nodeExpando.js';
17
+ import { markForwardTarget, nodeExpando } from '../nodeExpando.js';
18
18
  import { componentDisposer } from '../disposeOrder.js';
19
19
  import { pithyGlobals } from '../../types/globals.js';
20
20
  import { isSSRMode } from '../ssrMode.js';
@@ -489,6 +489,7 @@ export function bindComponentTags(root, rootCtx, disposers) {
489
489
  // Forward captured attributes so subsequent binders can attach the bindings
490
490
  if (forwardedAttrs.length > 0 && forwardTarget) {
491
491
  applyForwardedAttrs(forwardTarget, forwardedAttrs, tag);
492
+ markForwardTarget(forwardTarget, localCtx, new Set(forwardedAttrs.map(([name]) => name)));
492
493
  const styleProps = Object.keys(pithyNode?.directives?.styleMap ?? {});
493
494
  if (styleProps.length)
494
495
  nodeExpando(forwardTarget).__styleProps = styleProps;
@@ -1 +1 @@
1
- {"version":3,"file":"bindComponentsTags.js","sourceRoot":"","sources":["../../../src/compile/binds/bindComponentsTags.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EACL,kBAAkB,EAClB,eAAe,EACf,aAAa,EACb,eAAe,EACf,iBAAiB,EACjB,gBAAgB,GACjB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC1E,OAAO,EACL,8BAA8B,EAC9B,wBAAwB,EACxB,UAAU,GAEX,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAC9E,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,iBAAiB,EAAE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;YACvD,MAAM,YAAY,GAAG,MAAM,CAAC,IAAI,CAAC,SAAS,EAAE,UAAU,EAAE,QAAQ,IAAI,EAAE,CAAC,CAAC;YACxE,IAAI,YAAY,CAAC,MAAM;gBACrB,WAAW,CAAC,aAAa,CAAC,CAAC,cAAc,GAAG,YAAY,CAAC;YAC3D,wEAAwE;YACxE,qEAAqE;YACrE,IAAI,MAAM,IAAI,CAAC,aAAa,CAAC,UAAU,EAAE,CAAC;gBACxC,MAAM,QAAQ,GAAG,QAAQ,CAAC,sBAAsB,EAAE,CAAC;gBACnD,QAAQ,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;gBAC/B,mBAAmB,CAAC,QAAQ,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAC;YACrD,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.runtime.components\",\n \"title\": \"Component Tag Binding System\",\n \"category\": \"runtime\"\n}\n*/\n\nimport { compileExpression } from '../compileExpression';\nimport { isTemplateAttr } from './declaredDirective';\nimport {\n boundaryForElement,\n currentBoundary,\n replaceHidden,\n runWithBoundary,\n slotContentHidden,\n withSlotBoundary,\n} from './bindErrorBoundary';\nimport { bindAfterComponents } from './bindAfterComponents';\nimport { collectSlotMap, inProjectedContent } from '../contentProjection';\nimport {\n componentChildDirectiveMessage,\n componentChildDirectives,\n nativeTags,\n type PithyNode,\n} from '@pithyjs/compiler';\nimport { collectForwardedAttrs, applyForwardedAttrs } from './forwardedAttrs';\nimport { createRoot, untrack } from '@pithyjs/signals';\nimport { watchStaleRowProp } from './staleRowProps';\nimport { nodeExpando } from '../nodeExpando';\nimport { componentDisposer } from '../disposeOrder';\nimport { pithyGlobals } from '../../types/globals';\nimport { isSSRMode } from '../ssrMode';\nimport { clearSSRRenderCrash, reportComponentFailure } from '../ssrCrashes';\nimport { isRenderableComponentEl } from '../componentResult';\nimport { parsePropNames, type PropNames } from './propNames';\n\ninterface ComponentResult {\n /** Any DOM node — see the `Component` type for why this is not narrower. */\n el: Node;\n destroy?: () => void;\n}\ntype ComponentFn = (props: Record<string, unknown>) => ComponentResult;\n\n/**\n * Find the closest element-scoped context we attach in createLoopItem().\n * This is what exposes item(), gIdx(), count(), etc.\n */\n// Warn once per component/tag pair — the same idiom re-renders constantly\n// (e.g. a panel importing Button while using a native <button>), and\n// repeating the warning drowns out real ones.\nconst warnedComponentTags = new Set<string>();\nconst warnedChildDirectives = new WeakSet<PithyNode>();\n\n/** Test-only: forget which tags were warned about, so each render warns as a fresh process would. */\nexport function __resetComponentTagWarnings(): void {\n warnedComponentTags.clear();\n}\n\nfunction nearestCtx(\n el: Element,\n rootCtx: Record<string, unknown>\n): Record<string, unknown> {\n let n: Element | null = el;\n while (n) {\n const local = nodeExpando(n).__pithyCtx;\n if (local) return local;\n n = n.parentElement;\n }\n return rootCtx;\n}\n\n/**\n * Detect whether a node is inside a subtree that represents a NOT-YET-EXPANDED nested loop.\n * Those hosts are tagged in createLoopManager.createLoopItem() via `__pithySkipText`,\n * and real templates may also still carry @for / data-for before expansion.\n * We must *defer* binding for anything under such a host, otherwise expressions like item()\n * will throw ReferenceError (because inner loop ctx isn’t created yet).\n */\nfunction isInsidePendingLoopZone(node: Element): boolean {\n let p: Element | null = node;\n while (p) {\n if (nodeExpando(p).__pithySkipText) return true;\n if (\n p.hasAttribute &&\n (p.hasAttribute('@for') || p.hasAttribute('data-for'))\n ) {\n return true;\n }\n p = p.parentElement;\n }\n return false;\n}\n\n/** Evaluate `expr` in `ctx`. Try engine compiler first, then args-style fallback. */\nfunction evalInCtx(expr: string, ctx: Record<string, unknown>): unknown {\n // 1) Preferred: compileExpression uses `with(ctx) { return (...) }`\n try {\n const f = compileExpression(expr, ctx);\n try {\n return f();\n } catch {\n /* fall through to fallback */\n }\n } catch {\n /* fall through to fallback */\n }\n\n // 2) Fallback: args-style evaluator (robust even if compileExpression throws)\n const keys = Object.keys(ctx);\n const vals = keys.map(k => ctx[k]);\n // eslint-disable-next-line no-new-func -- args-style template expression evaluation is a core framework feature\n const fn = new Function(...keys, `return (${expr});`) as (\n ...args: unknown[]\n ) => unknown;\n return fn(...vals);\n}\n\nconst propNameCache = new WeakMap<ComponentFn, PropNames>();\n\nfunction readPropNames(componentFn: ComponentFn): PropNames {\n let cached = propNameCache.get(componentFn);\n if (!cached) {\n try {\n cached = parsePropNames(componentFn.toString());\n } catch {\n cached = { names: [], fromParam: false, exhaustive: false };\n }\n propNameCache.set(componentFn, cached);\n }\n return cached;\n}\n\nfunction extractExpectedPropNames(componentFn: ComponentFn): string[] {\n return readPropNames(componentFn).names;\n}\n\nconst warnedBoundProps = new Set<string>();\nconst GLOBAL_ATTRS = new Set([\n 'id',\n 'class',\n 'style',\n 'title',\n 'role',\n 'tabindex',\n 'hidden',\n]);\n\nfunction warnBoundProps(\n componentFn: ComponentFn,\n el: Element,\n componentName: string\n): void {\n const expected = extractExpectedPropNames(componentFn);\n for (const attr of Array.from(el.attributes)) {\n if (!attr.name.startsWith('data-bind-')) continue;\n const bound = attr.name.slice('data-bind-'.length);\n if (bound === 'slot' && !warnedBoundProps.has(`${componentName} slot`)) {\n warnedBoundProps.add(`${componentName} slot`);\n console.warn(\n `[PithyJS] <${componentName}> [slot] cannot choose a slot: the key is read as a literal, so this lands in the default slot. Write slot=\"name\".`\n );\n }\n if (GLOBAL_ATTRS.has(bound)) continue;\n const prop = expected.find(p => p.toLowerCase() === bound);\n const key = `${componentName} ${bound}`;\n if (!prop || warnedBoundProps.has(key)) continue;\n warnedBoundProps.add(key);\n console.warn(\n `[PithyJS] <${componentName}> [${bound}] sets an attribute on the rendered root, not the \\`${prop}\\` prop. Write ${prop}=\"…\" without brackets to set the prop; for a live value pass a signal or () => … if the prop accepts one.`\n );\n }\n}\n\n/** Dev warnings for unexpected props (only if destructuring is present). */\nfunction validateComponentProps(\n componentFn: ComponentFn,\n props: Record<string, unknown>,\n componentName: string\n): void {\n const { names: allNames, exhaustive } = readPropNames(componentFn);\n if (!exhaustive || allNames.length === 0) return;\n\n const passed = Object.keys(props);\n const expectedSet = new Set(allNames);\n\n const unexpected = passed.filter(p => !expectedSet.has(p));\n if (unexpected.length) {\n console.warn(\n `[PithyJS] 🔍 Component <${componentName}> received unexpected props: ${unexpected.join(\n ', '\n )}\\nExpected props: ${allNames.join(', ')}\\nPassed props: ${passed.join(', ')}`\n );\n }\n\n // NOTE: We intentionally do NOT warn about \"missing\" props here.\n // In template-driven usage, props are assembled at runtime by\n // bindComponentTags(), so TypeScript cannot catch missing required\n // props in this path. Components should self-validate critical\n // props where appropriate (e.g. Toggle warns on empty label).\n}\n\n/** DOM a component already rendered: its native tags may share a component's name. */\nfunction inComponentDom(el: Element): boolean {\n for (let n: Element | null = el; n; n = n.parentElement)\n if (nodeExpando(n).__pithyComponentDom) return true;\n return false;\n}\n\n/** Map lowercased DOM attr name to expected prop name (case-insensitive). */\nfunction normalizePropName(\n authoredName: string,\n expectedProps: string[]\n): string {\n if (expectedProps.includes(authoredName)) return authoredName;\n const lower = authoredName.toLowerCase();\n const matches = expectedProps.filter(p => p.toLowerCase() === lower);\n return matches.length === 1 ? matches[0] : authoredName;\n}\n\n/**\n * Replace custom component tags (<Counter/>, <NestedComponent/>) with rendered output.\n * - Skips anything under a pending nested loop host (bind after loop expansion)\n * - Evaluates prop expressions in nearest loop ctx\n * - Case-insensitive prop name normalization\n * - No raw-string fallback (prevents things like calling count() on a string)\n */\n/** @codexApi {\"parent\":\"pithy.runtime.components\",\"name\":\"bindComponentTags\",\"stability\":\"stable\",\"signature\":\"(root: Element | DocumentFragment, rootCtx: Record<string, unknown>, disposers: (() => void)[]) => void\"} */\nexport function bindComponentTags(\n root: Element | DocumentFragment,\n rootCtx: Record<string, unknown>,\n disposers: (() => void)[]\n): void {\n // case-insensitive tag lookup from context\n const tagMap = new Map<string, unknown>(\n Object.keys(rootCtx).map(k => [k.toLowerCase(), rootCtx[k]])\n );\n\n const scope =\n root instanceof Element ? (root as Element) : (root as DocumentFragment);\n const elements = Array.from(scope.querySelectorAll('*'));\n\n for (const el of elements) {\n // Skip elements removed from the tree by a parent component's render, or\n // hidden by an `@error-boundary` that has since activated.\n if (!scope.contains(el)) {\n // An element that has left the tree contributes nothing to the output, so\n // a crash recorded for it on an earlier DETACHED pass is stale. Leaving it\n // fails a route that rendered correctly: with two crashing components\n // under one boundary inside an `@if`, the detached pass records both, the\n // retry lets the boundary accept the first, and accepting synchronously\n // hides the second — which then never gets a retry to retract it.\n if (isSSRMode()) clearSSRRenderCrash(el);\n continue;\n }\n\n // Defer components inside not-yet-expanded loops\n if (isInsidePendingLoopZone(el)) continue;\n\n // A build's placeholder carries no AST: its children are DOM, which only\n // the AOT binder reads.\n const aotMount = nodeExpando(el).__pithyAotMount;\n if (aotMount) {\n // Marked as below, so the text pass skips what the component rendered.\n for (const node of aotMount(disposers))\n nodeExpando(node).__pithyComponentDom = true;\n continue;\n }\n\n const tag = el.tagName.toLowerCase();\n\n // Check if the parser marked this element as a component\n // This is the authoritative source - it checks originalTagName starts with uppercase\n // AND the tag name exists in importedIdentifiers\n const pithyNode = nodeExpando(el).__pithyNode;\n if (pithyNode) {\n // Parser processed this element - use its isComponent flag\n if (!pithyNode.isComponent) {\n // DEV: Warn if there's a component that matches case-insensitively\n // This helps developers catch typos like <button> when they meant <Button>\n // Skip warning if we're inside a component's render (the component might\n // legitimately use native elements like <button> in its implementation)\n const isInsideComponentRender =\n !!pithyGlobals().__pithyRenderingComponent;\n if (\n import.meta.env?.DEV &&\n !isInsideComponentRender &&\n !inComponentDom(el)\n ) {\n const matchingComponent = tagMap.get(tag);\n if (matchingComponent && typeof matchingComponent === 'function') {\n // Find the actual component name from context\n const componentName = Object.keys(rootCtx).find(\n k => k.toLowerCase() === tag && rootCtx[k] === matchingComponent\n );\n const warnKey = `${componentName}:${pithyNode.originalTagName}`;\n if (\n componentName &&\n componentName !== pithyNode.originalTagName &&\n !warnedComponentTags.has(warnKey)\n ) {\n warnedComponentTags.add(warnKey);\n console.warn(\n `[PithyJS] ⚠️ Component '${componentName}' is imported but used as '<${pithyNode.originalTagName}>'. ` +\n `Components must use PascalCase. Use '<${componentName}>' instead.`\n );\n }\n }\n }\n continue;\n }\n } else {\n // Fallback for elements not processed by our parser:\n // Skip native HTML elements to prevent <button> matching Button component\n if (nativeTags.has(tag)) continue;\n // Rendered already, e.g. a build's slot content.\n if (inComponentDom(el)) continue;\n }\n\n if (\n import.meta.env?.DEV &&\n pithyNode &&\n !warnedChildDirectives.has(pithyNode)\n ) {\n warnedChildDirectives.add(pithyNode);\n for (const name of componentChildDirectives(pithyNode))\n console.warn(\n `[pithy] ${componentChildDirectiveMessage(pithyNode.originalTagName ?? tag, name)}`\n );\n }\n\n let candidate = tagMap.get(tag);\n\n if (!candidate) continue;\n\n // Support default exports\n if (\n candidate &&\n typeof candidate === 'object' &&\n 'default' in candidate &&\n typeof candidate.default === 'function'\n ) {\n candidate = candidate.default;\n }\n if (typeof candidate !== 'function') continue;\n // Content a runtime-compiled receiver projected: bound detached, inside the\n // output of the component being rendered.\n const projectedHost =\n !el.closest('[data-error]') && inProjectedContent(el)\n ? pithyGlobals().__pithyComponentContext?.__slotHost\n : undefined;\n // Hidden like a sibling an activated boundary detached: never rendered.\n if (withSlotBoundary(undefined, projectedHost, () => slotContentHidden(el)))\n continue;\n\n const componentFn = candidate as ComponentFn;\n const localCtx = nearestCtx(el, rootCtx); // crucial for item(), gIdx(), etc.\n\n // Extract expected props for validation (DEV) and prop name normalization (always)\n // This ensures case-insensitive matching works even when originalAttrs is unavailable\n const { names, fromParam } = readPropNames(componentFn);\n const expectedProps = fromParam ? names : [];\n\n // Preserve originally-authored attribute names/casing from the parsed template\n // (pithyNode already extracted above for isComponent check)\n const originalAttrs: Record<string, string> | undefined =\n pithyNode?.originalAttrs;\n\n const props: Record<string, unknown> = {};\n\n const staleWatchers: (() => void)[] = [];\n\n // Evaluate attributes as expressions in localCtx\n for (const attr of Array.from(el.attributes)) {\n const name = attr.name;\n const raw = attr.value;\n\n // Skip internal/behavioral attributes\n if (name.startsWith('data-')) continue;\n if (name === 'class' || name === 'style' || name === 'slot') continue;\n if (!isTemplateAttr(attr)) continue;\n\n // Prefer originally-authored name (preserve casing), else DOM name\n const authored = originalAttrs?.[name] ?? name;\n const propName = normalizePropName(authored, expectedProps);\n\n try {\n const value = untrack(() => evalInCtx(raw, localCtx));\n props[propName] = value; // only set when evaluation succeeds\n if (import.meta.env?.DEV) {\n staleWatchers.push(() =>\n watchStaleRowProp(\n localCtx,\n pithyNode ?? el,\n pithyNode?.originalTagName || tag,\n propName,\n raw,\n value,\n () => evalInCtx(raw, localCtx),\n disposers\n )\n );\n }\n } catch (err) {\n if (import.meta.env?.DEV) {\n console.warn(\n `[PithyJS] ⚠️ Failed to evaluate prop \"${propName}\" = \"${raw}\"`,\n err\n );\n }\n // IMPORTANT: do NOT set a raw string fallback here.\n // Leaving it undefined lets the child use defaults and avoids count()-on-string.\n }\n }\n\n // Validate props for all components in DEV mode.\n // Native elements are already filtered out earlier (line 197 for fallback, line 171 for parser).\n if (import.meta.env?.DEV) {\n const displayTag = pithyNode?.originalTagName || tag;\n validateComponentProps(componentFn, props, displayTag);\n warnBoundProps(componentFn, el, displayTag);\n }\n\n // Collect content projection SlotMap from component children\n const pithyChildren: PithyNode[] = pithyNode?.children || [];\n const slotMap = collectSlotMap(pithyChildren, localCtx);\n\n // Create enhanced context with SlotMap for content projection\n const componentContext = {\n ...localCtx,\n __slotMap: slotMap,\n __childAstNodes: pithyChildren,\n __childFactory: undefined,\n __slotHost: el,\n };\n\n // Find nearest error boundary for this component\n const boundaryEl = el.closest('[data-error]') as Element | null;\n // Projected content is bound detached, during its receiver's render.\n const boundary =\n boundaryForElement(boundaryEl) ??\n (!boundaryEl && inProjectedContent(el) ? currentBoundary() : null);\n\n // Invoke component under boundary context; expect { el, destroy }\n let out: ComponentResult | undefined;\n let disposeSetup: (() => void) | undefined;\n try {\n out = runWithBoundary(boundary, () => {\n // Store the enhanced context globally for the component's html() calls to access.\n // This per-component context contains __slotMap for content projection.\n //\n // In SSR, there are TWO context sources that html() merges:\n // 1. AsyncLocalStorage context (__getComponentContext) - request-level isolation\n // 2. This global context (__pithyComponentContext) - per-component __slotMap\n //\n // Both are needed: AsyncLocalStorage provides request isolation, while this\n // global provides the __slotMap that changes for each component render.\n const g = pithyGlobals();\n const originalContext = g.__pithyComponentContext;\n const wasRendering = g.__pithyRenderingComponent;\n g.__pithyComponentContext = componentContext;\n // Mark that we're rendering a component to suppress casing warnings for\n // native elements used in component implementations (e.g., <button> in Button)\n g.__pithyRenderingComponent = true;\n\n try {\n const result = createRoot(disposeRoot => {\n disposeSetup = disposeRoot;\n return componentFn(props);\n });\n return result;\n } finally {\n // Restore original context\n g.__pithyComponentContext = originalContext;\n g.__pithyRenderingComponent = wasRendering;\n }\n });\n } catch (err) {\n // Route sync render errors to the nearest boundary with escalation\n if (boundary) {\n const error = err instanceof Error ? err : new Error(String(err));\n // A boundary being in scope does not mean it accepted the error: an\n // already-active boundary with no free ancestor drops it (React's\n // first-error-wins). A component inside that boundary's `@fallback` is\n // the everyday case, and the fallback is what the user actually sees.\n const accepted = reportComponentFailure(el, tag, error, boundary);\n if (import.meta.env?.DEV) {\n // Say which of the two actually happened. \"Captured\" on a rejected\n // error reports the opposite of the truth, and this branch exists\n // precisely because the two are not the same.\n console.log(\n accepted\n ? `[ErrorBoundary] Captured sync render error in <${tag}>:`\n : `[ErrorBoundary] Boundary already active — error from <${tag}> was NOT captured:`,\n error.message\n );\n }\n continue;\n }\n\n // No boundary in scope *yet*. Degrading is still the right call here in\n // both modes: throwing would pre-empt the retry pass that gives an\n // `@error-boundary` its only chance to claim a crash raised while the\n // subtree was detached.\n //\n // A static/server render additionally records the crash. Nobody reads a\n // console during `pithy-ssg`, so this used to leave the raw <${tag}> in\n // the emitted HTML while the route still counted as rendered and the CLI\n // exited 0 (BUG-018). Anything still recorded when the render finishes\n // makes the SSR renderer throw, and the per-route catch in `vite-ssg.ts`\n // fails that route.\n reportComponentFailure(\n el,\n tag,\n err instanceof Error ? err : new Error(String(err)),\n null\n );\n\n console.error(`❌ Component <${tag}> crashed during render:`, err);\n continue;\n }\n\n if (\n !out ||\n typeof out !== 'object' ||\n !('el' in out) ||\n !isRenderableComponentEl(out.el, el)\n ) {\n console.warn(\n `❌ Invalid render result from <${tag}>. Expected { el, destroy }`\n );\n // Not a throw, but the same outcome as one: the raw <${tag}> is left in\n // the document and the subtree never renders. Under SSR that is content\n // silently missing from the emitted HTML, so it is recorded exactly like\n // a crash (BUG-018). Recorded rather than merely left in place, because\n // this attempt may also be retracting an earlier attempt's record.\n // Same funnel as a throw: a boundary above this component gets the\n // chance to claim it and render its fallback, and only an unclaimed\n // failure is recorded. Bypassing this meant a component under\n // `@error-boundary` that returned garbage failed the route with the\n // boundary signal still null.\n reportComponentFailure(\n el,\n tag,\n new Error(\n `Invalid render result from <${tag}>; expected { el, destroy }`\n ),\n boundary\n );\n disposeSetup?.();\n continue;\n }\n\n const { el: renderedEl, destroy } = out;\n\n // Capture class and data-* attributes for forwarding to rendered root:\n // directive bindings (data-on-*, data-bind-*, data-class-toggle-*,\n // data-classes, data-style-*) plus any author-written data-* attribute.\n const forwardedClass = el.getAttribute('class');\n const forwardedAttrs = collectForwardedAttrs(el);\n\n const isFragment = renderedEl.nodeType === Node.DOCUMENT_FRAGMENT_NODE;\n let forwardTarget: HTMLElement | null = null;\n const hasForwardables = !!(forwardedClass || forwardedAttrs.length > 0);\n if (hasForwardables) {\n if (isFragment) {\n forwardTarget = (renderedEl as DocumentFragment)\n .firstElementChild as HTMLElement | null;\n if (import.meta.env?.DEV && !forwardTarget) {\n const displayTag = pithyNode?.originalTagName || tag;\n console.warn(\n `[PithyJS] <${displayTag}> has class or data-* attributes but returns a fragment with no element children — forwarding skipped.`\n );\n }\n } else if (renderedEl.nodeType === Node.ELEMENT_NODE) {\n forwardTarget = renderedEl as HTMLElement;\n }\n }\n\n const renderedNodes = isFragment\n ? Array.from(renderedEl.childNodes)\n : [renderedEl];\n for (const node of renderedNodes)\n nodeExpando(node).__pithyComponentDom = true;\n\n let replaced = true;\n let hidden = false;\n try {\n // A boundary that caught a crash in this render may have hidden `el`.\n hidden = replaceHidden(el, renderedNodes);\n if (!hidden) el.replaceWith(...renderedNodes);\n } catch (err) {\n // A failed replacement leaves the raw <${tag}> exactly where a crash\n // would have, so it is the same content loss and is recorded the same way.\n replaced = false;\n reportComponentFailure(\n el,\n tag,\n err instanceof Error ? err : new Error(String(err)),\n boundary\n );\n console.error(`❌ Failed to replace <${tag}> with rendered DOM:`, err);\n }\n\n // Retracted only here, and in the boundary catch above — never eagerly at\n // the top of an attempt, where any early `continue` added later would\n // silently drop a real record. This is the point at which the component is\n // known to have produced a usable node AND to have reached the document, so\n // an earlier detached attempt's crash is genuinely no longer the outcome.\n if (isSSRMode() && replaced) clearSSRRenderCrash(el);\n\n for (const watch of staleWatchers) watch();\n\n // Forward class from component tag onto the rendered root element\n if (forwardedClass && forwardTarget) {\n for (const cls of forwardedClass.split(/\\s+/)) {\n if (cls) forwardTarget.classList.add(cls);\n }\n }\n\n // Before any binding pass below, which can throw.\n const teardown = componentDisposer(\n destroy,\n disposeSetup,\n renderedNodes[0] ?? (replaced ? null : el)\n );\n if (teardown) disposers.push(teardown);\n\n // Forward captured attributes so subsequent binders can attach the bindings\n if (forwardedAttrs.length > 0 && forwardTarget) {\n applyForwardedAttrs(forwardTarget, forwardedAttrs, tag);\n const styleProps = Object.keys(pithyNode?.directives?.styleMap ?? {});\n if (styleProps.length)\n nodeExpando(forwardTarget).__styleProps = styleProps;\n const classToggles = Object.keys(pithyNode?.directives?.classMap ?? {});\n if (classToggles.length)\n nodeExpando(forwardTarget).__classToggles = classToggles;\n // Hidden, it is out of reach of this fragment's later passes. An active\n // nested boundary `hideContent` kept in place is still within reach.\n if (hidden && !forwardTarget.parentNode) {\n const detached = document.createDocumentFragment();\n detached.append(forwardTarget);\n bindAfterComponents(detached, localCtx, disposers);\n }\n }\n }\n}\n"]}
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U,EAAE,CAAC;gBACxC,MAAM,QAAQ,GAAG,QAAQ,CAAC,sBAAsB,EAAE,CAAC;gBACnD,QAAQ,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;gBAC/B,mBAAmB,CAAC,QAAQ,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAC;YACrD,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.runtime.components\",\n \"title\": \"Component Tag Binding System\",\n \"category\": \"runtime\"\n}\n*/\n\nimport { compileExpression } from '../compileExpression';\nimport { isTemplateAttr } from './declaredDirective';\nimport {\n boundaryForElement,\n currentBoundary,\n replaceHidden,\n runWithBoundary,\n slotContentHidden,\n withSlotBoundary,\n} from './bindErrorBoundary';\nimport { bindAfterComponents } from './bindAfterComponents';\nimport { collectSlotMap, inProjectedContent } from '../contentProjection';\nimport {\n componentChildDirectiveMessage,\n componentChildDirectives,\n nativeTags,\n type PithyNode,\n} from '@pithyjs/compiler';\nimport { collectForwardedAttrs, applyForwardedAttrs } from './forwardedAttrs';\nimport { createRoot, untrack } from '@pithyjs/signals';\nimport { watchStaleRowProp } from './staleRowProps';\nimport { markForwardTarget, nodeExpando } from '../nodeExpando';\nimport { componentDisposer } from '../disposeOrder';\nimport { pithyGlobals } from '../../types/globals';\nimport { isSSRMode } from '../ssrMode';\nimport { clearSSRRenderCrash, reportComponentFailure } from '../ssrCrashes';\nimport { isRenderableComponentEl } from '../componentResult';\nimport { parsePropNames, type PropNames } from './propNames';\n\ninterface ComponentResult {\n /** Any DOM node — see the `Component` type for why this is not narrower. */\n el: Node;\n destroy?: () => void;\n}\ntype ComponentFn = (props: Record<string, unknown>) => ComponentResult;\n\n/**\n * Find the closest element-scoped context we attach in createLoopItem().\n * This is what exposes item(), gIdx(), count(), etc.\n */\n// Warn once per component/tag pair — the same idiom re-renders constantly\n// (e.g. a panel importing Button while using a native <button>), and\n// repeating the warning drowns out real ones.\nconst warnedComponentTags = new Set<string>();\nconst warnedChildDirectives = new WeakSet<PithyNode>();\n\n/** Test-only: forget which tags were warned about, so each render warns as a fresh process would. */\nexport function __resetComponentTagWarnings(): void {\n warnedComponentTags.clear();\n}\n\nfunction nearestCtx(\n el: Element,\n rootCtx: Record<string, unknown>\n): Record<string, unknown> {\n let n: Element | null = el;\n while (n) {\n const local = nodeExpando(n).__pithyCtx;\n if (local) return local;\n n = n.parentElement;\n }\n return rootCtx;\n}\n\n/**\n * Detect whether a node is inside a subtree that represents a NOT-YET-EXPANDED nested loop.\n * Those hosts are tagged in createLoopManager.createLoopItem() via `__pithySkipText`,\n * and real templates may also still carry @for / data-for before expansion.\n * We must *defer* binding for anything under such a host, otherwise expressions like item()\n * will throw ReferenceError (because inner loop ctx isn’t created yet).\n */\nfunction isInsidePendingLoopZone(node: Element): boolean {\n let p: Element | null = node;\n while (p) {\n if (nodeExpando(p).__pithySkipText) return true;\n if (\n p.hasAttribute &&\n (p.hasAttribute('@for') || p.hasAttribute('data-for'))\n ) {\n return true;\n }\n p = p.parentElement;\n }\n return false;\n}\n\n/** Evaluate `expr` in `ctx`. Try engine compiler first, then args-style fallback. */\nfunction evalInCtx(expr: string, ctx: Record<string, unknown>): unknown {\n // 1) Preferred: compileExpression uses `with(ctx) { return (...) }`\n try {\n const f = compileExpression(expr, ctx);\n try {\n return f();\n } catch {\n /* fall through to fallback */\n }\n } catch {\n /* fall through to fallback */\n }\n\n // 2) Fallback: args-style evaluator (robust even if compileExpression throws)\n const keys = Object.keys(ctx);\n const vals = keys.map(k => ctx[k]);\n // eslint-disable-next-line no-new-func -- args-style template expression evaluation is a core framework feature\n const fn = new Function(...keys, `return (${expr});`) as (\n ...args: unknown[]\n ) => unknown;\n return fn(...vals);\n}\n\nconst propNameCache = new WeakMap<ComponentFn, PropNames>();\n\nfunction readPropNames(componentFn: ComponentFn): PropNames {\n let cached = propNameCache.get(componentFn);\n if (!cached) {\n try {\n cached = parsePropNames(componentFn.toString());\n } catch {\n cached = { names: [], fromParam: false, exhaustive: false };\n }\n propNameCache.set(componentFn, cached);\n }\n return cached;\n}\n\nfunction extractExpectedPropNames(componentFn: ComponentFn): string[] {\n return readPropNames(componentFn).names;\n}\n\nconst warnedBoundProps = new Set<string>();\nconst GLOBAL_ATTRS = new Set([\n 'id',\n 'class',\n 'style',\n 'title',\n 'role',\n 'tabindex',\n 'hidden',\n]);\n\nfunction warnBoundProps(\n componentFn: ComponentFn,\n el: Element,\n componentName: string\n): void {\n const expected = extractExpectedPropNames(componentFn);\n for (const attr of Array.from(el.attributes)) {\n if (!attr.name.startsWith('data-bind-')) continue;\n const bound = attr.name.slice('data-bind-'.length);\n if (bound === 'slot' && !warnedBoundProps.has(`${componentName} slot`)) {\n warnedBoundProps.add(`${componentName} slot`);\n console.warn(\n `[PithyJS] <${componentName}> [slot] cannot choose a slot: the key is read as a literal, so this lands in the default slot. Write slot=\"name\".`\n );\n }\n if (GLOBAL_ATTRS.has(bound)) continue;\n const prop = expected.find(p => p.toLowerCase() === bound);\n const key = `${componentName} ${bound}`;\n if (!prop || warnedBoundProps.has(key)) continue;\n warnedBoundProps.add(key);\n console.warn(\n `[PithyJS] <${componentName}> [${bound}] sets an attribute on the rendered root, not the \\`${prop}\\` prop. Write ${prop}=\"…\" without brackets to set the prop; for a live value pass a signal or () => … if the prop accepts one.`\n );\n }\n}\n\n/** Dev warnings for unexpected props (only if destructuring is present). */\nfunction validateComponentProps(\n componentFn: ComponentFn,\n props: Record<string, unknown>,\n componentName: string\n): void {\n const { names: allNames, exhaustive } = readPropNames(componentFn);\n if (!exhaustive || allNames.length === 0) return;\n\n const passed = Object.keys(props);\n const expectedSet = new Set(allNames);\n\n const unexpected = passed.filter(p => !expectedSet.has(p));\n if (unexpected.length) {\n console.warn(\n `[PithyJS] 🔍 Component <${componentName}> received unexpected props: ${unexpected.join(\n ', '\n )}\\nExpected props: ${allNames.join(', ')}\\nPassed props: ${passed.join(', ')}`\n );\n }\n\n // NOTE: We intentionally do NOT warn about \"missing\" props here.\n // In template-driven usage, props are assembled at runtime by\n // bindComponentTags(), so TypeScript cannot catch missing required\n // props in this path. Components should self-validate critical\n // props where appropriate (e.g. Toggle warns on empty label).\n}\n\n/** DOM a component already rendered: its native tags may share a component's name. */\nfunction inComponentDom(el: Element): boolean {\n for (let n: Element | null = el; n; n = n.parentElement)\n if (nodeExpando(n).__pithyComponentDom) return true;\n return false;\n}\n\n/** Map lowercased DOM attr name to expected prop name (case-insensitive). */\nfunction normalizePropName(\n authoredName: string,\n expectedProps: string[]\n): string {\n if (expectedProps.includes(authoredName)) return authoredName;\n const lower = authoredName.toLowerCase();\n const matches = expectedProps.filter(p => p.toLowerCase() === lower);\n return matches.length === 1 ? matches[0] : authoredName;\n}\n\n/**\n * Replace custom component tags (<Counter/>, <NestedComponent/>) with rendered output.\n * - Skips anything under a pending nested loop host (bind after loop expansion)\n * - Evaluates prop expressions in nearest loop ctx\n * - Case-insensitive prop name normalization\n * - No raw-string fallback (prevents things like calling count() on a string)\n */\n/** @codexApi {\"parent\":\"pithy.runtime.components\",\"name\":\"bindComponentTags\",\"stability\":\"stable\",\"signature\":\"(root: Element | DocumentFragment, rootCtx: Record<string, unknown>, disposers: (() => void)[]) => void\"} */\nexport function bindComponentTags(\n root: Element | DocumentFragment,\n rootCtx: Record<string, unknown>,\n disposers: (() => void)[]\n): void {\n // case-insensitive tag lookup from context\n const tagMap = new Map<string, unknown>(\n Object.keys(rootCtx).map(k => [k.toLowerCase(), rootCtx[k]])\n );\n\n const scope =\n root instanceof Element ? (root as Element) : (root as DocumentFragment);\n const elements = Array.from(scope.querySelectorAll('*'));\n\n for (const el of elements) {\n // Skip elements removed from the tree by a parent component's render, or\n // hidden by an `@error-boundary` that has since activated.\n if (!scope.contains(el)) {\n // An element that has left the tree contributes nothing to the output, so\n // a crash recorded for it on an earlier DETACHED pass is stale. Leaving it\n // fails a route that rendered correctly: with two crashing components\n // under one boundary inside an `@if`, the detached pass records both, the\n // retry lets the boundary accept the first, and accepting synchronously\n // hides the second — which then never gets a retry to retract it.\n if (isSSRMode()) clearSSRRenderCrash(el);\n continue;\n }\n\n // Defer components inside not-yet-expanded loops\n if (isInsidePendingLoopZone(el)) continue;\n\n // A build's placeholder carries no AST: its children are DOM, which only\n // the AOT binder reads.\n const aotMount = nodeExpando(el).__pithyAotMount;\n if (aotMount) {\n // Marked as below, so the text pass skips what the component rendered.\n for (const node of aotMount(disposers))\n nodeExpando(node).__pithyComponentDom = true;\n continue;\n }\n\n const tag = el.tagName.toLowerCase();\n\n // Check if the parser marked this element as a component\n // This is the authoritative source - it checks originalTagName starts with uppercase\n // AND the tag name exists in importedIdentifiers\n const pithyNode = nodeExpando(el).__pithyNode;\n if (pithyNode) {\n // Parser processed this element - use its isComponent flag\n if (!pithyNode.isComponent) {\n // DEV: Warn if there's a component that matches case-insensitively\n // This helps developers catch typos like <button> when they meant <Button>\n // Skip warning if we're inside a component's render (the component might\n // legitimately use native elements like <button> in its implementation)\n const isInsideComponentRender =\n !!pithyGlobals().__pithyRenderingComponent;\n if (\n import.meta.env?.DEV &&\n !isInsideComponentRender &&\n !inComponentDom(el)\n ) {\n const matchingComponent = tagMap.get(tag);\n if (matchingComponent && typeof matchingComponent === 'function') {\n // Find the actual component name from context\n const componentName = Object.keys(rootCtx).find(\n k => k.toLowerCase() === tag && rootCtx[k] === matchingComponent\n );\n const warnKey = `${componentName}:${pithyNode.originalTagName}`;\n if (\n componentName &&\n componentName !== pithyNode.originalTagName &&\n !warnedComponentTags.has(warnKey)\n ) {\n warnedComponentTags.add(warnKey);\n console.warn(\n `[PithyJS] ⚠️ Component '${componentName}' is imported but used as '<${pithyNode.originalTagName}>'. ` +\n `Components must use PascalCase. Use '<${componentName}>' instead.`\n );\n }\n }\n }\n continue;\n }\n } else {\n // Fallback for elements not processed by our parser:\n // Skip native HTML elements to prevent <button> matching Button component\n if (nativeTags.has(tag)) continue;\n // Rendered already, e.g. a build's slot content.\n if (inComponentDom(el)) continue;\n }\n\n if (\n import.meta.env?.DEV &&\n pithyNode &&\n !warnedChildDirectives.has(pithyNode)\n ) {\n warnedChildDirectives.add(pithyNode);\n for (const name of componentChildDirectives(pithyNode))\n console.warn(\n `[pithy] ${componentChildDirectiveMessage(pithyNode.originalTagName ?? tag, name)}`\n );\n }\n\n let candidate = tagMap.get(tag);\n\n if (!candidate) continue;\n\n // Support default exports\n if (\n candidate &&\n typeof candidate === 'object' &&\n 'default' in candidate &&\n typeof candidate.default === 'function'\n ) {\n candidate = candidate.default;\n }\n if (typeof candidate !== 'function') continue;\n // Content a runtime-compiled receiver projected: bound detached, inside the\n // output of the component being rendered.\n const projectedHost =\n !el.closest('[data-error]') && inProjectedContent(el)\n ? pithyGlobals().__pithyComponentContext?.__slotHost\n : undefined;\n // Hidden like a sibling an activated boundary detached: never rendered.\n if (withSlotBoundary(undefined, projectedHost, () => slotContentHidden(el)))\n continue;\n\n const componentFn = candidate as ComponentFn;\n const localCtx = nearestCtx(el, rootCtx); // crucial for item(), gIdx(), etc.\n\n // Extract expected props for validation (DEV) and prop name normalization (always)\n // This ensures case-insensitive matching works even when originalAttrs is unavailable\n const { names, fromParam } = readPropNames(componentFn);\n const expectedProps = fromParam ? names : [];\n\n // Preserve originally-authored attribute names/casing from the parsed template\n // (pithyNode already extracted above for isComponent check)\n const originalAttrs: Record<string, string> | undefined =\n pithyNode?.originalAttrs;\n\n const props: Record<string, unknown> = {};\n\n const staleWatchers: (() => void)[] = [];\n\n // Evaluate attributes as expressions in localCtx\n for (const attr of Array.from(el.attributes)) {\n const name = attr.name;\n const raw = attr.value;\n\n // Skip internal/behavioral attributes\n if (name.startsWith('data-')) continue;\n if (name === 'class' || name === 'style' || name === 'slot') continue;\n if (!isTemplateAttr(attr)) continue;\n\n // Prefer originally-authored name (preserve casing), else DOM name\n const authored = originalAttrs?.[name] ?? name;\n const propName = normalizePropName(authored, expectedProps);\n\n try {\n const value = untrack(() => evalInCtx(raw, localCtx));\n props[propName] = value; // only set when evaluation succeeds\n if (import.meta.env?.DEV) {\n staleWatchers.push(() =>\n watchStaleRowProp(\n localCtx,\n pithyNode ?? el,\n pithyNode?.originalTagName || tag,\n propName,\n raw,\n value,\n () => evalInCtx(raw, localCtx),\n disposers\n )\n );\n }\n } catch (err) {\n if (import.meta.env?.DEV) {\n console.warn(\n `[PithyJS] ⚠️ Failed to evaluate prop \"${propName}\" = \"${raw}\"`,\n err\n );\n }\n // IMPORTANT: do NOT set a raw string fallback here.\n // Leaving it undefined lets the child use defaults and avoids count()-on-string.\n }\n }\n\n // Validate props for all components in DEV mode.\n // Native elements are already filtered out earlier (line 197 for fallback, line 171 for parser).\n if (import.meta.env?.DEV) {\n const displayTag = pithyNode?.originalTagName || tag;\n validateComponentProps(componentFn, props, displayTag);\n warnBoundProps(componentFn, el, displayTag);\n }\n\n // Collect content projection SlotMap from component children\n const pithyChildren: PithyNode[] = pithyNode?.children || [];\n const slotMap = collectSlotMap(pithyChildren, localCtx);\n\n // Create enhanced context with SlotMap for content projection\n const componentContext = {\n ...localCtx,\n __slotMap: slotMap,\n __childAstNodes: pithyChildren,\n __childFactory: undefined,\n __slotHost: el,\n };\n\n // Find nearest error boundary for this component\n const boundaryEl = el.closest('[data-error]') as Element | null;\n // Projected content is bound detached, during its receiver's render.\n const boundary =\n boundaryForElement(boundaryEl) ??\n (!boundaryEl && inProjectedContent(el) ? currentBoundary() : null);\n\n // Invoke component under boundary context; expect { el, destroy }\n let out: ComponentResult | undefined;\n let disposeSetup: (() => void) | undefined;\n try {\n out = runWithBoundary(boundary, () => {\n // Store the enhanced context globally for the component's html() calls to access.\n // This per-component context contains __slotMap for content projection.\n //\n // In SSR, there are TWO context sources that html() merges:\n // 1. AsyncLocalStorage context (__getComponentContext) - request-level isolation\n // 2. This global context (__pithyComponentContext) - per-component __slotMap\n //\n // Both are needed: AsyncLocalStorage provides request isolation, while this\n // global provides the __slotMap that changes for each component render.\n const g = pithyGlobals();\n const originalContext = g.__pithyComponentContext;\n const wasRendering = g.__pithyRenderingComponent;\n g.__pithyComponentContext = componentContext;\n // Mark that we're rendering a component to suppress casing warnings for\n // native elements used in component implementations (e.g., <button> in Button)\n g.__pithyRenderingComponent = true;\n\n try {\n const result = createRoot(disposeRoot => {\n disposeSetup = disposeRoot;\n return componentFn(props);\n });\n return result;\n } finally {\n // Restore original context\n g.__pithyComponentContext = originalContext;\n g.__pithyRenderingComponent = wasRendering;\n }\n });\n } catch (err) {\n // Route sync render errors to the nearest boundary with escalation\n if (boundary) {\n const error = err instanceof Error ? err : new Error(String(err));\n // A boundary being in scope does not mean it accepted the error: an\n // already-active boundary with no free ancestor drops it (React's\n // first-error-wins). A component inside that boundary's `@fallback` is\n // the everyday case, and the fallback is what the user actually sees.\n const accepted = reportComponentFailure(el, tag, error, boundary);\n if (import.meta.env?.DEV) {\n // Say which of the two actually happened. \"Captured\" on a rejected\n // error reports the opposite of the truth, and this branch exists\n // precisely because the two are not the same.\n console.log(\n accepted\n ? `[ErrorBoundary] Captured sync render error in <${tag}>:`\n : `[ErrorBoundary] Boundary already active — error from <${tag}> was NOT captured:`,\n error.message\n );\n }\n continue;\n }\n\n // No boundary in scope *yet*. Degrading is still the right call here in\n // both modes: throwing would pre-empt the retry pass that gives an\n // `@error-boundary` its only chance to claim a crash raised while the\n // subtree was detached.\n //\n // A static/server render additionally records the crash. Nobody reads a\n // console during `pithy-ssg`, so this used to leave the raw <${tag}> in\n // the emitted HTML while the route still counted as rendered and the CLI\n // exited 0 (BUG-018). Anything still recorded when the render finishes\n // makes the SSR renderer throw, and the per-route catch in `vite-ssg.ts`\n // fails that route.\n reportComponentFailure(\n el,\n tag,\n err instanceof Error ? err : new Error(String(err)),\n null\n );\n\n console.error(`❌ Component <${tag}> crashed during render:`, err);\n continue;\n }\n\n if (\n !out ||\n typeof out !== 'object' ||\n !('el' in out) ||\n !isRenderableComponentEl(out.el, el)\n ) {\n console.warn(\n `❌ Invalid render result from <${tag}>. Expected { el, destroy }`\n );\n // Not a throw, but the same outcome as one: the raw <${tag}> is left in\n // the document and the subtree never renders. Under SSR that is content\n // silently missing from the emitted HTML, so it is recorded exactly like\n // a crash (BUG-018). Recorded rather than merely left in place, because\n // this attempt may also be retracting an earlier attempt's record.\n // Same funnel as a throw: a boundary above this component gets the\n // chance to claim it and render its fallback, and only an unclaimed\n // failure is recorded. Bypassing this meant a component under\n // `@error-boundary` that returned garbage failed the route with the\n // boundary signal still null.\n reportComponentFailure(\n el,\n tag,\n new Error(\n `Invalid render result from <${tag}>; expected { el, destroy }`\n ),\n boundary\n );\n disposeSetup?.();\n continue;\n }\n\n const { el: renderedEl, destroy } = out;\n\n // Capture class and data-* attributes for forwarding to rendered root:\n // directive bindings (data-on-*, data-bind-*, data-class-toggle-*,\n // data-classes, data-style-*) plus any author-written data-* attribute.\n const forwardedClass = el.getAttribute('class');\n const forwardedAttrs = collectForwardedAttrs(el);\n\n const isFragment = renderedEl.nodeType === Node.DOCUMENT_FRAGMENT_NODE;\n let forwardTarget: HTMLElement | null = null;\n const hasForwardables = !!(forwardedClass || forwardedAttrs.length > 0);\n if (hasForwardables) {\n if (isFragment) {\n forwardTarget = (renderedEl as DocumentFragment)\n .firstElementChild as HTMLElement | null;\n if (import.meta.env?.DEV && !forwardTarget) {\n const displayTag = pithyNode?.originalTagName || tag;\n console.warn(\n `[PithyJS] <${displayTag}> has class or data-* attributes but returns a fragment with no element children — forwarding skipped.`\n );\n }\n } else if (renderedEl.nodeType === Node.ELEMENT_NODE) {\n forwardTarget = renderedEl as HTMLElement;\n }\n }\n\n const renderedNodes = isFragment\n ? Array.from(renderedEl.childNodes)\n : [renderedEl];\n for (const node of renderedNodes)\n nodeExpando(node).__pithyComponentDom = true;\n\n let replaced = true;\n let hidden = false;\n try {\n // A boundary that caught a crash in this render may have hidden `el`.\n hidden = replaceHidden(el, renderedNodes);\n if (!hidden) el.replaceWith(...renderedNodes);\n } catch (err) {\n // A failed replacement leaves the raw <${tag}> exactly where a crash\n // would have, so it is the same content loss and is recorded the same way.\n replaced = false;\n reportComponentFailure(\n el,\n tag,\n err instanceof Error ? err : new Error(String(err)),\n boundary\n );\n console.error(`❌ Failed to replace <${tag}> with rendered DOM:`, err);\n }\n\n // Retracted only here, and in the boundary catch above — never eagerly at\n // the top of an attempt, where any early `continue` added later would\n // silently drop a real record. This is the point at which the component is\n // known to have produced a usable node AND to have reached the document, so\n // an earlier detached attempt's crash is genuinely no longer the outcome.\n if (isSSRMode() && replaced) clearSSRRenderCrash(el);\n\n for (const watch of staleWatchers) watch();\n\n // Forward class from component tag onto the rendered root element\n if (forwardedClass && forwardTarget) {\n for (const cls of forwardedClass.split(/\\s+/)) {\n if (cls) forwardTarget.classList.add(cls);\n }\n }\n\n // Before any binding pass below, which can throw.\n const teardown = componentDisposer(\n destroy,\n disposeSetup,\n renderedNodes[0] ?? (replaced ? null : el)\n );\n if (teardown) disposers.push(teardown);\n\n // Forward captured attributes so subsequent binders can attach the bindings\n if (forwardedAttrs.length > 0 && forwardTarget) {\n applyForwardedAttrs(forwardTarget, forwardedAttrs, tag);\n markForwardTarget(\n forwardTarget,\n localCtx,\n new Set(forwardedAttrs.map(([name]) => name))\n );\n const styleProps = Object.keys(pithyNode?.directives?.styleMap ?? {});\n if (styleProps.length)\n nodeExpando(forwardTarget).__styleProps = styleProps;\n const classToggles = Object.keys(pithyNode?.directives?.classMap ?? {});\n if (classToggles.length)\n nodeExpando(forwardTarget).__classToggles = classToggles;\n // Hidden, it is out of reach of this fragment's later passes. An active\n // nested boundary `hideContent` kept in place is still within reach.\n if (hidden && !forwardTarget.parentNode) {\n const detached = document.createDocumentFragment();\n detached.append(forwardTarget);\n bindAfterComponents(detached, localCtx, disposers);\n }\n }\n }\n}\n"]}