@zerosumstudio/spool 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,106 @@
1
+ <script lang="ts">
2
+ import { untrack, type Snippet } from 'svelte'
3
+ import {
4
+ createRemoteLoader,
5
+ warnUnknownRemote,
6
+ type RemoteError,
7
+ type RemoteLoader,
8
+ type RemoteState,
9
+ } from './core'
10
+ import { remotes, type RemoteEntry, type RemoteName } from './remotes'
11
+ import { reportRemoteError } from './report'
12
+
13
+ type MountFunction = (target: HTMLElement, props?: object) => () => void
14
+
15
+ interface Props {
16
+ name: RemoteName
17
+ /** Forwarded to the remote's mount(el, props). */
18
+ props?: object
19
+ /** Shown while the remote is still loading. */
20
+ fallback?: Snippet
21
+ /** Shown when it fails to load. Call retry to start the load over. */
22
+ error?: Snippet<[RemoteError, () => void]>
23
+ /** Called when it fails to load. */
24
+ onError?: (error: RemoteError, name: RemoteName) => void
25
+ }
26
+
27
+ let { name, props, fallback, error, onError }: Props = $props()
28
+
29
+ // Undefined while the name is not in the registry.
30
+ let remote = $state.raw<RemoteState>()
31
+ let target = $state<HTMLElement>()
32
+ let loader: RemoteLoader | undefined
33
+
34
+ function retry(): void {
35
+ loader?.retry()
36
+ }
37
+
38
+ function reloadPage(): void {
39
+ window.location.reload()
40
+ }
41
+
42
+ $effect(() => {
43
+ const current = name
44
+ const entry = remotes[current] as RemoteEntry | undefined
45
+ if (!entry) {
46
+ warnUnknownRemote(current)
47
+ loader = undefined
48
+ remote = undefined
49
+
50
+ return
51
+ }
52
+
53
+ const next = createRemoteLoader(current, entry.load)
54
+ let shown: RemoteState | undefined
55
+ const sync = () => {
56
+ const latest = next.getState()
57
+ if (latest === shown) return
58
+
59
+ shown = latest
60
+ remote = latest
61
+ if (latest.status === 'error') {
62
+ reportRemoteError(current, latest.error)
63
+ onError?.(latest.error, current)
64
+ }
65
+ }
66
+
67
+ loader = next
68
+ const stop = next.subscribe(sync)
69
+ untrack(sync)
70
+
71
+ return stop
72
+ })
73
+
74
+ $effect(() => {
75
+ if (remote?.status !== 'ready' || !target) return
76
+
77
+ const element = target
78
+ const mount = remote.module.default
79
+
80
+ return untrack(() => {
81
+ const entry = remotes[name] as RemoteEntry | undefined
82
+ const isComponent = entry?.contract === 'component'
83
+ if (isComponent) return entry.mountComponent?.(mount, element, props)
84
+
85
+ return (mount as MountFunction)(element, props)
86
+ })
87
+ })
88
+ </script>
89
+
90
+ {#if remote?.status === 'loading'}
91
+ {@render fallback?.()}
92
+ {:else if remote?.status === 'error'}
93
+ {#if error}
94
+ {@render error(remote.error, retry)}
95
+ {:else}
96
+ <div role="alert" data-remote-error>
97
+ <p>This section could not be loaded.</p>
98
+ {#if remote.error.needsReload}
99
+ <button type="button" onclick={reloadPage}>Reload page</button>
100
+ {:else}
101
+ <button type="button" onclick={retry}>Try again</button>
102
+ {/if}
103
+ </div>
104
+ {/if}
105
+ {/if}
106
+ <div bind:this={target}></div>
@@ -0,0 +1,118 @@
1
+ <script setup lang="ts">
2
+ import { computed, onBeforeUnmount, ref, shallowRef, watch } from 'vue'
3
+ import {
4
+ createRemoteLoader,
5
+ warnUnknownRemote,
6
+ type RemoteError,
7
+ type RemoteLoader,
8
+ type RemoteState,
9
+ } from './core'
10
+ import { remotes, type RemoteEntry, type RemoteName } from './remotes'
11
+ import { reportRemoteError } from './report'
12
+
13
+ type MountFunction = (target: HTMLElement, props?: object) => () => void
14
+
15
+ const input = defineProps<{
16
+ name: RemoteName
17
+ /** Forwarded to the remote's mount(el, props). */
18
+ props?: object
19
+ }>()
20
+ const emit = defineEmits<{
21
+ /** The remote failed to load. */
22
+ error: [error: RemoteError, name: RemoteName]
23
+ }>()
24
+ defineSlots<{
25
+ /** Shown while the remote is still loading. */
26
+ fallback?(): unknown
27
+ /** Shown when it fails to load. Call retry to start the load over. */
28
+ error?(scope: { error: RemoteError; retry: () => void }): unknown
29
+ }>()
30
+
31
+ // Undefined while the name is not in the registry.
32
+ const state = shallowRef<RemoteState>()
33
+ const target = ref<HTMLElement | null>(null)
34
+ let loader: RemoteLoader | undefined
35
+ let stop: (() => void) | undefined
36
+
37
+ const needsReload = computed(() => state.value?.status === 'error' && state.value.error.needsReload)
38
+
39
+ function retry(): void {
40
+ loader?.retry()
41
+ }
42
+
43
+ function handleDefaultAction(): void {
44
+ if (needsReload.value) window.location.reload()
45
+ else retry()
46
+ }
47
+
48
+ function sync(current: RemoteLoader, name: RemoteName): void {
49
+ const next = current.getState()
50
+ if (next === state.value) return
51
+
52
+ state.value = next
53
+ if (next.status === 'error') {
54
+ reportRemoteError(name, next.error)
55
+ emit('error', next.error, name)
56
+ }
57
+ }
58
+
59
+ watch(
60
+ () => input.name,
61
+ name => {
62
+ stop?.()
63
+ stop = undefined
64
+
65
+ const entry = remotes[name] as RemoteEntry | undefined
66
+ if (!entry) {
67
+ warnUnknownRemote(name)
68
+ loader = undefined
69
+ state.value = undefined
70
+
71
+ return
72
+ }
73
+
74
+ const current = createRemoteLoader(name, entry.load)
75
+ loader = current
76
+ stop = current.subscribe(() => {
77
+ sync(current, name)
78
+ })
79
+ sync(current, name)
80
+ },
81
+ { immediate: true },
82
+ )
83
+
84
+ watch(
85
+ [state, target],
86
+ ([current, element], _previous, onCleanup) => {
87
+ if (current?.status !== 'ready' || !element) return
88
+
89
+ const entry = remotes[input.name] as RemoteEntry | undefined
90
+ const mount = current.module.default
91
+ const unmount =
92
+ entry?.contract === 'component'
93
+ ? entry.mountComponent?.(mount, element, input.props)
94
+ : (mount as MountFunction)(element, input.props)
95
+ if (unmount) onCleanup(unmount)
96
+ },
97
+ { flush: 'post' },
98
+ )
99
+
100
+ onBeforeUnmount(() => {
101
+ stop?.()
102
+ })
103
+ </script>
104
+
105
+ <template>
106
+ <slot v-if="state?.status === 'loading'" name="fallback" />
107
+ <template v-else-if="state?.status === 'error'">
108
+ <slot name="error" :error="state.error" :retry="retry">
109
+ <div role="alert" data-remote-error>
110
+ <p>This section could not be loaded.</p>
111
+ <button type="button" @click="handleDefaultAction">
112
+ {{ needsReload ? 'Reload page' : 'Try again' }}
113
+ </button>
114
+ </div>
115
+ </slot>
116
+ </template>
117
+ <div ref="target"></div>
118
+ </template>
@@ -0,0 +1,421 @@
1
+ import { getInstance, type ModuleFederationRuntimePlugin } from '@module-federation/runtime'
2
+
3
+ /*
4
+ * TYPES
5
+ ***************************************************************************************************/
6
+ type Federation = NonNullable<ReturnType<typeof getInstance>>
7
+
8
+ export type RemoteErrorCode = 'TIMEOUT' | 'ENTRY_FAILED' | 'CHUNK_FAILED' | 'NOT_FOUND'
9
+
10
+ export interface RemoteModule {
11
+ default: unknown
12
+ }
13
+
14
+ export interface LoadOptions<Module> {
15
+ /** How long a load may take before it rejects with TIMEOUT. */
16
+ timeoutMs?: number
17
+ /** The bundler's own import of the remote, which also registers it with the runtime. */
18
+ importRemote?: () => Promise<Module>
19
+ }
20
+
21
+ export type RemoteState<Module = RemoteModule> =
22
+ | { status: 'loading' }
23
+ | { status: 'ready'; module: Module }
24
+ | { status: 'error'; error: RemoteError }
25
+
26
+ export interface RemoteLoader<Module = RemoteModule> {
27
+ getState: () => RemoteState<Module>
28
+ /** The first subscriber starts the load. Safe to call again after an unsubscribe. */
29
+ subscribe: (listener: () => void) => () => void
30
+ /** Starts the load over after an error. */
31
+ retry: () => void
32
+ }
33
+
34
+ interface RemoteEntries {
35
+ // The url each container was evaluated from. Every later load imports that
36
+ // url, so no container is evaluated twice.
37
+ loadedFrom: Map<string, string>
38
+ // WebKit can answer a second import() of a remoteEntry.js that failed with the
39
+ // same failure, without fetching it, so each failure moves the next attempt to
40
+ // a fresh url.
41
+ failures: Map<string, number>
42
+ // The url each entry is being loaded from right now.
43
+ loading: Map<string, string>
44
+ }
45
+
46
+ /*
47
+ * ERRORS
48
+ ***************************************************************************************************/
49
+ export const DEFAULT_TIMEOUT_MS = 15_000
50
+
51
+ export class RemoteError extends Error {
52
+ readonly code: RemoteErrorCode
53
+ /** The registry key or import id that was being loaded. */
54
+ readonly remote: string
55
+ /** This id failed again after its entry had loaded. WebKit keeps a failed module import
56
+ * for the life of the page, so only a reload can fix it. The first failure is worth a retry. */
57
+ readonly needsReload: boolean
58
+
59
+ constructor(
60
+ code: RemoteErrorCode,
61
+ remote: string,
62
+ options: { message?: string; needsReload?: boolean; cause?: unknown } = {},
63
+ ) {
64
+ super(options.message ?? formatMessage(code, remote), { cause: options.cause })
65
+ this.name = 'RemoteError'
66
+ this.code = code
67
+ this.remote = remote
68
+ this.needsReload = options.needsReload ?? false
69
+ }
70
+ }
71
+
72
+ function formatMessage(code: RemoteErrorCode, remote: string): string {
73
+ if (code === 'TIMEOUT') return `remote "${remote}" took too long to load`
74
+
75
+ if (code === 'CHUNK_FAILED') return `remote "${remote}" loaded, but one of its modules did not`
76
+
77
+ if (code === 'NOT_FOUND') return `no remote "${remote}" is registered`
78
+
79
+ return `remote "${remote}" could not load its entry`
80
+ }
81
+
82
+ /*
83
+ * SHARED STATE
84
+ ***************************************************************************************************/
85
+ // Shared by every spool host on the page and keyed by remoteEntry url, like the
86
+ // runtime's own entry cache: a nested host bundles its own copy of this file and
87
+ // of the runtime, but they all share that cache and the browser's module map.
88
+ const page = globalThis as typeof globalThis & { __spoolRemoteEntries?: RemoteEntries }
89
+ const entries: RemoteEntries = (page.__spoolRemoteEntries ??= {
90
+ loadedFrom: new Map(),
91
+ failures: new Map(),
92
+ loading: new Map(),
93
+ })
94
+
95
+ // The bundler's import("staff/App") keeps its first promise for the life of
96
+ // the page, even a rejected one, so an id whose import has failed goes to the
97
+ // runtime from then on.
98
+ const failedImports = new Set<string>()
99
+ // Ids that have failed once with their entry loaded, so a second failure means a reload.
100
+ const failedChunks = new Set<string>()
101
+ // Loads this bundle has started and not finished, by remote name.
102
+ const inFlight = new Map<string, number>()
103
+ const warnedUnknown = new Set<string>()
104
+
105
+ /*
106
+ * ENTRY PLUGIN
107
+ ***************************************************************************************************/
108
+ function buildAttemptUrl(entry: string): string {
109
+ const failures = entries.failures.get(entry)
110
+
111
+ if (!failures) return entry
112
+
113
+ const url = new URL(entry)
114
+ url.searchParams.set('spool-retry', String(failures))
115
+
116
+ return url.href
117
+ }
118
+
119
+ const remoteEntriesPlugin: ModuleFederationRuntimePlugin = {
120
+ name: 'spool-remote-entries',
121
+ loadEntry({ remoteInfo: { entry, type } }) {
122
+ const isImported = type === 'module' || type === 'esm'
123
+ const url = entries.loadedFrom.get(entry) ?? (isImported ? buildAttemptUrl(entry) : entry)
124
+ entries.loading.set(entry, url)
125
+
126
+ if (url !== entry) return import(/* @vite-ignore */ url)
127
+
128
+ return undefined
129
+ },
130
+ afterLoadEntry({ remoteInfo: { entry }, remoteEntryExports }) {
131
+ const url = entries.loading.get(entry)
132
+ entries.loading.delete(entry)
133
+
134
+ if (entries.loadedFrom.has(entry)) return
135
+
136
+ if (remoteEntryExports) {
137
+ entries.loadedFrom.set(entry, url ?? entry)
138
+ } else if (url) {
139
+ entries.failures.set(entry, (entries.failures.get(entry) ?? 0) + 1)
140
+ }
141
+ },
142
+ }
143
+
144
+ let withPlugin: Federation | undefined
145
+
146
+ function getFederation(): Federation | undefined {
147
+ const instance = getInstance() ?? undefined
148
+
149
+ if (instance && instance !== withPlugin) {
150
+ instance.registerPlugins([remoteEntriesPlugin])
151
+ withPlugin = instance
152
+ }
153
+
154
+ return instance
155
+ }
156
+
157
+ /*
158
+ * REGISTERED REMOTES
159
+ ***************************************************************************************************/
160
+ /** The remote a registry key or import id belongs to: "staff" for "staff" and
161
+ * "staff/App", "assessments" for "assessments/NewAssessment". */
162
+ export function getRemoteName(id: string): string {
163
+ const slash = id.indexOf('/')
164
+
165
+ return slash === -1 ? id : id.slice(0, slash)
166
+ }
167
+
168
+ function findRegisteredRemote(name: string) {
169
+ const instance = getFederation()
170
+ const remote = instance?.options.remotes.find(
171
+ candidate => candidate.name === name || candidate.alias === name,
172
+ )
173
+
174
+ return instance && remote ? { instance, remote } : undefined
175
+ }
176
+
177
+ function getCachedModule(name: string) {
178
+ const registered = findRegisteredRemote(name)
179
+
180
+ return registered?.instance.moduleCache.get(registered.remote.name)
181
+ }
182
+
183
+ /** Whether the remote's entry has run on this page, here or in another host's bundle. */
184
+ function hasLoadedEntry(name: string): boolean {
185
+ const module = getCachedModule(name)
186
+
187
+ if (!module) return false
188
+
189
+ return Boolean(module.remoteEntryExports) || entries.loadedFrom.has(module.remoteInfo.entry)
190
+ }
191
+
192
+ /** Records a failure of `id` and says whether it is the second one with the entry loaded. */
193
+ function isRepeatChunkFailure(id: string): boolean {
194
+ if (!hasLoadedEntry(getRemoteName(id))) return false
195
+
196
+ const isRepeat = failedChunks.has(id)
197
+ failedChunks.add(id)
198
+
199
+ return isRepeat
200
+ }
201
+
202
+ /** Re-registers a remote whose entry script failed to load, so the runtime
203
+ * drops the failure it keeps and fetches the entry again. Leaves a remote alone
204
+ * while it is loading, once its entry has loaded anywhere on the page, and when
205
+ * it never got as far as its entry, as nothing about it is kept then. */
206
+ export function forceReregister(id: string): void {
207
+ const name = getRemoteName(id)
208
+ const registered = findRegisteredRemote(name)
209
+
210
+ if (!registered || inFlight.has(name)) return
211
+
212
+ const { instance, remote } = registered
213
+ const module = instance.moduleCache.get(remote.name)
214
+
215
+ if (!module || module.remoteEntryExports) return
216
+
217
+ const { entry } = module.remoteInfo
218
+
219
+ if (entries.loadedFrom.has(entry) || entries.loading.has(entry)) return
220
+
221
+ instance.registerRemotes([remote], { force: true })
222
+ }
223
+
224
+ /** Gives up on a load that never answered, so the next attempt asks again. An entry script that
225
+ * hung moves to a fresh url. A manifest that hung is cleared by re-registering the remote: the
226
+ * runtime keeps its pending request in `__MANIFEST_LOADING__` until it rejects or the remote is
227
+ * removed, and a hung one does neither, so with no module cached forceReregister cannot see it. */
228
+ function abandonLoad(name: string): void {
229
+ const registered = findRegisteredRemote(name)
230
+
231
+ if (!registered) return
232
+
233
+ const { instance, remote } = registered
234
+ const module = instance.moduleCache.get(remote.name)
235
+
236
+ if (module?.remoteEntryExports) return
237
+
238
+ const entry = module?.remoteInfo.entry
239
+
240
+ if (entry !== undefined) {
241
+ if (entries.loadedFrom.has(entry)) return
242
+
243
+ if (entries.loading.delete(entry)) {
244
+ entries.failures.set(entry, (entries.failures.get(entry) ?? 0) + 1)
245
+ }
246
+ }
247
+
248
+ instance.registerRemotes([remote], { force: true })
249
+ }
250
+
251
+ function releaseLoad(name: string): void {
252
+ const loads = (inFlight.get(name) ?? 1) - 1
253
+
254
+ if (loads) inFlight.set(name, loads)
255
+ else inFlight.delete(name)
256
+ }
257
+
258
+ /*
259
+ * LOADING
260
+ ***************************************************************************************************/
261
+ /** Turns whatever a load threw into a RemoteError, working out whether the entry or a chunk failed. */
262
+ export function toRemoteError(id: string, cause: unknown): RemoteError {
263
+ if (cause instanceof RemoteError) return cause
264
+
265
+ const name = getRemoteName(id)
266
+
267
+ if (getFederation() && !findRegisteredRemote(name)) {
268
+ return new RemoteError('NOT_FOUND', id, { cause })
269
+ }
270
+
271
+ const hasEntry = hasLoadedEntry(name)
272
+
273
+ return new RemoteError(hasEntry ? 'CHUNK_FAILED' : 'ENTRY_FAILED', id, {
274
+ cause,
275
+ needsReload: isRepeatChunkFailure(id),
276
+ })
277
+ }
278
+
279
+ function startLoad<Module>(id: string, importRemote?: () => Promise<Module>): Promise<Module> {
280
+ const name = getRemoteName(id)
281
+ const registered =
282
+ !importRemote || failedImports.has(id) ? findRegisteredRemote(name) : undefined
283
+
284
+ if (registered) {
285
+ return registered.instance
286
+ .loadRemote<Module>(id)
287
+ .then(module => module ?? Promise.reject(new RemoteError('NOT_FOUND', id)))
288
+ }
289
+
290
+ if (!importRemote) return Promise.reject(new RemoteError('NOT_FOUND', id))
291
+
292
+ return importRemote().catch((error: unknown) => {
293
+ failedImports.add(id)
294
+ throw error
295
+ })
296
+ }
297
+
298
+ /** Loads a remote module, through the bundler's import while that works and through the
299
+ * runtime once it has failed. Rejects with a RemoteError, and with TIMEOUT after `timeoutMs`
300
+ * without waiting on a load that never answers. */
301
+ export function loadRemote<Module = RemoteModule>(
302
+ id: string,
303
+ { timeoutMs = DEFAULT_TIMEOUT_MS, importRemote }: LoadOptions<Module> = {},
304
+ ): Promise<Module> {
305
+ const name = getRemoteName(id)
306
+ forceReregister(name)
307
+ inFlight.set(name, (inFlight.get(name) ?? 0) + 1)
308
+
309
+ return new Promise<Module>((resolve, reject) => {
310
+ let isSettled = false
311
+ const settle = () => {
312
+ isSettled = true
313
+ clearTimeout(timer)
314
+ releaseLoad(name)
315
+ }
316
+
317
+ const timer = setTimeout(() => {
318
+ if (isSettled) return
319
+
320
+ // The count has to drop here, or forceReregister skips this remote for good.
321
+ settle()
322
+ const needsReload = isRepeatChunkFailure(id)
323
+ abandonLoad(name)
324
+ failedImports.add(id)
325
+ reject(
326
+ new RemoteError('TIMEOUT', id, {
327
+ message: `remote "${id}" did not load within ${String(timeoutMs)}ms`,
328
+ needsReload,
329
+ }),
330
+ )
331
+ }, timeoutMs)
332
+
333
+ new Promise<Module>(begin => {
334
+ begin(startLoad(id, importRemote))
335
+ }).then(
336
+ module => {
337
+ if (isSettled) return
338
+
339
+ settle()
340
+ failedChunks.delete(id)
341
+ resolve(module)
342
+ },
343
+ (cause: unknown) => {
344
+ if (isSettled) return
345
+
346
+ settle()
347
+ reject(toRemoteError(id, cause))
348
+ },
349
+ )
350
+ })
351
+ }
352
+
353
+ /*
354
+ * LOADER
355
+ ***************************************************************************************************/
356
+ const LOADING = { status: 'loading' } as const
357
+
358
+ /** The loading, ready and error states of one remote, for a <Remote> to render. */
359
+ export function createRemoteLoader<Module extends RemoteModule = RemoteModule>(
360
+ name: string,
361
+ load: () => Promise<Module>,
362
+ ): RemoteLoader<Module> {
363
+ let state: RemoteState<Module> = LOADING
364
+ let hasStarted = false
365
+ let attempt = 0
366
+ const listeners = new Set<() => void>()
367
+
368
+ function update(next: RemoteState<Module>): void {
369
+ state = next
370
+ for (const listener of [...listeners]) listener()
371
+ }
372
+
373
+ function run(): void {
374
+ const current = ++attempt
375
+
376
+ if (state !== LOADING) update(LOADING)
377
+
378
+ new Promise<Module>(begin => {
379
+ begin(load())
380
+ }).then(
381
+ module => {
382
+ if (current === attempt) update({ status: 'ready', module })
383
+ },
384
+ (cause: unknown) => {
385
+ if (current !== attempt) return
386
+
387
+ update({ status: 'error', error: toRemoteError(name, cause) })
388
+ },
389
+ )
390
+ }
391
+
392
+ return {
393
+ getState: () => state,
394
+ subscribe(listener) {
395
+ listeners.add(listener)
396
+
397
+ if (!hasStarted) {
398
+ hasStarted = true
399
+ run()
400
+ }
401
+
402
+ return () => {
403
+ listeners.delete(listener)
404
+ }
405
+ },
406
+ retry() {
407
+ if (state.status === 'error') run()
408
+ },
409
+ }
410
+ }
411
+
412
+ /*
413
+ * DEV WARNINGS
414
+ ***************************************************************************************************/
415
+ /** Warns once per name, in dev only, that <Remote> was given a name the registry does not have. */
416
+ export function warnUnknownRemote(name: string): void {
417
+ if (!import.meta.env.DEV || warnedUnknown.has(name)) return
418
+
419
+ warnedUnknown.add(name)
420
+ console.warn(`[federation] no remote named "${name}" in the registry`)
421
+ }