@hamur/adapter-angular 0.0.0-stage → 0.0.1

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.
Files changed (88) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +42 -2
  3. package/dist/chunks/browser-index-7h7x2xz2.js +131 -0
  4. package/dist/chunks/browser-index-nann848q.js +205 -0
  5. package/dist/chunks/browser-index-qn8q5fa2.js +580 -0
  6. package/dist/src/adapter.js +1073 -0
  7. package/dist/src/error-page.js +34 -0
  8. package/dist/src/index.js +1729 -0
  9. package/dist/src/keepalive.js +0 -0
  10. package/dist/src/runtime/client.js +21 -0
  11. package/dist/src/runtime/island.js +92 -0
  12. package/dist/src/runtime/server.js +175 -0
  13. package/dist/types/src/activation.d.ts +20 -0
  14. package/dist/types/src/adapter.d.ts +7 -0
  15. package/dist/types/src/app.d.ts +3 -0
  16. package/dist/types/src/async-data.d.ts +21 -0
  17. package/dist/types/src/client-parts.d.ts +32 -0
  18. package/dist/types/src/compile.d.ts +97 -0
  19. package/dist/types/src/context.d.ts +74 -0
  20. package/dist/types/src/data.d.ts +65 -0
  21. package/dist/types/src/definition.d.ts +13 -0
  22. package/dist/types/src/error-page.d.ts +5 -0
  23. package/dist/types/src/error.d.ts +4 -0
  24. package/dist/types/src/form.d.ts +65 -0
  25. package/dist/types/src/head.d.ts +12 -0
  26. package/dist/types/src/hmr.d.ts +14 -0
  27. package/dist/types/src/hydration.d.ts +16 -0
  28. package/dist/types/src/index.d.ts +24 -0
  29. package/dist/types/src/indicators.d.ts +69 -0
  30. package/dist/types/src/island.d.ts +39 -0
  31. package/dist/types/src/keepalive.d.ts +1 -0
  32. package/dist/types/src/link.d.ts +65 -0
  33. package/dist/types/src/markdown-page.d.ts +10 -0
  34. package/dist/types/src/markdown.d.ts +37 -0
  35. package/dist/types/src/mask.d.ts +12 -0
  36. package/dist/types/src/navigate.d.ts +14 -0
  37. package/dist/types/src/outlet.d.ts +71 -0
  38. package/dist/types/src/request.d.ts +31 -0
  39. package/dist/types/src/routing.d.ts +47 -0
  40. package/dist/types/src/runtime/client.d.ts +29 -0
  41. package/dist/types/src/runtime/hydration-dev.d.ts +1 -0
  42. package/dist/types/src/runtime/hydration.d.ts +8 -0
  43. package/dist/types/src/runtime/island.d.ts +8 -0
  44. package/dist/types/src/runtime/server.d.ts +15 -0
  45. package/dist/types/src/server-island.d.ts +21 -0
  46. package/dist/types/src/state.d.ts +14 -0
  47. package/dist/types/src/svg.d.ts +15 -0
  48. package/dist/types/src/time.d.ts +37 -0
  49. package/dist/types/src/wrapper.d.ts +21 -0
  50. package/package.json +56 -4
  51. package/src/activation.ts +83 -0
  52. package/src/adapter.ts +107 -0
  53. package/src/app.ts +6 -0
  54. package/src/async-data.ts +105 -0
  55. package/src/client-parts.ts +127 -0
  56. package/src/compile.ts +959 -0
  57. package/src/context.ts +189 -0
  58. package/src/data.ts +389 -0
  59. package/src/definition.ts +144 -0
  60. package/src/error-page.ts +17 -0
  61. package/src/error.ts +15 -0
  62. package/src/form.ts +253 -0
  63. package/src/head.ts +63 -0
  64. package/src/hmr.ts +61 -0
  65. package/src/hydration.ts +120 -0
  66. package/src/index.ts +98 -0
  67. package/src/indicators.ts +251 -0
  68. package/src/island.ts +95 -0
  69. package/src/keepalive.ts +1 -0
  70. package/src/link.ts +251 -0
  71. package/src/markdown-page.ts +31 -0
  72. package/src/markdown.ts +170 -0
  73. package/src/mask.ts +36 -0
  74. package/src/navigate.ts +19 -0
  75. package/src/outlet.ts +344 -0
  76. package/src/request.ts +170 -0
  77. package/src/routing.ts +218 -0
  78. package/src/runtime/client.ts +140 -0
  79. package/src/runtime/contract.d.ts +4 -0
  80. package/src/runtime/hydration-dev.ts +18 -0
  81. package/src/runtime/hydration.ts +7 -0
  82. package/src/runtime/island.ts +109 -0
  83. package/src/runtime/server.ts +228 -0
  84. package/src/server-island.ts +54 -0
  85. package/src/state.ts +70 -0
  86. package/src/svg.ts +65 -0
  87. package/src/time.ts +108 -0
  88. package/src/wrapper.ts +187 -0
