@hamur/adapter-angular 0.0.1 → 0.0.2

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.
@@ -1,127 +1,107 @@
1
- import {
2
- APP_ID,
3
- DestroyRef,
4
- Directive,
5
- InjectionToken,
6
- PendingTasks,
7
- TemplateRef,
8
- ViewContainerRef,
9
- afterNextRender,
10
- assertInInjectionContext,
11
- computed,
12
- inject,
13
- signal,
14
- type Resource,
15
- type ResourceSnapshot,
16
- type Signal,
17
- } from "@angular/core"
18
- import { checkTransitionName, prehydrate, settledOf } from "hamur/adapter"
19
- import { HAMUR_APP, mode, onServer, required } from "./context.ts"
20
-
1
+ import { APP_ID, DestroyRef, Directive, InjectionToken, PendingTasks, TemplateRef, ViewContainerRef, afterNextRender, assertInInjectionContext, computed, inject, signal, } from "@angular/core";
2
+ import { checkTransitionName, prehydrate, settledOf } from "hamur/adapter";
3
+ import { HAMUR_APP, mode, onServer, required } from "./context.ts";
4
+ import * as i0 from "@angular/core";
21
5
  /**
22
6
  * `<div *hamurDevOnly>…</div>` renders its template only in a dev build. A production client keeps the template's code:
23
7
  * a component named in it is a static import of the compiled one.
24
8
  */
25
- @Directive({ selector: "[hamurDevOnly]" })
26
9
  export class DevOnly {
27
- constructor() {
28
- if (mode.dev) inject(ViewContainerRef).createEmbeddedView(inject(TemplateRef))
29
- }
10
+ constructor() {
11
+ if (mode.dev)
12
+ inject(ViewContainerRef).createEmbeddedView(inject(TemplateRef));
13
+ }
14
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.3.2", ngImport: i0, type: DevOnly, deps: [], target: i0.ɵɵFactoryTarget.Directive });
15
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "22.3.2", type: DevOnly, isStandalone: true, selector: "[hamurDevOnly]", ngImport: i0 });
30
16
  }
31
-
32
- const isThenable = (value: unknown): value is PromiseLike<unknown> =>
33
- typeof (value as { then?: unknown } | null)?.then === "function"
34
-
17
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.3.2", ngImport: i0, type: DevOnly, decorators: [{
18
+ type: Directive,
19
+ args: [{ selector: "[hamurDevOnly]" }]
20
+ }], ctorParameters: () => [] });
21
+ const isThenable = (value) => typeof value?.then === "function";
35
22
  /**
36
23
  * The value of a promise a loader returned, as Angular's `Resource<T>`: read with `@if (value.hasValue()) … @else if
37
24
  * (value.error()) … @else …`. On the server the render waits for it; `value()` throws the error of a rejected promise,
38
25
  * as Angular's own resources do.
39
26
  */
