@mandujs/core 0.20.10 → 0.22.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.
Files changed (127) hide show
  1. package/README.md +2 -1
  2. package/package.json +28 -3
  3. package/src/auth/__tests__/login.test.ts +419 -0
  4. package/src/auth/__tests__/password.test.ts +122 -0
  5. package/src/auth/__tests__/reset.test.ts +296 -0
  6. package/src/auth/__tests__/tokens.test.ts +274 -0
  7. package/src/auth/__tests__/verification.test.ts +274 -0
  8. package/src/auth/index.ts +76 -0
  9. package/src/auth/login.ts +225 -0
  10. package/src/auth/password.ts +120 -0
  11. package/src/auth/reset.ts +243 -0
  12. package/src/auth/tokens.ts +612 -0
  13. package/src/auth/verification.ts +253 -0
  14. package/src/bundler/__tests__/cli-bench-utils.test.ts +149 -0
  15. package/src/bundler/__tests__/cold-start.test.ts +504 -0
  16. package/src/bundler/__tests__/csp-nonce.test.ts +278 -0
  17. package/src/bundler/__tests__/dev-reliability.test.ts +619 -0
  18. package/src/bundler/__tests__/extended-watch.test.ts +710 -0
  19. package/src/bundler/__tests__/fast-refresh.test.ts +596 -0
  20. package/src/bundler/__tests__/hdr.test.ts +353 -0
  21. package/src/bundler/__tests__/hmr-client.test.ts +532 -0
  22. package/src/bundler/__tests__/manifest-schema.test.ts +266 -0
  23. package/src/bundler/__tests__/prod-smoke.test.ts +138 -0
  24. package/src/bundler/__tests__/slot-dispatch.test.ts +573 -0
  25. package/src/bundler/__tests__/url-cap-and-slot-regex.test.ts +286 -0
  26. package/src/bundler/__tests__/vendor-cache.test.ts +455 -0
  27. package/src/bundler/build.test.ts +8 -1
  28. package/src/bundler/build.ts +495 -37
  29. package/src/bundler/css.ts +326 -323
  30. package/src/bundler/dev.ts +1671 -80
  31. package/src/bundler/fast-refresh-plugin.ts +307 -0
  32. package/src/bundler/hmr-types.ts +252 -0
  33. package/src/bundler/manifest-schema.ts +301 -0
  34. package/src/bundler/safe-build.test.ts +128 -0
  35. package/src/bundler/safe-build.ts +77 -0
  36. package/src/bundler/scenario-matrix.ts +229 -0
  37. package/src/bundler/types.ts +19 -0
  38. package/src/bundler/vendor-cache-types.ts +130 -0
  39. package/src/bundler/vendor-cache.ts +526 -0
  40. package/src/client/router.ts +214 -56
  41. package/src/config/validate.ts +1 -0
  42. package/src/db/__tests__/db.test.ts +485 -0
  43. package/src/db/index.ts +513 -0
  44. package/src/db/migrations/__tests__/runner.test.ts +661 -0
  45. package/src/db/migrations/history-table.ts +345 -0
  46. package/src/db/migrations/lock.ts +269 -0
  47. package/src/db/migrations/runner.ts +633 -0
  48. package/src/desktop/__tests__/smoke.test.ts +100 -0
  49. package/src/desktop/__tests__/window.test.ts +172 -0
  50. package/src/desktop/__tests__/worker.test.ts +266 -0
  51. package/src/desktop/index.ts +43 -0
  52. package/src/desktop/types.ts +158 -0
  53. package/src/desktop/window.ts +492 -0
  54. package/src/desktop/worker.ts +180 -0
  55. package/src/devtools/ai/mcp-connector.ts +18 -16
  56. package/src/devtools/client/components/mandu-character.tsx +4 -1
  57. package/src/devtools/client/components/panel/panel-container.tsx +20 -5
  58. package/src/email/__tests__/email.test.ts +355 -0
  59. package/src/email/index.ts +282 -0
  60. package/src/email/resend.ts +163 -0
  61. package/src/email/smtp.ts +64 -0
  62. package/src/filling/__tests__/session-sqlite.test.ts +454 -0
  63. package/src/filling/context.ts +72 -78
  64. package/src/filling/cookie-codec.ts +299 -0
  65. package/src/filling/deps.ts +25 -1
  66. package/src/filling/filling.ts +28 -3
  67. package/src/filling/session-sqlite.ts +617 -0
  68. package/src/filling/session.ts +265 -216
  69. package/src/guard/decision-memory.test.ts +52 -22
  70. package/src/id/__tests__/id.test.ts +120 -0
  71. package/src/id/index.ts +105 -0
  72. package/src/kitchen/index.ts +2 -2
  73. package/src/kitchen/kitchen-handler.ts +86 -0
  74. package/src/kitchen/stream/activity-sse.ts +2 -1
  75. package/src/middleware/csrf.ts +328 -0
  76. package/src/middleware/index.ts +40 -0
  77. package/src/middleware/oauth/__tests__/oauth.test.ts +574 -0
  78. package/src/middleware/oauth/index.ts +505 -0
  79. package/src/middleware/oauth/providers.ts +115 -0
  80. package/src/middleware/rate-limit/__tests__/rate-limit.test.ts +642 -0
  81. package/src/middleware/rate-limit/index.ts +522 -0
  82. package/src/middleware/rate-limit/sqlite-store.ts +382 -0
  83. package/src/middleware/secure/__tests__/secure.test.ts +360 -0
  84. package/src/middleware/secure/csp.ts +193 -0
  85. package/src/middleware/secure/index.ts +417 -0
  86. package/src/middleware/session.ts +174 -0
  87. package/src/observability/event-bus.ts +81 -79
  88. package/src/paths.ts +37 -0
  89. package/src/perf/hmr-markers.ts +215 -0
  90. package/src/perf/index.ts +104 -0
  91. package/src/resource/__tests__/generator.test.ts +603 -2
  92. package/src/resource/ddl/__tests__/diff.test.ts +639 -0
  93. package/src/resource/ddl/__tests__/emit.test.ts +799 -0
  94. package/src/resource/ddl/__tests__/snapshot.test.ts +499 -0
  95. package/src/resource/ddl/diff.ts +392 -0
  96. package/src/resource/ddl/emit.ts +548 -0
  97. package/src/resource/ddl/persistence-types.ts +218 -0
  98. package/src/resource/ddl/snapshot.ts +447 -0
  99. package/src/resource/ddl/type-map.ts +223 -0
  100. package/src/resource/ddl/types.ts +232 -0
  101. package/src/resource/generator-repo.ts +610 -0
  102. package/src/resource/generator-schema.ts +476 -0
  103. package/src/resource/generator.ts +117 -1
  104. package/src/resource/index.ts +17 -1
  105. package/src/resource/schema.ts +30 -0
  106. package/src/router/fs-scanner.ts +3 -0
  107. package/src/runtime/__tests__/error-boundary-redaction.test.ts +141 -0
  108. package/src/runtime/__tests__/hdr-client.test.ts +223 -0
  109. package/src/runtime/__tests__/http-errors.test.ts +117 -0
  110. package/src/runtime/__tests__/not-found.test.ts +152 -0
  111. package/src/runtime/boundary.tsx +21 -1
  112. package/src/runtime/fast-refresh-runtime.ts +322 -0
  113. package/src/runtime/fast-refresh-types.ts +128 -0
  114. package/src/runtime/hmr-client.ts +409 -0
  115. package/src/runtime/http-errors.ts +113 -0
  116. package/src/runtime/index.ts +6 -0
  117. package/src/runtime/logger.ts +678 -677
  118. package/src/runtime/not-found.ts +93 -0
  119. package/src/runtime/redirect.ts +133 -0
  120. package/src/runtime/server.ts +679 -23
  121. package/src/runtime/ssr.ts +340 -10
  122. package/src/runtime/streaming-ssr.ts +222 -19
  123. package/src/scheduler/__tests__/scheduler.test.ts +514 -0
  124. package/src/scheduler/index.ts +343 -0
  125. package/src/storage/s3/__tests__/s3.test.ts +479 -0
  126. package/src/storage/s3/index.ts +412 -0
  127. package/src/testing/index.ts +247 -189
