@tschk/moonshine-vue 0.4.4 → 0.4.80

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/app.ts CHANGED
@@ -1,10 +1,184 @@
1
- import { h, render, type DOMChild } from "@tschk/moonshine-dom/dom";
1
+ import {
2
+ createComponent,
3
+ peekComponentContext,
4
+ type ComponentContext,
5
+ } from "@tschk/moonshine-dom/component";
6
+ import { flushComponentReferences } from "@tschk/moonshine-dom/component-instance";
7
+ import { render, type DOMChild } from "@tschk/moonshine-dom/dom";
8
+ import { getOwner, onCleanup } from "@tschk/moonshine-dom/reactive";
9
+ import { h as hSSR, type SSRChild } from "@tschk/moonshine-dom/ssr";
10
+ import {
11
+ appContextKey,
12
+ peekAppContext,
13
+ withActiveAppContext,
14
+ type AppConfig,
15
+ type AppContextState,
16
+ type InjectionKey,
17
+ } from "./context";
18
+ import { componentErrorKey, type ComponentErrorInfo } from "./error-context";
19
+ export type { AppConfig } from "./context";
20
+ export type { ShallowUnwrap } from "./expose";
2
21
 
3
- export interface NativeApplication {
4
- mount(target: string | Element | ShadowRoot): void;
22
+ /** Erased return metadata supplied only by the native SFC compiler. */
23
+ declare const componentMetadata: unique symbol;
24
+ export type ComponentView<
25
+ View,
26
+ Exports extends object,
27
+ Props extends object = object,
28
+ > = View & {
29
+ readonly [componentMetadata]?: { props: Props; exports: Exports };
30
+ };
31
+ type Metadata<R> = [R] extends [never]
32
+ ? never
33
+ : typeof componentMetadata extends keyof NonNullable<R>
34
+ ? NonNullable<NonNullable<R>[typeof componentMetadata]>
35
+ : never;
36
+ export type ComponentProps<C extends (...args: never[]) => unknown> = [
37
+ Metadata<ReturnType<C>>,
38
+ ] extends [never]
39
+ ? never
40
+ : Metadata<ReturnType<C>> extends { props: infer P extends object }
41
+ ? P
42
+ : never;
43
+ export type ComponentExports<C extends (...args: never[]) => unknown> = [
44
+ Metadata<ReturnType<C>>,
45
+ ] extends [never]
46
+ ? never
47
+ : Metadata<ReturnType<C>> extends { exports: infer E extends object }
48
+ ? E
49
+ : never;
50
+ type ExportsOf<R> = [Metadata<R>] extends [never]
51
+ ? object
52
+ : Metadata<R> extends { exports: infer E extends object }
53
+ ? E
54
+ : object;
55
+
56
+ export interface DirectiveBinding<
57
+ V = any,
58
+ M extends string = string,
59
+ A extends string = string,
60
+ > {
61
+ instance: ComponentContext | null;
62
+ value: V;
63
+ oldValue: V | null;
64
+ arg?: A;
65
+ modifiers: Partial<Record<M, boolean>>;
66
+ dir: ObjectDirective<any, V, M, A>;
67
+ }
68
+
69
+ export type DirectiveHook<
70
+ HostElement = any,
71
+ V = any,
72
+ M extends string = string,
73
+ A extends string = string,
74
+ > = (
75
+ el: HostElement,
76
+ binding: DirectiveBinding<V, M, A>,
77
+ vnode?: null,
78
+ prevVNode?: null,
79
+ ) => void;
80
+
81
+ export interface ObjectDirective<
82
+ HostElement = any,
83
+ V = any,
84
+ M extends string = string,
85
+ A extends string = string,
86
+ > {
87
+ created?: DirectiveHook<HostElement, V, M, A>;
88
+ beforeMount?: DirectiveHook<HostElement, V, M, A>;
89
+ mounted?: DirectiveHook<HostElement, V, M, A>;
90
+ beforeUpdate?: DirectiveHook<HostElement, V, M, A>;
91
+ updated?: DirectiveHook<HostElement, V, M, A>;
92
+ beforeUnmount?: DirectiveHook<HostElement, V, M, A>;
93
+ unmounted?: DirectiveHook<HostElement, V, M, A>;
94
+ getSSRProps?: (
95
+ binding: DirectiveBinding<V, M, A>,
96
+ vnode?: null,
97
+ ) => Record<string, any> | undefined;
98
+ deep?: boolean;
99
+ }
100
+
101
+ export type FunctionDirective<
102
+ HostElement = any,
103
+ V = any,
104
+ M extends string = string,
105
+ A extends string = string,
106
+ > = DirectiveHook<HostElement, V, M, A>;
107
+
108
+ export type Directive<
109
+ HostElement = any,
110
+ V = any,
111
+ M extends string = string,
112
+ A extends string = string,
113
+ > =
114
+ | ObjectDirective<HostElement, V, M, A>
115
+ | FunctionDirective<HostElement, V, M, A>;
116
+
117
+ export type DirectiveArguments = Array<
118
+ | [Directive | undefined]
119
+ | [Directive | undefined, any]
120
+ | [Directive | undefined, any, string]
121
+ | [Directive | undefined, any, string | undefined, Record<string, boolean>]
122
+ >;
123
+
124
+ export type FunctionPlugin<Options = any[]> = Options extends unknown[]
125
+ ? (app: NativeApplication<any>, ...options: Options) => any
126
+ : (app: NativeApplication<any>, options: Options) => any;
127
+
128
+ export type ObjectPlugin<Options = any[]> = {
129
+ install: FunctionPlugin<Options>;
130
+ };
131
+
132
+ export type Plugin<Options = any[]> =
133
+ FunctionPlugin<Options> | ObjectPlugin<Options>;
134
+
135
+ export function definePlugin<Options = any[]>(
136
+ plugin: Plugin<Options>,
137
+ ): Plugin<Options> {
138
+ return plugin;
139
+ }
140
+
141
+ export const renderAppSSRSymbol = /* @__PURE__ */ Symbol(
142
+ "moonshine.vue.app.ssr",
143
+ );
144
+
145
+ export interface NativeApplication<out E extends object = object> {
146
+ readonly version: string;
147
+ readonly config: AppConfig;
148
+ readonly _context: {
149
+ app: NativeApplication<any>;
150
+ config: AppConfig;
151
+ mixins: Array<Record<string, any>>;
152
+ components: Record<string, (...args: any[]) => any>;
153
+ directives: Record<string, Directive>;
154
+ provides: Record<PropertyKey, unknown>;
155
+ };
156
+ use<Options extends unknown[]>(
157
+ plugin: Plugin<Options>,
158
+ ...options: Options
159
+ ): this;
160
+ use<Options>(plugin: Plugin<Options>, options: Options): this;
161
+ provide<T>(key: InjectionKey<T> | string | number, value: T): this;
162
+ runWithContext<T>(fn: () => T): T;
163
+ component(name: string): ((...args: any[]) => any) | undefined;
164
+ component<T extends (...args: any[]) => any>(
165
+ name: string,
166
+ component: T,
167
+ ): this;
168
+ directive(name: string): Directive | undefined;
169
+ directive(name: string, directive: Directive): this;
170
+ mixin(mixin: Record<string, any>): this;
171
+ onUnmount(cb: () => void): void;
172
+ mount(target: string | Element | ShadowRoot): E;
5
173
  unmount(): void;
174
+ readonly [renderAppSSRSymbol]?: () => SSRChild;
6
175
  }
7
176
 
177
+ export type App<E extends object = object> = NativeApplication<E>;
178
+
179
+ const emptyInstance: object = /* @__PURE__ */ Object.freeze(
180
+ /* @__PURE__ */ Object.create(null),
181
+ );
8
182
  const leases = /* @__PURE__ */ new WeakMap<
9
183
  Element | ShadowRoot,
10
184
  NativeApplication
@@ -24,15 +198,68 @@ function content(value: DOMChild): DOMChild {
24
198
  return value;
25
199
  }
26
200
 
201
+ function attachAppOwnerContext(appState: AppContextState): void {
202
+ const scope = getOwner();
203
+ if (!scope) return;
204
+ scope.context = new Map(scope.context);
205
+ scope.context.set(appContextKey, appState);
206
+ scope.context.set(
207
+ componentErrorKey,
208
+ (error: unknown, info: ComponentErrorInfo) => {
209
+ if (appState.config.errorHandler) {
210
+ appState.config.errorHandler(error, info.component, info.phase);
211
+ } else {
212
+ throw error;
213
+ }
214
+ },
215
+ );
216
+ }
217
+
27
218
  /** Mount a native compiled/component factory; this does not execute Vue VNodes. */
28
- export function createApp<P extends object>(
29
- component: (props: P) => DOMChild,
219
+ export function createApp<R extends DOMChild>(
220
+ component: (props?: Record<string, never>) => R,
221
+ ): NativeApplication<ExportsOf<R>>;
222
+ export function createApp<P extends object, R extends DOMChild>(
223
+ component: (props: P) => R,
30
224
  props: P,
31
- ): NativeApplication {
225
+ ): NativeApplication<ExportsOf<R>>;
226
+ export function createApp<
227
+ P extends object = Record<string, any>,
228
+ R extends DOMChild = DOMChild,
229
+ >(component: (props: P) => R, props?: P): NativeApplication<ExportsOf<R>> {
32
230
  if (typeof component !== "function")
33
231
  throw new TypeError("Native applications require a component factory");
34
- if (props === null || typeof props !== "object" || Array.isArray(props))
232
+ const resolvedProps = (arguments.length > 1 ? props : ({} as P)) as P;
233
+ if (
234
+ resolvedProps === null ||
235
+ typeof resolvedProps !== "object" ||
236
+ Array.isArray(resolvedProps)
237
+ )
35
238
  throw new TypeError("Native application props must be an object");
239
+
240
+ const config: AppConfig = {
241
+ errorHandler: undefined,
242
+ warnHandler: undefined,
243
+ globalProperties: {},
244
+ performance: false,
245
+ idPrefix: undefined,
246
+ compilerOptions: {},
247
+ optionMergeStrategies: {},
248
+ throwUnhandledErrorInProduction: false,
249
+ };
250
+
251
+ const appState: AppContextState = {
252
+ provides: new Map(),
253
+ components: new Map(),
254
+ directives: new Map(),
255
+ mixins: [],
256
+ config,
257
+ idState: { next: 0 },
258
+ };
259
+
260
+ const installedPlugins = new Set<unknown>();
261
+ const unmountCallbacks: Array<() => void> = [];
262
+
36
263
  let state: "new" | "mounting" | "mounted" | "stopped" = "new";
37
264
  let stop: (() => void) | undefined;
38
265
  const stopped = () => state === "stopped";
@@ -41,10 +268,48 @@ export function createApp<P extends object>(
41
268
  state = "stopped";
42
269
  const dispose = stop;
43
270
  stop = undefined;
44
- dispose?.();
271
+ let firstError: unknown;
272
+ let hasError = false;
273
+ try {
274
+ dispose?.();
275
+ } catch (err) {
276
+ firstError = err;
277
+ hasError = true;
278
+ }
279
+ for (const cb of unmountCallbacks.splice(0)) {
280
+ try {
281
+ cb();
282
+ } catch (err) {
283
+ if (config.errorHandler) {
284
+ config.errorHandler(err, undefined, "app unmount");
285
+ } else if (!hasError) {
286
+ firstError = err;
287
+ hasError = true;
288
+ }
289
+ }
290
+ }
291
+ if (hasError) {
292
+ throw firstError;
293
+ }
294
+ };
295
+
296
+ const componentsRecord: Record<string, (...args: any[]) => any> = {};
297
+ const directivesRecord: Record<string, Directive> = {};
298
+ const providesRecord: Record<PropertyKey, unknown> = Object.create(null);
299
+
300
+ const appContextObj = {
301
+ get app() {
302
+ return app;
303
+ },
304
+ config,
305
+ mixins: appState.mixins,
306
+ components: componentsRecord,
307
+ directives: directivesRecord,
308
+ provides: providesRecord,
45
309
  };
46
- const app: NativeApplication = {
47
- mount(target) {
310
+
311
+ const app = {
312
+ mount(target: string | Element | ShadowRoot) {
48
313
  if (state !== "new")
49
314
  throw new Error("Native application cannot be mounted again");
50
315
  if (typeof document === "undefined")
@@ -63,16 +328,28 @@ export function createApp<P extends object>(
63
328
  // Clearing and disposal can synchronously reenter another app mount.
64
329
  leases.set(container, app);
65
330
  state = "mounting";
331
+ let instance: object | undefined;
66
332
  try {
67
333
  container.replaceChildren();
68
334
  if (stopped()) {
69
335
  release();
70
- return;
336
+ return emptyInstance as ExportsOf<R>;
71
337
  }
72
- const dispose = render(
73
- () => h((input: P) => content(component(input)), props),
74
- container,
75
- );
338
+ const dispose = render(() => {
339
+ attachAppOwnerContext(appState);
340
+ return withActiveAppContext(appState, () =>
341
+ createComponent(
342
+ (input: P) => content(component(input)),
343
+ resolvedProps,
344
+ "dom",
345
+ {
346
+ capture: (value) => {
347
+ instance = value;
348
+ },
349
+ },
350
+ ),
351
+ );
352
+ }, container);
76
353
  const finish = () => {
77
354
  try {
78
355
  dispose();
@@ -82,9 +359,11 @@ export function createApp<P extends object>(
82
359
  };
83
360
  if (stopped()) finish();
84
361
  else {
362
+ flushComponentReferences();
85
363
  stop = finish;
86
364
  state = "mounted";
87
365
  }
366
+ return (instance ?? emptyInstance) as ExportsOf<R>;
88
367
  } catch (error) {
89
368
  release();
90
369
  state = "stopped";
@@ -92,6 +371,193 @@ export function createApp<P extends object>(
92
371
  }
93
372
  },
94
373
  unmount,
95
- };
374
+ [renderAppSSRSymbol]() {
375
+ appState.idState.next = 0;
376
+ attachAppOwnerContext(appState);
377
+ return withActiveAppContext(appState, () =>
378
+ hSSR(component as unknown as (props: P) => SSRChild, resolvedProps),
379
+ );
380
+ },
381
+ } as NativeApplication<ExportsOf<R>>;
382
+
383
+ Object.defineProperties(app, {
384
+ version: { value: "3.5.13", writable: false, configurable: true },
385
+ config: { value: config, writable: false, configurable: true },
386
+ _context: { value: appContextObj, writable: false, configurable: true },
387
+ use: {
388
+ value(plugin: Plugin<any>, ...options: any[]) {
389
+ if (installedPlugins.has(plugin)) {
390
+ return app;
391
+ }
392
+ if (plugin && typeof (plugin as ObjectPlugin).install === "function") {
393
+ installedPlugins.add(plugin);
394
+ withActiveAppContext(appState, () =>
395
+ (plugin as ObjectPlugin).install(app, ...options),
396
+ );
397
+ } else if (typeof plugin === "function") {
398
+ installedPlugins.add(plugin);
399
+ withActiveAppContext(appState, () =>
400
+ (plugin as (...args: any[]) => any)(app, ...options),
401
+ );
402
+ }
403
+ return app;
404
+ },
405
+ writable: true,
406
+ configurable: true,
407
+ },
408
+ provide: {
409
+ value(key: PropertyKey, value: unknown) {
410
+ appState.provides.set(key, value);
411
+ providesRecord[key] = value;
412
+ return app;
413
+ },
414
+ writable: true,
415
+ configurable: true,
416
+ },
417
+ runWithContext: {
418
+ value<T>(fn: () => T): T {
419
+ return withActiveAppContext(appState, fn);
420
+ },
421
+ writable: true,
422
+ configurable: true,
423
+ },
424
+ component: {
425
+ value(name: string, comp?: (...args: any[]) => any): any {
426
+ if (comp === undefined) {
427
+ return appState.components.get(name);
428
+ }
429
+ appState.components.set(name, comp);
430
+ componentsRecord[name] = comp;
431
+ return app;
432
+ },
433
+ writable: true,
434
+ configurable: true,
435
+ },
436
+ directive: {
437
+ value(name: string, dir?: Directive): any {
438
+ if (dir === undefined) {
439
+ return appState.directives.get(name);
440
+ }
441
+ appState.directives.set(name, dir);
442
+ directivesRecord[name] = dir;
443
+ return app;
444
+ },
445
+ writable: true,
446
+ configurable: true,
447
+ },
448
+ mixin: {
449
+ value(mixin: Record<string, any>) {
450
+ if (!appState.mixins.includes(mixin)) {
451
+ appState.mixins.push(mixin);
452
+ }
453
+ return app;
454
+ },
455
+ writable: true,
456
+ configurable: true,
457
+ },
458
+ onUnmount: {
459
+ value(cb: () => void) {
460
+ if (typeof cb === "function") {
461
+ unmountCallbacks.push(cb);
462
+ }
463
+ },
464
+ writable: true,
465
+ configurable: true,
466
+ },
467
+ });
96
468
  return app;
97
469
  }
470
+
471
+ /** Create an SSR-capable native Vue application instance. */
472
+ export function createSSRApp<P extends object = Record<string, any>, R = any>(
473
+ component: (props: P) => R,
474
+ props?: P,
475
+ ): NativeApplication<ExportsOf<R>> {
476
+ return (
477
+ arguments.length > 1
478
+ ? createApp(component as unknown as (props: P) => DOMChild, props!)
479
+ : createApp(component as unknown as () => DOMChild)
480
+ ) as NativeApplication<ExportsOf<R>>;
481
+ }
482
+
483
+ /** Resolve a globally registered component from the active application context. */
484
+ export function resolveComponent(
485
+ name: string,
486
+ ): ((...args: any[]) => any) | string {
487
+ const appCtx = peekAppContext();
488
+ return appCtx?.components.get(name) ?? name;
489
+ }
490
+
491
+ /** Resolve a globally registered custom directive from the active application context. */
492
+ export function resolveDirective(name: string): Directive | undefined {
493
+ return peekAppContext()?.directives.get(name);
494
+ }
495
+
496
+ /** Apply custom directives to a rendered DOM element or SSR props object. */
497
+ export function withDirectives<T>(node: T, directives: DirectiveArguments): T {
498
+ const instance = peekComponentContext() ?? null;
499
+ if (typeof Element !== "undefined" && node instanceof Element) {
500
+ for (const entry of directives) {
501
+ const dir = entry[0];
502
+ if (!dir) continue;
503
+ const value = entry[1];
504
+ const arg = entry[2];
505
+ const modifiers = entry[3] ?? {};
506
+ const dirObj: ObjectDirective =
507
+ typeof dir === "function" ? { mounted: dir, updated: dir } : dir;
508
+ const binding: DirectiveBinding = {
509
+ instance,
510
+ value,
511
+ oldValue: null,
512
+ arg,
513
+ modifiers,
514
+ dir: dirObj,
515
+ };
516
+ dirObj.created?.(node, binding, null, null);
517
+ dirObj.beforeMount?.(node, binding, null, null);
518
+ dirObj.mounted?.(node, binding, null, null);
519
+ if (getOwner() && (dirObj.beforeUnmount || dirObj.unmounted)) {
520
+ onCleanup(() => {
521
+ dirObj.beforeUnmount?.(node, binding, null, null);
522
+ dirObj.unmounted?.(node, binding, null, null);
523
+ });
524
+ }
525
+ }
526
+ return node;
527
+ }
528
+ if (node !== null && typeof node === "object" && !Array.isArray(node)) {
529
+ const merged: Record<string, any> = { ...(node as Record<string, any>) };
530
+ for (const entry of directives) {
531
+ const dir = entry[0];
532
+ if (!dir || typeof dir === "function") continue;
533
+ const value = entry[1];
534
+ const arg = entry[2];
535
+ const modifiers = entry[3] ?? {};
536
+ const binding: DirectiveBinding = {
537
+ instance,
538
+ value,
539
+ oldValue: null,
540
+ arg,
541
+ modifiers,
542
+ dir,
543
+ };
544
+ const ssrProps = dir.getSSRProps?.(binding, null);
545
+ if (ssrProps && typeof ssrProps === "object") {
546
+ Object.assign(merged, ssrProps);
547
+ }
548
+ }
549
+ return merged as T;
550
+ }
551
+ return node;
552
+ }
553
+
554
+ /** Emit a warning through the active application's `config.warnHandler` or `console.warn`. */
555
+ export function warn(msg: string, ...args: unknown[]): void {
556
+ const appCtx = peekAppContext();
557
+ const instance = peekComponentContext();
558
+ if (appCtx?.config.warnHandler) {
559
+ appCtx.config.warnHandler(msg, instance, "");
560
+ return;
561
+ }
562
+ console.warn(`[Vue warn]: ${msg}`, ...args);
563
+ }