package/src/request.ts ADDED
@@ -0,0 +1,170 @@
1
+ import {
2
+ DestroyRef,
3
+ afterNextRender,
4
+ assertInInjectionContext,
5
+ computed,
6
+ inject,
7
+ signal,
8
+ type Signal,
9
+ type WritableSignal,
10
+ } from "@angular/core"
11
+ import {
12
+ APP_UPDATE_OFF,
13
+ createAppUpdate,
14
+ isOnline,
15
+ pollInterval,
16
+ runtimeConfigOf,
17
+ siteConfigOf,
18
+ startPoll,
19
+ subscribeOnline,
20
+ whenAppReady,
21
+ } from "hamur/adapter"
22
+ import type { AppUpdateActions, AppUpdateState } from "hamur/adapter"
23
+ import {
24
+ reportWebVitals,
25
+ setResponseStatus as setResponseStatusOf,
26
+ usePreviewMode as previewModeOf,
27
+ useRequestEvent as requestEventOf,
28
+ useRequestFetch as requestFetchOf,
29
+ useRequestHeader as requestHeaderOf,
30
+ useRequestHeaders as requestHeadersOf,
31
+ useRequestURL as requestURLOf,
32
+ useResponseHeader as responseHeaderOf,
33
+ } from "hamur/app"
34
+ import type {
35
+ $Fetch,
36
+ AppContext,
37
+ AppHooks,
38
+ ClientRuntimeConfig,
39
+ PreviewMode,
40
+ SiteConfig,
41
+ WebVitalMetric,
42
+ } from "hamur/app"
43
+ import type { HamurEvent } from "hamur/server"
44
+ import { HAMUR_APP, HAMUR_ROUTER, required } from "./context.ts"
45
+ import { writableOf } from "./state.ts"
46
+
47
+ const appOf = (name: string): AppContext => required(HAMUR_APP, name)
48
+
49
+ export function injectApp(): AppContext {
50
+ assertInInjectionContext(injectApp)
51
+ return appOf("injectApp")
52
+ }
53
+
54
+ export function injectRuntimeConfig(): ClientRuntimeConfig {
55
+ assertInInjectionContext(injectRuntimeConfig)
56
+ return runtimeConfigOf(appOf("injectRuntimeConfig"))
57
+ }
58
+
59
+ export function injectSiteConfig(): SiteConfig {
60
+ assertInInjectionContext(injectSiteConfig)
61
+ return siteConfigOf(appOf("injectSiteConfig"))
62
+ }
63
+
64
+ /** A hook of the app, removed when the component is destroyed. */
65
+ export function injectRuntimeHook<K extends keyof AppHooks>(name: K, fn: AppHooks[K]): void {
66
+ assertInInjectionContext(injectRuntimeHook)
67
+ inject(DestroyRef).onDestroy(appOf("injectRuntimeHook").hooks.hook(name, fn))
68
+ }
69
+
70
+ export function injectReportWebVitals(fn: (metric: WebVitalMetric) => void | Promise<void>): void {
71
+ assertInInjectionContext(injectReportWebVitals)
72
+ inject(DestroyRef).onDestroy(reportWebVitals(appOf("injectReportWebVitals"), fn))
73
+ }
74
+
75
+ export function onAppReady(fn: () => void | Promise<void>): void {
76
+ assertInInjectionContext(onAppReady)
77
+ whenAppReady(appOf("onAppReady"), fn)
78
+ }
79
+
80
+ /** Preview mode: enabled by the payload's `draft` or by `?preview=true` on the first URL. */
81
+ export function injectPreviewMode(): PreviewMode {
82
+ assertInInjectionContext(injectPreviewMode)
83
+ return previewModeOf(appOf("injectPreviewMode"))
84
+ }
85
+
86
+ export function injectRequestEvent(): HamurEvent | undefined {
87
+ assertInInjectionContext(injectRequestEvent)
88
+ return requestEventOf(appOf("injectRequestEvent"))
89
+ }
90
+
91
+ export function injectRequestHeaders(names?: readonly string[]): Record<string, string> {
92
+ assertInInjectionContext(injectRequestHeaders)
93
+ return requestHeadersOf(appOf("injectRequestHeaders"), names)
94
+ }
95
+
96
+ export function injectRequestHeader(name: string): string | undefined {
97
+ assertInInjectionContext(injectRequestHeader)
98
+ return requestHeaderOf(appOf("injectRequestHeader"), name)
99
+ }
100
+
101
+ export function injectRequestURL(): URL {
102
+ assertInInjectionContext(injectRequestURL)
103
+ return requestURLOf(appOf("injectRequestURL"))
104
+ }
105
+
106
+ export function injectRequestFetch(): $Fetch {
107
+ assertInInjectionContext(injectRequestFetch)
108
+ return requestFetchOf(appOf("injectRequestFetch"))
109
+ }
110
+
111
+ /** Sets the status of the page's answer; does nothing in the browser. */
112
+ export function setResponseStatus(status: number, statusText?: string): void {
113
+ assertInInjectionContext(setResponseStatus)
114
+ setResponseStatusOf(appOf("setResponseStatus"), status, statusText)
115
+ }
116
+
117
+ /** A header of the page's answer; a write sets it, `undefined` removes it. */
118
+ export function injectResponseHeader(name: string): WritableSignal<string | undefined> {
119
+ assertInInjectionContext(injectResponseHeader)
120
+ const header = responseHeaderOf(appOf("injectResponseHeader"), name)
121
+ const read = signal<string | undefined>(header.get())
122
+ return writableOf(read, (value) => {
123
+ header.set(value)
124
+ read.set(header.get())
125
+ })
126
+ }
127
+
128
+ /** `true` until the browser reports otherwise; set after the first render, so the server's HTML and the hydration agree. */
129
+ export function injectOnline(): Signal<boolean> {
130
+ assertInInjectionContext(injectOnline)
131
+ const online = signal(true)
132
+ const destroy = inject(DestroyRef)
133
+ afterNextRender(() => {
134
+ online.set(isOnline())
135
+ destroy.onDestroy(subscribeOnline((value) => online.set(value)))
136
+ })
137
+ return online.asReadonly()
138
+ }
139
+
140
+ /** `refresh({ keys })` every `ms` while the document is visible, from the first render until the component is destroyed. */
141
+ export function injectPoll(ms: number, options: { keys?: string[] } = {}): void {
142
+ assertInInjectionContext(injectPoll)
143
+ pollInterval(ms)
144
+ const router = required(HAMUR_ROUTER, "injectPoll")
145
+ const destroy = inject(DestroyRef)
146
+ afterNextRender(() =>
147
+ destroy.onDestroy(startPoll(ms, () => (options.keys ? router.refresh(options.keys) : router.refresh()))),
148
+ )
149
+ }
150
+
151
+ export function injectAppUpdate(): { [K in keyof AppUpdateState]: Signal<AppUpdateState[K]> } & AppUpdateActions {
152
+ assertInInjectionContext(injectAppUpdate)
153
+ const store = createAppUpdate(appOf("injectAppUpdate"))
154
+ const state = signal<AppUpdateState>(APP_UPDATE_OFF)
155
+ const destroy = inject(DestroyRef)
156
+ afterNextRender(() => {
157
+ state.set(store.get())
158
+ destroy.onDestroy(store.subscribe(() => state.set(store.get())))
159
+ })
160
+ return {
161
+ available: computedOf(state, "available"),
162
+ buildId: computedOf(state, "buildId"),
163
+ time: computedOf(state, "time"),
164
+ check: store.check,
165
+ }
166
+ }
167
+
168
+ function computedOf<K extends keyof AppUpdateState>(state: Signal<AppUpdateState>, key: K): Signal<AppUpdateState[K]> {
169
+ return computed(() => state()[key])
170
+ }
package/src/routing.ts ADDED
@@ -0,0 +1,218 @@
1
+ import {
2
+ DestroyRef,
3
+ afterNextRender,
4
+ assertInInjectionContext,
5
+ computed,
6
+ effect,
7
+ inject,
8
+ signal,
9
+ type Signal,
10
+ } from "@angular/core"
11
+ import {
12
+ createBlocker,
13
+ layoutOf,
14
+ layoutSegments,
15
+ matchesOf,
16
+ navigationBlocker,
17
+ navigationHook,
18
+ registerSnapshot,
19
+ resolveRelative,
20
+ routeDataOf,
21
+ routeGuard,
22
+ equalSearch,
23
+ } from "hamur/adapter"
24
+ import type {
25
+ AfterNavigateHook,
26
+ BeforeNavigateHook,
27
+ Blocker,
28
+ MatchedRoute,
29
+ NavigateHook,
30
+ NavigationBlocker,
31
+ NavigationGuard,
32
+ NavigationHookKind,
33
+ NavigationState,
34
+ RouteDataName,
35
+ RouteDataOf,
36
+ RouteFor,
37
+ RouteGuardKind,
38
+ RouteName,
39
+ RouteValue,
40
+ RouterApi,
41
+ SetSearch,
42
+ ShouldBlock,
43
+ SnapshotOptions,
44
+ UseBlockerOptions,
45
+ } from "hamur/adapter"
46
+ import {
47
+ HAMUR_NAVIGATION,
48
+ HAMUR_OUTLET_CONTEXT,
49
+ HAMUR_PAYLOAD,
50
+ HAMUR_ROOT_TREE,
51
+ HAMUR_ROUTE,
52
+ HAMUR_ROUTER,
53
+ dataOf,
54
+ entryOf,
55
+ required,
56
+ } from "./context.ts"
57
+
58
+ /** The route on screen; one signal per component, a new value on every navigation. */
59
+ export function injectRoute<N extends RouteName>(name: N): Signal<RouteFor<N>>
60
+ export function injectRoute<N extends RouteName = never>(): Signal<RouteFor<N>>
61
+ export function injectRoute(): Signal<RouteValue>
62
+ export function injectRoute(_name?: string): Signal<RouteValue> {
63
+ assertInInjectionContext(injectRoute)
64
+ return required(HAMUR_ROUTE, "injectRoute")
65
+ }
66
+
67
+ export function injectRouter(): RouterApi {
68
+ assertInInjectionContext(injectRouter)
69
+ return required(HAMUR_ROUTER, "injectRouter")
70
+ }
71
+
72
+ export function injectNavigation(): Signal<NavigationState> {
73
+ assertInInjectionContext(injectNavigation)
74
+ return required(HAMUR_NAVIGATION, "injectNavigation")
75
+ }
76
+
77
+ /** The app path a relative `to` leads to from the route on screen. */
78
+ export function injectResolvedPath(
79
+ to: string | (() => string),
80
+ { relative }: { relative?: "route" } = {},
81
+ ): Signal<string> {
82
+ assertInInjectionContext(injectResolvedPath)
83
+ const route = required(HAMUR_ROUTE, "injectResolvedPath")
84
+ return computed(() => resolveRelative(typeof to === "function" ? to() : to, route(), relative))
85
+ }
86
+
87
+ /** The `context` of the nearest `Outlet` above that has one. */
88
+ export function injectOutletContext<T = unknown>(): Signal<T> {
89
+ assertInInjectionContext(injectOutletContext)
90
+ const value = inject(HAMUR_OUTLET_CONTEXT, { optional: true })
91
+ return computed(() => value?.() as T)
92
+ }
93
+
94
+ /** The path segments of the route below the calling level, outermost first. */
95
+ export function injectLayoutSegments(_slot?: string): Signal<string[]> {
96
+ assertInInjectionContext(injectLayoutSegments)
97
+ const route = required(HAMUR_ROUTE, "injectLayoutSegments")
98
+ const entry = entryOf("injectLayoutSegments")
99
+ return computed(() => layoutSegments(route(), entry()))
100
+ }
101
+
102
+ export function injectLayoutSegment(slot?: string): Signal<string | null> {
103
+ assertInInjectionContext(injectLayoutSegment)
104
+ const segments = injectLayoutSegments(slot)
105
+ return computed(() => segments()[0] ?? null)
106
+ }
107
+
108
+ /** The layout the page renders in and its props; `{ name: false, props: {} }` when it renders none. */
109
+ export function injectLayout(): Signal<ReturnType<typeof layoutOf>> {
110
+ assertInInjectionContext(injectLayout)
111
+ const tree = required(HAMUR_ROOT_TREE, "injectLayout")
112
+ return computed(() => layoutOf(tree()))
113
+ }
114
+
115
+ /** The matched routes, outermost first, each with its params and loader data. */
116
+ export function injectMatches(): Signal<MatchedRoute[]> {
117
+ assertInInjectionContext(injectMatches)
118
+ const route = required(HAMUR_ROUTE, "injectMatches")
119
+ const payload = required(HAMUR_PAYLOAD, "injectMatches")
120
+ return computed(() => matchesOf(route(), dataOf(payload)))
121
+ }
122
+
123
+ /** The loader data of route `name` while it is in the matched chain, else `undefined`. */
124
+ export function injectRouteData<N extends RouteDataName>(name: N): Signal<RouteDataOf<N>> {
125
+ assertInInjectionContext(injectRouteData)
126
+ const route = required(HAMUR_ROUTE, "injectRouteData")
127
+ const payload = required(HAMUR_PAYLOAD, "injectRouteData")
128
+ return computed(() => routeDataOf(route(), dataOf(payload), name) as RouteDataOf<N>)
129
+ }
130
+
131
+ /** The validated search params of the route and a setter that replaces the entry, or pushes one with `{ replace: false }`. */
132
+ export function injectSearch(): { value: Signal<RouteValue["search"]>; set: SetSearch }
133
+ export function injectSearch<S>(select: (search: RouteValue["search"]) => S): { value: Signal<S>; set: SetSearch }
134
+ export function injectSearch<S>(select?: (search: RouteValue["search"]) => S): {
135
+ value: Signal<S | RouteValue["search"]>
136
+ set: SetSearch
137
+ } {
138
+ assertInInjectionContext(injectSearch)
139
+ const route = required(HAMUR_ROUTE, "injectSearch")
140
+ const router = required(HAMUR_ROUTER, "injectSearch")
141
+ const value = computed<S | RouteValue["search"]>(() => (select ? select(route().search) : route().search), {
142
+ equal: equalSearch,
143
+ })
144
+ const set: SetSearch = (change, { replace = true } = {}) => {
145
+ const update = { query: (prev: RouteValue["search"]) => (typeof change === "function" ? change(prev) : change) }
146
+ return replace ? router.replace(update) : router.navigate(update)
147
+ }
148
+ return { value, set }
149
+ }
150
+
151
+ function whileAlive(register: () => () => void): void {
152
+ inject(DestroyRef).onDestroy(register())
153
+ }
154
+
155
+ function hook(kind: NavigationHookKind, fn: (...args: never[]) => unknown): void {
156
+ whileAlive(() => navigationHook(kind, fn as never))
157
+ }
158
+
159
+ /** Runs `fn` before a navigation; removed when the component is destroyed. */
160
+ export function onBeforeNavigate(fn: BeforeNavigateHook): void {
161
+ assertInInjectionContext(onBeforeNavigate)
162
+ hook("before", fn)
163
+ }
164
+
165
+ export function onNavigate(fn: NavigateHook): void {
166
+ assertInInjectionContext(onNavigate)
167
+ hook("navigate", fn)
168
+ }
169
+
170
+ export function onAfterNavigate(fn: AfterNavigateHook): void {
171
+ assertInInjectionContext(onAfterNavigate)
172
+ hook("after", fn)
173
+ }
174
+
175
+ function guard(kind: RouteGuardKind, fn: NavigationGuard, name: string): void {
176
+ const entry = entryOf(name)
177
+ whileAlive(() => routeGuard(kind, entry(), fn))
178
+ }
179
+
180
+ /** Runs `fn` when the navigation leaves this page; removed when the component is destroyed. */
181
+ export function onBeforeRouteLeave(fn: NavigationGuard): void {
182
+ assertInInjectionContext(onBeforeRouteLeave)
183
+ guard("leave", fn, "onBeforeRouteLeave")
184
+ }
185
+
186
+ /** Runs `fn` when the navigation keeps this page and changes its params or query. */
187
+ export function onBeforeRouteUpdate(fn: NavigationGuard): void {
188
+ assertInInjectionContext(onBeforeRouteUpdate)
189
+ guard("update", fn, "onBeforeRouteUpdate")
190
+ }
191
+
192
+ /** `fn` answers whether a navigation is stopped; removed when the component is destroyed. */
193
+ export function injectPreventNavigate(fn: NavigationBlocker): void {
194
+ assertInInjectionContext(injectPreventNavigate)
195
+ whileAlive(() => navigationBlocker(fn))
196
+ }
197
+
198
+ /** A blocker held while the component lives; its state is a signal. */
199
+ export function injectBlocker(options: ShouldBlock | UseBlockerOptions): Signal<Blocker> {
200
+ assertInInjectionContext(injectBlocker)
201
+ const store = createBlocker(options)
202
+ const value = signal(store.get())
203
+ const unsubscribe = store.subscribe(() => value.set(store.get()))
204
+ const stop = store.start()
205
+ effect(() => store.sync())
206
+ inject(DestroyRef).onDestroy(() => {
207
+ stop()
208
+ unsubscribe()
209
+ })
210
+ return value.asReadonly()
211
+ }
212
+
213
+ /** Keeps `capture()` per history entry and calls `restore` when back or a reload returns to it, from the first render until the component is destroyed. */
214
+ export function injectSnapshot<T>(key: string, options: SnapshotOptions<T>): void {
215
+ assertInInjectionContext(injectSnapshot)
216
+ const destroy = inject(DestroyRef)
217
+ afterNextRender(() => destroy.onDestroy(registerSnapshot(key, options)))
218
+ }
@@ -0,0 +1,140 @@
1
+ import {
2
+ APP_ID,
3
+ CSP_NONCE,
4
+ ErrorHandler,
5
+ ɵresetCompiledComponents as resetCompiledComponents,
6
+ type ApplicationRef,
7
+ type Provider,
8
+ } from "@angular/core"
9
+ import {
10
+ createApplication,
11
+ provideClientHydration,
12
+ withEventReplay,
13
+ withNoHttpTransferCache,
14
+ } from "@angular/platform-browser"
15
+ import { reportClientError, setAdapterInstance } from "hamur/adapter"
16
+ import type { ClientContext } from "hamur/adapter"
17
+ import type { AppContext, HamurError } from "hamur/app"
18
+ import { HamurApp } from "../app.ts"
19
+ import { createState, hamurProviders, setupOf, type HamurState } from "../context.ts"
20
+ import { boundaryKey, maskInPlace } from "../mask.ts"
21
+ import { devHydration, type HydrationWatch } from "./hydration.ts"
22
+
23
+ const HOST = "hamur-app"
24
+
25
+ // A .ts edit reaches the client entry, which evaluates the edited class beside the old one before it reloads the page.
26
+ if (import.meta.hot) import.meta.hot.on("bun:beforeUpdate", () => resetCompiledComponents())
27
+
28
+ /** A throw outside a level (a listener, an effect) is reported and the page stays; in dev it reaches the overlay. */
29
+ export class ClientErrors extends ErrorHandler {
30
+ private readonly viewErrors = new WeakSet<object>()
31
+ private caught = 0
32
+
33
+ /** `hydrating`: until the hydrated app is stable, a caught error stands for the `@error` block the server rendered. */
34
+ constructor(
35
+ private readonly app: AppContext,
36
+ public hydrating = false,
37
+ private readonly watch?: HydrationWatch,
38
+ ) {
39
+ super()
40
+ }
41
+
42
+ override handleError(error: unknown): void {
43
+ // A hydration mismatch shows in the hydration panel instead of the error overlay; app:error still gets it.
44
+ if (this.watch?.failed(error)) {
45
+ reportClientError(this.app, error, { render: false })
46
+ return
47
+ }
48
+ if (import.meta.hot && typeof reportError === "function") reportError(error)
49
+ else console.error(error)
50
+ reportClientError(this.app, error, { render: false })
51
+ }
52
+
53
+ /**
54
+ * An `@boundary` caught it and shows its `@error` block: `app:error` hears it once, the page stays. While hydrating the block
55
+ * shows the masked error, the text the server rendered there, since Angular creates that block again (A6).
56
+ */
57
+ override onViewError(error: Error): void {
58
+ if (this.viewErrors.has(error)) return
59
+ this.viewErrors.add(error)
60
+ reportClientError(this.app, error, { render: false, source: "render" })
61
+ if (import.meta.hot && typeof reportError === "function") reportError(error)
62
+ if (!this.hydrating) return
63
+ const key = boundaryKey(this.caught++)
64
+ const shown = this.app.state.get<HamurError>(key)
65
+ if (shown === undefined) return
66
+ this.app.state.set(key, undefined)
67
+ maskInPlace(error, shown)
68
+ }
69
+ }
70
+
71
+ /** The nonce a browser keeps as the DOM property of a script the server wrote. */
72
+ export const documentNonce = (): string | null =>
73
+ document.querySelector<HTMLScriptElement>("script[nonce]")?.nonce || null
74
+
75
+ let running: { appRef: ApplicationRef; state: HamurState } | undefined
76
+
77
+ async function start(ctx: ClientContext, hydrating: boolean): Promise<void> {
78
+ running?.appRef.destroy()
79
+ running = undefined
80
+ const { setup, bootstrapped } = setupOf(ctx.app)
81
+ await setAdapterInstance(ctx.app, setup)
82
+ const state = createState(ctx)
83
+ const watch = hydrating ? devHydration.watch?.(ctx.root, () => ctx.navigator.currentRoute.name) : undefined
84
+ const errors = new ClientErrors(ctx.app, hydrating, watch)
85
+ // A level throws while Angular walks the view; the error page's update ticks, which inside that tick is NG0101.
86
+ // The page's level catches a hydration mismatch Angular throws while it creates the page, so it reaches here, not the ErrorHandler.
87
+ const fail = (error: unknown) => {
88
+ const mismatch = watch?.failed(error) ?? false
89
+ queueMicrotask(() =>
90
+ reportClientError(ctx.app, error, mismatch ? { render: false, source: "render" } : { render: true }),
91
+ )
92
+ }
93
+ const providers: Provider[] = [
94
+ { provide: APP_ID, useValue: "hamur" },
95
+ { provide: CSP_NONCE, useValue: documentNonce() },
96
+ { provide: ErrorHandler, useValue: errors },
97
+ ...hamurProviders(ctx.app, state, fail),
98
+ ]
99
+ const appRef = await createApplication({
100
+ providers: [
101
+ ...(hydrating ? [provideClientHydration(withEventReplay(), withNoHttpTransferCache())] : []),
102
+ ...providers,
103
+ ...setup.providers,
104
+ ],
105
+ })
106
+ bootstrapped(appRef.injector)
107
+ running = { appRef, state }
108
+ let host = ctx.root.querySelector(`:scope > ${HOST}`)
109
+ if (!hydrating || !host) {
110
+ host?.remove()
111
+ host = ctx.root.appendChild(document.createElement(HOST))
112
+ }
113
+ try {
114
+ appRef.bootstrap(HamurApp, host)
115
+ } catch (error) {
116
+ if (!watch?.failed(error)) throw error
117
+ }
118
+ await appRef.whenStable()
119
+ errors.hydrating = false
120
+ }
121
+
122
+ /** Hydrates the server's `<hamur-app>`; event replay replays the clicks made before. */
123
+ export function hydrate(ctx: ClientContext): Promise<void> {
124
+ return start(ctx, true)
125
+ }
126
+
127
+ /** `ssr: false`: a new `<hamur-app>` appended to the root, without hydration. */
128
+ export function mount(ctx: ClientContext): Promise<void> {
129
+ return start(ctx, false)
130
+ }
131
+
132
+ /** Resolves once the new tree is in the DOM and the page's pending tasks settled. */
133
+ export async function update(ctx: ClientContext): Promise<void> {
134
+ if (!running) throw new Error("update() called before hydrate() or mount()")
135
+ running.state.write(ctx)
136
+ running.appRef.tick()
137
+ await running.appRef.whenStable()
138
+ }
139
+
140
+ export { clientComponentOnClient as clientComponent, serverComponentOnClient as serverComponent } from "../wrapper.ts"
@@ -0,0 +1,4 @@
1
+ declare module "@angular/core/event-dispatch-contract.min.js" {
2
+ const source: string
3
+ export default source
4
+ }
@@ -0,0 +1,18 @@
1
+ import { reportHydrationMismatch, snapshotHydration } from "hamur/adapter/dev"
2
+ import { angularMismatch } from "../hydration.ts"
3
+ import { devHydration } from "./hydration.ts"
4
+
5
+ devHydration.watch = (root, route) => {
6
+ const handled = new WeakSet<object>()
7
+ return {
8
+ failed(error) {
9
+ if (error instanceof Error && handled.has(error)) return true
10
+ if (!snapshotHydration(root).active) return false
11
+ const report = angularMismatch(error, route(), root)
12
+ if (!report) return false
13
+ handled.add(error as Error)
14
+ reportHydrationMismatch(report)
15
+ return true
16
+ },
17
+ }
18
+ }
@@ -0,0 +1,7 @@
1
+ /** What `hydration-dev.ts` hands the client runtime in `hamur dev`; a production client never sets it. */
2
+ export interface HydrationWatch {
3
+ /** An error of the hydration; `true` when it is a mismatch and was reported, so it goes no further. */
4
+ failed(error: unknown): boolean
5
+ }
6
+
7
+ export const devHydration: { watch?: (root: Element, route: () => string) => HydrationWatch } = {}
@@ -0,0 +1,109 @@
1
+ import { APP_ID, CSP_NONCE, ErrorHandler, type ApplicationRef, type Provider } from "@angular/core"
2
+ import {
3
+ createApplication,
4
+ provideClientHydration,
5
+ withEventReplay,
6
+ withNoHttpTransferCache,
7
+ } from "@angular/platform-browser"
8
+ import { reportClientError, setAdapterInstance } from "hamur/adapter"
9
+ import type { IslandContext } from "hamur/adapter"
10
+ import { HamurApp } from "../app.ts"
11
+ import { createState, hamurProviders, islandHref, setupOf, type HamurState } from "../context.ts"
12
+ import { ClientErrors, documentNonce } from "./client.ts"
13
+
14
+ const HOST = "hamur-app"
15
+ const ISLAND_ENTRY = "island"
16
+
17
+ interface Running {
18
+ appRef?: ApplicationRef
19
+ state: HamurState
20
+ component: unknown
21
+ ctx: IslandContext
22
+ }
23
+
24
+ const islands = new WeakMap<Element, Running>()
25
+
26
+ const sourceOf = (component: unknown, props: Record<string, unknown>, ctx: IslandContext) => ({
27
+ app: ctx.app,
28
+ route: ctx.route,
29
+ payload: {},
30
+ tree: { components: [{ id: ISLAND_ENTRY, component, props }] },
31
+ baseURL: ctx.baseURL,
32
+ href: islandHref(ctx.baseURL),
33
+ })
34
+
35
+ /** `Island`: the island as an application of its own, its `APP_ID` the island's `idPrefix`, as `renderComponent` rendered it. */
36
+ async function start(
37
+ el: Element,
38
+ component: unknown,
39
+ props: Record<string, unknown>,
40
+ ctx: IslandContext,
41
+ hydrating: boolean,
42
+ ): Promise<void> {
43
+ islands.get(el)?.appRef?.destroy()
44
+ const running: Running = { state: createState(sourceOf(component, props, ctx)), component, ctx }
45
+ islands.set(el, running)
46
+ const { setup, bootstrapped } = setupOf(ctx.app)
47
+ await setAdapterInstance(ctx.app, setup)
48
+ const providers: Provider[] = [
49
+ { provide: APP_ID, useValue: ctx.idPrefix },
50
+ { provide: CSP_NONCE, useValue: documentNonce() },
51
+ { provide: ErrorHandler, useValue: new ClientErrors(ctx.app) },
52
+ ...hamurProviders(ctx.app, running.state, (error) => reportClientError(ctx.app, error, { render: true })),
53
+ ]
54
+ const appRef = await createApplication({
55
+ providers: [
56
+ ...(hydrating ? [provideClientHydration(withEventReplay(), withNoHttpTransferCache())] : []),
57
+ ...providers,
58
+ ...setup.providers,
59
+ ],
60
+ })
61
+ // An unmountIsland during the awaits found no application yet; starting now would leave one live on a removed element.
62
+ if (islands.get(el) !== running) return void appRef.destroy()
63
+ running.appRef = appRef
64
+ bootstrapped(appRef.injector)
65
+ let host = el.querySelector(`:scope > ${HOST}`)
66
+ if (!hydrating || !host) {
67
+ host?.remove()
68
+ host = el.appendChild(document.createElement(HOST))
69
+ }
70
+ appRef.bootstrap(HamurApp, host)
71
+ await appRef.whenStable()
72
+ }
73
+
74
+ /** Hydrates the island's server HTML in `el`; event replay, scoped to `el`, replays the clicks made inside it before. */
75
+ export function hydrateIsland(
76
+ el: Element,
77
+ component: unknown,
78
+ props: Record<string, unknown>,
79
+ ctx: IslandContext,
80
+ ): Promise<void> {
81
+ return start(el, component, props, ctx, true)
82
+ }
83
+
84
+ /** Mounts the island into `el` in place of the fallback it holds. */
85
+ export function mountIsland(
86
+ el: Element,
87
+ component: unknown,
88
+ props: Record<string, unknown>,
89
+ ctx: IslandContext,
90
+ ): Promise<void> {
91
+ el.replaceChildren()
92
+ return start(el, component, props, ctx, false)
93
+ }
94
+
95
+ export function unmountIsland(el: Element): void {
96
+ islands.get(el)?.appRef?.destroy()
97
+ islands.delete(el)
98
+ }
99
+
100
+ /** Gives the island's application new props, which keeps its state. */
101
+ export async function updateIsland(el: Element, props: Record<string, unknown>): Promise<void> {
102
+ const running = islands.get(el)
103
+ if (!running) return
104
+ running.state.write(sourceOf(running.component, props, running.ctx))
105
+ // Still being created: the application bootstraps over the state written here.
106
+ if (!running.appRef) return
107
+ running.appRef.tick()
108
+ await running.appRef.whenStable()
109
+ }