@@ -29,12 +29,32 @@ export interface ErrorBoundaryProps {
29
29
  }
30
30
 
31
31
  export interface ErrorFallbackProps {
32
- /** 발생한 에러 */
32
+ /**
33
+ * 발생한 에러.
34
+ *
35
+ * Phase 6.3 redaction contract:
36
+ * - In dev (`isDev === true`): the original Error is passed through with
37
+ * full `.stack`, identical to throw time.
38
+ * - In prod (`isDev === false`): a shallow clone is passed with
39
+ * `.message` preserved and `.stack` set to the top 3 frames only.
40
+ * The `digest` prop correlates the redacted client view with the
41
+ * full stack emitted to server logs.
42
+ *
43
+ * The enforcement point is `loadPageData` / `renderPageSSR` error
44
+ * paths in `runtime/server.ts` — user-land `error.tsx` components
45
+ * simply consume the props they're given.
46
+ */
33
47
  error: Error;
34
48
  /** 에러 정보 */
35
49
  errorInfo?: ErrorInfo;
36
50
  /** 리셋 함수 (에러 상태 초기화) */
37
51
  resetError: () => void;
52
+ /**
53
+ * Short opaque identifier correlating this error with the server-side
54
+ * log entry. Present in both dev and prod. Users display it in their
55
+ * error.tsx so support teams can find the exact failure.
56
+ */
57
+ digest?: string;
38
58
  }
