@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,289 @@
1
+ /*
2
+ * Lets a developer swap one remote's entry from the browser console, without
3
+ * touching the deployed manifest. An override is only taken from localStorage,
4
+ * never from the url: a crafted link must not swap in someone else's remote.
5
+ * It has to point at an origin listed in spool.json "overrides.origins", and it
6
+ * expires after a day.
7
+ */
8
+ import {
9
+ getInstance,
10
+ registerPlugins,
11
+ type ModuleFederationRuntimePlugin,
12
+ } from '@module-federation/runtime'
13
+
14
+ /*
15
+ * TYPES
16
+ ***************************************************************************************************/
17
+ export interface RemoteOverride {
18
+ url: string
19
+ /** Epoch milliseconds. */
20
+ expiresAt: number
21
+ }
22
+
23
+ export interface OverrideOptions {
24
+ /** How long the override lasts: at most 24 hours, which is also the default. */
25
+ ttlMs?: number
26
+ }
27
+
28
+ // Set by the spool vite plugin from spool.json. Missing means no origin is allowed.
29
+ declare const __SPOOL_OVERRIDE_ORIGINS__: readonly string[] | undefined
30
+
31
+ /*
32
+ * CONSTANTS
33
+ ***************************************************************************************************/
34
+ export const MAX_OVERRIDE_TTL_MS = 24 * 60 * 60 * 1000
35
+
36
+ const STORAGE_PREFIX = 'spool:remote:'
37
+ const ENTRY_FILES = ['mf-manifest.json', 'remoteEntry.js']
38
+ const LOCAL_HOSTS = ['localhost', '127.0.0.1', '[::1]']
39
+ const warned = new Set<string>()
40
+
41
+ /*
42
+ * VALIDATION
43
+ ***************************************************************************************************/
44
+ function getAllowedOrigins(): readonly string[] {
45
+ return typeof __SPOOL_OVERRIDE_ORIGINS__ === 'undefined' ? [] : __SPOOL_OVERRIDE_ORIGINS__
46
+ }
47
+
48
+ /** Why `value` cannot be an override, or undefined when it can. */
49
+ export function checkOverrideUrl(value: string): string | undefined {
50
+ let url: URL
51
+ try {
52
+ url = new URL(value)
53
+ } catch {
54
+ return 'not a valid url'
55
+ }
56
+
57
+ const isLocalDev = import.meta.env.DEV && LOCAL_HOSTS.includes(url.hostname)
58
+ const isSecure = url.protocol === 'https:' || (url.protocol === 'http:' && isLocalDev)
59
+
60
+ if (!isSecure) return 'must be https (http only to localhost in dev)'
61
+
62
+ if (url.username || url.password) return 'must not carry credentials'
63
+
64
+ if (!getAllowedOrigins().includes(url.origin)) {
65
+ return `${url.origin} is not in spool.json "overrides.origins"`
66
+ }
67
+
68
+ if (/[?#]/.test(url.href)) return 'must not have a query string or fragment'
69
+
70
+ const file = url.pathname.slice(url.pathname.lastIndexOf('/') + 1)
71
+
72
+ if (!ENTRY_FILES.includes(file)) return `must end in ${ENTRY_FILES.join(' or ')}`
73
+
74
+ return undefined
75
+ }
76
+
77
+ function getOrigin(value: string): string {
78
+ try {
79
+ return new URL(value).origin
80
+ } catch {
81
+ return ''
82
+ }
83
+ }
84
+
85
+ function getEntry(remote: object): string {
86
+ return 'entry' in remote && typeof remote.entry === 'string' ? remote.entry : ''
87
+ }
88
+
89
+ /** Why code from this manifest snapshot may not load for an overridden remote, or undefined. */
90
+ function checkSnapshot(snapshot: object, manifestUrl: string): string | undefined {
91
+ const { publicPath, getPublicPath } = snapshot as {
92
+ publicPath?: unknown
93
+ getPublicPath?: unknown
94
+ }
95
+
96
+ if (getPublicPath !== undefined) return 'its manifest computes its public path at run time'
97
+
98
+ if (typeof publicPath !== 'string' || publicPath === '' || publicPath === 'auto') {
99
+ return undefined
100
+ }
101
+
102
+ let resolved: string
103
+ try {
104
+ resolved = new URL(publicPath, manifestUrl).origin
105
+ } catch {
106
+ return `its manifest has an unreadable publicPath ${publicPath}`
107
+ }
108
+
109
+ return getAllowedOrigins().includes(resolved)
110
+ ? undefined
111
+ : `its manifest loads code from ${resolved}, which is not on a listed origin`
112
+ }
113
+
114
+ /*
115
+ * STORAGE
116
+ ***************************************************************************************************/
117
+ function toStorageKey(name: string): string {
118
+ return STORAGE_PREFIX + name
119
+ }
120
+
121
+ function parseOverride(raw: string | null): RemoteOverride | undefined {
122
+ if (raw === null) return undefined
123
+
124
+ try {
125
+ const value: unknown = JSON.parse(raw)
126
+
127
+ if (typeof value !== 'object' || value === null) return undefined
128
+
129
+ const { url, expiresAt } = value as Partial<RemoteOverride>
130
+
131
+ if (typeof url !== 'string' || typeof expiresAt !== 'number') return undefined
132
+
133
+ return { url, expiresAt }
134
+ } catch {
135
+ return undefined
136
+ }
137
+ }
138
+
139
+ /** The live override for `name`. One that expired, or no longer passes the checks, is removed. */
140
+ function readOverride(name: string): RemoteOverride | undefined {
141
+ const key = toStorageKey(name)
142
+ const raw = localStorage.getItem(key)
143
+
144
+ if (raw === null) return undefined
145
+
146
+ const override = parseOverride(raw)
147
+ const now = Date.now()
148
+ // An expiry further out than the longest lifetime was not written by setRemoteOverride.
149
+ const isLive =
150
+ override !== undefined &&
151
+ override.expiresAt > now &&
152
+ override.expiresAt <= now + MAX_OVERRIDE_TTL_MS &&
153
+ !checkOverrideUrl(override.url)
154
+
155
+ if (isLive) return { url: new URL(override.url).href, expiresAt: override.expiresAt }
156
+
157
+ localStorage.removeItem(key)
158
+
159
+ return undefined
160
+ }
161
+
162
+ /** Point `name` at `url` (its mf-manifest.json or remoteEntry.js), or clear the override with null.
163
+ * Reload the page afterwards. */
164
+ export function setRemoteOverride(
165
+ name: string,
166
+ url: string | null,
167
+ { ttlMs = MAX_OVERRIDE_TTL_MS }: OverrideOptions = {},
168
+ ): void {
169
+ if (url === null) {
170
+ localStorage.removeItem(toStorageKey(name))
171
+
172
+ return
173
+ }
174
+
175
+ const problem = checkOverrideUrl(url)
176
+
177
+ if (problem) throw new Error(`[federation] cannot override "${name}": ${problem}`)
178
+
179
+ const override: RemoteOverride = {
180
+ url: new URL(url).href,
181
+ expiresAt: Date.now() + Math.min(ttlMs, MAX_OVERRIDE_TTL_MS),
182
+ }
183
+ localStorage.setItem(toStorageKey(name), JSON.stringify(override))
184
+ }
185
+
186
+ /** Every remote name currently overridden, with the override it points to. */
187
+ export function listRemoteOverrides(): Record<string, RemoteOverride> {
188
+ const names: string[] = []
189
+ for (let index = 0; index < localStorage.length; index++) {
190
+ const key = localStorage.key(index)
191
+
192
+ if (key?.startsWith(STORAGE_PREFIX)) names.push(key.slice(STORAGE_PREFIX.length))
193
+ }
194
+
195
+ const overrides: Record<string, RemoteOverride> = {}
196
+ for (const name of names) {
197
+ const override = readOverride(name)
198
+
199
+ if (override) overrides[name] = override
200
+ }
201
+
202
+ return overrides
203
+ }
204
+
205
+ /*
206
+ * RUNTIME PLUGIN
207
+ ***************************************************************************************************/
208
+ function warnOnce(name: string, override: RemoteOverride): void {
209
+ if (warned.has(name)) return
210
+
211
+ warned.add(name)
212
+ const until = new Date(override.expiresAt).toISOString()
213
+ console.warn(
214
+ `[federation] "${name}" is overridden to ${override.url} until ${until}. ` +
215
+ `Clear it with setRemoteOverride("${name}", null).`,
216
+ )
217
+ }
218
+
219
+ const remoteOverridesPlugin: ModuleFederationRuntimePlugin = {
220
+ name: 'spool-remote-overrides',
221
+ beforeRegisterRemote({ remote, origin }) {
222
+ if (!('entry' in remote)) return { remote, origin }
223
+
224
+ const name = remote.alias ?? remote.name
225
+ const override = readOverride(name)
226
+
227
+ if (override) {
228
+ remote.entry = override.url
229
+ warnOnce(name, override)
230
+ }
231
+
232
+ return { remote, origin }
233
+ },
234
+ // A manifest names where its code lives (metaData.publicPath), and a listed manifest can
235
+ // name any origin. The runtime starts preloading from the snapshot as soon as it has one,
236
+ // before an entry is ever loaded, so this is the earliest hook that sees it. Where the
237
+ // runtime offers nothing earlier, an origin on the list has to serve only your own builds.
238
+ loadRemoteSnapshot(args) {
239
+ const { moduleInfo, remoteSnapshot } = args
240
+ const name = moduleInfo.alias ?? moduleInfo.name
241
+
242
+ if (!readOverride(name)) return args
243
+
244
+ const problem = checkSnapshot(remoteSnapshot, args.manifestUrl ?? getEntry(moduleInfo))
245
+
246
+ if (problem) throw new Error(`[federation] "${name}" is overridden, and ${problem}`)
247
+
248
+ return args
249
+ },
250
+ // The entry the runtime resolved, for an override that points at a remoteEntry.js directly.
251
+ loadEntry({ remoteInfo }) {
252
+ if (!readOverride(remoteInfo.alias ?? remoteInfo.name)) return undefined
253
+
254
+ if (!getAllowedOrigins().includes(getOrigin(remoteInfo.entry))) {
255
+ throw new Error(
256
+ `[federation] "${remoteInfo.alias ?? remoteInfo.name}" is overridden, and its entry ${remoteInfo.entry} is not on a listed origin`,
257
+ )
258
+ }
259
+
260
+ return undefined
261
+ },
262
+ }
263
+
264
+ // The runtime registers remotes at init, before this file loads, so overrides are re-applied here.
265
+ function applyRemoteOverrides(): void {
266
+ const instance = getInstance()
267
+
268
+ if (!instance) return
269
+
270
+ for (const remote of instance.options.remotes) {
271
+ if (!('entry' in remote)) continue
272
+
273
+ const name = remote.alias ?? remote.name
274
+ const override = readOverride(name)
275
+
276
+ if (override && remote.entry !== override.url) {
277
+ warnOnce(name, override)
278
+ instance.registerRemotes([{ ...remote, entry: override.url }], { force: true })
279
+ }
280
+ }
281
+ }
282
+
283
+ /** Only with a live federation runtime. Tests and plain vite builds have none. */
284
+ export function installRemoteOverrides(): void {
285
+ if (!getInstance()) return
286
+
287
+ registerPlugins([remoteOverridesPlugin])
288
+ applyRemoteOverrides()
289
+ }
@@ -0,0 +1,105 @@
1
+ import {
2
+ useEffect,
3
+ useMemo,
4
+ useEffectEvent,
5
+ useRef,
6
+ useSyncExternalStore,
7
+ type ComponentType,
8
+ type ReactNode,
9
+ } from 'react'
10
+ import { createRemoteLoader, warnUnknownRemote, type RemoteError } from './core'
11
+ import { remotes, type RemoteEntry, type RemoteName } from './remotes'
12
+ import { reportRemoteError } from './report'
13
+
14
+ type MountFunction = (target: HTMLElement, props?: object) => () => void
15
+
16
+ export interface RemoteProps<Props extends object = Record<string, never>> {
17
+ name: RemoteName
18
+ /** Forwarded to the remote: props on a component contract, a second
19
+ * mount(el, props) argument on a mount contract. */
20
+ props?: Props
21
+ /** Shown while the remote is still loading. */
22
+ fallback?: ReactNode
23
+ /** Shown when it fails to load. Call retry to start the load over. Errors
24
+ * the remote throws once loaded go to the app's error boundaries instead. */
25
+ renderError?: (error: RemoteError, retry: () => void) => ReactNode
26
+ /** Called when it fails to load. */
27
+ onError?: (error: RemoteError, name: RemoteName) => void
28
+ }
29
+
30
+ type RemoteViewProps<Props extends object> = RemoteProps<Props> & { entry: RemoteEntry }
31
+
32
+ export function Remote<Props extends object = Record<string, never>>(props: RemoteProps<Props>) {
33
+ const entry = remotes[props.name] as RemoteEntry | undefined
34
+
35
+ if (!entry) {
36
+ warnUnknownRemote(props.name)
37
+
38
+ return null
39
+ }
40
+
41
+ // Keyed by name, so a new name starts a new load.
42
+ return <RemoteView key={props.name} {...props} entry={entry} />
43
+ }
44
+
45
+ function RemoteView<Props extends object>({
46
+ name,
47
+ entry,
48
+ props,
49
+ fallback = null,
50
+ renderError = renderDefaultError,
51
+ onError,
52
+ }: RemoteViewProps<Props>) {
53
+ const loader = useMemo(() => createRemoteLoader(name, entry.load), [name, entry])
54
+ const state = useSyncExternalStore(loader.subscribe, loader.getState, loader.getState)
55
+ const reportError = useEffectEvent((error: RemoteError) => {
56
+ reportRemoteError(name, error)
57
+ onError?.(error, name)
58
+ })
59
+
60
+ useEffect(() => {
61
+ if (state.status === 'error') reportError(state.error)
62
+ }, [state])
63
+
64
+ if (state.status === 'loading') return fallback
65
+
66
+ if (state.status === 'error') return renderError(state.error, loader.retry)
67
+
68
+ if (entry.contract === 'component') {
69
+ const View = state.module.default as ComponentType<Record<string, unknown>>
70
+
71
+ return <View {...props} />
72
+ }
73
+
74
+ return <MountTarget mount={state.module.default as MountFunction} props={props} />
75
+ }
76
+
77
+ function MountTarget({ mount, props }: { mount: MountFunction; props?: object | undefined }) {
78
+ const target = useRef<HTMLDivElement>(null)
79
+ // A mount function takes its props once, when it mounts.
80
+ const mountProps = useRef(props)
81
+
82
+ useEffect(() => {
83
+ if (!target.current) return
84
+
85
+ return mount(target.current, mountProps.current)
86
+ }, [mount])
87
+
88
+ return <div ref={target} />
89
+ }
90
+
91
+ function reloadPage(): void {
92
+ window.location.reload()
93
+ }
94
+
95
+ /** Unstyled on purpose. Pass renderError to make it yours. */
96
+ function renderDefaultError(error: RemoteError, retry: () => void): ReactNode {
97
+ return (
98
+ <div role="alert" data-remote-error="">
99
+ <p>This section could not be loaded.</p>
100
+ <button type="button" onClick={error.needsReload ? reloadPage : retry}>
101
+ {error.needsReload ? 'Reload page' : 'Try again'}
102
+ </button>
103
+ </div>
104
+ )
105
+ }