@pyreon/core 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Compat-mode native-component marker.
3
+ *
4
+ * Pyreon ships compat layers (`@pyreon/{react,preact,vue,solid}-compat`) that
5
+ * wrap every JSX-called component function to emulate that source framework's
6
+ * render-on-state-change semantics. That wrapping is correct for user code
7
+ * (the whole point of compat mode) but corrupts Pyreon framework components
8
+ * — those manage their own reactivity via `provide()` / signals / lifecycle
9
+ * hooks, and wrapping them runs their setup body inside the compat layer's
10
+ * render context instead of Pyreon's, breaking `provide()` and
11
+ * `onMount()` / `onUnmount()` calls.
12
+ *
13
+ * Framework components opt out of compat wrapping by setting a well-known
14
+ * registry symbol (`Symbol.for('pyreon:native-compat')`) on the function.
15
+ * The compat layer reads that symbol and routes marked components straight
16
+ * through Pyreon's `h()` mount path. The symbol is registry-shared, so no
17
+ * import direction between framework and compat is implied — both sides
18
+ * reference the same global symbol via the helpers exported here.
19
+ *
20
+ * Audience: framework-package authors writing JSX components in `@pyreon/*`
21
+ * packages whose setup body uses `provide()` / lifecycle hooks / signal
22
+ * subscriptions. Wrap exported components with `nativeCompat()`. One line
23
+ * per export site; zero runtime cost beyond a single property write at
24
+ * module load.
25
+ */
26
+
27
+ /**
28
+ * The well-known registry symbol that marks a component as a Pyreon native
29
+ * framework component. Compat layers check this symbol to decide whether to
30
+ * skip their `wrapCompatComponent` call.
31
+ *
32
+ * Exported for advanced cases where a caller needs to test the marker
33
+ * directly (most callers should use `isNativeCompat()`).
34
+ */
35
+ export const NATIVE_COMPAT_MARKER: symbol = Symbol.for('pyreon:native-compat')
36
+
37
+ /**
38
+ * Mark a Pyreon framework component as "self-managing" — compat layers will
39
+ * skip their React/Vue/Solid/Preact-style wrapping and route the component
40
+ * directly through Pyreon's mount path. Use on every `@pyreon/*` JSX
41
+ * component whose setup body uses `provide()`, lifecycle hooks
42
+ * (`onMount` / `onUnmount`), signal-driven reactivity, or any other Pyreon
43
+ * native pattern that depends on the active component-setup frame.
44
+ *
45
+ * Idempotent: re-applying the marker is a no-op. Non-function inputs pass
46
+ * through unchanged so callers don't have to typecheck before wrapping.
47
+ *
48
+ * @example
49
+ * import { nativeCompat, provide } from '@pyreon/core'
50
+ *
51
+ * export const RouterView = nativeCompat(function RouterView(props) {
52
+ * provide(RouterContext, ...)
53
+ * return <div data-pyreon-router-view>{children}</div>
54
+ * })
55
+ */
56
+ export function nativeCompat<T>(fn: T): T {
57
+ if (typeof fn === 'function') {
58
+ ;(fn as unknown as Record<symbol, boolean>)[NATIVE_COMPAT_MARKER] = true
59
+ }
60
+ return fn
61
+ }
62
+
63
+ /**
64
+ * Read whether a component has been marked as a Pyreon native framework
65
+ * component. Compat-layer code calls this from its `jsx()` to decide whether
66
+ * to wrap or pass through.
67
+ *
68
+ * @example
69
+ * import { isNativeCompat } from '@pyreon/core'
70
+ *
71
+ * if (isNativeCompat(type)) return h(type, props)
72
+ * return wrapCompatComponent(type)(props)
73
+ */
74
+ export function isNativeCompat(fn: unknown): boolean {
75
+ return (
76
+ typeof fn === 'function' &&
77
+ (fn as unknown as Record<symbol, boolean>)[NATIVE_COMPAT_MARKER] === true
78
+ )
79
+ }
package/src/context.ts CHANGED
@@ -5,6 +5,7 @@
5
5
  * The renderer maintains the context stack as it walks the VNode tree.
6
6
  */
7
7
 
8
+ import { setSnapshotCapture } from '@pyreon/reactivity'
8
9
  import { onUnmount } from './lifecycle'
9
10
 