39
59
 
40
60
  interface ErrorBoundaryState {
@@ -0,0 +1,322 @@
1
+ /**
2
+ * Phase 7.1 B-2 — Browser-side Fast Refresh glue.
3
+ *
4
+ * This module runs in the dev-mode browser. It is the **only** module that
5
+ * imports `react-refresh/runtime`, so the attack surface (Phase 7.1.E
6
+ * security audit) is exactly one file and one well-known global:
7
+ * `window.__MANDU_HMR__`.
8
+ *
9
+ * Why this file exists
10
+ * ─────────────────────
11
+ * Bun 1.3.12's `Bun.build({ reactFastRefresh: true })` inserts calls to
12
+ * `$RefreshReg$` and `$RefreshSig$` into every `.tsx`/`.ts` module. Those
13
+ * globals must be present **before** the transformed module evaluates.
14
+ * `installGlobal()` wires them up to the official React Refresh runtime,
15
+ * and also exposes the three-call surface described in
16
+ * `fast-refresh-types.ts` (`acceptFile` / `performReactRefresh` /
17
+ * `isBoundary`) so the rest of Mandu's HMR plumbing (bundler-injected
18
+ * boundary code + `hmr-client.ts`'s `dispatchReplacement`) has a single
19
+ * stable API to talk to.
20
+ *
21
+ * Design constraints honored here:
22
+ *
23
+ * 1. **Deduplicated boundaries** — `acceptFile(url)` is idempotent. Calling
24
+ * it twice for the same URL is a no-op. This matters because the same
25
+ * island JS file is loaded once at hydration and re-loaded after every
26
+ * hot replace; both loads re-execute the bundler-injected call.
27
+ *
28
+ * 2. **Coalesced refreshes** — multiple replacements in the same tick (for
29
+ * example, a batched rebuild that emitted 3 new island bundles) must
30
+ * produce a single React tree re-render. We schedule the refresh on a
31
+ * microtask and clear the flag when it fires; subsequent same-tick
32
+ * calls are absorbed.
33
+ *
34
+ * 3. **Degradable** — if `react-refresh/runtime` fails to load (user
35
+ * ejected it, firewall, whatever), `installGlobal()` still installs a
36
+ * no-op `__MANDU_HMR__` so `dispatchReplacement` doesn't throw; it just
37
+ * never triggers a refresh, so the fallback full-reload path in the
38
+ * HMR client script owns recovery.
39
+ *
40
+ * 4. **Test-only reset** — `_testOnly_reset()` clears both the boundary
41
+ * registry and any pending microtask. It is exposed via the runtime
42
+ * API surface (and namespaced with `_testOnly_` to make audit easy),
43
+ * not via a separate export, because the HTML preamble binds against
44
+ * `__MANDU_HMR__` and we want tests to exercise the same object.
45
+ *
46
+ * References:
47
+ * docs/bun/phase-7-1-diagnostics/fast-refresh-strategy.md §4
48
+ * docs/bun/phase-7-1-team-plan.md §4 Agent B
49
+ * packages/core/src/runtime/fast-refresh-types.ts
50
+ * https://github.com/facebook/react/tree/main/packages/react-refresh
51
+ */
52
+
53
+ import type { ManduHMRGlobal } from "./fast-refresh-types";
54
+
55
+ // ============================================
56
+ // react-refresh/runtime shape (structural)
57
+ // ============================================
58
+
59
+ /**
60
+ * Subset of the `react-refresh/runtime` API we consume. Kept as a local
61
+ * structural type rather than `@types/react-refresh` to avoid introducing
62
+ * a dev-dep and keep this module compilable even when the runtime is
63
+ * absent (see degradable design above). The four members below are
64
+ * stable across `react-refresh` >=0.10 per the upstream README.
65
+ */
66
+ export interface ReactRefreshRuntime {
67
+ /**
68
+ * Install module-registry hooks into React internals. Called once
69
+ * during `installGlobal()`. Idempotent in the upstream runtime.
70
+ */
71
+ injectIntoGlobalHook: (target: typeof globalThis) => void;
72
+ /**
73
+ * Register a component type so its next swap can be matched. Bundler
74
+ * emits `$RefreshReg$(type, id)` which delegates here.
75
+ */
76
+ register: (type: unknown, id: string) => void;
77
+ /**
78
+ * Return a function used to wrap components and annotate hook usage.
79
+ * Bundler emits `$RefreshSig$()` → returns the wrapper — then calls
80
+ * the wrapper with the component and its hook hash.
81
+ */
82
+ createSignatureFunctionForTransform: () => (
83
+ ...args: readonly unknown[]
84
+ ) => unknown;
85
+ /**
86
+ * Walk every registered family and force a React re-render of any
87
+ * component whose identity has changed since the last refresh. Safe to
88
+ * call with no changes — a no-op in that case.
89
+ */
90
+ performReactRefresh: () => void;
91
+ }
92
+
93
+ // ============================================
94
+ // Internal state
95
+ // ============================================
96
+
97
+ /**
98
+ * Fully loaded runtime. `null` until `installGlobal()` resolves the import.
99
+ */
100
+ let runtime: ReactRefreshRuntime | null = null;
101
+
102
+ /**
103
+ * Boundary registry. Each entry is a module URL the bundler (or the
104
+ * user, via `window.__MANDU_HMR__.acceptFile(...)`) has claimed as a
105
+ * Fast Refresh root.
106
+ */
107
+ const boundaries = new Set<string>();
108
+
109
+ /**
110
+ * Coalescing flag for `performReactRefresh`. Set to `true` the moment a
111
+ * refresh is scheduled and cleared inside the microtask body. Further
112
+ * calls in the same tick short-circuit.
113
+ */
114
+ let refreshScheduled = false;
115
+
116
+ // ============================================
117
+ // Exports
118
+ // ============================================
119
+
120
+ /**
121
+ * Install a stub `$RefreshReg$` / `$RefreshSig$` on the target object
122
+ * **before** any transformed module evaluates. The stubs are inert —
123
+ * they capture the minimum information we need to connect to the real
124
+ * runtime later via `bindRuntime()`. Exposed separately so the HTML
125
+ * preamble (Phase 7.1 B-3, `bundler/dev.ts`) can call it inline without
126
+ * waiting for the ES-module-loaded runtime.
127
+ *
128
+ * Calling this before the runtime has loaded is the correct sequence
129
+ * per React Refresh docs: Vite does the same thing in its preamble.
130
+ */
131
+ export function installPreamble(target: typeof globalThis): void {
132
+ // These stubs must be assignable even in strict mode — cast via
133
+ // `(target as any)` so TS doesn't complain about unknown globals.
134
+ const t = target as unknown as {
135
+ $RefreshReg$?: unknown;
136
+ $RefreshSig$?: unknown;
137
+ };
138
+ if (!t.$RefreshReg$) {
139
+ t.$RefreshReg$ = () => undefined;
140
+ }
141
+ if (!t.$RefreshSig$) {
142
+ // Identity signature — returns a function whose return is its arg.
143
+ t.$RefreshSig$ = () => (type: unknown) => type;
144
+ }
145
+ }
146
+
147
+ /**
148
+ * Connect the loaded `react-refresh/runtime` to the globals and to our
149
+ * dispatcher. After this runs:
150
+ * - `$RefreshReg$(type, id)` → `runtime.register(type, id)`
151
+ * - `$RefreshSig$()` → `runtime.createSignatureFunctionForTransform()`
152
+ * - `window.__MANDU_HMR__.performReactRefresh()` is backed by the real
153
+ * `runtime.performReactRefresh`
154
+ *
155
+ * Safe to call multiple times; the last runtime wins.
156
+ */
157
+ export function bindRuntime(rt: ReactRefreshRuntime): void {
158
+ runtime = rt;
159
+
160
+ // Install into React internals. `react-refresh` manages its own
161
+ // idempotency so re-binding the same runtime is fine.
162
+ try {
163
+ rt.injectIntoGlobalHook(globalThis as typeof globalThis);
164
+ } catch (err) {
165
+ // Non-fatal — we still want the stubs installed. Log and continue.
166
+ // eslint-disable-next-line no-console
167
+ console.error(
168
+ "[Mandu Fast Refresh] injectIntoGlobalHook threw; refresh will be a no-op:",
169
+ err,
170
+ );
171
+ }
172
+
173
+ // Replace the stubs the preamble installed with live wrappers.
174
+ const g = globalThis as unknown as {
175
+ $RefreshReg$?: (type: unknown, id: string) => void;
176
+ $RefreshSig$?: () => (...args: readonly unknown[]) => unknown;
177
+ };
178
+ g.$RefreshReg$ = (type: unknown, id: string): void => {
179
+ try {
180
+ rt.register(type, id);
181
+ } catch {
182
+ // Mismatched runtime versions or bad transforms — never throw
183
+ // into user code during HMR.
184
+ }
185
+ };
186
+ g.$RefreshSig$ = (): ((...args: readonly unknown[]) => unknown) => {
187
+ try {
188
+ return rt.createSignatureFunctionForTransform();
189
+ } catch {
190
+ // Return identity so transformed code keeps working.
191
+ return (t: unknown) => t;
192
+ }
193
+ };
194
+ }
195
+
196
+ /**
197
+ * The `ManduHMRGlobal` implementation installed at
198
+ * `window.__MANDU_HMR__`. Kept as a named export so tests can assert on
199
+ * it directly without inspecting `window`.
200
+ */
201
+ export const manduHMR: ManduHMRGlobal = {
202
+ acceptFile(moduleUrl: string): void {
203
+ if (typeof moduleUrl !== "string" || moduleUrl.length === 0) return;
204
+ // Idempotent — `Set` already handles this but kept explicit for
205
+ // clarity in security audit reviews.
206
+ boundaries.add(moduleUrl);
207
+ },
208
+
209
+ isBoundary(moduleUrl: string): boolean {
210
+ return boundaries.has(moduleUrl);
211
+ },
212
+
213
+ performReactRefresh(): void {
214
+ // Coalesce: if another call already scheduled a refresh for this
215
+ // tick, defer to it. This matters when a batched rebuild replaces
216
+ // 3 modules — we only want one refresh pass.
217
+ if (refreshScheduled) return;
218
+
219
+ // No runtime = degraded mode. The HMR client's full-reload path
220
+ // owns recovery, so we just silently no-op.
221
+ if (runtime === null) return;
222
+
223
+ refreshScheduled = true;
224
+ // Microtask beats both `setTimeout` and `requestAnimationFrame`
225
+ // here — we want the refresh to run before the next paint so the
226
+ // user doesn't see the stale tree flash. `queueMicrotask` is
227
+ // available in every browser Mandu targets (ES2020+).
228
+ queueMicrotask(() => {
229
+ refreshScheduled = false;
230
+ try {
231
+ runtime?.performReactRefresh();
232
+ } catch (err) {
233
+ // eslint-disable-next-line no-console
234
+ console.error("[Mandu Fast Refresh] performReactRefresh threw:", err);
235
+ }
236
+ });
237
+ },
238
+
239
+ _testOnly_reset(): void {
240
+ boundaries.clear();
241
+ refreshScheduled = false;
242
+ runtime = null;
243
+ },
244
+ };
245
+
246
+ /**
247
+ * Install the preamble stubs, attach `__MANDU_HMR__`, and asynchronously
248
+ * bind the real `react-refresh/runtime`. This is the single entry point
249
+ * the HTML preamble calls. Safe to call from a `<script type="module">`
250
+ * or a cold top-level import.
251
+ *
252
+ * The async-bind shape is intentional: the preamble runs inline, but
253
+ * the runtime binary is an ES module that must be fetched. During the
254
+ * window between "preamble runs" and "runtime binds", transformed
255
+ * modules that import-then-call `$RefreshReg$` hit the stub, which is a
256
+ * no-op. The worst-case consequence is that the first module evaluated
257
+ * in the page isn't registered — which is fine, because a refresh
258
+ * can't target an unloaded module anyway.
259
+ */
260
+ export async function installGlobal(options?: {
261
+ runtime?: ReactRefreshRuntime;
262
+ runtimeImport?: () => Promise<ReactRefreshRuntime | { default: ReactRefreshRuntime }>;
263
+ }): Promise<void> {
264
+ installPreamble(globalThis as typeof globalThis);
265
+
266
+ // Attach the global. We keep a single identity across calls so tests
267
+ // that import `manduHMR` directly see the same object as
268
+ // `window.__MANDU_HMR__`.
269
+ const w = globalThis as unknown as { __MANDU_HMR__?: ManduHMRGlobal };
270
+ w.__MANDU_HMR__ = manduHMR;
271
+
272
+ let rt: ReactRefreshRuntime | null = options?.runtime ?? null;
273
+ if (rt === null && options?.runtimeImport) {
274
+ try {
275
+ const mod = await options.runtimeImport();
276
+ rt =
277
+ (mod as { default?: ReactRefreshRuntime }).default ??
278
+ (mod as ReactRefreshRuntime);
279
+ } catch (err) {
280
+ // eslint-disable-next-line no-console
281
+ console.error(
282
+ "[Mandu Fast Refresh] failed to load react-refresh runtime:",
283
+ err,
284
+ );
285
+ rt = null;
286
+ }
287
+ }
288
+
289
+ if (rt !== null) {
290
+ bindRuntime(rt);
291
+ }
292
+ }
293
+
294
+ // ============================================
295
+ // Test helpers — NOT part of the public API
296
+ // ============================================
297
+
298
+ /**
299
+ * Test-only: inspect registered boundary count.
300
+ * @internal
301
+ */
302
+ export function _getBoundaryCountForTests(): number {
303
+ return boundaries.size;
304
+ }
305
+
306
+ /**
307
+ * Test-only: inspect whether a refresh is queued.
308
+ * @internal
309
+ */
310
+ export function _isRefreshScheduledForTests(): boolean {
311
+ return refreshScheduled;
312
+ }
313
+
314
+ /**
315
+ * Test-only: reset module-level state. Equivalent to
316
+ * `manduHMR._testOnly_reset()` but exposed as a named export so tests
317
+ * can be explicit.
318
+ * @internal
319
+ */
320
+ export function _resetForTests(): void {
321
+ manduHMR._testOnly_reset();
322
+ }
@@ -0,0 +1,128 @@
1
+ /**
2
+ * Phase 7.1 — Fast Refresh shared types
3
+ *
4
+ * Bun 1.3.12 ships a native `Bun.build({ reactFastRefresh: true })` flag
5
+ * that performs the `$RefreshReg$` / `$RefreshSig$` source transform
6
+ * (equivalent to `babel-plugin-react-refresh`). Agent B's implementation
7
+ * wires this into Mandu's bundler + a browser-side runtime that glues
8
+ * `react-refresh/runtime` to our existing `ManduHot` dispatcher from
9
+ * Phase 7.0.C.
10
+ *
11
+ * This file is the CONTRACT. Types only — the implementation lives in:
12
+ * - packages/core/src/bundler/fast-refresh-plugin.ts (Agent B new)
13
+ * - packages/core/src/runtime/fast-refresh-runtime.ts (Agent B new)
14
+ * - packages/core/src/bundler/build.ts (Agent B extend — vendor shim)
15
+ * - packages/core/src/bundler/dev.ts (Agent B extend — HTML preamble)
16
+ *
17
+ * References:
18
+ * docs/bun/phase-7-1-diagnostics/fast-refresh-strategy.md
19
+ * docs/bun/phase-7-1-team-plan.md §3.2
20
+ * https://bun.com/reference/bun/NormalBuildConfig/reactFastRefresh
21
+ */
22
+
23
+ // ============================================
24
+ // Browser-side `__MANDU_HMR__` global
25
+ // ============================================
26
+
27
+ /**
28
+ * The single global object Mandu's bundler-emitted boundary code talks
29
+ * to. Installed by the HTML preamble script before any island runs.
30
+ *
31
+ * Keeping all Fast Refresh wiring behind this single namespace makes
32
+ * the attack surface (Phase 7.1.E security audit) a single module.
33
+ */
34
+ export interface ManduHMRGlobal {
35
+ /**
36
+ * Register a module URL as an HMR boundary. Emitted by the bundler
37
+ * onLoad plugin (Agent B) for each `.client.tsx` / `.island.tsx`.
38
+ * Idempotent — registering the same URL twice is a no-op.
39
+ */
40
+ acceptFile(moduleUrl: string): void;
41
+
42
+ /**
43
+ * Invoke `react-refresh/runtime.performReactRefresh()` on the next
44
+ * microtask. Coalesces multiple calls within the same tick into a
45
+ * single refresh, so a batched rebuild that swaps 3 modules only
46
+ * re-renders the React tree once.
47
+ */
48
+ performReactRefresh(): void;
49
+
50
+ /**
51
+ * Whether `moduleUrl` was ever registered via `acceptFile`. Used by
52
+ * `dispatchReplacement` (Phase 7.0.C runtime/hmr-client.ts) to decide
53
+ * between "call performReactRefresh" vs "full reload fallback".
54
+ */
55
+ isBoundary(moduleUrl: string): boolean;
56
+
57
+ /**
58
+ * Reset state — test-only. Clears the boundary registry and React
59
+ * refresh runtime scheduling state. Must NOT be exposed in production
60
+ * bundles; tests import this via the `runtime/fast-refresh-runtime.ts`
61
+ * module directly.
62
+ */
63
+ _testOnly_reset(): void;
64
+ }
65
+
66
+ /**
67
+ * Metadata the bundler attaches to each emitted boundary. Not part of
68
+ * the runtime API — consumed only by dev-mode tooling (hmr-bench,
69
+ * Kitchen DevTools) and by the security audit (Phase 7.1.E) to verify
70
+ * that every injected boundary traces back to a real source file.
71
+ */
72
+ export interface RefreshBoundaryMetadata {
73
+ /** URL the module is served under (e.g. `/.mandu/client/home.island.js`). */
74
+ moduleUrl: string;
75
+ /** Source files that were bundled into this module, from Bun.build's
76
+ * inline sourcemap `sources[]` (same mechanism Phase 7.0.B uses). */
77
+ sources: readonly string[];
78
+ /** Unix ms when the boundary was registered — for debug log ordering. */
79
+ registeredAt: number;
80
+ }
81
+
82
+ // ============================================
83
+ // Bundler side
84
+ // ============================================
85
+
86
+ /**
87
+ * Options passed to the Fast Refresh Bun.build plugin (Agent B new file
88
+ * `bundler/fast-refresh-plugin.ts`). All optional — sensible defaults
89
+ * match Vite's `@vitejs/plugin-react` behavior.
90
+ */
91
+ export interface FastRefreshPluginOptions {
92
+ /** Only transform files matching this test. Default: `/\.(client|island)\.tsx?$/`. */
93
+ include?: RegExp;
94
+ /** Bypass the transform entirely. Used for prod builds. Default: `false`. */
95
+ disabled?: boolean;
96
+ /**
97
+ * Runtime module specifier the plugin's injected import points at.
98
+ * Default: `"@mandujs/core/runtime/fast-refresh-runtime"`. Tests can
99
+ * override to a tmpdir-local stub.
100
+ */
101
+ runtimeImport?: string;
102
+ }
103
+
104
+ /**
105
+ * Classification of why a module was (or wasn't) made a Fast Refresh
106
+ * boundary. Used by the plugin's debug log + Agent D's E2E assertions.
107
+ */
108
+ export type BoundaryDecision =
109
+ | { accepted: true; reason: "matched-include"; source: string }
110
+ | { accepted: false; reason: "excluded-by-include" | "disabled" | "non-react" };
111
+
112
+ // ============================================
113
+ // Global augmentation — Window type
114
+ // ============================================
115
+
116
+ /**
117
+ * Expose `__MANDU_HMR__` on the browser Window without polluting Node
118
+ * typings. Users of the plugin see `window.__MANDU_HMR__.acceptFile(...)`
119
+ * as strongly typed in TSX files.
120
+ */
121
+ declare global {
122
+ interface Window {
123
+ /** Phase 7.1 Fast Refresh glue. Installed by HTML preamble. */
124
+ __MANDU_HMR__?: ManduHMRGlobal;
125
+ }
126
+ }
127
+
128
+ export {}; // ensure this file is a module for `declare global`