40
- export function injectDeferred<T>(promise: PromiseLike<T> | T): Resource<Awaited<T>> {
41
- assertInInjectionContext(injectDeferred)
42
- type V = Awaited<T>
43
- const snapshot = signal<ResourceSnapshot<V | undefined>>({ status: "loading", value: undefined })
44
- const known = isThenable(promise) ? settledOf(promise) : ({ status: "fulfilled", value: promise } as const)
45
- if (known)
46
- snapshot.set(
47
- known.status === "fulfilled"
48
- ? { status: "resolved", value: known.value as V }
49
- : { status: "error", error: errorOf(known.reason) },
50
- )
51
- else {
52
- const done = onServer() ? inject(PendingTasks).add() : undefined
53
- const destroyed = { value: false }
54
- inject(DestroyRef).onDestroy(() => (destroyed.value = true))
55
- Promise.resolve(promise as PromiseLike<V>).then(
56
- (value) => {
57
- if (!destroyed.value) snapshot.set({ status: "resolved", value })
58
- done?.()
59
- },
60
- (reason: unknown) => {
61
- if (!destroyed.value) snapshot.set({ status: "error", error: errorOf(reason) })
62
- done?.()
63
- },
64
- )
65
- }
66
- const read = snapshot.asReadonly()
67
- return {
68
- value: computed(() => {
69
- const current = read()
70
- if (current.status === "error") throw current.error
71
- return current.value
72
- }),
73
- status: computed(() => read().status),
74
- error: computed(() => {
75
- const current = read()
76
- return current.status === "error" ? current.error : undefined
77
- }),
78
- isLoading: computed(() => read().status === "loading"),
79
- snapshot: read,
80
- hasValue: () => {
81
- const current = read()
82
- return current.status === "resolved"
83
- },
84
- } as unknown as Resource<V>
27
+ export function injectDeferred(promise) {
28
+ assertInInjectionContext(injectDeferred);
29
+ const snapshot = signal({ status: "loading", value: undefined }, /* @ts-ignore */
30
+ ...(ngDevMode ? [{ debugName: "snapshot" }] : /* istanbul ignore next */ []));
31
+ const known = isThenable(promise) ? settledOf(promise) : { status: "fulfilled", value: promise };
32
+ if (known)
33
+ snapshot.set(known.status === "fulfilled"
34
+ ? { status: "resolved", value: known.value }
35
+ : { status: "error", error: errorOf(known.reason) });
36
+ else {
37
+ const done = onServer() ? inject(PendingTasks).add() : undefined;
38
+ const destroyed = { value: false };
39
+ inject(DestroyRef).onDestroy(() => (destroyed.value = true));
40
+ Promise.resolve(promise).then((value) => {
41
+ if (!destroyed.value)
42
+ snapshot.set({ status: "resolved", value });
43
+ done?.();
44
+ }, (reason) => {
45
+ if (!destroyed.value)
46
+ snapshot.set({ status: "error", error: errorOf(reason) });
47
+ done?.();
48
+ });
49
+ }
50
+ const read = snapshot.asReadonly();
51
+ return {
52
+ value: computed(() => {
53
+ const current = read();
54
+ if (current.status === "error")
55
+ throw current.error;
56
+ return current.value;
57
+ }),
58
+ status: computed(() => read().status),
59
+ error: computed(() => {
60
+ const current = read();
61
+ return current.status === "error" ? current.error : undefined;
62
+ }),
63
+ isLoading: computed(() => read().status === "loading"),
64
+ snapshot: read,
65
+ hasValue: () => {
66
+ const current = read();
67
+ return current.status === "resolved";
68
+ },
69
+ };
85
70
  }
86
-
87
- const errorOf = (reason: unknown): Error => (reason instanceof Error ? reason : new Error(String(reason)))
88
-
71
+ const errorOf = (reason) => (reason instanceof Error ? reason : new Error(String(reason)));
89
72
  /** `false` on the server and until the first render of a hydrated page is done; `true` at once after a client navigation. */
90
- export function injectHydrated(): Signal<boolean> {
91
- assertInInjectionContext(injectHydrated)
92
- const app = required(HAMUR_APP, "injectHydrated")
93
- const hydrated = signal(typeof document !== "undefined" && !onServer() && !app.asyncData.hydrating)
94
- const destroy = inject(DestroyRef)
95
- afterNextRender(() => {
96
- hydrated.set(!app.asyncData.hydrating)
97
- destroy.onDestroy(app.hooks.hook("app:mounted", () => hydrated.set(true)))
98
- })
99
- return hydrated.asReadonly()
73
+ export function injectHydrated() {
74
+ assertInInjectionContext(injectHydrated);
75
+ const app = required(HAMUR_APP, "injectHydrated");
76
+ const hydrated = signal(typeof document !== "undefined" && !onServer() && !app.asyncData.hydrating, /* @ts-ignore */
77
+ ...(ngDevMode ? [{ debugName: "hydrated" }] : /* istanbul ignore next */ []));
78
+ const destroy = inject(DestroyRef);
79
+ afterNextRender(() => {
80
+ hydrated.set(!app.asyncData.hydrating);
81
+ destroy.onDestroy(app.hooks.hook("app:mounted", () => hydrated.set(true)));
82
+ });
83
+ return hydrated.asReadonly();
100
84
  }
101
-
102
85
  /** The counter `injectId` reads; a server-only component's render has one of its own, with a prefix, so it leaves the page's numbering alone. */
103
- export const HAMUR_IDS = new InjectionToken<{ next: number; prefix: string }>("hamur ids", {
104
- providedIn: "root",
105
- factory: () => ({ next: 0, prefix: "" }),
106
- })
107
-
86
+ export const HAMUR_IDS = new InjectionToken("hamur ids", {
87
+ providedIn: "root",
88
+ factory: () => ({ next: 0, prefix: "" }),
89
+ });
108
90
  /**
109
91
  * An id that is the same in the server's HTML and in hydration, `<APP_ID>-<n>`: Angular 22 has no id function of
110
92
  * its own, and the components of both renders are created in the same order.
111
93
  */
112
- export function injectId(): string {
113
- assertInInjectionContext(injectId)
114
- const counter = inject(HAMUR_IDS)
115
- return `${counter.prefix}${inject(APP_ID)}-${counter.next++}`
94
+ export function injectId() {
95
+ assertInInjectionContext(injectId);
96
+ const counter = inject(HAMUR_IDS);
97
+ return `${counter.prefix}${inject(APP_ID)}-${counter.next++}`;
116
98
  }
117
-
118
99
  /** The id for `data-hamur-p` on the element `fn` is called with, as an inline script before hydration; `undefined` in the browser. */
119
- export function onPrehydrate(fn: (el: Element) => void): string | undefined {
120
- assertInInjectionContext(onPrehydrate)
121
- return prehydrate(required(HAMUR_APP, "onPrehydrate"), fn)
100
+ export function onPrehydrate(fn) {
101
+ assertInInjectionContext(onPrehydrate);
102
+ return prehydrate(required(HAMUR_APP, "onPrehydrate"), fn);
122
103
  }
123
-
124
104
  /** The `[style]` that names an element for a view transition. */
125
- export function transitionName(name: string): { "view-transition-name": string } {
126
- return { "view-transition-name": checkTransitionName(name) }
105
+ export function transitionName(name) {
106
+ return { "view-transition-name": checkTransitionName(name) };
127
107
  }
package/src/compile.ts CHANGED
@@ -8,7 +8,8 @@ import type { AdapterBuildContext, AdapterTransform } from "hamur/adapter"
8
8
  import { readDefinition, selectorOf } from "./definition.ts"
9
9
 
10
10
  const COMPILE_ID = /^(?!.*[\\/]node_modules[\\/]).*\.[cm]?ts$/
11
- const LINK_ID = /[\\/]node_modules[\\/].+\.m?js$/
11
+ /** Packages of the `@hamur` scope ship their partial-compiled components under the name of the source, `src/<name>.ts`. */
12
+ const LINK_ID = /[\\/]node_modules[\\/](?:.+\.m?js|(?:.+[\\/])?@hamur[\\/][^\\/]+[\\/]src[\\/].+\.ts)$/
12
13
 
13
14
  const SCRIPT = /\.[cm]?ts$/
14
15
  const DECORATED = /^\s*@(?:Component|Directive|Pipe|NgModule|Injectable)\s*\(/m
@@ -40,6 +41,8 @@ interface Angular {
40
41
  export interface AngularEmit {
41
42
  code: string
42
43
  map?: string
44
+ /** The declarations, emitted by `compilePartial` only. */
45
+ types?: string
43
46
  }
44
47
 
45
48
  /** One error line of the program, with the real path of the file it names. */
@@ -259,6 +262,7 @@ function compilerHost(ng: Angular, options: AngularCli.CompilerOptions, setup: H
259
262
  const key = real(source.fileName)
260
263
  const entry = setup.files.get(key) ?? { code: "" }
261
264
  if (fileName.endsWith(".map")) entry.map = text
265
+ else if (fileName.endsWith(".d.ts")) entry.types = text
262
266
  else if (/\.[cm]?js$/.test(fileName)) entry.code = text.replace(MAP_COMMENT, "")
263
267
  else return
264
268
  setup.files.set(key, entry)
@@ -922,8 +926,8 @@ export function linkStep(ctx: AdapterBuildContext): AdapterTransform {
922
926
  }
923
927
  }
924
928
 
925
- /** The package's own components in `compilationMode: "partial"`, as `scripts/release.ts` publishes them: real source path to JavaScript. */
926
- export async function compilePartial(packageDir: string, from = packageDir): Promise<Map<string, string>> {
929
+ /** The package's own components in `compilationMode: "partial"`, as `scripts/release.ts` publishes them: real source path to JavaScript and declarations. */
930
+ export async function compilePartial(packageDir: string, from = packageDir): Promise<Map<string, AngularEmit>> {
927
931
  const ng = await loadAngular(from)
928
932
  const roots = scripts(join(packageDir, "src")).filter(
929
933
  (file) => !file.endsWith(".test.ts") && DECORATED.test(readFileSync(file, "utf8")),
@@ -944,7 +948,7 @@ export async function compilePartial(packageDir: string, from = packageDir): Pro
944
948
  strictTemplates: true,
945
949
  skipLibCheck: true,
946
950
  allowImportingTsExtensions: true,
947
- declaration: false,
951
+ declaration: true,
948
952
  noEmit: false,
949
953
  },
950
954
  undefined,
@@ -953,7 +957,7 @@ export async function compilePartial(packageDir: string, from = packageDir): Pro
953
957
  return new Map(
954
958
  roots.flatMap((file) => {
955
959
  const emitted = files.get(real(file))
956
- return emitted ? [[real(file), emitted.code] as const] : []
960
+ return emitted ? [[real(file), emitted] as const] : []
957
961
  }),
958
962
  )
959
963
  }
package/src/error-page.ts CHANGED
@@ -1,17 +1,30 @@
1
- import { Component, input } from "@angular/core"
2
- import type { ErrorPageProps } from "hamur/app"
3
-
4
- @Component({
5
- template: `<main style="font-family: system-ui, sans-serif; text-align: center; padding: 4rem 1rem">
1
+ import { Component, input } from "@angular/core";
2
+ import * as i0 from "@angular/core";
3
+ export default class DefaultErrorPage {
4
+ error = input.required(/* @ts-ignore */
5
+ ...(ngDevMode ? [{ debugName: "error" }] : /* istanbul ignore next */ []));
6
+ clearError = input(/* @ts-ignore */
7
+ ...(ngDevMode ? [undefined, { debugName: "clearError" }] : /* istanbul ignore next */ []));
8
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.3.2", ngImport: i0, type: DefaultErrorPage, deps: [], target: i0.ɵɵFactoryTarget.Component });
9
+ static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "22.3.2", type: DefaultErrorPage, isStandalone: true, selector: "ng-component", inputs: { error: { classPropertyName: "error", publicName: "error", isSignal: true, isRequired: true, transformFunction: null }, clearError: { classPropertyName: "clearError", publicName: "clearError", isSignal: true, isRequired: false, transformFunction: null } }, ngImport: i0, template: `<main style="font-family: system-ui, sans-serif; text-align: center; padding: 4rem 1rem">
6
10
  <h1 style="font-size: 4rem; margin: 0">{{ error().status }}</h1>
7
11
  <p>{{ error().message }}</p>
8
12
  @if (error().stack) {
9
13
  <pre>{{ error().stack }}</pre>
10
14
  }
11
15
  <a href="/">Back home</a>
12
- </main>`,
13
- })
14
- export default class DefaultErrorPage {
15
- readonly error = input.required<ErrorPageProps>()
16
- readonly clearError = input<() => void>()
16
+ </main>`, isInline: true });
17
17
  }
18
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.3.2", ngImport: i0, type: DefaultErrorPage, decorators: [{
19
+ type: Component,
20
+ args: [{
21
+ template: `<main style="font-family: system-ui, sans-serif; text-align: center; padding: 4rem 1rem">
22
+ <h1 style="font-size: 4rem; margin: 0">{{ error().status }}</h1>
23
+ <p>{{ error().message }}</p>
24
+ @if (error().stack) {
25
+ <pre>{{ error().stack }}</pre>
26
+ }
27
+ <a href="/">Back home</a>
28
+ </main>`,
29
+ }]
30
+ }], propDecorators: { error: [{ type: i0.Input, args: [{ isSignal: true, alias: "error", required: true }] }], clearError: [{ type: i0.Input, args: [{ isSignal: true, alias: "clearError", required: false }] }] } });