10
11
  export interface Context<T> {
@@ -66,8 +67,7 @@ function getStack(): Map<symbol, unknown>[] {
66
67
 
67
68
  // Dev-mode gate: see `pyreon/no-process-dev-gate` lint rule for why this
68
69
  // uses `import.meta.env.DEV` instead of `typeof process !== 'undefined'`.
69
- // @ts-ignore `import.meta.env.DEV` is provided by Vite/Rolldown at build time
70
- const __DEV__ = import.meta.env?.DEV === true
70
+ const __DEV__ = process.env.NODE_ENV !== 'production'
71
71
 
72
72
  export function pushContext(values: Map<symbol, unknown>) {
73
73
  getStack().push(values)
@@ -149,13 +149,22 @@ export function captureContextStack(): ContextSnapshot {
149
149
 
150
150
  /**
151
151
  * Execute `fn()` with a previously captured context stack active.
152
- * Restores the original stack after `fn()` completes (even on throw).
152
+ *
153
+ * After `fn()` returns, removes ONLY the snapshot frames this call pushed
154
+ * — anything `fn()` itself pushed (typically provider frames from
155
+ * `provide()` calls during component mount) stays on the stack so
156
+ * subsequent reactive re-runs (e.g. `_bind` text bindings,
157
+ * `renderEffect` callbacks) can still find ancestor providers via
158
+ * `useContext`. Pre-fix this method was `stack.length = savedLength`,
159
+ * which destructively truncated provider frames pushed during mount —
160
+ * silently breaking `useMode()` / `useTheme()` / `useRouter()` etc. on
161
+ * every signal-driven update under a `mountReactive` boundary.
153
162
  */
154
163
  export function restoreContextStack<T>(snapshot: ContextSnapshot, fn: () => T): T {
155
164
  const stack = getStack()
156
- const savedLength = stack.length
165
+ const insertIndex = stack.length
157
166
 
158
- // Push all captured frames onto the current stack
167
+ // Push captured snapshot frames at the END of the current stack.
159
168
  for (const frame of snapshot) {
160
169
  stack.push(frame)
161
170
  }
@@ -163,7 +172,29 @@ export function restoreContextStack<T>(snapshot: ContextSnapshot, fn: () => T):
163
172
  try {
164
173
  return fn()
165
174
  } finally {
166
- // Remove only the frames we pushed (preserve anything added by fn)
167
- stack.length = savedLength
175
+ // Splice out exactly the snapshot frames we pushed (they sit at
176
+ // [insertIndex, insertIndex + snapshot.length)). Any frames `fn()`
177
+ // pushed AFTER our snapshot (provider frames) get shifted down by
178
+ // `snapshot.length` positions but remain on the stack. Their owning
179
+ // components' `onUnmount(popContext)` handlers will pop them in
180
+ // LIFO order on subtree teardown — splice preserves that ordering
181
+ // because it doesn't touch frames at indices >= insertIndex +
182
+ // snapshot.length until the splice operation itself.
183
+ stack.splice(insertIndex, snapshot.length)
168
184
  }
169
185
  }
186
+
187
+ // ─── Reactivity-layer DI: install context capture/restore for effects ────────
188
+ //
189
+ // `_bind` / `renderEffect` / `effect` (in `@pyreon/reactivity`) capture this
190
+ // snapshot at setup and restore it on every subsequent re-run. Without this,
191
+ // signal-driven re-runs after the synchronous mount see whatever the GLOBAL
192
+ // context stack looks like at that moment — which may be missing provider
193
+ // frames for any number of reasons (sibling subtree mounts/unmounts mutating
194
+ // the stack, async re-render cycles, etc.). Defense-in-depth alongside the
195
+ // `restoreContextStack` splice fix above.
196
+ setSnapshotCapture({
197
+ capture: () => captureContextStack(),
198
+ restore: <T>(snap: unknown, fn: () => T): T =>
199
+ restoreContextStack(snap as ContextSnapshot, fn),
200
+ })
package/src/dynamic.ts CHANGED
@@ -1,21 +1,32 @@
1
1
  import { h } from './h'
2
- import type { ComponentFn, Props, VNode } from './types'
2
+ import type { ComponentFn, Props, VNode, VNodeChild } from './types'
3
3
 
4
4
  // Dev-mode gate: see `pyreon/no-process-dev-gate` lint rule for why this
5
5
  // uses `import.meta.env.DEV` instead of `typeof process !== 'undefined'`.
6
- // @ts-ignore `import.meta.env.DEV` is provided by Vite/Rolldown at build time
7
- const __DEV__ = import.meta.env?.DEV === true
6
+ const __DEV__ = process.env.NODE_ENV !== 'production'
8
7
 
9
8
  export interface DynamicProps extends Props {
10
9
  component: ComponentFn | string
11
10
  }
12
11
 
13
12
  export function Dynamic(props: DynamicProps): VNode | null {
14
- const { component, ...rest } = props
13
+ const { component, children, ...rest } = props as DynamicProps & { children?: unknown }
15
14
  if (__DEV__ && !component) {
16
15
  // oxlint-disable-next-line no-console
17
16
  console.warn('[Pyreon] <Dynamic> received a falsy `component` prop. Nothing will be rendered.')
18
17
  }
19
18
  if (!component) return null
20
- return h(component as string | ComponentFn, rest as Props)
19
+ // Children must NOT remain in props. When `component` is a string tag
20
+ // (e.g. <Dynamic component="h3">x</Dynamic>), runtime-dom's prop applier
21
+ // forwards every prop key to setAttribute, so a leaked `children` prop
22
+ // crashes with `setAttribute('children', ...)`. Re-emit them as h() rest
23
+ // args so they land in vnode.children, which is where both string-tag
24
+ // mounts and component-merge expect them.
25
+ if (children === undefined) {
26
+ return h(component as string | ComponentFn, rest as Props)
27
+ }
28
+ if (Array.isArray(children)) {
29
+ return h(component as string | ComponentFn, rest as Props, ...(children as VNodeChild[]))
30
+ }
31
+ return h(component as string | ComponentFn, rest as Props, children as VNodeChild)
21
32
  }
@@ -1,4 +1,5 @@
1
1
  import { signal } from '@pyreon/reactivity'
2
+ import { nativeCompat } from './compat-marker'
2
3
  import { popErrorBoundary, pushErrorBoundary } from './component'
3
4
  import { onUnmount } from './lifecycle'
4
5
  import { reportError } from './telemetry'
@@ -6,8 +7,7 @@ import type { VNodeChild, VNodeChildAtom } from './types'
6
7
 
7
8
  // Dev-mode gate: see `pyreon/no-process-dev-gate` lint rule for why this
8
9
  // uses `import.meta.env.DEV` instead of `typeof process !== 'undefined'`.
9
- // @ts-ignore `import.meta.env.DEV` is provided by Vite/Rolldown at build time
10
- const __DEV__ = import.meta.env?.DEV === true
10
+ const __DEV__ = process.env.NODE_ENV !== 'production'
11
11
 
12
12
  /**
13
13
  * ErrorBoundary — catches errors thrown by child components and renders a
@@ -53,6 +53,14 @@ export function ErrorBoundary(props: {
53
53
 
54
54
  const handler = (err: unknown): boolean => {
55
55
  if (error.peek() !== null) return false // already in error state — let outer boundary catch it
56
+ // Synchronous signal write. The handler fires from inside mountComponent's
57
+ // catch, which is itself inside the boundary's own mountReactive effect
58
+ // run (the run that mounted the throwing child). The batch system's
59
+ // two-tier flush handles this correctly: this `error.set(err)` enqueues
60
+ // the boundary's run into the effects queue's nextPass (since the run is
61
+ // currently being visited), and the next pass fires it to swap to the
62
+ // fallback subtree. See packages/core/reactivity/src/batch.ts for the
63
+ // multi-pass effect drain contract.
56
64
  error.set(err)
57
65
  reportError({ component: 'ErrorBoundary', phase: 'render', error: err, timestamp: Date.now() })
58
66
  return true
@@ -69,3 +77,8 @@ export function ErrorBoundary(props: {
69
77
  return (typeof ch === 'function' ? ch() : ch) as VNodeChildAtom
70
78
  }
71
79
  }
80
+
81
+ // Mark as native so compat-mode jsx() runtimes (react/preact/vue/solid-compat)
82
+ // skip wrapCompatComponent — ErrorBoundary uses pushErrorBoundary/onUnmount,
83
+ // which need Pyreon's setup frame (compat wrapping breaks dispatchToErrorBoundary).
84
+ nativeCompat(ErrorBoundary)
package/src/index.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  // @pyreon/core — component model, VNode types, lifecycle hooks
2
2
 
3
3
  export { defineComponent, dispatchToErrorBoundary, propagateError, runWithHooks } from './component'
4
+ export { isNativeCompat, NATIVE_COMPAT_MARKER, nativeCompat } from './compat-marker'
4
5
  export type { Context, ContextSnapshot, ReactiveContext } from './context'
5
6
  export {
6
7
  captureContextStack,
@@ -1,9 +1,17 @@
1
+ /// <reference lib="dom" />
1
2
  /**
2
3
  * JSX automatic runtime.
3
4
  *
4
5
  * When tsconfig has `"jsxImportSource": "@pyreon/core"`, the TS/bundler compiler
5
6
  * rewrites JSX to imports from this file automatically:
6
7
  * <div class="x" /> → jsx("div", { class: "x" })
8
+ *
9
+ * The triple-slash reference above makes this file self-declare its DOM-lib
10
+ * dependency. Without it, any consumer whose tsconfig has `lib: ["ESNext"]`
11
+ * (no DOM) — e.g. backend-only packages like @pyreon/cli — fails to typecheck
12
+ * once `@pyreon/core` becomes resolvable from their dependency graph (e.g. via
13
+ * a transitive devDep), because tsc auto-resolves jsxImportSource and pulls
14
+ * jsx-runtime.ts into the consumer's compilation unit.
7
15
  */
8
16
  import { Fragment, h } from './h'
9
17
  import type { RefProp } from './ref'
@@ -132,6 +140,8 @@ export interface PyreonHTMLAttributes<E extends Element = HTMLElement> {
132
140
  // Events — typed currentTarget via generic E
133
141
  onClick?: ((e: TargetedEvent<E, MouseEvent>) => void) | undefined
134
142
  onDblClick?: ((e: TargetedEvent<E, MouseEvent>) => void) | undefined
143
+ // React-compat alias for onDblClick — compiler maps to `dblclick` DOM event.
144
+ onDoubleClick?: ((e: TargetedEvent<E, MouseEvent>) => void) | undefined
135
145
  onMouseDown?: ((e: TargetedEvent<E, MouseEvent>) => void) | undefined
136
146
  onMouseUp?: ((e: TargetedEvent<E, MouseEvent>) => void) | undefined
137
147
  onMouseEnter?: ((e: TargetedEvent<E, MouseEvent>) => void) | undefined
@@ -197,7 +207,11 @@ export interface InputAttributes extends PyreonHTMLAttributes<HTMLInputElement>
197
207
  defaultChecked?: boolean | undefined
198
208
  placeholder?: string | (() => string) | undefined
199
209
  disabled?: boolean | (() => boolean) | undefined
200
- readOnly?: boolean | undefined
210
+ // `readOnly` is paired with `disabled` semantically — both accept a
211
+ // reactive callable so consumers can spread `useForm.register()`'s
212
+ // return value (which produces `readOnly: Accessor<boolean>`) directly
213
+ // onto `<input>` / `<textarea>` without losing reactivity.
214
+ readOnly?: boolean | (() => boolean) | undefined
201
215
  required?: boolean | (() => boolean) | undefined
202
216
  min?: string | number | undefined
203
217
  max?: string | number | undefined
@@ -249,7 +263,11 @@ export interface TextareaAttributes extends PyreonHTMLAttributes<HTMLTextAreaEle
249
263
  defaultValue?: string | undefined
250
264
  placeholder?: string | (() => string) | undefined
251
265
  disabled?: boolean | (() => boolean) | undefined
252
- readOnly?: boolean | undefined
266
+ // `readOnly` is paired with `disabled` semantically — both accept a
267
+ // reactive callable so consumers can spread `useForm.register()`'s
268
+ // return value (which produces `readOnly: Accessor<boolean>`) directly
269
+ // onto `<input>` / `<textarea>` without losing reactivity.
270
+ readOnly?: boolean | (() => boolean) | undefined
253
271
  required?: boolean | (() => boolean) | undefined
254
272
  rows?: number | undefined
255
273
  cols?: number | undefined
package/src/lifecycle.ts CHANGED
@@ -2,8 +2,7 @@ import type { CleanupFn, LifecycleHooks } from './types'
2
2
 
3
3
  // Dev-mode gate: see `pyreon/no-process-dev-gate` lint rule for why this
4
4
  // uses `import.meta.env.DEV` instead of `typeof process !== 'undefined'`.
5
- // @ts-ignore `import.meta.env.DEV` is provided by Vite/Rolldown at build time
6
- const __DEV__ = import.meta.env?.DEV === true
5
+ const __DEV__ = process.env.NODE_ENV !== 'production'
7
6
 
8
7
  // The currently-executing component's hook storage, set by the renderer
9
8
  // before calling the component function, cleared immediately after.
package/src/manifest.ts CHANGED
@@ -249,14 +249,14 @@ const getMode = useContext(ModeCtx) // reactive: returns () => T`,
249
249
  kind: 'component',
250
250
  signature: '<Show when={condition} fallback={alternative}>{children}</Show>',
251
251
  summary:
252
- 'Reactive conditional rendering. Mounts children when `when` is truthy, unmounts and shows `fallback` when falsy. More efficient than ternary for signal-driven conditions because it avoids re-evaluating the entire branch expression on every signal change — `Show` only transitions between mounted/unmounted when the boolean flips.',
252
+ 'Reactive conditional rendering. Mounts children when `when` is truthy, unmounts and shows `fallback` when falsy. More efficient than ternary for signal-driven conditions because it avoids re-evaluating the entire branch expression on every signal change — `Show` only transitions between mounted/unmounted when the boolean flips. `when` accepts BOTH a value (`when={true}`, `when={signal()}`) and an accessor (`when={() => signal()}`) — the framework normalizes via `typeof === "function"`. The accessor form is required for true reactivity (the framework re-evaluates it on signal change); a bare `when={signal}` reference works because the compiler\'s signal auto-call rewrites it to `when={signal()}`.',
253
253
  example: `<Show when={isLoggedIn()} fallback={<LoginForm />}>
254
254
  <Dashboard />
255
255
  </Show>`,
256
256
  mistakes: [
257
257
  '`{cond() ? <A /> : <B />}` — works but less efficient than `<Show>` for signal-driven conditions',
258
258
  '`<Show when={items().length}>` — works (truthy check), but be explicit: `<Show when={items().length > 0}>`',
259
- '`<Show when={user}>` without calling the signal must call: `<Show when={user()}>`',
259
+ '`<Show when={signal}>` (bare reference) — relies on the compiler\'s signal auto-call to rewrite to `when={signal()}`. Works defensively but use `when={() => signal()}` for explicit accessor semantics across the entire reactive lifecycle.',
260
260
  ],
261
261
  seeAlso: ['Switch', 'Match', 'For'],
262
262
  },
@@ -284,7 +284,7 @@ const getMode = useContext(ModeCtx) // reactive: returns () => T`,
284
284
  kind: 'component',
285
285
  signature: '<Match when={condition}>{children}</Match>',
286
286
  summary:
287
- 'A branch inside a `<Switch>`. Renders its children when `when` is truthy and it is the first truthy `<Match>` in the parent `<Switch>`. Must be a direct child of `<Switch>`.',
287
+ 'A branch inside a `<Switch>`. Renders its children when `when` is truthy and it is the first truthy `<Match>` in the parent `<Switch>`. Must be a direct child of `<Switch>`. `when` accepts both a value and an accessor (same normalization as `<Show>`).',
288
288
  example: `<Switch>
289
289
  <Match when={tab() === "home"}><Home /></Match>
290
290
  <Match when={tab() === "settings"}><Settings /></Match>
@@ -481,6 +481,46 @@ return <input ref={inputRef} />`,
481
481
  })`,
482
482
  seeAlso: ['@pyreon/reactivity'],
483
483
  },
484
+ {
485
+ name: 'nativeCompat',
486
+ kind: 'function',
487
+ signature: '<T>(fn: T) => T',
488
+ summary:
489
+ 'Mark a Pyreon framework component as "self-managing" so compat layers (`@pyreon/{react,preact,vue,solid}-compat`) skip their wrapping and route the component through Pyreon\'s mount path. Use on every `@pyreon/*` JSX component whose setup body uses `provide()` / lifecycle hooks / signal subscriptions — wrapping breaks those by running the body inside the compat layer\'s render context instead of Pyreon\'s. Idempotent; non-function inputs pass through unchanged. The marker is a registry symbol (`Symbol.for("pyreon:native-compat")`), so framework and compat sides share it without an import dependency between them.',
490
+ example: `// In a framework package:
491
+ export const RouterView = nativeCompat(function RouterView(props) {
492
+ provide(RouterContext, ...)
493
+ return <div>{children}</div>
494
+ })`,
495
+ seeAlso: ['isNativeCompat', 'NATIVE_COMPAT_MARKER'],
496
+ mistakes: [
497
+ 'Forgetting to mark a new framework JSX export — under compat mode, the component\'s `provide()` / `onMount()` calls fail with "called outside component setup" warnings and the rendered DOM silently breaks.',
498
+ 'Marking user-app components — only `@pyreon/*` framework components that already manage their own reactivity should be marked. User components in compat mode are SUPPOSED to be wrapped (that\'s how they get re-render-on-state-change semantics).',
499
+ ],
500
+ },
501
+ {
502
+ name: 'isNativeCompat',
503
+ kind: 'function',
504
+ signature: '(fn: unknown) => boolean',
505
+ summary:
506
+ 'Compat-layer-side: read whether a function has been marked as a Pyreon native framework component via `nativeCompat()`. Compat `jsx()` calls this to decide whether to skip the React/Vue/Solid/Preact-style wrapping. Always returns `false` for non-function inputs.',
507
+ example: `// In a compat layer's jsx-runtime:
508
+ if (isNativeCompat(type)) return h(type, props)
509
+ return wrapCompatComponent(type)(props)`,
510
+ seeAlso: ['nativeCompat', 'NATIVE_COMPAT_MARKER'],
511
+ },
512
+ {
513
+ name: 'NATIVE_COMPAT_MARKER',
514
+ kind: 'constant',
515
+ signature: 'symbol',
516
+ summary:
517
+ 'The well-known registry symbol (`Symbol.for("pyreon:native-compat")`) used to mark a component as a Pyreon native framework component. Most callers should use `nativeCompat()` / `isNativeCompat()` instead of touching the symbol directly; exported for advanced cases (e.g., a compat layer that wants to inspect the property without going through the helper).',
518
+ example: `import { NATIVE_COMPAT_MARKER } from '@pyreon/core'
519
+
520
+ // Equivalent to nativeCompat(MyComponent):
521
+ ;(MyComponent as Record<symbol, boolean>)[NATIVE_COMPAT_MARKER] = true`,
522
+ seeAlso: ['nativeCompat', 'isNativeCompat'],
523
+ },
484
524
  {
485
525
  name: 'ExtractProps',
486
526
  kind: 'type',
package/src/show.ts CHANGED
@@ -3,12 +3,25 @@ import type { Props, VNode, VNodeChild, VNodeChildAtom } from './types'
3
3
  // ─── Show ─────────────────────────────────────────────────────────────────────
4
4
 
5
5
  export interface ShowProps extends Props {
6
- /** Accessor — children render when truthy, fallback when falsy. */
7
- when: () => unknown
6
+ /**
7
+ * Truthy condition. Accepts a value or an accessor.
8
+ *
9
+ * Use an accessor (`() => signal()`) for reactive conditions.
10
+ * Bare values are accepted for static cases and as a defensive normalization
11
+ * for cases where the compiler's signal auto-call has already invoked
12
+ * a signal at the prop site (e.g. `when={mySignal}` becomes `when={mySignal()}`).
13
+ */
14
+ when: unknown | (() => unknown)
8
15
  fallback?: VNodeChild
9
16
  children?: VNodeChild
10
17
  }
11
18
 
19
+ // Normalize a value-or-accessor `when` into a single accessor.
20
+ // Same shape used by Match — kept inline (one branch) to stay zero-cost.
21
+ function callWhen(when: unknown): unknown {
22
+ return typeof when === 'function' ? (when as () => unknown)() : when
23
+ }
24
+
12
25
  /**
13
26
  * Conditionally render children based on a reactive condition.
14
27
  *
@@ -25,7 +38,7 @@ export interface ShowProps extends Props {
25
38
  export function Show(props: ShowProps): VNode | null {
26
39
  // Returns a reactive accessor; the renderer unwraps it at mount time.
27
40
  return ((): VNodeChildAtom =>
28
- (props.when()
41
+ (callWhen(props.when)
29
42
  ? (props.children ?? null)
30
43
  : (props.fallback ?? null)) as VNodeChildAtom) as unknown as VNode
31
44
  }
@@ -33,8 +46,8 @@ export function Show(props: ShowProps): VNode | null {
33
46
  // ─── Switch / Match ───────────────────────────────────────────────────────────
34
47
 
35
48
  export interface MatchProps extends Props {
36
- /** Accessor this branch renders when truthy. */
37
- when: () => unknown
49
+ /** Truthy condition. Accepts a value or an accessor — see {@link ShowProps.when}. */
50
+ when: unknown | (() => unknown)
38
51
  children?: VNodeChild
39
52
  }
