@tschk/moonshine-vue 0.4.4 → 0.4.49

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
@@ -20,17 +20,20 @@ import { fromMoonshineSignal } from "@tschk/moonshine-vue";
20
20
  import { ref } from "@tschk/moonshine-vue/reactive";
21
21
  ```
22
22
 
23
- | Subpath | Provides |
24
- | ---------------- | -------------------------------------------------------------------------------------------------------------------- |
25
- | `.` | signal bridges, lazy native SSR compatibility renderer |
26
- | `./vue` | `vue` runtime re-exports |
27
- | `./compiler-sfc` | `vue/compiler-sfc` re-exports |
28
- | `./reactive` | native refs/`shallowRef`, `toRef`/`toRefs`/`unref`/`isRef`, `reactive`/`isReactive`, `computed`, synchronous `watch` |
29
- | `./context` | native component `provide`, `inject`, `hasInjectionContext` |
30
- | `./text` | native DOM and SSR interpolation conversion |
31
- | `./props` | compiler-facing shallow declared props and owned parent refresh |
32
- | `./events` | compiler-facing typed component callbacks, callback arrays and per-instance once delivery |
33
- | `./normalize` | native class/style normalization and compiler-facing DOM/SSR policies |
23
+ | Subpath | Provides |
24
+ | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
25
+ | `.` | signal bridges, lazy native SSR compatibility renderer |
26
+ | `./vue` | `vue` runtime re-exports |
27
+ | `./compiler-sfc` | `vue/compiler-sfc` re-exports |
28
+ | `./reactive` | native `ref`/`shallowRef`/`customRef`/`triggerRef`/`useTemplateRef`/`useModel`/`createModel`/`useId` (`ModelRef`, `DefineModelOptions`), `toRef`/`toRefs`/`unref`/`toValue`/`isRef`, `reactive`/`shallowReactive`/`readonly`/`shallowReadonly`, `isReactive`/`isReadonly`/`isShallow`/`isProxy`/`toRaw`/`markRaw`, `computed`, `watch`/`watchSyncEffect`/`onWatcherCleanup` (`WatchHandle`), `effectScope`/`getCurrentScope`/`onScopeDispose` |
29
+ | `./context` | native component `provide`, `inject`, `hasInjectionContext`, `useId` |
30
+ | `./lifecycle` | native component `onBeforeMount`, `onMounted`, `onBeforeUnmount`, `onUnmounted`, `onErrorCaptured` (`ErrorCapturedHook`) |
31
+ | `./text` | native DOM and SSR interpolation conversion |
32
+ | `./props` | compiler-facing shallow declared props and owned parent refresh |
33
+ | `./events` | compiler-facing typed component callbacks, callback arrays and per-instance once delivery |
34
+ | `./normalize` | native class/style normalization and compiler-facing DOM/SSR policies |
35
+ | `./expose` | compiler-facing `exposeRefs`, `bindRef`, `bindComponentRef`, and `useTemplateRef` for `defineExpose` and template refs |
36
+ | `./app` | native `createApp` returning `{ mount, unmount }` where `mount(target)` returns the root's exposed instance |
34
37
 
35
38
  `./framework` exports the same lazy `crepusRenderer` compatibility name as the
36
39
  root. Its optional `@tschk/moonshine-framework` peer is needed only when rendering.
@@ -41,14 +44,36 @@ The compatibility root renderer loads source files under Bun. Bundled deployment
41
44
 
42
45
  Legacy peer: `vue` >= 3, needed only for `/vue` and `/compiler-sfc`.
43
46
 
44
- Native `watch` requires `{ flush: "sync" }`; component scheduling, deep watches,
45
- and Vue collection proxies are not implemented by this entry. Plain objects and
47
+ Native `watch` requires `{ flush: "sync" }` and supports `immediate`, `deep`
48
+ (`boolean` or finite depth `number`), `once`, reactive object sources (deep by
49
+ default for `reactive`, depth `1` by default for `shallowReactive` or
50
+ `{ deep: false }`), `onWatcherCleanup(fn, failSilently?)`, and `WatchHandle`
51
+ (`stop()`, `pause()`, `resume()`, and callable `handle()`). Component
52
+ pre/post render scheduling and Vue Map/WeakMap/WeakSet collection proxies are
53
+ not implemented by this entry. Plain objects and
46
54
  arrays are reactive; nested refs unwrap on object properties and retain their
47
55
  identity at integer array entries.
48
- Each watcher run can register multiple cleanup callbacks. Reruns and stops drain
56
+ Each watcher run can register multiple cleanup callbacks (via the callback's
57
+ third parameter or `onWatcherCleanup`). Reruns and stops drain
49
58
  them in registration order, attempt all callbacks after a failure, and preserve
50
59
  the first error. A cleanup that stops its watcher prevents another callback run.
51
60
 
61
+ ### Native Set tracking
62
+
63
+ `reactive(new Set())`, `shallowReactive(new Set())`, `readonly(new Set())`,
64
+ `shallowReadonly(new Set())`, deep refs containing Sets and Sets nested in plain state
65
+ use the independent native graph. Membership reads track individual keys;
66
+ size, iteration and `forEach` track membership changes. Duplicate additions,
67
+ missing deletions and empty clears do not notify. Object entries retain
68
+ raw/proxy membership identity and wrap on iteration in deep `reactive`/`readonly`; stored native refs retain
69
+ their identity. `shallowRef` keeps external Sets raw and tracks replacement only.
70
+ Map/WeakMap/WeakSet reactivity and Set algebra methods remain unsupported. Mutating an original raw Set bypasses notification.
71
+
72
+ The local compiler accepts unshadowed global `Set<T>` prop values. Local `Set`
73
+ bindings, including conservative checks in nested scopes, remain rejected until
74
+ full type-resolution metadata is available. The existing authored counter fixture grows by 730 gzip bytes with
75
+ this support; the default signal kernel remains unchanged. No speed claim.
76
+
52
77
  ### Optional native watch errors
53
78
 
54
79
  `./errors` exports `withComponentErrorHandler(handler, setup)`, which requires a
@@ -76,15 +101,37 @@ configuration or `onErrorCaptured`, and adds no watcher or component frame.
76
101
  and wraps getters in readonly refs without caching their results. Its optional
77
102
  property default applies only to `undefined`; an alias does not make a plain
78
103
  source object reactive. Function-valued properties and
79
- defaults stay literal. `unref` unwraps native refs once and never calls functions.
80
- `isRef` recognizes only this entry's native refs, including computed/getter refs;
104
+ defaults stay literal. `unref` unwraps native refs once and never calls functions;
105
+ `toValue` unwraps native refs and invokes zero-argument getter functions while
106
+ keeping `ref(fn)` function values literal.
107
+ `isRef` recognizes only this entry's native refs, including computed/getter/custom refs;
81
108
  it does not accept Vue host refs or objects with a spoofed `__v_isRef` flag.
82
109
 
83
110
  `shallowRef` stores raw values unchanged and tracks replacement of `.value` using
84
111
  `Object.is` equality. It preserves existing native refs, existing reactive proxies,
85
- and literal function values. Nested raw mutations do not notify; an already
86
- reactive proxy keeps its own tracking. This supports external snapshots without
87
- deep conversion. `triggerRef` is not implemented.
112
+ and literal function values. Nested raw mutations do not notify automatically;
113
+ calling `triggerRef(ref)` forces subscribers (including `computed`, `watchSyncEffect`,
114
+ and synchronous `watch`) to re-evaluate after in-place mutations. `customRef((track, trigger) => ({ get, set }))`
115
+ creates a native ref with explicit dependency tracking and notification control.
116
+
117
+ `shallowReactive` tracks root-level object properties, array indices/length/mutations,
118
+ and `Set` membership without deep wrapping or nested ref unwrapping. `readonly`
119
+ creates a deep read-only view over plain objects, arrays, `Set`s, reactive proxies,
120
+ and refs (forwarding reactive tracking when wrapping a reactive target while throwing
121
+ `TypeError` on writes, deletes, `defineProperty`, or `Set` mutations); `shallowReadonly`
122
+ enforces read-only access only at the root level. `markRaw` marks an object or `Set`
123
+ so `reactive`, `shallowReactive`, `readonly`, `shallowReadonly`, and `ref` return it
124
+ unwrapped (both at root and nested positions), and `toRaw` unwraps any native proxy
125
+ layer back to the underlying raw object. `isReactive`, `isReadonly`, `isShallow`,
126
+ and `isProxy` inspect native proxy and ref flags.
127
+
128
+ `effectScope(detached?)`, `EffectScope`, `getCurrentScope()`, and `onScopeDispose(fn, failSilently?)`
129
+ manage grouped reactive ownership (`watch`, `watchSyncEffect`, `computed`, nested
130
+ non-detached `effectScope`s, and `onScopeDispose` callbacks). Non-detached scopes
131
+ attach to the enclosing active `EffectScope` or native component/root owner;
132
+ detached scopes (`effectScope(true)`) remain active until their own `.stop()` is called.
133
+ Inside native component initialization, `getCurrentScope()` and `onScopeDispose()`
134
+ bind to the component's scope and clean up on component unmount.
88
135
 
89
136
  Native computed refs are lazy and cached, propagate previous successful values,
90
137
  and keep writable setters. Stopping an owner releases its watchers without
@@ -100,62 +147,203 @@ handlers, non-finite defaults and unsupported Boolean prop variants still diagno
100
147
  scheduling, effectful parent getter timing, general component composition and
101
148
  the VNode ABI remain incomplete. These compiler changes are local and unreleased.
102
149
 
103
- Native `./context` provides `provide`, `inject`, `hasInjectionContext`, and typed
104
- `InjectionKey` symbols during synchronous native component initialization. Injection
150
+ The local compiler also accepts ordinary props-less `<script setup>` components,
151
+ including empty setup, constants, JavaScript/TypeScript counters and imported
152
+ children. It supplies an empty props type when no props macro is present, after
153
+ the existing macro, import and async-setup validation. Components that declare
154
+ typed props keep their existing contract. This removes an unnecessary
155
+ `defineProps` declaration; it adds no attrs fallthrough, Options API or host VNode
156
+ support. The compiler work is unpublished. Set
157
+ `MOONSHINE_CREPUS_COMPILER` to the local compiler to enable the isolated source
158
+ regression in `test/standalone.test.ts`.
159
+
160
+ The local compiler lowers text and numeric input/textarea `v-model` to the opt-in
161
+ `./model` DOM factory and `./model/ssr` server factory. Plain models and `.lazy`,
162
+ `.trim`, `.number` use the independent graph, including IME composition handling,
163
+ focused trimming, empty numeric strings and owner cleanup. Writable setup
164
+ `ref`/`shallowRef` targets and member targets rooted in setup refs or `reactive`
165
+ objects are supported. Input types must be static text, search, tel, url, email,
166
+ password, number or range; textarea children and explicit value/defaultValue
167
+ conflicts reject. Static checkbox/radio models also compile locally: scalar typed
168
+ true/false values, loose array membership in click order, identity-based Sets,
169
+ programmatic Set updates and listener cleanup use independent factories.
170
+ Checked-model modifiers and file models remain unsupported,
171
+ as do dynamic types and readonly/unknown targets. Source lowering
172
+ is local and unpublished; this does not implement Vue directives or hydration.
173
+
174
+ Checked models match eleven direct browser cases and thirteen authored SFC phases
175
+ against Vue 3.5.13. Source SSR follows Vue's distinct root/nested policy: empty
176
+ Sets are truthy on the server, while DOM Set membership is identity-based;
177
+ nested scalar models use `true-value`, while root fallthrough SSR uses scalar
178
+ truthiness. Explicit checked attributes remain meaningful. Repeated Bun and
179
+ minified Node SSR compare all structure, attributes and text, ignoring only
180
+ attribute order and equivalent checked-attribute spelling. This is mount/SSR
181
+ support, without hydration. The existing counter bundle has no size change;
182
+ the compared form workload is 9,957 gzip bytes native versus 21,855 for Vue.
183
+ These are fixture sizes, without a startup or runtime speed claim.
184
+
185
+ Native `./select` supports single/multiple select models with inline options and
186
+ optgroups, typed option values, `.number`, Array/Set outputs and owner cleanup.
187
+ Undefined models do not adopt authored defaults. Arrays use loose membership;
188
+ Sets retain identity. Accepted writes preserve the user's duplicate option choice;
189
+ later authored component updates reconcile selection through the existing Vue
190
+ scheduler. Typed option updates and programmatic Set changes remain reactive.
191
+ `./select/ssr` follows source SSR selection, including duplicate selected options,
192
+ null models with omitted option values, and distinct Set behavior. It does not
193
+ infer an omitted option value from its label on the server. These DOM/SSR
194
+ policies intentionally differ, matching the compared Vue source behavior.
195
+
196
+ The local Crepus compiler supplies the select/option factories and writable-target
197
+ checks. Other select modifiers, nested selects, component-supplied options and
198
+ non-option markup in selects reject. Hydration remains unsupported. Eight direct
199
+ Chromium cases, eleven source SSR cases, thirteen actual SFC browser phases, repeated fresh Bun/minified Node SSR and both source
200
+ and declaration-consumer type lanes pass. The existing counter bundle stays
201
+ unchanged. This select fixture is 11,722 gzip bytes versus Vue 3.5.13's 21,900;
202
+ there is no startup/runtime speed claim. Compiler changes remain unpublished.
203
+
204
+ Plain component `v-model` compiles locally when the imported Vue SFC child declares
205
+ `modelValue` in typed props and `update:modelValue` in typed emits, or declares
206
+ `defineModel`. It uses the
207
+ existing live props and event protocol, with no added runtime or dependencies.
208
+ Explicit update listeners retain template attribute order relative to the setter;
209
+ `.once` listeners preserve the distinct DOM/server policies. Readonly targets,
210
+ conflicting explicit model props/listeners and missing child contracts reject.
211
+ Static named and multiple models also compile locally: identifier/kebab arguments
212
+ normalize to canonical child prop names, each with a matching declared update
213
+ event. Listener order is tracked separately for each model. Model props named
214
+ `class` and `style` use the existing component normalizers. Dynamic model arguments
215
+ remain unsupported. Component modifiers compile locally as described
216
+ below. This is source support, not Vue's compiled component ABI or hydration.
217
+
218
+ `@tschk/moonshine-vue/reactive` exports `useModel(props, name, options?)`,
219
+ compiler-facing `createModel`, `ModelRef<T, M, G, S>`, and
220
+ `DefineModelOptions<T, G, S>`. Top-level `const` `defineModel` declarations
221
+ (including `const [model, modifiers] = defineModel<T, M>(...)` and
222
+ `const [model, modifiers] = useModel(props, name, options)`) lower in the local
223
+ Crepus compiler to `createModel`, augmenting the component's public TypeScript
224
+ props type with the model prop (`required` when `{ required: true }` without
225
+ `default`), modifier prop (`modelModifiers`/`modelValueModifiers` or
226
+ `<name>Modifiers`), and `EventListeners<{ "update:<name>": [value: T] }>` while
227
+ registering child `defineModel` metadata for parent `v-model` and boolean-cast
228
+ validation. `createModel` / `useModel` support static and cached factory
229
+ defaults (running factories within the component consumer context for `inject()`
230
+ and preserving function defaults when the model type is a sole function),
231
+ Boolean prop casting, custom `get` and `set` transforms (with normalization
232
+ force-trigger when `set` normalizes an assigned value back to the current model
233
+ value), standalone local state when the parent omits `v-model`, controlled
234
+ parent props, and SSR reads/writes.
235
+
236
+ Thirteen authored parent/child browser phases compare both listener orders,
237
+ `.once`, external parent updates, multiple instances and disposal against Vue
238
+ 3.5.13. Server setup emits are compared across repeated fresh Bun/minified Node
239
+ renders; both source and declaration consumers pass in tsc/tsgo, including invalid
240
+ prop and callback payload checks. Before emit modifier support, this default-model
241
+ fixture was 10,510 gzip bytes versus Vue's 21,104. No startup/runtime speed claim; compiler changes remain
242
+ local and unpublished.
243
+
244
+ The named-model fixture adds fourteen browser phases covering distinct payloads,
245
+ kebab arguments, per-model listener order, `.once`, class/style normalization,
246
+ multiple roots and disposal. Repeated Bun/minified Node SSR setup emits and both
247
+ source/declaration type lanes pass. Before emit modifier support, its production
248
+ browser bundle was 10,983 gzip bytes versus Vue 3.5.13's 21,335 for the same fixture; this is no timing claim.
249
+ These compiler changes remain local and unpublished.
250
+
251
+ Component modifiers now compile locally through the opt-in event protocol.
252
+ `.trim` maps string arguments; `.number` converts every original emitted argument
253
+ with `parseFloat`, retaining the original value on NaN. When both flags are set,
254
+ number conversion uses the original arguments, including their whitespace.
255
+ Regular and once listeners receive the same converted arguments. Custom flags
256
+ are available to children that declare the corresponding modifier prop; they do
257
+ not change payloads automatically. Flag order is preserved and repeated flags
258
+ collapse. Bare models add no modifier object. Explicit `v-model:modelValue.trim`
259
+ passes `modelValueModifiers`, unlike plain `v-model.trim`'s `modelModifiers`,
260
+ preserving Vue's distinct behavior. Empty and `__proto__` modifiers reject.
261
+
262
+ Nine authored cases pass nineteen Chromium phases and repeated fresh
263
+ Bun/minified Node SSR comparisons against Vue 3.5.13. Source and declaration
264
+ consumers pass both typecheckers. Undeclared modifier props still reach the raw
265
+ emitter; Vue's extra root DOM attribute is omitted because native attrs
266
+ fallthrough remains unsupported. Modifier objects have stable identity per native
267
+ component instance. Mutating a modifier object after a parent model update differs
268
+ from Vue: native emits observe that mutation, while Vue emits use the new render's
269
+ raw modifier object. This mutation pattern is not compatible yet. This
270
+ fixture is 10,943 gzip bytes versus Vue's 21,493. The unchanged named-model control
271
+ adds 158 gzip bytes for emit conversion (11,141 versus its previous 10,983);
272
+ the signal kernel stays unchanged. No startup/runtime speed claim. Compiler
273
+ changes remain local and unpublished; dynamic model arguments and hydration
274
+ remain unsupported.
275
+
276
+ Native `./context` provides `provide`, `inject`, `hasInjectionContext`, `useId`, and typed
277
+ `InjectionKey` symbols during synchronous native component initialization (`./reactive` also re-exports `useId`). Injection
105
278
  searches ancestors, never the same component's own providers. Nearest ancestors
106
279
  shadow outer values, including explicitly provided `undefined`; refs stay refs.
107
280
  Defaults are values unless the third argument is `true`, which invokes a missing
108
281
  value's factory untracked. Factories have no Vue public-instance `this` receiver.
109
- Outside initialization, `provide`/`inject` throw; `hasInjectionContext` returns false.
282
+ `useId()` generates deterministic tree-scoped IDs (`v-0`, `v-1`, ...) scoped to the
283
+ root owner of the component/render/SSR tree so DOM and SSR produce identical IDs
284
+ without cross-request or cross-instance counter state.
285
+ Outside initialization, `provide`/`inject`/`useId` throw; `hasInjectionContext` returns false.
110
286
  This supports DOM and SSR component scopes, not Vue app-level injection or
111
287
  `app.runWithContext`, and does not establish full SFC compiler compatibility.
112
288
 
113
289
  ### Optional native lifecycle
114
290
 
115
- `@tschk/moonshine-vue/lifecycle` exports `onMounted`, `onBeforeUnmount`, and
116
- `onUnmounted`. Register synchronously during native component initialization, or
291
+ `@tschk/moonshine-vue/lifecycle` exports `onBeforeMount`, `onMounted`, `onBeforeUnmount`,
292
+ `onUnmounted`, `onErrorCaptured`, and `ErrorCapturedHook`. Register synchronously during native component initialization,
293
+ register `onMounted`/`onBeforeUnmount`/`onUnmounted` inside an `onBeforeMount` callback, or
117
294
  register `onUnmounted` inside an `onMounted` or `onBeforeUnmount` callback.
118
- SSR skips all three. Mounted hooks run after synchronous children and DOM commits,
295
+ SSR skips `onBeforeMount`, `onMounted`, `onBeforeUnmount`, and `onUnmounted` (`onErrorCaptured` remains active in both DOM and SSR for setup/watch error propagation).
296
+ `onBeforeMount` hooks run synchronously as each component's setup finishes before its template nodes are attached to the parent DOM container and before `onMounted` hooks flush.
297
+ Mounted hooks run after synchronous children and DOM commits,
119
298
  with pending component references published first. Disposed components skip queued
120
299
  mounts. Before-unmount hooks run parent first with DOM and watchers still active;
121
300
  unmounted hooks run child first after DOM removal and reactive teardown. Callbacks
122
301
  are untracked; returned cleanup functions are ignored. Mounted callbacks flush
123
302
  pending references first, recheck that the owner is live, then invoke the hook
124
- with its component context. Mounted and before-unmount callbacks restore the previous
303
+ with its component context. Before-mount, mounted, and before-unmount callbacks restore the previous
125
304
  context even when they throw. Registration from an already disposed owner,
126
305
  including an unmounted callback, is rejected.
306
+ `onErrorCaptured(hook)` intercepts descendant component errors (synchronous or asynchronous `watch` getter/callback/effect/cleanup errors and descendant lifecycle hook errors) bottom-up across the native component hierarchy (`hook(err, instance, info)` runs untracked in the capturing ancestor's injection context; returning `false` stops further propagation and prevents unhandled rethrow).
127
307
 
128
308
  This optional entry has no Vue dependency. It does not provide Vue public-instance
129
309
  receivers, app lifecycle, update hooks, async component/Suspense scheduling, or
130
- full SFC compatibility. Crepus lowers named/aliased imports of these three hooks
310
+ full SFC compatibility. Crepus lowers named/aliased imports of these five hooks
131
311
  in the accepted authored source slice. Permanent DOM/SSR fixtures verify nested
132
312
  registration, connected mount/before phases, disconnected child-first cleanup,
133
- two instances and server callback suppression. Template refs and Vue's full
134
- error-handler policy remain unproven. A failed native mounted hook tears down
135
- its owner; the reference can retain the subtree until unmount.
313
+ two instances and server callback suppression. Intrinsic and imported component
314
+ template refs (`ref="x"` and `:ref="'x'"` targeting top-level `const` `ref`,
315
+ `shallowRef`, or `useTemplateRef` setup declarations) publish before `onMounted` hooks run and clear
316
+ to `null` on unmount. Vue's full error-handler policy remains unproven. A failed
317
+ native mounted hook tears down its owner; the reference can retain the subtree
318
+ until unmount.
136
319
 
137
- Callback failures propagate after pending peers and disposal finish. Native
138
- exported-instance reference cleanup remains deferred; Vue template-ref lowering
139
- is still pending.
320
+ Callback failures propagate after pending peers and disposal finish.
140
321
 
141
322
  A watch started under an already disposed native owner throws. Ownerless watches
142
323
  remain manually stoppable.
143
324
 
144
- `./reactive` also exports `watchSyncEffect(effect)`, returning a stop function.
145
- The effect runs immediately and tracks synchronous reads, including conditional
146
- sources. Its supplied cleanup registrar accepts multiple callbacks, including
147
- late registrations while active; registrations after stopping are ignored.
148
- Cleanup runs untracked before reruns and on stop. Writes made by the effect or
149
- its cleanup do not recursively invoke that same effect; cleanup writes remain
150
- visible to the following run. Native owners stop their effects on disposal;
151
- ownerless effects require manual stopping. SSR sync effects run and stop with the
152
- request owner. Promise continuations are not tracked.
325
+ `./reactive` also exports `watchSyncEffect(effect)` and
326
+ `onWatcherCleanup(cleanupFn, failSilently?)`, with `watch` and `watchSyncEffect`
327
+ returning a `WatchHandle` (`stop()`, `pause()`, `resume()`, and callable
328
+ `handle()`). The effect runs immediately and tracks synchronous reads, including
329
+ conditional sources. Its supplied cleanup registrar and `onWatcherCleanup`
330
+ accept multiple callbacks while active; registrations after stopping are ignored
331
+ in `watchSyncEffect` and run immediately in `watch`. Calling `onWatcherCleanup`
332
+ outside an active watcher execution (or inside a `watch` source getter or
333
+ cleanup function) throws unless `failSilently` is `true`. Cleanup runs untracked
334
+ before reruns and on stop. Writes made by the effect or its cleanup do not
335
+ recursively invoke that same effect; cleanup writes remain visible to the
336
+ following run. `pause()` suspends callback/effect reruns while retaining tracked
337
+ dependencies, and `resume()` synchronously flushes if any tracked dependency
338
+ changed while paused. Native owners stop their effects on disposal; ownerless
339
+ effects require manual stopping. SSR sync effects run and stop with the request
340
+ owner. Promise continuations are not tracked.
153
341
 
154
342
  Cleanup attempts every registered callback and propagates the first failure;
155
343
  failed effect runs release their registered cleanup while preserving the effect
156
344
  error. This follows native error handling rather than Vue's app error handler.
157
- This entry does not supply scheduled `watchEffect`, pause/resume handles, or a
158
- Vue component render scheduler.
345
+ This entry does not supply scheduled `watchEffect` / `watchPostEffect` or a Vue
346
+ component render scheduler.
159
347
 
160
348
  `./reactive` exports `toRefs(object)` for destructuring linked properties without
161
349
  losing live reads or writes. It snapshots enumerable string keys (including
@@ -276,12 +464,47 @@ error policy. Render-expression evaluation and fallback, props-job error
276
464
  attribution, and full Vue lifecycle timing remain separate work. The optional `/errors` scope handles watch phases; it does not
277
465
  turn a default factory failure into an app error handler call.
278
466
 
467
+ ### Compiler-facing expose and template refs
468
+
469
+ `@tschk/moonshine-vue/expose` exports `exposeRefs(exposed)` and its
470
+ `ShallowUnwrap<T>` type helper, `bindRef`, `bindComponentRef`, and re-exports
471
+ `useTemplateRef` and `TemplateRef<T>` from `@tschk/moonshine-vue/reactive`.
472
+ `exposeRefs` returns a shallow-unwrapping proxy for `defineExpose(record)` where
473
+ top-level native refs (`ref`, `shallowRef`, `computed`, `toRef`,
474
+ `useTemplateRef`) unwrap on `get` and forward `set` to writable `.value`
475
+ (throwing `TypeError` on readonly refs), while plain values, getters/setters and
476
+ reactive objects retain their descriptors and prototype checks. When a `<script setup>`
477
+ component omits `defineExpose` or calls `defineExpose()`, it exposes an empty
478
+ null-prototype object (`exposeRefs({})`) so component template refs receive a
479
+ non-null exposed instance rather than leaking internal setup bindings.
480
+
481
+ `useTemplateRef<T>(key)` requires active component initialization and a unique
482
+ non-empty string key per component instance, returning a `TemplateRef<T>`
483
+ (`Readonly<Ref<T | null>>`) initialized to `null` whose user `.value = ...`
484
+ setter throws `TypeError` while internal `bindRef` / `bindComponentRef` bindings
485
+ publish and clear the reference.
486
+
487
+ The local Crepus compiler lowers top-level `defineExpose` and static template
488
+ refs (`ref="x"` and `:ref="'x'"` targeting a top-level `const` `ref`,
489
+ `shallowRef`, or `useTemplateRef("x")` setup binding) on intrinsic elements
490
+ (including `<input>`, `<textarea>`, `<select>`, and `<option>` with `v-model`)
491
+ and imported PascalCase components. Intrinsic refs bind through `bindRef` and
492
+ component refs bind through `componentRef` (or `bindComponentRef` for
493
+ `useTemplateRef` targets) with `cleanup: "commit"`, publishing before `onMounted`
494
+ hooks run and clearing to `null` on unmount. In SSR, `defineExpose` runtime
495
+ evaluation and template `ref` attributes are erased while preserving the
496
+ component's `ComponentView<Node, Exports, Props>` return brand. Dynamic ref
497
+ expressions, function refs, and `v-for` ref arrays remain explicit compile errors.
498
+
279
499
  ### Optional native application mount
280
500
 
281
- `@tschk/moonshine-vue/app` exports `createApp(component, props)` for native
282
- component factories, including Crepus-compiled Vue components. Props retain the
283
- factory's public type. The returned native application has only `mount(target)`
284
- and `unmount()`; `mount` returns `void`, not a Vue public instance.
501
+ `@tschk/moonshine-vue/app` exports `createApp(component, props)` and the
502
+ `ComponentExports<C>` type helper for native component factories, including
503
+ Crepus-compiled Vue components. Props retain the factory's public type. The
504
+ returned native application has `mount(target)` and `unmount()`; `mount` returns
505
+ the root component's exposed value (`ComponentExports<typeof component>`, or a
506
+ null-prototype empty object when nothing is exposed), not a full Vue public
507
+ instance (`$el`, `$props`, `$emit`).
285
508
 
286
509
  `mount` accepts a selector, Element or ShadowRoot in the current DOM realm,
287
510
  clears its existing children and mounts one owned root. A private container lease
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tschk/moonshine-vue",
3
- "version": "0.4.4",
3
+ "version": "0.4.49",
4
4
  "description": "Native composition helpers and signal bridges with optional legacy Vue runtime/compiler entries",
5
5
  "license": "ISC",
6
6
  "type": "module",
@@ -15,23 +15,28 @@
15
15
  "./context": "./src/context.ts",
16
16
  "./lifecycle": "./src/lifecycle.ts",
17
17
  "./text": "./src/text.ts",
18
+ "./model": "./src/model.ts",
19
+ "./model/ssr": "./src/model-ssr.ts",
20
+ "./select": "./src/select.ts",
21
+ "./select/ssr": "./src/select-ssr.ts",
18
22
  "./props": "./src/props.ts",
19
23
  "./slots": "./src/slots.ts",
20
24
  "./events": "./src/events.ts",
21
25
  "./normalize": "./src/normalize.ts",
22
26
  "./errors": "./src/errors.ts",
27
+ "./expose": "./src/expose.ts",
23
28
  "./app": "./src/app.ts"
24
29
  },
25
30
  "dependencies": {
26
- "@tschk/moonshine": "^0.4.4",
27
- "@tschk/moonshine-dom": "^0.4.4"
31
+ "@tschk/moonshine": "^0.4.48",
32
+ "@tschk/moonshine-dom": "^0.4.48"
28
33
  },
29
34
  "devDependencies": {
30
35
  "typescript": "7.0.2"
31
36
  },
32
37
  "peerDependencies": {
33
38
  "vue": ">=3",
34
- "@tschk/moonshine-framework": "^0.4.4"
39
+ "@tschk/moonshine-framework": "^0.4.48"
35
40
  },
36
41
  "peerDependenciesMeta": {
37
42
  "vue": {
package/src/app.ts CHANGED
@@ -1,10 +1,50 @@
1
- import { h, render, type DOMChild } from "@tschk/moonshine-dom/dom";
1
+ import { createComponent } from "@tschk/moonshine-dom/component";
2
+ import { flushComponentReferences } from "@tschk/moonshine-dom/component-instance";
3
+ import { render, type DOMChild } from "@tschk/moonshine-dom/dom";
4
+ export type { ShallowUnwrap } from "./expose";
2
5
 
3
- export interface NativeApplication {
4
- mount(target: string | Element | ShadowRoot): void;
6
+ /** Erased return metadata supplied only by the native SFC compiler. */
7
+ declare const componentMetadata: unique symbol;
8
+ export type ComponentView<
9
+ View,
10
+ Exports extends object,
11
+ Props extends object = object,
12
+ > = View & {
13
+ readonly [componentMetadata]?: { props: Props; exports: Exports };
14
+ };
15
+ type Metadata<R> = [R] extends [never]
16
+ ? never
17
+ : typeof componentMetadata extends keyof NonNullable<R>
18
+ ? NonNullable<NonNullable<R>[typeof componentMetadata]>
19
+ : never;
20
+ export type ComponentProps<C extends (...args: never[]) => unknown> = [
21
+ Metadata<ReturnType<C>>,
22
+ ] extends [never]
23
+ ? never
24
+ : Metadata<ReturnType<C>> extends { props: infer P extends object }
25
+ ? P
26
+ : never;
27
+ export type ComponentExports<C extends (...args: never[]) => unknown> = [
28
+ Metadata<ReturnType<C>>,
29
+ ] extends [never]
30
+ ? never
31
+ : Metadata<ReturnType<C>> extends { exports: infer E extends object }
32
+ ? E
33
+ : never;
34
+ type ExportsOf<R> = [Metadata<R>] extends [never]
35
+ ? object
36
+ : Metadata<R> extends { exports: infer E extends object }
37
+ ? E
38
+ : object;
39
+
40
+ export interface NativeApplication<out E extends object = object> {
41
+ mount(target: string | Element | ShadowRoot): E;
5
42
  unmount(): void;
6
43
  }
7
44
 
45
+ const emptyInstance: object = /* @__PURE__ */ Object.freeze(
46
+ /* @__PURE__ */ Object.create(null),
47
+ );
8
48
  const leases = /* @__PURE__ */ new WeakMap<
9
49
  Element | ShadowRoot,
10
50
  NativeApplication
@@ -25,10 +65,10 @@ function content(value: DOMChild): DOMChild {
25
65
  }
26
66
 
27
67
  /** Mount a native compiled/component factory; this does not execute Vue VNodes. */
28
- export function createApp<P extends object>(
29
- component: (props: P) => DOMChild,
68
+ export function createApp<P extends object, R extends DOMChild = DOMChild>(
69
+ component: (props: P) => R,
30
70
  props: P,
31
- ): NativeApplication {
71
+ ): NativeApplication<ExportsOf<R>> {
32
72
  if (typeof component !== "function")
33
73
  throw new TypeError("Native applications require a component factory");
34
74
  if (props === null || typeof props !== "object" || Array.isArray(props))
@@ -43,7 +83,7 @@ export function createApp<P extends object>(
43
83
  stop = undefined;
44
84
  dispose?.();
45
85
  };
46
- const app: NativeApplication = {
86
+ const app: NativeApplication<ExportsOf<R>> = {
47
87
  mount(target) {
48
88
  if (state !== "new")
49
89
  throw new Error("Native application cannot be mounted again");
@@ -63,14 +103,25 @@ export function createApp<P extends object>(
63
103
  // Clearing and disposal can synchronously reenter another app mount.
64
104
  leases.set(container, app);
65
105
  state = "mounting";
106
+ let instance: object | undefined;
66
107
  try {
67
108
  container.replaceChildren();
68
109
  if (stopped()) {
69
110
  release();
70
- return;
111
+ return emptyInstance as ExportsOf<R>;
71
112
  }
72
113
  const dispose = render(
73
- () => h((input: P) => content(component(input)), props),
114
+ () =>
115
+ createComponent(
116
+ (input: P) => content(component(input)),
117
+ props,
118
+ "dom",
119
+ {
120
+ capture: (value) => {
121
+ instance = value;
122
+ },
123
+ },
124
+ ),
74
125
  container,
75
126
  );
76
127
  const finish = () => {
@@ -82,9 +133,11 @@ export function createApp<P extends object>(
82
133
  };
83
134
  if (stopped()) finish();
84
135
  else {
136
+ flushComponentReferences();
85
137
  stop = finish;
86
138
  state = "mounted";
87
139
  }
140
+ return (instance ?? emptyInstance) as ExportsOf<R>;
88
141
  } catch (error) {
89
142
  release();
90
143
  state = "stopped";
package/src/context.ts CHANGED
@@ -5,11 +5,12 @@ import {
5
5
  setContext,
6
6
  type ComponentContext,
7
7
  } from "@tschk/moonshine-dom/component";
8
- import { untrack } from "@tschk/moonshine-dom/reactive";
8
+ import { untrack, type Owner } from "@tschk/moonshine-dom/reactive";
9
9
 
10
10
  declare const injectionType: unique symbol;
11
11
  export type InjectionKey<T> = symbol & { readonly [injectionType]?: T };
12
12
  const providesKey = Symbol("moonshine.vue.provides");
13
+ const idCounters = /* @__PURE__ */ new WeakMap<Owner, { next: number }>();
13
14
  type Provides = {
14
15
  frame: ComponentContext;
15
16
  parent?: Provides;
@@ -57,3 +58,14 @@ export function hasInjectionContext(): boolean {
57
58
  const frame = peekComponentContext();
58
59
  return !!frame?.active && !frame.owner.disposed;
59
60
  }
61
+ export function useId(): string {
62
+ const frame = getComponentContext();
63
+ let root: Owner = frame.owner;
64
+ while (root.parent) root = root.parent;
65
+ let state = idCounters.get(root);
66
+ if (!state) {
67
+ state = { next: 0 };
68
+ idCounters.set(root, state);
69
+ }
70
+ return `v-${state.next++}`;
71
+ }