40
53
 
@@ -97,7 +110,7 @@ export function Switch(props: SwitchProps): VNode | null {
97
110
  for (const branch of branches) {
98
111
  if (!isMatchVNode(branch)) continue
99
112
  const matchProps = branch.props as unknown as MatchProps
100
- if (matchProps.when()) return resolveMatchChildren(branch)
113
+ if (callWhen(matchProps.when)) return resolveMatchChildren(branch)
101
114
  }
102
115
 
103
116
  return (props.fallback ?? null) as VNodeChildAtom
package/src/suspense.ts CHANGED
@@ -3,8 +3,7 @@ import type { Props, VNode, VNodeChild } from './types'
3
3
 
4
4
  // Dev-mode gate: see `pyreon/no-process-dev-gate` lint rule for why this
5
5
  // uses `import.meta.env.DEV` instead of `typeof process !== 'undefined'`.
6
- // @ts-ignore `import.meta.env.DEV` is provided by Vite/Rolldown at build time
7
- const __DEV__ = import.meta.env?.DEV === true
6
+ const __DEV__ = process.env.NODE_ENV !== 'production'
8
7
 
9
8
  /** Internal marker attached to lazy()-wrapped components */
10
9
  export type LazyComponent<P extends Props = Props> = ((props: P) => VNodeChild) & {
package/src/telemetry.ts CHANGED
@@ -1,6 +1,10 @@
1
1
  /**
2
2
  * Error telemetry — hook into Pyreon's error reporting for Sentry, Datadog, etc.
3
3
  *
4
+ * Captures errors from ALL lifecycle phases including reactive effects.
5
+ * `effect()` errors thrown by `@pyreon/reactivity` are bridged through a
6
+ * globalThis sink (no upward import — reactivity doesn't depend on core).
7
+ *
4
8
  * @example
5
9
  * import { registerErrorHandler } from "@pyreon/core"
6
10
  * import * as Sentry from "@sentry/browser"
@@ -13,7 +17,7 @@
13
17
  */
14
18
 
15
19
  export interface ErrorContext {
16
- /** Component function name, or "Anonymous" */
20
+ /** Component function name, "Anonymous", or "Effect" for reactive effects */
17
21
  component: string
18
22
  /** Lifecycle phase where the error occurred */
19
23
  phase: 'setup' | 'render' | 'mount' | 'unmount' | 'effect'
@@ -31,10 +35,17 @@ let _handlers: ErrorHandler[] = []
31
35
 
32
36
  /**
33
37
  * Register a global error handler. Called whenever a component throws in any
34
- * lifecycle phase. Returns an unregister function.
38
+ * lifecycle phase, OR an effect throws in `@pyreon/reactivity`. Returns an
39
+ * unregister function.
40
+ *
41
+ * Also installs a `globalThis.__pyreon_report_error__` bridge so the
42
+ * reactivity package (which can't depend on core) can forward effect errors
43
+ * into the same telemetry pipeline. Pre-fix the two surfaces were
44
+ * disconnected — Sentry/Datadog wiring missed effect-thrown errors.
35
45
  */
36
46
  export function registerErrorHandler(handler: ErrorHandler): () => void {
37
47
  _handlers.push(handler)
48
+ _installReactivityBridge()
38
49
  return () => {
39
50
  _handlers = _handlers.filter((h) => h !== handler)
40
51
  }
@@ -53,3 +64,20 @@ export function reportError(ctx: ErrorContext): void {
53
64
  }
54
65
  }
55
66
  }
67
+
68
+ // ─── Reactivity bridge ──────────────────────────────────────────────────────
69
+ // Installs `globalThis.__pyreon_report_error__` so `@pyreon/reactivity`
70
+ // effect-error path can forward into reportError. Idempotent — multiple
71
+ // `registerErrorHandler` calls install once.
72
+
73
+ interface PyreonErrorBridge {
74
+ __pyreon_report_error__?: (err: unknown, phase: 'effect') => void
75
+ }
76
+ const _bridgeHost = globalThis as PyreonErrorBridge
77
+
78
+ function _installReactivityBridge(): void {
79
+ if (_bridgeHost.__pyreon_report_error__) return
80
+ _bridgeHost.__pyreon_report_error__ = (err, phase) => {
81
+ reportError({ component: 'Effect', phase, error: err, timestamp: Date.now() })
82
+ }
83
+ }
@@ -0,0 +1,96 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { isNativeCompat, NATIVE_COMPAT_MARKER, nativeCompat } from '../compat-marker'
3
+
4
+ describe('NATIVE_COMPAT_MARKER', () => {
5
+ it('is the same registry symbol regardless of how it is referenced', () => {
6
+ // Symbol.for(...) registry contract — every consumer that uses the same
7
+ // string key (compat layers reading it, framework packages writing it)
8
+ // gets the SAME symbol identity. Changing the string is a breaking
9
+ // change to the marker contract.
10
+ expect(NATIVE_COMPAT_MARKER).toBe(Symbol.for('pyreon:native-compat'))
11
+ })
12
+
13
+ it('is a `symbol`-typed value', () => {
14
+ expect(typeof NATIVE_COMPAT_MARKER).toBe('symbol')
15
+ })
16
+ })
17
+
18
+ describe('nativeCompat', () => {
19
+ it('attaches the marker to a function and returns the same reference', () => {
20
+ function RouterView() {
21
+ return null
22
+ }
23
+ const marked = nativeCompat(RouterView)
24
+ expect(marked).toBe(RouterView)
25
+ expect((RouterView as unknown as Record<symbol, boolean>)[NATIVE_COMPAT_MARKER]).toBe(true)
26
+ })
27
+
28
+ it('is idempotent — applying twice yields the same property state', () => {
29
+ const Component = () => null
30
+ nativeCompat(Component)
31
+ nativeCompat(Component)
32
+ expect((Component as unknown as Record<symbol, boolean>)[NATIVE_COMPAT_MARKER]).toBe(true)
33
+ })
34
+
35
+ it('passes non-function values through unchanged', () => {
36
+ // Defensive: callers may pipe variables of unknown shape (e.g. lazy
37
+ // imports that resolve to objects, or null during HMR boundary
38
+ // teardown). The helper must be safe regardless.
39
+ expect(nativeCompat(null as unknown)).toBe(null)
40
+ expect(nativeCompat(undefined as unknown)).toBe(undefined)
41
+ const obj = { foo: 'bar' }
42
+ expect(nativeCompat(obj)).toBe(obj)
43
+ expect((obj as unknown as Record<symbol, boolean>)[NATIVE_COMPAT_MARKER]).toBeUndefined()
44
+ })
45
+
46
+ it('preserves the function signature for typed callers', () => {
47
+ // The generic `T` flows through unchanged so framework component
48
+ // exports keep their typed callable shape after wrapping.
49
+ const Typed = (props: { name: string }): string => `hello ${props.name}`
50
+ const marked: typeof Typed = nativeCompat(Typed)
51
+ expect(marked({ name: 'world' })).toBe('hello world')
52
+ })
53
+ })
54
+
55
+ describe('isNativeCompat', () => {
56
+ it('returns true for a marked function', () => {
57
+ const Comp = nativeCompat(() => null)
58
+ expect(isNativeCompat(Comp)).toBe(true)
59
+ })
60
+
61
+ it('returns false for an unmarked function', () => {
62
+ expect(isNativeCompat(() => null)).toBe(false)
63
+ })
64
+
65
+ it('returns false for non-function inputs', () => {
66
+ expect(isNativeCompat(null)).toBe(false)
67
+ expect(isNativeCompat(undefined)).toBe(false)
68
+ expect(isNativeCompat('string')).toBe(false)
69
+ expect(isNativeCompat(42)).toBe(false)
70
+ expect(isNativeCompat({ [NATIVE_COMPAT_MARKER]: true })).toBe(false)
71
+ })
72
+
73
+ it('returns false when the marker is set to a non-true value', () => {
74
+ // Defensive against accidental shape mismatch — only `=== true` qualifies.
75
+ function Comp() {
76
+ return null
77
+ }
78
+ ;(Comp as unknown as Record<symbol, unknown>)[NATIVE_COMPAT_MARKER] = 1
79
+ expect(isNativeCompat(Comp)).toBe(false)
80
+ ;(Comp as unknown as Record<symbol, unknown>)[NATIVE_COMPAT_MARKER] = 'yes'
81
+ expect(isNativeCompat(Comp)).toBe(false)
82
+ })
83
+
84
+ it('reads the same registry symbol that nativeCompat writes', () => {
85
+ // Cross-side contract: a function marked here is detectable by
86
+ // someone who looked up the symbol via `Symbol.for('pyreon:native-compat')`
87
+ // independently — without importing NATIVE_COMPAT_MARKER from this module.
88
+ const Comp = nativeCompat(function Comp() {
89
+ return null
90
+ })
91
+ const externallyDiscoveredSymbol = Symbol.for('pyreon:native-compat')
92
+ expect(
93
+ (Comp as unknown as Record<symbol, boolean>)[externallyDiscoveredSymbol],
94
+ ).toBe(true)
95
+ })
96
+ })
@@ -1,6 +1,6 @@
1
1
  import { Dynamic } from '../dynamic'
2
2
  import { h } from '../h'
3
- import type { ComponentFn, VNode } from '../types'
3
+ import type { ComponentFn, VNode, VNodeChild } from '../types'
4
4
 
5
5
  describe('Dynamic', () => {
6
6
  test('renders component function', () => {
@@ -52,4 +52,36 @@ describe('Dynamic', () => {
52
52
  expect(result).not.toBeNull()
53
53
  expect((result as VNode).type).toBe('br')
54
54
  })
55
+
56
+ test('does not leak children as a prop on string-tag mount', () => {
57
+ // Regression: for string `component`, runtime-dom forwards every prop
58
+ // key to setAttribute. If `children` stayed in props it crashed at
59
+ // mount with `setAttribute('children', ...)`. The fix re-emits them
60
+ // as h() rest args, landing them in vnode.children.
61
+ const result = Dynamic({ component: 'h3', children: 'hello' })
62
+ expect((result as VNode).type).toBe('h3')
63
+ expect((result as VNode).props.children).toBeUndefined()
64
+ expect((result as VNode).children).toEqual(['hello'])
65
+ })
66
+
67
+ test('flattens array children to vnode.children', () => {
68
+ const a = h('span', null, 'a')
69
+ const b = h('span', null, 'b')
70
+ const result = Dynamic({ component: 'div', children: [a, b] })
71
+ expect((result as VNode).props.children).toBeUndefined()
72
+ expect((result as VNode).children).toHaveLength(2)
73
+ })
74
+
75
+ test('component children still reach props.children at mount', () => {
76
+ // For component (not string), the merge happens at mount via
77
+ // mergeChildrenIntoProps — verified end-to-end by mount tests in
78
+ // runtime-dom. Here we just confirm the vnode shape is correct so the
79
+ // merge will fire (children must be on vnode.children, not props).
80
+ const Comp: ComponentFn = (props) =>
81
+ h('div', null, (props as { children?: VNodeChild }).children ?? null)
82
+ const result = Dynamic({ component: Comp, children: 'hi' })
83
+ expect((result as VNode).type).toBe(Comp)
84
+ expect((result as VNode).props.children).toBeUndefined()
85
+ expect((result as VNode).children).toEqual(['hi'])
86
+ })
55
87
  })