@mandujs/core 0.54.32 → 0.55.0-beta.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 (414) hide show
  1. package/README.md +654 -654
  2. package/package.json +106 -210
  3. package/scripts/postinstall-lock.ts +153 -153
  4. package/src/a11y/__tests__/run-audit.test.ts +333 -333
  5. package/src/a11y/fix-hints.ts +76 -76
  6. package/src/a11y/index.ts +18 -18
  7. package/src/a11y/run-audit.ts +15 -15
  8. package/src/a11y/types.ts +125 -125
  9. package/src/agent/__tests__/apply.test.ts +224 -0
  10. package/src/agent/__tests__/context.test.ts +97 -98
  11. package/src/agent/apply.ts +1031 -0
  12. package/src/agent/context.ts +552 -552
  13. package/src/agent/index.ts +4 -3
  14. package/src/agent/plan.ts +161 -243
  15. package/src/agent/repair.ts +239 -162
  16. package/src/agent/sync.ts +197 -198
  17. package/src/agent/types.ts +242 -94
  18. package/src/agent/verify.ts +55 -55
  19. package/src/auth/__tests__/login.test.ts +1 -1
  20. package/src/auth/__tests__/password.test.ts +15 -5
  21. package/src/auth/__tests__/reset.test.ts +2 -2
  22. package/src/auth/__tests__/tokens.test.ts +274 -274
  23. package/src/auth/__tests__/verification.test.ts +274 -274
  24. package/src/auth/index.ts +76 -76
  25. package/src/auth/login.ts +225 -225
  26. package/src/auth/password.ts +14 -2
  27. package/src/auth/reset.ts +243 -243
  28. package/src/auth/tokens.ts +612 -612
  29. package/src/auth/verification.ts +253 -253
  30. package/src/brain/__tests__/redactor.test.ts +94 -94
  31. package/src/brain/adapters/__tests__/_helpers.ts +83 -83
  32. package/src/brain/adapters/__tests__/anthropic-oauth.test.ts +196 -196
  33. package/src/brain/adapters/__tests__/chatgpt-auth.test.ts +193 -193
  34. package/src/brain/adapters/__tests__/openai-oauth.test.ts +209 -209
  35. package/src/brain/adapters/__tests__/resolver.test.ts +143 -143
  36. package/src/brain/adapters/anthropic-oauth.ts +1 -1
  37. package/src/brain/adapters/chatgpt-auth.ts +300 -300
  38. package/src/brain/adapters/index.ts +319 -319
  39. package/src/brain/adapters/oauth-flow.ts +439 -439
  40. package/src/brain/consent.ts +240 -240
  41. package/src/brain/credentials.ts +396 -396
  42. package/src/brain/doctor/analyzer.ts +7 -7
  43. package/src/bundler/__snapshots__/build.test.ts.snap +5 -5
  44. package/src/bundler/__tests__/build-runner.ts +166 -166
  45. package/src/bundler/__tests__/client-boundary-transform.test.ts +524 -524
  46. package/src/bundler/__tests__/cold-start.test.ts +60 -60
  47. package/src/bundler/__tests__/css.test.ts +49 -20
  48. package/src/bundler/__tests__/dev-reliability.test.ts +619 -619
  49. package/src/bundler/__tests__/extended-watch.test.ts +711 -711
  50. package/src/bundler/__tests__/fast-refresh.test.ts +24 -24
  51. package/src/bundler/__tests__/generation.test.ts +447 -0
  52. package/src/bundler/__tests__/hdr.test.ts +24 -18
  53. package/src/bundler/__tests__/hmr-client.test.ts +62 -24
  54. package/src/bundler/__tests__/jsx-runtime-shim.test.ts +179 -140
  55. package/src/bundler/__tests__/manifest-schema.test.ts +305 -266
  56. package/src/bundler/__tests__/prod-smoke.test.ts +138 -138
  57. package/src/bundler/__tests__/reverse-import-graph.test.ts +42 -42
  58. package/src/bundler/__tests__/slot-dispatch.test.ts +573 -573
  59. package/src/bundler/__tests__/url-cap-and-slot-regex.test.ts +286 -286
  60. package/src/bundler/__tests__/vendor-cache.test.ts +455 -455
  61. package/src/bundler/analyzer.ts +15 -15
  62. package/src/bundler/budget.ts +404 -404
  63. package/src/bundler/build.test.ts +898 -915
  64. package/src/bundler/build.ts +113 -24
  65. package/src/bundler/client-boundary-transform.ts +977 -977
  66. package/src/bundler/css.ts +65 -44
  67. package/src/bundler/dev.ts +105 -73
  68. package/src/bundler/fast-refresh-preamble.ts +47 -47
  69. package/src/bundler/generation.ts +602 -0
  70. package/src/bundler/index.ts +3 -3
  71. package/src/bundler/manifest-schema.ts +55 -40
  72. package/src/bundler/plugins/__tests__/block-generated-imports.test.ts +13 -13
  73. package/src/bundler/plugins/__tests__/react-compiler-config.test.ts +83 -83
  74. package/src/bundler/plugins/__tests__/react-compiler-lint.test.ts +110 -110
  75. package/src/bundler/plugins/block-generated-imports.ts +16 -15
  76. package/src/bundler/plugins/index.ts +83 -83
  77. package/src/bundler/plugins/react-compiler-config.ts +108 -108
  78. package/src/bundler/plugins/react-compiler-lint.ts +253 -253
  79. package/src/bundler/plugins/react-compiler.ts +162 -162
  80. package/src/bundler/prerender.ts +29 -9
  81. package/src/bundler/reverse-import-graph.ts +339 -339
  82. package/src/bundler/safe-build.test.ts +1 -1
  83. package/src/bundler/safe-build.ts +103 -103
  84. package/src/bundler/scenario-matrix.ts +229 -229
  85. package/src/bundler/types.ts +58 -56
  86. package/src/bundler/vendor-cache-types.ts +130 -130
  87. package/src/bundler/vendor-cache.ts +526 -526
  88. package/src/change/snapshot.ts +18 -18
  89. package/src/client/Form.tsx +105 -105
  90. package/src/client/Link.tsx +9 -9
  91. package/src/client/__tests__/props-serialization.test.ts +37 -37
  92. package/src/client/__tests__/use-sse.test.ts +153 -153
  93. package/src/client/globals.ts +1 -1
  94. package/src/client/hooks.ts +362 -362
  95. package/src/client/hydrate.ts +2 -2
  96. package/src/client/index.ts +1 -1
  97. package/src/client/island.ts +79 -79
  98. package/src/client/prefetch-helper.ts +55 -55
  99. package/src/client/props-serialization.ts +233 -233
  100. package/src/client/runtime-entry.ts +598 -598
  101. package/src/client/runtime.ts +1 -1
  102. package/src/client/serialize.ts +50 -50
  103. package/src/client/use-fetch.ts +6 -6
  104. package/src/client/use-head.ts +197 -197
  105. package/src/client/use-sse.ts +378 -378
  106. package/src/client/window-state.ts +101 -101
  107. package/src/components/Image-compat.ts +3 -0
  108. package/src/components/Image.tsx +162 -162
  109. package/src/config/validate.ts +1 -1
  110. package/src/config/watcher.ts +311 -311
  111. package/src/constants.ts +40 -40
  112. package/src/content/collection.ts +9 -9
  113. package/src/content/content-layer.ts +7 -7
  114. package/src/content/data-store.ts +245 -245
  115. package/src/content/frontmatter.ts +189 -189
  116. package/src/content/generate-types.ts +1 -1
  117. package/src/content/index.ts +2 -2
  118. package/src/content/loader-context.ts +171 -171
  119. package/src/content/loaders/api.ts +216 -216
  120. package/src/content/loaders/file.ts +172 -172
  121. package/src/content/loaders/glob.ts +253 -253
  122. package/src/content/loaders/index.ts +34 -34
  123. package/src/content/loaders/types.ts +137 -137
  124. package/src/content/meta-store.ts +209 -209
  125. package/src/content/prebuild.test.ts +571 -571
  126. package/src/content/prebuild.ts +636 -636
  127. package/src/content/schema.ts +20 -20
  128. package/src/content/sidebar.ts +630 -630
  129. package/src/content/slug.ts +110 -110
  130. package/src/content/types.ts +282 -282
  131. package/src/content/watcher.ts +135 -135
  132. package/src/contract/client-safe.test.ts +42 -42
  133. package/src/contract/client-safe.ts +114 -114
  134. package/src/contract/define.ts +11 -11
  135. package/src/contract/index.ts +1 -1
  136. package/src/contract/normalize.test.ts +276 -276
  137. package/src/contract/normalize.ts +410 -410
  138. package/src/contract/registry.test.ts +206 -206
  139. package/src/contract/route-helpers.ts +1 -1
  140. package/src/contract/rpc.ts +443 -443
  141. package/src/contract/types.ts +58 -58
  142. package/src/db/__tests__/db.test.ts +9 -9
  143. package/src/db/index.ts +2 -2
  144. package/src/db/migrations/history-table.ts +345 -345
  145. package/src/db/migrations/index.ts +3 -3
  146. package/src/db/migrations/lock.ts +324 -324
  147. package/src/db/migrations/runner.ts +650 -650
  148. package/src/deploy/cache.ts +140 -140
  149. package/src/deploy/compile/vercel.ts +344 -344
  150. package/src/deploy/index.ts +87 -87
  151. package/src/deploy/inference/brain.ts +268 -268
  152. package/src/deploy/inference/context.ts +82 -82
  153. package/src/deploy/inference/filling-extract.ts +245 -245
  154. package/src/deploy/inference/heuristic.ts +182 -182
  155. package/src/deploy/intent.ts +173 -173
  156. package/src/deploy/plan.ts +178 -178
  157. package/src/design/__tests__/agents-link.test.ts +109 -109
  158. package/src/design/__tests__/extract-patch-diff.test.ts +265 -265
  159. package/src/design/__tests__/lint.test.ts +110 -110
  160. package/src/design/__tests__/parser.test.ts +195 -195
  161. package/src/design/__tests__/tailwind-theme.test.ts +229 -229
  162. package/src/design/agents-link.ts +165 -165
  163. package/src/design/diff.ts +138 -138
  164. package/src/design/extract.ts +285 -285
  165. package/src/design/index.ts +102 -102
  166. package/src/design/lint.ts +209 -209
  167. package/src/design/parser.ts +555 -555
  168. package/src/design/patch.ts +241 -241
  169. package/src/design/scaffold.ts +147 -147
  170. package/src/design/tailwind-theme.ts +441 -441
  171. package/src/design/types.ts +210 -210
  172. package/src/desktop/__tests__/smoke.test.ts +2 -2
  173. package/src/desktop/__tests__/webview-fallback.test.ts +12 -32
  174. package/src/desktop/__tests__/window.test.ts +20 -99
  175. package/src/desktop/__tests__/worker.test.ts +266 -266
  176. package/src/desktop/index.ts +43 -43
  177. package/src/desktop/types.ts +158 -158
  178. package/src/desktop/webview-fallback.ts +17 -4
  179. package/src/desktop/window.ts +17 -8
  180. package/src/desktop/worker.ts +180 -180
  181. package/src/dev-error-overlay/__tests__/overlay-injector.test.ts +241 -241
  182. package/src/dev-error-overlay/index.ts +30 -30
  183. package/src/dev-error-overlay/overlay-injector.ts +243 -243
  184. package/src/dev-error-overlay/overlay-styles.ts +52 -52
  185. package/src/dev-error-overlay/types.ts +66 -66
  186. package/src/devtools/ai/context-builder.ts +375 -375
  187. package/src/devtools/ai/index.ts +25 -25
  188. package/src/devtools/ai/mcp-connector.ts +25 -25
  189. package/src/devtools/client/catchers/error-catcher.ts +344 -344
  190. package/src/devtools/client/catchers/index.ts +18 -18
  191. package/src/devtools/client/components/index.ts +39 -39
  192. package/src/devtools/client/components/mandu-character.tsx +331 -331
  193. package/src/devtools/client/components/panel/errors-panel.tsx +259 -259
  194. package/src/devtools/client/components/panel/guard-panel.tsx +30 -30
  195. package/src/devtools/client/components/panel/islands-panel.tsx +16 -16
  196. package/src/devtools/client/components/panel/network-panel.tsx +291 -291
  197. package/src/devtools/client/components/panel/panel-container.tsx +1 -1
  198. package/src/devtools/client/components/panel/preview-panel.tsx +46 -46
  199. package/src/devtools/client/filters/context-filters.ts +282 -282
  200. package/src/devtools/client/filters/index.ts +16 -16
  201. package/src/devtools/client/index.ts +63 -63
  202. package/src/devtools/hook/create-hook.ts +207 -207
  203. package/src/devtools/hook/index.ts +13 -13
  204. package/src/devtools/index.ts +439 -439
  205. package/src/devtools/init.ts +265 -265
  206. package/src/devtools/protocol.ts +237 -237
  207. package/src/devtools/server/index.ts +17 -17
  208. package/src/devtools/types.ts +35 -35
  209. package/src/devtools/worker/index.ts +25 -25
  210. package/src/devtools/worker/redaction-worker.ts +233 -233
  211. package/src/diagnose/__tests__/checks.test.ts +136 -136
  212. package/src/diagnose/checks.ts +185 -185
  213. package/src/diagnose/index.ts +17 -17
  214. package/src/diagnose/run.ts +10 -10
  215. package/src/diagnose/types.ts +53 -53
  216. package/src/email/__tests__/email.test.ts +355 -355
  217. package/src/email/index.ts +282 -282
  218. package/src/email/smtp.ts +64 -64
  219. package/src/error/domains.ts +265 -265
  220. package/src/error/types.ts +6 -6
  221. package/src/errors/extractor.ts +409 -409
  222. package/src/errors/index.ts +19 -19
  223. package/src/filling/__tests__/session-sqlite.test.ts +5 -1
  224. package/src/filling/auth.ts +308 -308
  225. package/src/filling/body-parse.test.ts +60 -60
  226. package/src/filling/cookie-codec.ts +5 -3
  227. package/src/filling/deps.ts +265 -265
  228. package/src/filling/head-method.test.ts +154 -154
  229. package/src/filling/session-sqlite.ts +617 -617
  230. package/src/filling/sse.ts +5 -5
  231. package/src/filling/ws.ts +78 -78
  232. package/src/generator/generate.ts +30 -30
  233. package/src/generator/index.ts +3 -3
  234. package/src/generator/templates.test.ts +48 -48
  235. package/src/generator/templates.ts +219 -219
  236. package/src/guard/__tests__/design-inline-class.test.ts +219 -219
  237. package/src/guard/__tests__/tsgolint-bridge.test.ts +347 -347
  238. package/src/guard/analyzer.ts +360 -360
  239. package/src/guard/auto-correct.ts +1 -1
  240. package/src/guard/check.ts +39 -24
  241. package/src/guard/config-guard.ts +13 -13
  242. package/src/guard/contract-guard.ts +9 -9
  243. package/src/guard/define-rule.ts +243 -243
  244. package/src/guard/design-inline-class.ts +393 -393
  245. package/src/guard/file-type.test.ts +24 -24
  246. package/src/guard/fs-routes-policy.ts +51 -51
  247. package/src/guard/graph.ts +1 -1
  248. package/src/guard/healing.ts +36 -36
  249. package/src/guard/index.ts +11 -11
  250. package/src/guard/presets/atomic.ts +70 -70
  251. package/src/guard/presets/clean.ts +77 -77
  252. package/src/guard/presets/fsd.ts +79 -79
  253. package/src/guard/presets/hexagonal.ts +68 -68
  254. package/src/guard/reporter.ts +442 -442
  255. package/src/guard/rule-presets.ts +379 -379
  256. package/src/guard/semantic-slots.ts +1 -1
  257. package/src/guard/suggestions.ts +358 -358
  258. package/src/guard/tsgolint-bridge.ts +512 -512
  259. package/src/guard/types.ts +348 -348
  260. package/src/guard/watcher.ts +405 -405
  261. package/src/i18n/define.ts +126 -126
  262. package/src/i18n/index.ts +52 -52
  263. package/src/i18n/message-registry.ts +173 -173
  264. package/src/i18n/types.ts +112 -112
  265. package/src/id/__tests__/id.test.ts +3 -3
  266. package/src/id/index.ts +105 -105
  267. package/src/index.ts +9 -48
  268. package/src/internal/client-boundary.ts +266 -266
  269. package/src/internal/index.ts +2 -2
  270. package/src/kitchen/api/agent-devtools-api.ts +779 -779
  271. package/src/kitchen/api/bundle-inspector.ts +179 -0
  272. package/src/kitchen/api/errors-grouping.ts +126 -126
  273. package/src/kitchen/api/file-api.ts +11 -11
  274. package/src/kitchen/kitchen-handler.ts +36 -0
  275. package/src/kitchen/kitchen-ui.ts +456 -0
  276. package/src/logging/index.ts +22 -22
  277. package/src/logging/transports.ts +365 -365
  278. package/src/middleware/bridge.ts +147 -147
  279. package/src/middleware/compose.ts +134 -134
  280. package/src/middleware/compress.ts +62 -62
  281. package/src/middleware/cors.ts +47 -47
  282. package/src/middleware/csrf.ts +328 -328
  283. package/src/middleware/define.ts +132 -132
  284. package/src/middleware/jwt.ts +134 -134
  285. package/src/middleware/logger.ts +58 -58
  286. package/src/middleware/oauth/__tests__/oauth.test.ts +1 -1
  287. package/src/middleware/oauth/index.ts +505 -505
  288. package/src/middleware/oauth/providers.ts +115 -115
  289. package/src/middleware/rate-limit/index.ts +522 -522
  290. package/src/middleware/rate-limit/sqlite-store.ts +382 -382
  291. package/src/middleware/scheduler-cron.ts +96 -96
  292. package/src/middleware/secure/__tests__/secure.test.ts +360 -360
  293. package/src/middleware/secure/csp.ts +193 -193
  294. package/src/middleware/session.ts +174 -174
  295. package/src/middleware/timeout.ts +55 -55
  296. package/src/observability/logger-adapter.ts +36 -36
  297. package/src/observability/sqlite-store.ts +254 -254
  298. package/src/openapi/generator.ts +1 -1
  299. package/src/openapi/openapi.test.ts +43 -43
  300. package/src/perf/__tests__/user-marks.test.ts +354 -354
  301. package/src/perf/index.ts +133 -133
  302. package/src/perf/user-marks.ts +1 -1
  303. package/src/plugins/__tests__/lifecycle-integration.test.ts +272 -272
  304. package/src/plugins/__tests__/runner.test.ts +409 -409
  305. package/src/plugins/define.ts +124 -124
  306. package/src/plugins/examples/dep-check-plugin.ts +80 -80
  307. package/src/plugins/examples/prerender-cache-plugin.ts +111 -111
  308. package/src/plugins/examples/sitemap-plugin.ts +65 -65
  309. package/src/plugins/runner.ts +361 -361
  310. package/src/plugins/types.ts +368 -368
  311. package/src/report/index.ts +1 -1
  312. package/src/resource/__tests__/generator.test.ts +7 -7
  313. package/src/resource/__tests__/schema.test.ts +14 -14
  314. package/src/resource/ddl/__tests__/diff.test.ts +639 -639
  315. package/src/resource/ddl/__tests__/emit.test.ts +165 -165
  316. package/src/resource/ddl/__tests__/snapshot.test.ts +499 -499
  317. package/src/resource/ddl/emit.ts +146 -146
  318. package/src/resource/ddl/persistence-types.ts +218 -218
  319. package/src/resource/ddl/type-map.ts +223 -223
  320. package/src/resource/ddl/types.ts +232 -232
  321. package/src/resource/generator-repo.ts +630 -630
  322. package/src/resource/generator-schema.ts +11 -11
  323. package/src/resource/generators/slot.ts +72 -72
  324. package/src/resource/schema.ts +21 -21
  325. package/src/router/client-entry.test.ts +227 -227
  326. package/src/router/client-entry.ts +218 -218
  327. package/src/router/fs-patterns.test.ts +96 -96
  328. package/src/router/fs-routes.test.ts +532 -532
  329. package/src/router/fs-routes.ts +53 -53
  330. package/src/router/fs-scanner.ts +216 -216
  331. package/src/router/fs-types.ts +19 -19
  332. package/src/router/route-source-analyzer.ts +521 -521
  333. package/src/routes/index.ts +74 -74
  334. package/src/routes/metadata-routes.ts +427 -427
  335. package/src/routes/types.ts +341 -341
  336. package/src/runtime/__tests__/devtools-adapter.test.ts +68 -68
  337. package/src/runtime/__tests__/error-boundary-redaction.test.ts +141 -141
  338. package/src/runtime/__tests__/hdr-client.test.ts +223 -223
  339. package/src/runtime/__tests__/http-errors.test.ts +117 -117
  340. package/src/runtime/__tests__/inline-client-hydration.test.ts +237 -237
  341. package/src/runtime/__tests__/not-found.test.ts +152 -152
  342. package/src/runtime/__tests__/observability-lifecycle.test.ts +103 -103
  343. package/src/runtime/__tests__/page-render-response.test.ts +517 -517
  344. package/src/runtime/__tests__/request-middleware.test.ts +70 -70
  345. package/src/runtime/__tests__/searchparams-page-props.test.ts +81 -81
  346. package/src/runtime/adapter.ts +47 -47
  347. package/src/runtime/boundary.tsx +252 -252
  348. package/src/runtime/cache.ts +494 -494
  349. package/src/runtime/compose.ts +222 -222
  350. package/src/runtime/devtools-adapter.ts +68 -68
  351. package/src/runtime/escape.ts +34 -34
  352. package/src/runtime/fast-refresh-runtime.ts +322 -322
  353. package/src/runtime/fast-refresh-types.ts +1 -1
  354. package/src/runtime/handler.ts +65 -65
  355. package/src/runtime/handlers.ts +30 -11
  356. package/src/runtime/http-errors.ts +113 -113
  357. package/src/runtime/image-handler.ts +1 -1
  358. package/src/runtime/lifecycle.ts +381 -381
  359. package/src/runtime/logger.test.ts +345 -345
  360. package/src/runtime/middleware.ts +264 -264
  361. package/src/runtime/not-found.ts +93 -93
  362. package/src/runtime/observability-lifecycle.ts +290 -290
  363. package/src/runtime/openapi-endpoint.ts +236 -236
  364. package/src/runtime/page-render-response.ts +287 -274
  365. package/src/runtime/ppr.ts +74 -74
  366. package/src/runtime/rate-limit.ts +1 -1
  367. package/src/runtime/redirect.ts +1 -1
  368. package/src/runtime/registry.ts +171 -171
  369. package/src/runtime/request-middleware.ts +31 -31
  370. package/src/runtime/router.test.ts +4 -4
  371. package/src/runtime/router.ts +10 -10
  372. package/src/runtime/server.ts +127 -211
  373. package/src/runtime/shims.ts +48 -48
  374. package/src/runtime/ssr.ts +43 -17
  375. package/src/runtime/static-files.ts +369 -289
  376. package/src/runtime/streaming-ssr.ts +219 -180
  377. package/src/runtime/trace.ts +144 -144
  378. package/src/scheduler/__tests__/scheduler.test.ts +12 -11
  379. package/src/scheduler/index.ts +11 -5
  380. package/src/scheduler/validate.ts +169 -169
  381. package/src/seo/index.ts +219 -219
  382. package/src/seo/integration/ssr.ts +306 -306
  383. package/src/seo/render/basic.ts +435 -435
  384. package/src/seo/render/index.ts +143 -143
  385. package/src/seo/render/jsonld.ts +539 -539
  386. package/src/seo/render/opengraph.ts +197 -197
  387. package/src/seo/render/robots.ts +116 -116
  388. package/src/seo/render/sitemap.ts +137 -137
  389. package/src/seo/render/twitter.ts +127 -127
  390. package/src/seo/resolve/opengraph.ts +143 -143
  391. package/src/seo/resolve/robots.ts +73 -73
  392. package/src/seo/resolve/title.ts +94 -94
  393. package/src/seo/resolve/twitter.ts +73 -73
  394. package/src/seo/resolve/url.ts +104 -104
  395. package/src/seo/routes/index.ts +290 -290
  396. package/src/seo/types.ts +588 -588
  397. package/src/slot/validator.ts +39 -39
  398. package/src/spec/schema.ts +35 -35
  399. package/src/storage/s3/__tests__/s3.test.ts +479 -479
  400. package/src/storage/s3/index.ts +412 -412
  401. package/src/testing/__tests__/assertions.test.ts +632 -632
  402. package/src/testing/__tests__/reporter.test.ts +454 -454
  403. package/src/testing/assertions.ts +986 -986
  404. package/src/testing/db.ts +157 -157
  405. package/src/testing/index.ts +9 -3
  406. package/src/testing/lcov.ts +192 -0
  407. package/src/testing/mocks.ts +203 -203
  408. package/src/testing/session.ts +190 -190
  409. package/src/types/branded.ts +56 -56
  410. package/src/types/index.ts +1 -1
  411. package/src/utils/safe-io.ts +188 -188
  412. package/src/utils/string-safe.ts +298 -298
  413. package/src/watcher/__tests__/watcher.test.ts +59 -59
  414. package/src/watcher/watcher.ts +61 -61
@@ -1,915 +1,898 @@
1
- import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2
- import { mkdtemp, mkdir, readFile, rm, writeFile } from "fs/promises";
3
- import path from "path";
4
- import { pathToFileURL } from "url";
5
- import { serializeProps } from "../client/serialize";
6
- import { toMatchSnapshot } from "../testing/snapshot";
7
- import { setupHappyDom } from "../../tests/setup";
8
-
9
- setupHappyDom();
10
-
11
- // 모든 테스트가 하나의 빌드 결과를 공유 — 병렬 Bun.build 충돌 방지
12
- let rootDir: string;
13
- let result: { success: boolean; errors: string[] };
14
- const repoTempRoot = path.resolve(import.meta.dir, "../../../..", ".tmp-test-artifacts");
15
-
16
- async function mkRepoTempDir(prefix: string): Promise<string> {
17
- await mkdir(repoTempRoot, { recursive: true });
18
- return mkdtemp(path.join(repoTempRoot, prefix));
19
- }
20
-
21
- async function importBuiltModule(relativePath: string): Promise<Record<string, unknown>> {
22
- const fileUrl = pathToFileURL(path.join(rootDir, relativePath)).href;
23
- return import(`${fileUrl}?t=${Date.now()}`);
24
- }
25
-
26
- async function evaluateGeneratedHydrationRuntime(): Promise<{ hydrateIslands: () => void }> {
27
- const sourcePath = path.join(rootDir, ".mandu", "client", "_runtime.src.js");
28
- const bundledPath = path.join(rootDir, ".mandu", "client", "_runtime.js");
29
- const runtimeSource = await readFile(await Bun.file(sourcePath).exists() ? sourcePath : bundledPath, "utf-8");
30
- const instrumented = runtimeSource
31
- .replace(
32
- /import\s+React,\s*\{[^}]*\}\s+from\s+['"]react['"];?/,
33
- "const React = globalThis.__MANDU_TEST_REACT__; const { useState, useEffect, Component } = React;",
34
- )
35
- .replace(
36
- /import\s+\{[^}]*\}\s+from\s+['"]react-dom\/client['"];?/,
37
- "const { hydrateRoot, createRoot } = globalThis.__MANDU_TEST_REACT_DOM_CLIENT__;",
38
- )
39
- .replace(
40
- /export\s*\{[^}]*\};?/g,
41
- "globalThis.__MANDU_TEST_RUNTIME__ = { hydrateIslands, unmountIsland, hydratedRoots };",
42
- );
43
-
44
- const reactStub = {
45
- Component: class {
46
- render() {
47
- return null;
48
- }
49
- },
50
- createElement(type: unknown, props: Record<string, unknown> | null, ...children: unknown[]) {
51
- if (
52
- typeof type === "function" &&
53
- !(typeof type === "function" && "prototype" in type && (type as { prototype?: { render?: unknown } }).prototype?.render)
54
- ) {
55
- return (type as (props: Record<string, unknown>) => unknown)({
56
- ...(props ?? {}),
57
- children: children.length <= 1 ? children[0] : children,
58
- });
59
- }
60
- return { type, props: props ?? {}, children };
61
- },
62
- isValidElement(value: unknown) {
63
- return !!value && typeof value === "object" && "type" in value;
64
- },
65
- useEffect(effect: () => void) {
66
- effect();
67
- },
68
- useState<T>(initial: T) {
69
- return [initial, () => {}] as const;
70
- },
71
- };
72
- const rootStub = {
73
- render() {},
74
- unmount() {},
75
- };
76
- Object.assign(globalThis, {
77
- __MANDU_TEST_REACT__: reactStub,
78
- __MANDU_TEST_REACT_DOM_CLIENT__: {
79
- createRoot: () => rootStub,
80
- hydrateRoot: () => rootStub,
81
- },
82
- });
83
-
84
- new Function(instrumented)();
85
- return (globalThis as typeof globalThis & {
86
- __MANDU_TEST_RUNTIME__: { hydrateIslands: () => void };
87
- }).__MANDU_TEST_RUNTIME__;
88
- }
89
-
90
- async function waitForRuntimeAssertion(assertion: () => boolean): Promise<void> {
91
- for (let attempt = 0; attempt < 25; attempt++) {
92
- if (assertion()) return;
93
- await new Promise((resolve) => setTimeout(resolve, 0));
94
- }
95
- expect(assertion()).toBe(true);
96
- }
97
-
98
- /**
99
- * Run `buildClientBundles` in an isolated `bun` subprocess.
100
- *
101
- * Bun 1.3.x exhibits a deterministic `AggregateError: Bundle failed` when
102
- * `buildClientBundles` is called from a test file AND the same `bun test`
103
- * process has previously imported `react` / `react-dom` through any sibling
104
- * test file (happens transitively through almost every `src/testing/*` or
105
- * `src/runtime/*` consumer). Retrying in-process does not recover the
106
- * resolver state is sticky. A fresh subprocess has a clean module graph.
107
- * See `__tests__/build-runner.ts` for the subprocess entrypoint and more
108
- * background.
109
- */
110
- async function runBuildInSubprocess(root: string, mode?: string): Promise<{
111
- success: boolean;
112
- errors: string[];
113
- manifest?: {
114
- routes?: Array<{
115
- id?: string;
116
- module?: string;
117
- componentModule?: string;
118
- boundaries?: Array<{
119
- id?: string;
120
- routeId?: string;
121
- module?: string;
122
- importSpecifier?: string;
123
- exportName?: string;
124
- localName?: string;
125
- hydrate?: string;
126
- ordinal?: number;
127
- propsSource?: string;
128
- propsKeys?: string[];
129
- hasSpreadProps?: boolean;
130
- source?: {
131
- file?: string;
132
- line?: number;
133
- column?: number;
134
- };
135
- }>;
136
- }>;
137
- bundles?: Record<string, { js?: string }>;
138
- boundaries?: Record<string, { js?: string; route?: string; module?: string; exportName?: string; hydrate?: string }>;
139
- } | null;
140
- }> {
141
- const runner = path.join(
142
- import.meta.dir,
143
- "__tests__",
144
- "build-runner.ts",
145
- );
146
- try {
147
- const args = [process.execPath, "run", runner, root];
148
- if (mode) args.push(mode);
149
- const proc = Bun.spawn(args, {
150
- cwd: path.resolve(import.meta.dir, "..", ".."),
151
- stdin: "ignore",
152
- stdout: "pipe",
153
- stderr: "inherit",
154
- });
155
- const out = await new Response(proc.stdout).text();
156
- await proc.exited;
157
-
158
- // Find the final JSON line — the runner may log Mandu dev banners
159
- // (e.g. "[Mandu] DevTools …") before emitting the payload. The
160
- // contract is: last non-empty line is the JSON blob.
161
- const lines = out.split(/\r?\n/).filter((l) => l.trim().length > 0);
162
- const last = lines[lines.length - 1] ?? "";
163
- try {
164
- const parsed = JSON.parse(last);
165
- return {
166
- success: parsed.success === true,
167
- errors: Array.isArray(parsed.errors) ? parsed.errors : [],
168
- manifest: parsed.manifest ?? null,
169
- };
170
- } catch (e) {
171
- return {
172
- success: false,
173
- errors: [
174
- `build-runner output could not be parsed as JSON: ${String(e)}\nLast stdout line: ${last}`,
175
- ],
176
- manifest: null,
177
- };
178
- }
179
- } catch (err) {
180
- return { success: false, errors: [`spawn failed: ${String(err)}`], manifest: null };
181
- }
182
- }
183
-
184
- beforeAll(async () => {
185
- rootDir = await mkRepoTempDir("bundler-");
186
-
187
- await mkdir(path.join(rootDir, "app"), { recursive: true });
188
- await writeFile(
189
- path.join(rootDir, "package.json"),
190
- JSON.stringify({ name: "mandu-build-test", type: "module" }, null, 2),
191
- "utf-8",
192
- );
193
- await writeFile(
194
- path.join(rootDir, "app", "demo.client.tsx"),
195
- "export default function DemoIsland() { return null; }\n",
196
- "utf-8",
197
- );
198
-
199
- result = await runBuildInSubprocess(rootDir);
200
- });
201
-
202
- afterAll(async () => {
203
- if (rootDir) {
204
- await rm(rootDir, { recursive: true, force: true });
205
- }
206
- });
207
-
208
- // Historical note — `MANDU_SKIP_BUNDLER_TESTS` gate REMOVED.
209
- //
210
- // A previous revision gated this describe block behind
211
- // `describe.skipIf(MANDU_SKIP_BUNDLER_TESTS === "1")` because running
212
- // `bun test src/bundler/` without the gate hung indefinitely on Windows
213
- // (see Phase 0.6 and `docs/qa/wave-R2-integration-report.md`). Root cause
214
- // was NOT actually in THIS file — it was a deadlock in `safe-build.test.ts`'s
215
- // "slot handoff" regression test, which drove Bun's microtask queue with a
216
- // `while (!stop) { await Promise.resolve() }` sampler. That starved libuv
217
- // I/O callbacks, so the 7 parallel `safeBuild()` calls never completed, the
218
- // whole test process hung, and downstream test files (including this one
219
- // when run in the same invocation) looked flaky when they were simply
220
- // never reached. The handoff sampler now yields via `setImmediate`, which
221
- // unblocks Bun.build completion and makes `bun test src/bundler/` finish
222
- // deterministically in ~35s on Windows. Confirmed green 3/3 runs without
223
- // the gate on 2026-04-20. If you are tempted to re-introduce the skip here,
224
- // first check whether a sibling test is starving the event loop.
225
- //
226
- // A second, independent flake — Bun.build `AggregateError: Bundle failed`
227
- // when another test file in the same invocation has imported `react` —
228
- // is now sidestepped by running `buildClientBundles` in a spawned `bun`
229
- // subprocess via `__tests__/build-runner.ts`. In-process retry does not
230
- // recover from that one; a fresh module graph does.
231
- describe("buildClientBundles vendor shims", () => {
232
- test("build succeeds", () => {
233
- if (!result.success) {
234
- console.error("[build.test] errors:", result.errors);
235
- }
236
- expect(result.success).toBe(true);
237
- });
238
-
239
- test("runtime reads canonical data-hydrate strategies", async () => {
240
- const runtimePath = path.join(rootDir, ".mandu", "client", "_runtime.js");
241
- const runtimeSource = await readFile(runtimePath, "utf-8");
242
-
243
- expect(runtimeSource).toContain("data-hydrate");
244
- expect(runtimeSource).toContain("matchMedia");
245
- expect(runtimeSource).toContain("200px");
246
- expect(runtimeSource).toContain('"click"');
247
- expect(runtimeSource).not.toContain("mouseenter");
248
- expect(runtimeSource).not.toContain("pointerdown");
249
- });
250
-
251
- test("re-exports modern React 19 APIs used by islands", async () => {
252
- const reactShim = await importBuiltModule(".mandu/client/_react.js");
253
- const requiredExports = [
254
- "Activity",
255
- "__COMPILER_RUNTIME",
256
- "cache",
257
- "cacheSignal",
258
- "startTransition",
259
- "use",
260
- "useActionState",
261
- "useEffectEvent",
262
- "useOptimistic",
263
- "unstable_useCacheRefresh",
264
- ];
265
-
266
- for (const exportName of requiredExports) {
267
- expect(exportName in reactShim).toBe(true);
268
- }
269
- });
270
-
271
- test("re-exports modern react-dom and react-dom/client APIs", async () => {
272
- const reactDomShim = await importBuiltModule(".mandu/client/_react-dom.js");
273
- for (const exportName of [
274
- "preconnect",
275
- "prefetchDNS",
276
- "preinit",
277
- "preinitModule",
278
- "preload",
279
- "preloadModule",
280
- "requestFormReset",
281
- "unstable_batchedUpdates",
282
- "useFormState",
283
- "useFormStatus",
284
- ]) {
285
- expect(exportName in reactDomShim).toBe(true);
286
- }
287
-
288
- const reactDomClientShim = await importBuiltModule(".mandu/client/_react-dom-client.js");
289
- for (const exportName of ["createRoot", "hydrateRoot", "version"]) {
290
- expect(exportName in reactDomClientShim).toBe(true);
291
- }
292
- });
293
-
294
- test("embeds hydration guards for deferred trigger strategies", async () => {
295
- const runtimeSource = await readFile(path.join(rootDir, ".mandu", "client", "_runtime.js"), "utf-8");
296
- expect(runtimeSource).toContain("function resolveHydrationTarget");
297
- expect(runtimeSource).toContain("function hasHydratableMarkup");
298
- expect(runtimeSource).toContain("function shouldHydrateCompiledIsland");
299
- expect(runtimeSource).toContain("onRecoverableError");
300
- expect(runtimeSource).toContain("data-mandu-hydrating");
301
- expect(runtimeSource).toContain("data-mandu-render-mode");
302
- expect(runtimeSource).toContain("data-mandu-recoverable-error");
303
- expect(runtimeSource).toContain('"click"');
304
- expect(runtimeSource).not.toContain("pointerdown");
305
- });
306
-
307
- test("runtime parses SSR data script before island setup", async () => {
308
- const runtimeSource = await readFile(path.join(rootDir, ".mandu", "client", "_runtime.js"), "utf-8");
309
- expect(runtimeSource).toContain("function readManduData");
310
- expect(runtimeSource).toContain("document.getElementById(\"__MANDU_DATA__\")");
311
- expect(runtimeSource).toContain("function parsePropsScript");
312
- expect(runtimeSource).toContain("data-mandu-props");
313
- expect(runtimeSource).toContain("Missing boundary-local props for transformed client boundary");
314
- expect(runtimeSource).toContain("warnedBoundaryPropFallbacks");
315
- expect(runtimeSource).toContain("deserializeProps");
316
- expect(runtimeSource).toContain("new Date");
317
- expect(runtimeSource).toContain("new Map");
318
- });
319
-
320
- test("runtime hydrates named client boundary from boundary-local props before route data", async () => {
321
- const modulePath = path.join(rootDir, ".mandu", "client", "runtime-named-boundary.js");
322
- await writeFile(
323
- modulePath,
324
- `
325
- export default function WrongDefault(props) {
326
- globalThis.__MANDU_TEST_DEFAULT_PROPS__ = props;
327
- return null;
328
- }
329
- export function NamedBoundary(props) {
330
- globalThis.__MANDU_TEST_NAMED_PROPS__ = props;
331
- return null;
332
- }
333
- `,
334
- "utf-8",
335
- );
336
- Object.assign(globalThis, {
337
- __MANDU_TEST_NAMED_PROPS__: undefined,
338
- __MANDU_TEST_DEFAULT_PROPS__: undefined,
339
- });
340
- document.body.innerHTML = `
341
- <div
342
- data-mandu-island="named--0"
343
- data-mandu-boundary-id="named--0"
344
- data-mandu-route-id="named-route"
345
- data-mandu-client-export="NamedBoundary"
346
- data-mandu-src="${pathToFileURL(modulePath).href}?t=${Date.now()}"
347
- data-hydrate="load"
348
- ></div>
349
- <script type="application/json" data-mandu-props="named--0">${serializeProps({ label: "boundary-local" })}</script>
350
- `;
351
- (window as typeof window & { __MANDU_DATA__?: unknown; __MANDU_ROOTS__?: Map<string, unknown> }).__MANDU_DATA__ = {
352
- "named-route": { serverData: { label: "route-data" } },
353
- };
354
- (window as typeof window & { __MANDU_ROOTS__?: Map<string, unknown> }).__MANDU_ROOTS__ = new Map();
355
-
356
- const runtime = await evaluateGeneratedHydrationRuntime();
357
- runtime.hydrateIslands();
358
-
359
- await waitForRuntimeAssertion(() =>
360
- (globalThis as typeof globalThis & { __MANDU_TEST_NAMED_PROPS__?: { label?: string } }).__MANDU_TEST_NAMED_PROPS__?.label === "boundary-local"
361
- );
362
- expect((globalThis as typeof globalThis & { __MANDU_TEST_DEFAULT_PROPS__?: unknown }).__MANDU_TEST_DEFAULT_PROPS__).toBeUndefined();
363
- });
364
-
365
- test("surfaces an island hydration failure to the DevTools hook (#324)", async () => {
366
- const modulePath = path.join(rootDir, ".mandu", "client", "runtime-failing-boundary.js");
367
- // A module that throws at import time loadAndHydrate's catch runs.
368
- await writeFile(modulePath, `throw new Error("boom at import");`, "utf-8");
369
-
370
- const emitted: Array<{ type?: string; data?: { message?: string; islandId?: string } }> = [];
371
- (window as unknown as { __MANDU_DEVTOOLS_HOOK__?: { emit: (e: unknown) => void } }).__MANDU_DEVTOOLS_HOOK__ = {
372
- emit: (e: unknown) => {
373
- emitted.push(e as { type?: string });
374
- },
375
- };
376
-
377
- document.body.innerHTML = `
378
- <div
379
- data-mandu-island="failing--0"
380
- data-mandu-src="${pathToFileURL(modulePath).href}?t=${Date.now()}"
381
- data-hydrate="load"
382
- ></div>
383
- `;
384
- (window as typeof window & { __MANDU_ROOTS__?: Map<string, unknown> }).__MANDU_ROOTS__ = new Map();
385
-
386
- try {
387
- const runtime = await evaluateGeneratedHydrationRuntime();
388
- runtime.hydrateIslands();
389
-
390
- await waitForRuntimeAssertion(() => emitted.some((e) => e.type === "error"));
391
- const errorEvent = emitted.find((e) => e.type === "error");
392
- expect(errorEvent?.data?.islandId).toBe("failing--0");
393
- expect(errorEvent?.data?.message).toContain("boom at import");
394
- } finally {
395
- delete (window as unknown as { __MANDU_DEVTOOLS_HOOK__?: unknown }).__MANDU_DEVTOOLS_HOOK__;
396
- }
397
- });
398
-
399
- test("runtime hydrates default client boundary from boundary-local props", async () => {
400
- const modulePath = path.join(rootDir, ".mandu", "client", "runtime-default-boundary.js");
401
- await writeFile(
402
- modulePath,
403
- `
404
- export default function DefaultBoundary(props) {
405
- globalThis.__MANDU_TEST_DEFAULT_BOUNDARY_PROPS__ = props;
406
- return null;
407
- }
408
- `,
409
- "utf-8",
410
- );
411
- Object.assign(globalThis, {
412
- __MANDU_TEST_DEFAULT_BOUNDARY_PROPS__: undefined,
413
- });
414
- document.body.innerHTML = `
415
- <div
416
- data-mandu-island="default--0"
417
- data-mandu-boundary-id="default--0"
418
- data-mandu-route-id="default-route"
419
- data-mandu-client-export="default"
420
- data-mandu-src="${pathToFileURL(modulePath).href}?t=${Date.now()}"
421
- data-hydrate="load"
422
- ></div>
423
- <script type="application/json" data-mandu-props="default--0">${serializeProps({ label: "default-boundary" })}</script>
424
- `;
425
- (window as typeof window & { __MANDU_DATA__?: unknown; __MANDU_ROOTS__?: Map<string, unknown> }).__MANDU_DATA__ = {};
426
- (window as typeof window & { __MANDU_ROOTS__?: Map<string, unknown> }).__MANDU_ROOTS__ = new Map();
427
-
428
- const runtime = await evaluateGeneratedHydrationRuntime();
429
- runtime.hydrateIslands();
430
-
431
- await waitForRuntimeAssertion(() =>
432
- (globalThis as typeof globalThis & { __MANDU_TEST_DEFAULT_BOUNDARY_PROPS__?: { label?: string } }).__MANDU_TEST_DEFAULT_BOUNDARY_PROPS__?.label === "default-boundary"
433
- );
434
- });
435
-
436
- test("runtime keeps explicit island API data-props fallback working", async () => {
437
- const modulePath = path.join(rootDir, ".mandu", "client", "runtime-explicit-island.js");
438
- await writeFile(
439
- modulePath,
440
- `
441
- export default {
442
- __mandu_island: true,
443
- definition: {
444
- setup(data) {
445
- globalThis.__MANDU_TEST_EXPLICIT_ISLAND_DATA__ = data;
446
- return data;
447
- },
448
- render() {
449
- return null;
450
- }
451
- }
452
- };
453
- `,
454
- "utf-8",
455
- );
456
- Object.assign(globalThis, {
457
- __MANDU_TEST_EXPLICIT_ISLAND_DATA__: undefined,
458
- });
459
- document.body.innerHTML = `
460
- <div
461
- data-mandu-island="explicit-island"
462
- data-mandu-src="${pathToFileURL(modulePath).href}?t=${Date.now()}"
463
- data-props="${serializeProps({ label: "data-props" }).replace(/"/g, "&quot;")}"
464
- data-hydrate="load"
465
- ></div>
466
- `;
467
- (window as typeof window & { __MANDU_DATA__?: unknown; __MANDU_ROOTS__?: Map<string, unknown> }).__MANDU_DATA__ = {};
468
- (window as typeof window & { __MANDU_ROOTS__?: Map<string, unknown> }).__MANDU_ROOTS__ = new Map();
469
-
470
- const runtime = await evaluateGeneratedHydrationRuntime();
471
- runtime.hydrateIslands();
472
-
473
- await waitForRuntimeAssertion(() =>
474
- (globalThis as typeof globalThis & { __MANDU_TEST_EXPLICIT_ISLAND_DATA__?: { label?: string } }).__MANDU_TEST_EXPLICIT_ISLAND_DATA__?.label === "data-props"
475
- );
476
- });
477
-
478
- test("runtime falls back to route-level server data when boundary-local props are absent", async () => {
479
- const modulePath = path.join(rootDir, ".mandu", "client", "runtime-route-data-fallback.js");
480
- await writeFile(
481
- modulePath,
482
- `
483
- export default function RouteFallbackBoundary(props) {
484
- globalThis.__MANDU_TEST_ROUTE_DATA_FALLBACK_PROPS__ = props;
485
- return null;
486
- }
487
- `,
488
- "utf-8",
489
- );
490
- Object.assign(globalThis, {
491
- __MANDU_TEST_ROUTE_DATA_FALLBACK_PROPS__: undefined,
492
- });
493
- document.body.innerHTML = `
494
- <div
495
- data-mandu-island="route-fallback--0"
496
- data-mandu-boundary-id="route-fallback--0"
497
- data-mandu-route-id="route-fallback"
498
- data-mandu-src="${pathToFileURL(modulePath).href}?t=${Date.now()}"
499
- data-hydrate="load"
500
- ></div>
501
- `;
502
- (window as typeof window & { __MANDU_DATA__?: unknown; __MANDU_ROOTS__?: Map<string, unknown> }).__MANDU_DATA__ = {
503
- "route-fallback": { serverData: { label: "route-level" } },
504
- };
505
- (window as typeof window & { __MANDU_ROOTS__?: Map<string, unknown> }).__MANDU_ROOTS__ = new Map();
506
-
507
- const runtime = await evaluateGeneratedHydrationRuntime();
508
- runtime.hydrateIslands();
509
-
510
- await waitForRuntimeAssertion(() =>
511
- (globalThis as typeof globalThis & { __MANDU_TEST_ROUTE_DATA_FALLBACK_PROPS__?: { label?: string } }).__MANDU_TEST_ROUTE_DATA_FALLBACK_PROPS__?.label === "route-level"
512
- );
513
- });
514
-
515
- test("does not bundle a server page when stale manifest marks page.tsx as clientModule", async () => {
516
- const staleRoot = await mkRepoTempDir("stale-client-module-");
517
- try {
518
- await mkdir(path.join(staleRoot, "app"), { recursive: true });
519
- await mkdir(path.join(staleRoot, "src", "shared", "contracts"), { recursive: true });
520
- await writeFile(
521
- path.join(staleRoot, "package.json"),
522
- JSON.stringify({ name: "mandu-stale-client-module-test", type: "module" }, null, 2),
523
- "utf-8",
524
- );
525
- await writeFile(
526
- path.join(staleRoot, "src", "shared", "contracts", "api.ts"),
527
- 'export const INTERNAL_BASE = process.env.MANDU_INTERNAL_URL ?? "http://localhost:3333";\n',
528
- "utf-8",
529
- );
530
- await writeFile(
531
- path.join(staleRoot, "app", "page.tsx"),
532
- 'import { INTERNAL_BASE } from "../src/shared/contracts/api";\n' +
533
- "export default async function HomePage() {\n" +
534
- " return <main>{INTERNAL_BASE}</main>;\n" +
535
- "}\n",
536
- "utf-8",
537
- );
538
-
539
- const staleResult = await runBuildInSubprocess(staleRoot, "server-page-client-module");
540
- expect(staleResult.success).toBe(false);
541
- expect(staleResult.errors.join("\n")).toContain("missing \"use client\"");
542
- expect(await Bun.file(path.join(staleRoot, ".mandu", "client", "index.island.js")).exists()).toBe(false);
543
- } finally {
544
- await rm(staleRoot, { recursive: true, force: true });
545
- }
546
- });
547
-
548
- test("rewrites route-component clientModule to the real client import before bundling", async () => {
549
- const routeClientRoot = await mkRepoTempDir("route-client-import-");
550
- try {
551
- await mkdir(path.join(routeClientRoot, "app", "login"), { recursive: true });
552
- await mkdir(path.join(routeClientRoot, "src", "client", "pages", "login"), { recursive: true });
553
- await writeFile(
554
- path.join(routeClientRoot, "package.json"),
555
- JSON.stringify({ name: "mandu-route-client-import-test", type: "module" }, null, 2),
556
- "utf-8",
557
- );
558
- await writeFile(
559
- path.join(routeClientRoot, "app", "login", "page.tsx"),
560
- 'import LoginPage from "@/client/pages/login/LoginPage.client";\n' +
561
- "export default function Page() {\n" +
562
- " return <LoginPage />;\n" +
563
- "}\n",
564
- "utf-8",
565
- );
566
- await writeFile(
567
- path.join(routeClientRoot, "src", "client", "pages", "login", "LoginPage.client.tsx"),
568
- '"use client";\n' +
569
- 'import { useState } from "react";\n' +
570
- "export default function LoginPage() {\n" +
571
- ' const [email, setEmail] = useState("");\n' +
572
- ' return <form><input value={email} onChange={(event) => setEmail(event.currentTarget.value)} /></form>;\n' +
573
- "}\n",
574
- "utf-8",
575
- );
576
-
577
- const routeClientResult = await runBuildInSubprocess(routeClientRoot, "server-page-route-client-import");
578
- expect(routeClientResult.success).toBe(true);
579
- const bundlePath = path.join(routeClientRoot, ".mandu", "client", "login.island.js");
580
- expect(await Bun.file(bundlePath).exists()).toBe(true);
581
-
582
- const bundleSource = await readFile(bundlePath, "utf-8");
583
- expect(bundleSource).not.toContain("var LoginPage = LoginPage;");
584
- const parseResult = await Bun.build({
585
- entrypoints: [bundlePath],
586
- target: "browser",
587
- external: ["react", "react-dom", "react-dom/client", "react/jsx-dev-runtime"],
588
- });
589
- expect(parseResult.success).toBe(true);
590
- } finally {
591
- await rm(routeClientRoot, { recursive: true, force: true });
592
- }
593
- });
594
-
595
- test("bundles route-level named client exports without requiring a default export", async () => {
596
- const routeClientRoot = await mkRepoTempDir("route-named-client-import-");
597
- try {
598
- await mkdir(path.join(routeClientRoot, "app", "login"), { recursive: true });
599
- await mkdir(path.join(routeClientRoot, "src", "client", "pages", "login"), { recursive: true });
600
- await writeFile(
601
- path.join(routeClientRoot, "package.json"),
602
- JSON.stringify({ name: "mandu-route-named-client-import-test", type: "module" }, null, 2),
603
- "utf-8",
604
- );
605
- await writeFile(
606
- path.join(routeClientRoot, "app", "login", "page.tsx"),
607
- 'import { LoginPage } from "@/client/pages/login/LoginPage.client";\n' +
608
- "export default function Page() {\n" +
609
- " return <LoginPage />;\n" +
610
- "}\n",
611
- "utf-8",
612
- );
613
- await writeFile(
614
- path.join(routeClientRoot, "src", "client", "pages", "login", "LoginPage.client.tsx"),
615
- '"use client";\n' +
616
- 'import { useState } from "react";\n' +
617
- "export function LoginPage() {\n" +
618
- ' const [email, setEmail] = useState("");\n' +
619
- ' return <form><input value={email} onChange={(event) => setEmail(event.currentTarget.value)} /></form>;\n' +
620
- "}\n",
621
- "utf-8",
622
- );
623
-
624
- const routeClientResult = await runBuildInSubprocess(routeClientRoot, "server-page-route-named-client-import");
625
- if (!routeClientResult.success) {
626
- console.error("[named route client] errors:", routeClientResult.errors);
627
- }
628
- expect(routeClientResult.success).toBe(true);
629
- const bundlePath = path.join(routeClientRoot, ".mandu", "client", "login.island.js");
630
- expect(await Bun.file(bundlePath).exists()).toBe(true);
631
-
632
- const bundleSource = await readFile(bundlePath, "utf-8");
633
- expect(bundleSource).toContain("LoginPage");
634
- expect(bundleSource).not.toContain("Client islands cannot use server-side modules");
635
- const parseResult = await Bun.build({
636
- entrypoints: [bundlePath],
637
- target: "browser",
638
- external: ["react", "react-dom", "react-dom/client", "react/jsx-dev-runtime"],
639
- });
640
- expect(parseResult.success).toBe(true);
641
- } finally {
642
- await rm(routeClientRoot, { recursive: true, force: true });
643
- }
644
- });
645
-
646
- test("uses Windows-safe asset filenames for locale-prefixed route ids", async () => {
647
- const localeRoot = await mkRepoTempDir("i18n-locale-route-id-");
648
- try {
649
- await mkdir(path.join(localeRoot, "app"), { recursive: true });
650
- await writeFile(
651
- path.join(localeRoot, "package.json"),
652
- JSON.stringify({ name: "mandu-i18n-route-id-test", type: "module" }, null, 2),
653
- "utf-8",
654
- );
655
- await writeFile(
656
- path.join(localeRoot, "app", "demo.client.tsx"),
657
- "export default function DemoIsland() { return null; }\n",
658
- "utf-8",
659
- );
660
-
661
- const localeResult = await runBuildInSubprocess(localeRoot, "i18n-locale-route-id");
662
- expect(localeResult.success).toBe(true);
663
- const bundle = localeResult.manifest?.bundles?.["ko::demo"];
664
- expect(bundle?.js).toBe("/.mandu/client/ko_3a__3a_demo.island.js");
665
- expect(bundle?.js).not.toContain(":");
666
- expect(await Bun.file(path.join(localeRoot, ".mandu", "client", "ko_3a__3a_demo.island.js")).exists()).toBe(true);
667
- } finally {
668
- await rm(localeRoot, { recursive: true, force: true });
669
- }
670
- });
671
-
672
- test("fails when hydration is enabled but no clientModule can be resolved", async () => {
673
- const missingRoot = await mkRepoTempDir("hydration-no-client-");
674
- try {
675
- await mkdir(path.join(missingRoot, "app", "login"), { recursive: true });
676
- await mkdir(path.join(missingRoot, "src", "client", "widgets", "login-form"), { recursive: true });
677
- await writeFile(
678
- path.join(missingRoot, "package.json"),
679
- JSON.stringify({ name: "mandu-hydration-no-client-test", type: "module" }, null, 2),
680
- "utf-8",
681
- );
682
- await writeFile(
683
- path.join(missingRoot, "app", "login", "page.tsx"),
684
- 'import { LoginForm } from "../../src/client/widgets/login-form/LoginForm.client";\n' +
685
- "export default function LoginPage() {\n" +
686
- " return <main><LoginForm /></main>;\n" +
687
- "}\n",
688
- "utf-8",
689
- );
690
- await writeFile(
691
- path.join(missingRoot, "src", "client", "widgets", "login-form", "LoginForm.client.tsx"),
692
- "export function LoginForm() { return <form />; }\n",
693
- "utf-8",
694
- );
695
-
696
- const noClientResult = await runBuildInSubprocess(missingRoot, "hydration-no-client-module");
697
- const errors = noClientResult.errors.join("\n");
698
- expect(noClientResult.success).toBe(false);
699
- expect(errors).toContain("no clientModule could be resolved");
700
- expect(errors).toContain("LoginForm.client");
701
- expect(errors).toContain("run mandu generate");
702
- } finally {
703
- await rm(missingRoot, { recursive: true, force: true });
704
- }
705
- });
706
- });
707
-
708
- describe("buildClientBundles client boundaries", () => {
709
- async function createBoundaryFixture(prefix: string): Promise<string> {
710
- const boundaryRoot = await mkRepoTempDir(prefix);
711
- await mkdir(path.join(boundaryRoot, "app", "boundary"), { recursive: true });
712
- await mkdir(path.join(boundaryRoot, "src", "client"), { recursive: true });
713
- await writeFile(
714
- path.join(boundaryRoot, "package.json"),
715
- JSON.stringify({ name: "mandu-boundary-test", type: "module" }, null, 2),
716
- "utf-8",
717
- );
718
- await writeFile(
719
- path.join(boundaryRoot, "app", "boundary", "page.tsx"),
720
- "export default function Page() { return null; }\n",
721
- "utf-8",
722
- );
723
- await writeFile(
724
- path.join(boundaryRoot, "src", "client", "BoundaryWidget.client.tsx"),
725
- `
726
- import React from "react";
727
-
728
- export default function WrongDefault({ label }) {
729
- return React.createElement("p", null, "default:" + label);
730
- }
731
-
732
- export function BoundaryWidget({ label }) {
733
- return React.createElement("button", null, "named:" + label);
734
- }
735
- `,
736
- "utf-8",
737
- );
738
- return boundaryRoot;
739
- }
740
-
741
- test("emits boundary bundle manifest entries", async () => {
742
- const boundaryRoot = await createBoundaryFixture("bundler-boundary-");
743
- try {
744
- const boundaryResult = await runBuildInSubprocess(boundaryRoot, "client-boundary");
745
-
746
- if (!boundaryResult.success) {
747
- console.error("[build.test boundary] errors:", boundaryResult.errors);
748
- }
749
- expect(boundaryResult.success).toBe(true);
750
- expect(boundaryResult.manifest?.boundaries?.["boundary-demo--0"]).toMatchObject({
751
- route: "boundary-demo",
752
- module: "src/client/BoundaryWidget.client.tsx",
753
- exportName: "BoundaryWidget",
754
- hydrate: "visible",
755
- });
756
- expect(boundaryResult.manifest?.boundaries?.["boundary-demo--0"]?.js).toMatch(
757
- /^\/\.mandu\/client\/boundary-demo--0\.boundary\.js$/,
758
- );
759
- expect(boundaryResult.manifest?.bundles?.["boundary-demo"]).toBeUndefined();
760
-
761
- const refreshGlobal = globalThis as typeof globalThis & {
762
- $RefreshReg$?: unknown;
763
- $RefreshSig$?: unknown;
764
- };
765
- refreshGlobal.$RefreshReg$ = () => {};
766
- refreshGlobal.$RefreshSig$ = () => (type: unknown) => type;
767
- try {
768
- const boundaryBundle = await import(
769
- `${pathToFileURL(path.join(boundaryRoot, ".mandu", "client", "boundary-demo--0.boundary.js")).href}?t=${Date.now()}`
770
- );
771
- const React = await import("react");
772
- const { renderToStaticMarkup } = await import("react-dom/server");
773
-
774
- expect(typeof boundaryBundle.default).toBe("function");
775
- expect(typeof boundaryBundle.BoundaryWidget).toBe("function");
776
- expect(renderToStaticMarkup(React.createElement(boundaryBundle.default, { label: "ok" }))).toContain("named:ok");
777
- expect(renderToStaticMarkup(React.createElement(boundaryBundle.BoundaryWidget, { label: "ok" }))).toContain("named:ok");
778
- } finally {
779
- delete refreshGlobal.$RefreshReg$;
780
- delete refreshGlobal.$RefreshSig$;
781
- }
782
- } finally {
783
- await rm(boundaryRoot, { recursive: true, force: true });
784
- }
785
- });
786
-
787
- test("snapshots route and bundle boundary metadata", async () => {
788
- const boundaryRoot = await createBoundaryFixture("bundler-boundary-snapshot-");
789
- try {
790
- const boundaryResult = await runBuildInSubprocess(boundaryRoot, "client-boundary");
791
- expect(boundaryResult.success).toBe(true);
792
-
793
- toMatchSnapshot(
794
- {
795
- routes: boundaryResult.manifest?.routes?.map((route) => ({
796
- id: route.id,
797
- module: route.module,
798
- componentModule: route.componentModule,
799
- boundaries: route.boundaries,
800
- })),
801
- bundleBoundaries: boundaryResult.manifest?.boundaries,
802
- },
803
- {
804
- testFile: path.join(import.meta.dir, "build.test.ts"),
805
- name: "client boundary manifest metadata",
806
- },
807
- );
808
- } finally {
809
- await rm(boundaryRoot, { recursive: true, force: true });
810
- }
811
- });
812
-
813
- test("updates boundary manifest entries in target-route builds", async () => {
814
- const boundaryRoot = await createBoundaryFixture("bundler-boundary-target-");
815
- try {
816
- const boundaryResult = await runBuildInSubprocess(boundaryRoot, "client-boundary-target");
817
- expect(boundaryResult.success).toBe(true);
818
- expect(boundaryResult.manifest?.boundaries?.["boundary-demo--0"]?.js).toBe(
819
- "/.mandu/client/boundary-demo--0.boundary.js",
820
- );
821
- } finally {
822
- await rm(boundaryRoot, { recursive: true, force: true });
823
- }
824
- });
825
-
826
- test("fails before manifest generation when boundary ids are duplicated", async () => {
827
- const boundaryRoot = await createBoundaryFixture("bundler-boundary-duplicate-");
828
- try {
829
- const boundaryResult = await runBuildInSubprocess(boundaryRoot, "client-boundary-duplicate-id");
830
-
831
- expect(boundaryResult.success).toBe(false);
832
- expect(boundaryResult.errors.join("\n")).toContain("MANDU_BOUNDARY_DUPLICATE_ID");
833
- expect(boundaryResult.errors.join("\n")).toContain("boundary-demo--0");
834
- } finally {
835
- await rm(boundaryRoot, { recursive: true, force: true });
836
- }
837
- });
838
-
839
- test("updates boundary manifest entries when framework bundles are skipped", async () => {
840
- const boundaryRoot = await createBoundaryFixture("bundler-boundary-skip-");
841
- try {
842
- const boundaryResult = await runBuildInSubprocess(boundaryRoot, "client-boundary-skip-framework");
843
- expect(boundaryResult.success).toBe(true);
844
- expect(boundaryResult.manifest?.boundaries?.["boundary-demo--0"]?.js).toBe(
845
- "/.mandu/client/boundary-demo--0.boundary.js",
846
- );
847
- } finally {
848
- await rm(boundaryRoot, { recursive: true, force: true });
849
- }
850
- });
851
-
852
- test("builds manifest-generated boundaries from route-owned server wrappers", async () => {
853
- const boundaryRoot = await mkRepoTempDir("bundler-boundary-generated-wrapper-");
854
- try {
855
- await mkdir(path.join(boundaryRoot, "app", "account", "components"), { recursive: true });
856
- await writeFile(
857
- path.join(boundaryRoot, "package.json"),
858
- JSON.stringify({ name: "mandu-boundary-generated-wrapper-test", type: "module" }, null, 2),
859
- "utf-8",
860
- );
861
- await writeFile(
862
- path.join(boundaryRoot, "app", "account", "page.tsx"),
863
- `
864
- import { AccountShell } from "./components/AccountShell";
865
-
866
- export default function Page() {
867
- return <main><AccountShell name="Ada" /></main>;
868
- }
869
- `,
870
- "utf-8",
871
- );
872
- await writeFile(
873
- path.join(boundaryRoot, "app", "account", "components", "AccountShell.tsx"),
874
- `
875
- import { AccountCard } from "./AccountCard.client";
876
-
877
- export function AccountShell({ name }) {
878
- return <AccountCard name={name} />;
879
- }
880
- `,
881
- "utf-8",
882
- );
883
- await writeFile(
884
- path.join(boundaryRoot, "app", "account", "components", "AccountCard.client.tsx"),
885
- `
886
- import React from "react";
887
- export function AccountCard({ name }) {
888
- return React.createElement("button", null, name);
889
- }
890
- `,
891
- "utf-8",
892
- );
893
-
894
- const boundaryResult = await runBuildInSubprocess(boundaryRoot, "client-boundary-generated-transitive");
895
-
896
- if (!boundaryResult.success) {
897
- console.error("[build.test generated boundary] errors:", boundaryResult.errors);
898
- }
899
- expect(boundaryResult.success).toBe(true);
900
- expect(boundaryResult.manifest?.boundaries?.["account--0"]).toMatchObject({
901
- route: "account",
902
- module: "app/account/components/AccountCard.client.tsx",
903
- exportName: "AccountCard",
904
- hydrate: "visible",
905
- });
906
- expect(boundaryResult.manifest?.boundaries?.["account--0"]?.js).toBe(
907
- "/.mandu/client/account--0.boundary.js",
908
- );
909
- expect(boundaryResult.manifest?.bundles?.account).toBeUndefined();
910
- expect(await Bun.file(path.join(boundaryRoot, ".mandu", "client", "account--0.boundary.js")).exists()).toBe(true);
911
- } finally {
912
- await rm(boundaryRoot, { recursive: true, force: true });
913
- }
914
- });
915
- });
1
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2
+ import { mkdtemp, mkdir, readFile, rm, writeFile } from "fs/promises";
3
+ import path from "path";
4
+ import { pathToFileURL } from "url";
5
+ import { serializeProps } from "../client/serialize";
6
+ import { toMatchSnapshot } from "../testing/snapshot";
7
+ import { setupHappyDom } from "../../tests/setup";
8
+
9
+ setupHappyDom();
10
+
11
+ const skipBundlerTests = process.env.MANDU_SKIP_BUNDLER_TESTS === "1";
12
+
13
+ // 모든 테스트가 하나의 빌드 결과를 공유 — 병렬 Bun.build 충돌 방지
14
+ let rootDir: string;
15
+ let result: { success: boolean; errors: string[] };
16
+ const repoTempRoot = path.resolve(import.meta.dir, "../../../..", ".tmp-test-artifacts");
17
+
18
+ async function mkRepoTempDir(prefix: string): Promise<string> {
19
+ await mkdir(repoTempRoot, { recursive: true });
20
+ return mkdtemp(path.join(repoTempRoot, prefix));
21
+ }
22
+
23
+ async function importBuiltModule(relativePath: string): Promise<Record<string, unknown>> {
24
+ const fileUrl = pathToFileURL(path.join(rootDir, relativePath)).href;
25
+ return import(`${fileUrl}?t=${Date.now()}`);
26
+ }
27
+
28
+ async function evaluateGeneratedHydrationRuntime(): Promise<{ hydrateIslands: () => void }> {
29
+ const sourcePath = path.join(rootDir, ".mandu", "client", "_runtime.src.js");
30
+ const bundledPath = path.join(rootDir, ".mandu", "client", "_runtime.js");
31
+ const runtimeSource = await readFile(await Bun.file(sourcePath).exists() ? sourcePath : bundledPath, "utf-8");
32
+ const instrumented = runtimeSource
33
+ .replace(
34
+ /import\s+React,\s*\{[^}]*\}\s+from\s+['"]react['"];?/,
35
+ "const React = globalThis.__MANDU_TEST_REACT__; const { useState, useEffect, Component } = React;",
36
+ )
37
+ .replace(
38
+ /import\s+\{[^}]*\}\s+from\s+['"]react-dom\/client['"];?/,
39
+ "const { hydrateRoot, createRoot } = globalThis.__MANDU_TEST_REACT_DOM_CLIENT__;",
40
+ )
41
+ .replace(
42
+ /export\s*\{[^}]*\};?/g,
43
+ "globalThis.__MANDU_TEST_RUNTIME__ = { hydrateIslands, unmountIsland, hydratedRoots };",
44
+ );
45
+
46
+ const reactStub = {
47
+ Component: class {
48
+ render() {
49
+ return null;
50
+ }
51
+ },
52
+ createElement(type: unknown, props: Record<string, unknown> | null, ...children: unknown[]) {
53
+ if (
54
+ typeof type === "function" &&
55
+ !(typeof type === "function" && "prototype" in type && (type as { prototype?: { render?: unknown } }).prototype?.render)
56
+ ) {
57
+ return (type as (props: Record<string, unknown>) => unknown)({
58
+ ...(props ?? {}),
59
+ children: children.length <= 1 ? children[0] : children,
60
+ });
61
+ }
62
+ return { type, props: props ?? {}, children };
63
+ },
64
+ isValidElement(value: unknown) {
65
+ return !!value && typeof value === "object" && "type" in value;
66
+ },
67
+ useEffect(effect: () => void) {
68
+ effect();
69
+ },
70
+ useState<T>(initial: T) {
71
+ return [initial, () => {}] as const;
72
+ },
73
+ };
74
+ const rootStub = {
75
+ render() {},
76
+ unmount() {},
77
+ };
78
+ Object.assign(globalThis, {
79
+ __MANDU_TEST_REACT__: reactStub,
80
+ __MANDU_TEST_REACT_DOM_CLIENT__: {
81
+ createRoot: () => rootStub,
82
+ hydrateRoot: () => rootStub,
83
+ },
84
+ });
85
+
86
+ new Function(instrumented)();
87
+ return (globalThis as typeof globalThis & {
88
+ __MANDU_TEST_RUNTIME__: { hydrateIslands: () => void };
89
+ }).__MANDU_TEST_RUNTIME__;
90
+ }
91
+
92
+ async function waitForRuntimeAssertion(assertion: () => boolean): Promise<void> {
93
+ for (let attempt = 0; attempt < 25; attempt++) {
94
+ if (assertion()) return;
95
+ await new Promise((resolve) => setTimeout(resolve, 0));
96
+ }
97
+ expect(assertion()).toBe(true);
98
+ }
99
+
100
+ /**
101
+ * Run `buildClientBundles` in an isolated `bun` subprocess.
102
+ *
103
+ * Bun 1.3.x exhibits a deterministic `AggregateError: Bundle failed` when
104
+ * `buildClientBundles` is called from a test file AND the same `bun test`
105
+ * process has previously imported `react` / `react-dom` through any sibling
106
+ * test file (happens transitively through almost every `src/testing/*` or
107
+ * `src/runtime/*` consumer). Retrying in-process does not recover — the
108
+ * resolver state is sticky. A fresh subprocess has a clean module graph.
109
+ * See `__tests__/build-runner.ts` for the subprocess entrypoint and more
110
+ * background.
111
+ */
112
+ async function runBuildInSubprocess(root: string, mode?: string): Promise<{
113
+ success: boolean;
114
+ errors: string[];
115
+ manifest?: {
116
+ routes?: Array<{
117
+ id?: string;
118
+ module?: string;
119
+ componentModule?: string;
120
+ boundaries?: Array<{
121
+ id?: string;
122
+ routeId?: string;
123
+ module?: string;
124
+ importSpecifier?: string;
125
+ exportName?: string;
126
+ localName?: string;
127
+ hydrate?: string;
128
+ ordinal?: number;
129
+ propsSource?: string;
130
+ propsKeys?: string[];
131
+ hasSpreadProps?: boolean;
132
+ source?: {
133
+ file?: string;
134
+ line?: number;
135
+ column?: number;
136
+ };
137
+ }>;
138
+ }>;
139
+ bundles?: Record<string, { js?: string }>;
140
+ boundaries?: Record<string, { js?: string; route?: string; module?: string; exportName?: string; hydrate?: string }>;
141
+ } | null;
142
+ }> {
143
+ const runner = path.join(
144
+ import.meta.dir,
145
+ "__tests__",
146
+ "build-runner.ts",
147
+ );
148
+ try {
149
+ const args = [process.execPath, "run", runner, root];
150
+ if (mode) args.push(mode);
151
+ const proc = Bun.spawn(args, {
152
+ cwd: path.resolve(import.meta.dir, "..", ".."),
153
+ stdin: "ignore",
154
+ stdout: "pipe",
155
+ stderr: "inherit",
156
+ });
157
+ const out = await new Response(proc.stdout).text();
158
+ await proc.exited;
159
+
160
+ // Find the final JSON line the runner may log Mandu dev banners
161
+ // (e.g. "[Mandu] DevTools …") before emitting the payload. The
162
+ // contract is: last non-empty line is the JSON blob.
163
+ const lines = out.split(/\r?\n/).filter((l) => l.trim().length > 0);
164
+ const last = lines[lines.length - 1] ?? "";
165
+ try {
166
+ const parsed = JSON.parse(last);
167
+ return {
168
+ success: parsed.success === true,
169
+ errors: Array.isArray(parsed.errors) ? parsed.errors : [],
170
+ manifest: parsed.manifest ?? null,
171
+ };
172
+ } catch (e) {
173
+ return {
174
+ success: false,
175
+ errors: [
176
+ `build-runner output could not be parsed as JSON: ${String(e)}\nLast stdout line: ${last}`,
177
+ ],
178
+ manifest: null,
179
+ };
180
+ }
181
+ } catch (err) {
182
+ return { success: false, errors: [`spawn failed: ${String(err)}`], manifest: null };
183
+ }
184
+ }
185
+
186
+ beforeAll(async () => {
187
+ if (skipBundlerTests) return;
188
+ rootDir = await mkRepoTempDir("bundler-");
189
+
190
+ await mkdir(path.join(rootDir, "app"), { recursive: true });
191
+ await writeFile(
192
+ path.join(rootDir, "package.json"),
193
+ JSON.stringify({ name: "mandu-build-test", type: "module" }, null, 2),
194
+ "utf-8",
195
+ );
196
+ await writeFile(
197
+ path.join(rootDir, "app", "demo.client.tsx"),
198
+ "export default function DemoIsland() { return null; }\n",
199
+ "utf-8",
200
+ );
201
+
202
+ result = await runBuildInSubprocess(rootDir);
203
+ });
204
+
205
+ afterAll(async () => {
206
+ if (rootDir) {
207
+ await rm(rootDir, { recursive: true, force: true });
208
+ }
209
+ });
210
+
211
+ // Bun 1.3.x still serializes parts of Bun.build across concurrent test files.
212
+ // The product test runner gates this file in the main process and executes it
213
+ // alone, while direct `bun test build.test.ts` keeps the complete coverage.
214
+ describe.skipIf(skipBundlerTests)("buildClientBundles vendor shims", () => {
215
+ test("build succeeds", () => {
216
+ if (!result.success) {
217
+ console.error("[build.test] errors:", result.errors);
218
+ }
219
+ expect(result.success).toBe(true);
220
+ });
221
+
222
+ test("runtime reads canonical data-hydrate strategies", async () => {
223
+ const runtimePath = path.join(rootDir, ".mandu", "client", "_runtime.js");
224
+ const runtimeSource = await readFile(runtimePath, "utf-8");
225
+
226
+ expect(runtimeSource).toContain("data-hydrate");
227
+ expect(runtimeSource).toContain("matchMedia");
228
+ expect(runtimeSource).toContain("200px");
229
+ expect(runtimeSource).toContain('"click"');
230
+ expect(runtimeSource).not.toContain("mouseenter");
231
+ expect(runtimeSource).not.toContain("pointerdown");
232
+ });
233
+
234
+ test("re-exports modern React 19 APIs used by islands", async () => {
235
+ const reactShim = await importBuiltModule(".mandu/client/_react.js");
236
+ const requiredExports = [
237
+ "Activity",
238
+ "__COMPILER_RUNTIME",
239
+ "cache",
240
+ "cacheSignal",
241
+ "startTransition",
242
+ "use",
243
+ "useActionState",
244
+ "useEffectEvent",
245
+ "useOptimistic",
246
+ "unstable_useCacheRefresh",
247
+ ];
248
+
249
+ for (const exportName of requiredExports) {
250
+ expect(exportName in reactShim).toBe(true);
251
+ }
252
+ });
253
+
254
+ test("re-exports modern react-dom and react-dom/client APIs", async () => {
255
+ const reactDomShim = await importBuiltModule(".mandu/client/_react-dom.js");
256
+ for (const exportName of [
257
+ "preconnect",
258
+ "prefetchDNS",
259
+ "preinit",
260
+ "preinitModule",
261
+ "preload",
262
+ "preloadModule",
263
+ "requestFormReset",
264
+ "unstable_batchedUpdates",
265
+ "useFormState",
266
+ "useFormStatus",
267
+ ]) {
268
+ expect(exportName in reactDomShim).toBe(true);
269
+ }
270
+
271
+ const reactDomClientShim = await importBuiltModule(".mandu/client/_react-dom-client.js");
272
+ for (const exportName of ["createRoot", "hydrateRoot", "version"]) {
273
+ expect(exportName in reactDomClientShim).toBe(true);
274
+ }
275
+ });
276
+
277
+ test("embeds hydration guards for deferred trigger strategies", async () => {
278
+ const runtimeSource = await readFile(path.join(rootDir, ".mandu", "client", "_runtime.js"), "utf-8");
279
+ expect(runtimeSource).toContain("function resolveHydrationTarget");
280
+ expect(runtimeSource).toContain("function hasHydratableMarkup");
281
+ expect(runtimeSource).toContain("function shouldHydrateCompiledIsland");
282
+ expect(runtimeSource).toContain("onRecoverableError");
283
+ expect(runtimeSource).toContain("data-mandu-hydrating");
284
+ expect(runtimeSource).toContain("data-mandu-render-mode");
285
+ expect(runtimeSource).toContain("data-mandu-recoverable-error");
286
+ expect(runtimeSource).toContain('"click"');
287
+ expect(runtimeSource).not.toContain("pointerdown");
288
+ });
289
+
290
+ test("runtime parses SSR data script before island setup", async () => {
291
+ const runtimeSource = await readFile(path.join(rootDir, ".mandu", "client", "_runtime.js"), "utf-8");
292
+ expect(runtimeSource).toContain("function readManduData");
293
+ expect(runtimeSource).toContain("document.getElementById(\"__MANDU_DATA__\")");
294
+ expect(runtimeSource).toContain("function parsePropsScript");
295
+ expect(runtimeSource).toContain("data-mandu-props");
296
+ expect(runtimeSource).toContain("Missing boundary-local props for transformed client boundary");
297
+ expect(runtimeSource).toContain("warnedBoundaryPropFallbacks");
298
+ expect(runtimeSource).toContain("deserializeProps");
299
+ expect(runtimeSource).toContain("new Date");
300
+ expect(runtimeSource).toContain("new Map");
301
+ });
302
+
303
+ test("runtime hydrates named client boundary from boundary-local props before route data", async () => {
304
+ const modulePath = path.join(rootDir, ".mandu", "client", "runtime-named-boundary.js");
305
+ await writeFile(
306
+ modulePath,
307
+ `
308
+ export default function WrongDefault(props) {
309
+ globalThis.__MANDU_TEST_DEFAULT_PROPS__ = props;
310
+ return null;
311
+ }
312
+ export function NamedBoundary(props) {
313
+ globalThis.__MANDU_TEST_NAMED_PROPS__ = props;
314
+ return null;
315
+ }
316
+ `,
317
+ "utf-8",
318
+ );
319
+ Object.assign(globalThis, {
320
+ __MANDU_TEST_NAMED_PROPS__: undefined,
321
+ __MANDU_TEST_DEFAULT_PROPS__: undefined,
322
+ });
323
+ document.body.innerHTML = `
324
+ <div
325
+ data-mandu-island="named--0"
326
+ data-mandu-boundary-id="named--0"
327
+ data-mandu-route-id="named-route"
328
+ data-mandu-client-export="NamedBoundary"
329
+ data-mandu-src="${pathToFileURL(modulePath).href}?t=${Date.now()}"
330
+ data-hydrate="load"
331
+ ></div>
332
+ <script type="application/json" data-mandu-props="named--0">${serializeProps({ label: "boundary-local" })}</script>
333
+ `;
334
+ (window as typeof window & { __MANDU_DATA__?: unknown; __MANDU_ROOTS__?: Map<string, unknown> }).__MANDU_DATA__ = {
335
+ "named-route": { serverData: { label: "route-data" } },
336
+ };
337
+ (window as typeof window & { __MANDU_ROOTS__?: Map<string, unknown> }).__MANDU_ROOTS__ = new Map();
338
+
339
+ const runtime = await evaluateGeneratedHydrationRuntime();
340
+ runtime.hydrateIslands();
341
+
342
+ await waitForRuntimeAssertion(() =>
343
+ (globalThis as typeof globalThis & { __MANDU_TEST_NAMED_PROPS__?: { label?: string } }).__MANDU_TEST_NAMED_PROPS__?.label === "boundary-local"
344
+ );
345
+ expect((globalThis as typeof globalThis & { __MANDU_TEST_DEFAULT_PROPS__?: unknown }).__MANDU_TEST_DEFAULT_PROPS__).toBeUndefined();
346
+ });
347
+
348
+ test("surfaces an island hydration failure to the DevTools hook (#324)", async () => {
349
+ const modulePath = path.join(rootDir, ".mandu", "client", "runtime-failing-boundary.js");
350
+ // A module that throws at import time → loadAndHydrate's catch runs.
351
+ await writeFile(modulePath, `throw new Error("boom at import");`, "utf-8");
352
+
353
+ const emitted: Array<{ type?: string; data?: { message?: string; islandId?: string } }> = [];
354
+ (window as unknown as { __MANDU_DEVTOOLS_HOOK__?: { emit: (e: unknown) => void } }).__MANDU_DEVTOOLS_HOOK__ = {
355
+ emit: (e: unknown) => {
356
+ emitted.push(e as { type?: string });
357
+ },
358
+ };
359
+
360
+ document.body.innerHTML = `
361
+ <div
362
+ data-mandu-island="failing--0"
363
+ data-mandu-src="${pathToFileURL(modulePath).href}?t=${Date.now()}"
364
+ data-hydrate="load"
365
+ ></div>
366
+ `;
367
+ (window as typeof window & { __MANDU_ROOTS__?: Map<string, unknown> }).__MANDU_ROOTS__ = new Map();
368
+
369
+ try {
370
+ const runtime = await evaluateGeneratedHydrationRuntime();
371
+ runtime.hydrateIslands();
372
+
373
+ await waitForRuntimeAssertion(() => emitted.some((e) => e.type === "error"));
374
+ const errorEvent = emitted.find((e) => e.type === "error");
375
+ expect(errorEvent?.data?.islandId).toBe("failing--0");
376
+ expect(errorEvent?.data?.message).toContain("boom at import");
377
+ } finally {
378
+ delete (window as unknown as { __MANDU_DEVTOOLS_HOOK__?: unknown }).__MANDU_DEVTOOLS_HOOK__;
379
+ }
380
+ });
381
+
382
+ test("runtime hydrates default client boundary from boundary-local props", async () => {
383
+ const modulePath = path.join(rootDir, ".mandu", "client", "runtime-default-boundary.js");
384
+ await writeFile(
385
+ modulePath,
386
+ `
387
+ export default function DefaultBoundary(props) {
388
+ globalThis.__MANDU_TEST_DEFAULT_BOUNDARY_PROPS__ = props;
389
+ return null;
390
+ }
391
+ `,
392
+ "utf-8",
393
+ );
394
+ Object.assign(globalThis, {
395
+ __MANDU_TEST_DEFAULT_BOUNDARY_PROPS__: undefined,
396
+ });
397
+ document.body.innerHTML = `
398
+ <div
399
+ data-mandu-island="default--0"
400
+ data-mandu-boundary-id="default--0"
401
+ data-mandu-route-id="default-route"
402
+ data-mandu-client-export="default"
403
+ data-mandu-src="${pathToFileURL(modulePath).href}?t=${Date.now()}"
404
+ data-hydrate="load"
405
+ ></div>
406
+ <script type="application/json" data-mandu-props="default--0">${serializeProps({ label: "default-boundary" })}</script>
407
+ `;
408
+ (window as typeof window & { __MANDU_DATA__?: unknown; __MANDU_ROOTS__?: Map<string, unknown> }).__MANDU_DATA__ = {};
409
+ (window as typeof window & { __MANDU_ROOTS__?: Map<string, unknown> }).__MANDU_ROOTS__ = new Map();
410
+
411
+ const runtime = await evaluateGeneratedHydrationRuntime();
412
+ runtime.hydrateIslands();
413
+
414
+ await waitForRuntimeAssertion(() =>
415
+ (globalThis as typeof globalThis & { __MANDU_TEST_DEFAULT_BOUNDARY_PROPS__?: { label?: string } }).__MANDU_TEST_DEFAULT_BOUNDARY_PROPS__?.label === "default-boundary"
416
+ );
417
+ });
418
+
419
+ test("runtime keeps explicit island API data-props fallback working", async () => {
420
+ const modulePath = path.join(rootDir, ".mandu", "client", "runtime-explicit-island.js");
421
+ await writeFile(
422
+ modulePath,
423
+ `
424
+ export default {
425
+ __mandu_island: true,
426
+ definition: {
427
+ setup(data) {
428
+ globalThis.__MANDU_TEST_EXPLICIT_ISLAND_DATA__ = data;
429
+ return data;
430
+ },
431
+ render() {
432
+ return null;
433
+ }
434
+ }
435
+ };
436
+ `,
437
+ "utf-8",
438
+ );
439
+ Object.assign(globalThis, {
440
+ __MANDU_TEST_EXPLICIT_ISLAND_DATA__: undefined,
441
+ });
442
+ document.body.innerHTML = `
443
+ <div
444
+ data-mandu-island="explicit-island"
445
+ data-mandu-src="${pathToFileURL(modulePath).href}?t=${Date.now()}"
446
+ data-props="${serializeProps({ label: "data-props" }).replace(/"/g, "&quot;")}"
447
+ data-hydrate="load"
448
+ ></div>
449
+ `;
450
+ (window as typeof window & { __MANDU_DATA__?: unknown; __MANDU_ROOTS__?: Map<string, unknown> }).__MANDU_DATA__ = {};
451
+ (window as typeof window & { __MANDU_ROOTS__?: Map<string, unknown> }).__MANDU_ROOTS__ = new Map();
452
+
453
+ const runtime = await evaluateGeneratedHydrationRuntime();
454
+ runtime.hydrateIslands();
455
+
456
+ await waitForRuntimeAssertion(() =>
457
+ (globalThis as typeof globalThis & { __MANDU_TEST_EXPLICIT_ISLAND_DATA__?: { label?: string } }).__MANDU_TEST_EXPLICIT_ISLAND_DATA__?.label === "data-props"
458
+ );
459
+ });
460
+
461
+ test("runtime falls back to route-level server data when boundary-local props are absent", async () => {
462
+ const modulePath = path.join(rootDir, ".mandu", "client", "runtime-route-data-fallback.js");
463
+ await writeFile(
464
+ modulePath,
465
+ `
466
+ export default function RouteFallbackBoundary(props) {
467
+ globalThis.__MANDU_TEST_ROUTE_DATA_FALLBACK_PROPS__ = props;
468
+ return null;
469
+ }
470
+ `,
471
+ "utf-8",
472
+ );
473
+ Object.assign(globalThis, {
474
+ __MANDU_TEST_ROUTE_DATA_FALLBACK_PROPS__: undefined,
475
+ });
476
+ document.body.innerHTML = `
477
+ <div
478
+ data-mandu-island="route-fallback--0"
479
+ data-mandu-boundary-id="route-fallback--0"
480
+ data-mandu-route-id="route-fallback"
481
+ data-mandu-src="${pathToFileURL(modulePath).href}?t=${Date.now()}"
482
+ data-hydrate="load"
483
+ ></div>
484
+ `;
485
+ (window as typeof window & { __MANDU_DATA__?: unknown; __MANDU_ROOTS__?: Map<string, unknown> }).__MANDU_DATA__ = {
486
+ "route-fallback": { serverData: { label: "route-level" } },
487
+ };
488
+ (window as typeof window & { __MANDU_ROOTS__?: Map<string, unknown> }).__MANDU_ROOTS__ = new Map();
489
+
490
+ const runtime = await evaluateGeneratedHydrationRuntime();
491
+ runtime.hydrateIslands();
492
+
493
+ await waitForRuntimeAssertion(() =>
494
+ (globalThis as typeof globalThis & { __MANDU_TEST_ROUTE_DATA_FALLBACK_PROPS__?: { label?: string } }).__MANDU_TEST_ROUTE_DATA_FALLBACK_PROPS__?.label === "route-level"
495
+ );
496
+ });
497
+
498
+ test("does not bundle a server page when stale manifest marks page.tsx as clientModule", async () => {
499
+ const staleRoot = await mkRepoTempDir("stale-client-module-");
500
+ try {
501
+ await mkdir(path.join(staleRoot, "app"), { recursive: true });
502
+ await mkdir(path.join(staleRoot, "src", "shared", "contracts"), { recursive: true });
503
+ await writeFile(
504
+ path.join(staleRoot, "package.json"),
505
+ JSON.stringify({ name: "mandu-stale-client-module-test", type: "module" }, null, 2),
506
+ "utf-8",
507
+ );
508
+ await writeFile(
509
+ path.join(staleRoot, "src", "shared", "contracts", "api.ts"),
510
+ 'export const INTERNAL_BASE = process.env.MANDU_INTERNAL_URL ?? "http://localhost:3333";\n',
511
+ "utf-8",
512
+ );
513
+ await writeFile(
514
+ path.join(staleRoot, "app", "page.tsx"),
515
+ 'import { INTERNAL_BASE } from "../src/shared/contracts/api";\n' +
516
+ "export default async function HomePage() {\n" +
517
+ " return <main>{INTERNAL_BASE}</main>;\n" +
518
+ "}\n",
519
+ "utf-8",
520
+ );
521
+
522
+ const staleResult = await runBuildInSubprocess(staleRoot, "server-page-client-module");
523
+ expect(staleResult.success).toBe(false);
524
+ expect(staleResult.errors.join("\n")).toContain("missing \"use client\"");
525
+ expect(await Bun.file(path.join(staleRoot, ".mandu", "client", "index.island.js")).exists()).toBe(false);
526
+ } finally {
527
+ await rm(staleRoot, { recursive: true, force: true });
528
+ }
529
+ });
530
+
531
+ test("rewrites route-component clientModule to the real client import before bundling", async () => {
532
+ const routeClientRoot = await mkRepoTempDir("route-client-import-");
533
+ try {
534
+ await mkdir(path.join(routeClientRoot, "app", "login"), { recursive: true });
535
+ await mkdir(path.join(routeClientRoot, "src", "client", "pages", "login"), { recursive: true });
536
+ await writeFile(
537
+ path.join(routeClientRoot, "package.json"),
538
+ JSON.stringify({ name: "mandu-route-client-import-test", type: "module" }, null, 2),
539
+ "utf-8",
540
+ );
541
+ await writeFile(
542
+ path.join(routeClientRoot, "app", "login", "page.tsx"),
543
+ 'import LoginPage from "@/client/pages/login/LoginPage.client";\n' +
544
+ "export default function Page() {\n" +
545
+ " return <LoginPage />;\n" +
546
+ "}\n",
547
+ "utf-8",
548
+ );
549
+ await writeFile(
550
+ path.join(routeClientRoot, "src", "client", "pages", "login", "LoginPage.client.tsx"),
551
+ '"use client";\n' +
552
+ 'import { useState } from "react";\n' +
553
+ "export default function LoginPage() {\n" +
554
+ ' const [email, setEmail] = useState("");\n' +
555
+ ' return <form><input value={email} onChange={(event) => setEmail(event.currentTarget.value)} /></form>;\n' +
556
+ "}\n",
557
+ "utf-8",
558
+ );
559
+
560
+ const routeClientResult = await runBuildInSubprocess(routeClientRoot, "server-page-route-client-import");
561
+ expect(routeClientResult.success).toBe(true);
562
+ const bundlePath = path.join(routeClientRoot, ".mandu", "client", "login.island.js");
563
+ expect(await Bun.file(bundlePath).exists()).toBe(true);
564
+
565
+ const bundleSource = await readFile(bundlePath, "utf-8");
566
+ expect(bundleSource).not.toContain("var LoginPage = LoginPage;");
567
+ const parseResult = await Bun.build({
568
+ entrypoints: [bundlePath],
569
+ target: "browser",
570
+ external: ["react", "react-dom", "react-dom/client", "react/jsx-dev-runtime"],
571
+ });
572
+ expect(parseResult.success).toBe(true);
573
+ } finally {
574
+ await rm(routeClientRoot, { recursive: true, force: true });
575
+ }
576
+ });
577
+
578
+ test("bundles route-level named client exports without requiring a default export", async () => {
579
+ const routeClientRoot = await mkRepoTempDir("route-named-client-import-");
580
+ try {
581
+ await mkdir(path.join(routeClientRoot, "app", "login"), { recursive: true });
582
+ await mkdir(path.join(routeClientRoot, "src", "client", "pages", "login"), { recursive: true });
583
+ await writeFile(
584
+ path.join(routeClientRoot, "package.json"),
585
+ JSON.stringify({ name: "mandu-route-named-client-import-test", type: "module" }, null, 2),
586
+ "utf-8",
587
+ );
588
+ await writeFile(
589
+ path.join(routeClientRoot, "app", "login", "page.tsx"),
590
+ 'import { LoginPage } from "@/client/pages/login/LoginPage.client";\n' +
591
+ "export default function Page() {\n" +
592
+ " return <LoginPage />;\n" +
593
+ "}\n",
594
+ "utf-8",
595
+ );
596
+ await writeFile(
597
+ path.join(routeClientRoot, "src", "client", "pages", "login", "LoginPage.client.tsx"),
598
+ '"use client";\n' +
599
+ 'import { useState } from "react";\n' +
600
+ "export function LoginPage() {\n" +
601
+ ' const [email, setEmail] = useState("");\n' +
602
+ ' return <form><input value={email} onChange={(event) => setEmail(event.currentTarget.value)} /></form>;\n' +
603
+ "}\n",
604
+ "utf-8",
605
+ );
606
+
607
+ const routeClientResult = await runBuildInSubprocess(routeClientRoot, "server-page-route-named-client-import");
608
+ if (!routeClientResult.success) {
609
+ console.error("[named route client] errors:", routeClientResult.errors);
610
+ }
611
+ expect(routeClientResult.success).toBe(true);
612
+ const bundlePath = path.join(routeClientRoot, ".mandu", "client", "login.island.js");
613
+ expect(await Bun.file(bundlePath).exists()).toBe(true);
614
+
615
+ const bundleSource = await readFile(bundlePath, "utf-8");
616
+ expect(bundleSource).toContain("LoginPage");
617
+ expect(bundleSource).not.toContain("Client islands cannot use server-side modules");
618
+ const parseResult = await Bun.build({
619
+ entrypoints: [bundlePath],
620
+ target: "browser",
621
+ external: ["react", "react-dom", "react-dom/client", "react/jsx-dev-runtime"],
622
+ });
623
+ expect(parseResult.success).toBe(true);
624
+ } finally {
625
+ await rm(routeClientRoot, { recursive: true, force: true });
626
+ }
627
+ });
628
+
629
+ test("uses Windows-safe asset filenames for locale-prefixed route ids", async () => {
630
+ const localeRoot = await mkRepoTempDir("i18n-locale-route-id-");
631
+ try {
632
+ await mkdir(path.join(localeRoot, "app"), { recursive: true });
633
+ await writeFile(
634
+ path.join(localeRoot, "package.json"),
635
+ JSON.stringify({ name: "mandu-i18n-route-id-test", type: "module" }, null, 2),
636
+ "utf-8",
637
+ );
638
+ await writeFile(
639
+ path.join(localeRoot, "app", "demo.client.tsx"),
640
+ "export default function DemoIsland() { return null; }\n",
641
+ "utf-8",
642
+ );
643
+
644
+ const localeResult = await runBuildInSubprocess(localeRoot, "i18n-locale-route-id");
645
+ expect(localeResult.success).toBe(true);
646
+ const bundle = localeResult.manifest?.bundles?.["ko::demo"];
647
+ expect(bundle?.js).toBe("/.mandu/client/ko_3a__3a_demo.island.js");
648
+ expect(bundle?.js).not.toContain(":");
649
+ expect(await Bun.file(path.join(localeRoot, ".mandu", "client", "ko_3a__3a_demo.island.js")).exists()).toBe(true);
650
+ } finally {
651
+ await rm(localeRoot, { recursive: true, force: true });
652
+ }
653
+ });
654
+
655
+ test("fails when hydration is enabled but no clientModule can be resolved", async () => {
656
+ const missingRoot = await mkRepoTempDir("hydration-no-client-");
657
+ try {
658
+ await mkdir(path.join(missingRoot, "app", "login"), { recursive: true });
659
+ await mkdir(path.join(missingRoot, "src", "client", "widgets", "login-form"), { recursive: true });
660
+ await writeFile(
661
+ path.join(missingRoot, "package.json"),
662
+ JSON.stringify({ name: "mandu-hydration-no-client-test", type: "module" }, null, 2),
663
+ "utf-8",
664
+ );
665
+ await writeFile(
666
+ path.join(missingRoot, "app", "login", "page.tsx"),
667
+ 'import { LoginForm } from "../../src/client/widgets/login-form/LoginForm.client";\n' +
668
+ "export default function LoginPage() {\n" +
669
+ " return <main><LoginForm /></main>;\n" +
670
+ "}\n",
671
+ "utf-8",
672
+ );
673
+ await writeFile(
674
+ path.join(missingRoot, "src", "client", "widgets", "login-form", "LoginForm.client.tsx"),
675
+ "export function LoginForm() { return <form />; }\n",
676
+ "utf-8",
677
+ );
678
+
679
+ const noClientResult = await runBuildInSubprocess(missingRoot, "hydration-no-client-module");
680
+ const errors = noClientResult.errors.join("\n");
681
+ expect(noClientResult.success).toBe(false);
682
+ expect(errors).toContain("no clientModule could be resolved");
683
+ expect(errors).toContain("LoginForm.client");
684
+ expect(errors).toContain("run mandu generate");
685
+ } finally {
686
+ await rm(missingRoot, { recursive: true, force: true });
687
+ }
688
+ });
689
+ });
690
+
691
+ describe.skipIf(skipBundlerTests)("buildClientBundles client boundaries", () => {
692
+ async function createBoundaryFixture(prefix: string): Promise<string> {
693
+ const boundaryRoot = await mkRepoTempDir(prefix);
694
+ await mkdir(path.join(boundaryRoot, "app", "boundary"), { recursive: true });
695
+ await mkdir(path.join(boundaryRoot, "src", "client"), { recursive: true });
696
+ await writeFile(
697
+ path.join(boundaryRoot, "package.json"),
698
+ JSON.stringify({ name: "mandu-boundary-test", type: "module" }, null, 2),
699
+ "utf-8",
700
+ );
701
+ await writeFile(
702
+ path.join(boundaryRoot, "app", "boundary", "page.tsx"),
703
+ "export default function Page() { return null; }\n",
704
+ "utf-8",
705
+ );
706
+ await writeFile(
707
+ path.join(boundaryRoot, "src", "client", "BoundaryWidget.client.tsx"),
708
+ `
709
+ import React from "react";
710
+
711
+ export default function WrongDefault({ label }) {
712
+ return React.createElement("p", null, "default:" + label);
713
+ }
714
+
715
+ export function BoundaryWidget({ label }) {
716
+ return React.createElement("button", null, "named:" + label);
717
+ }
718
+ `,
719
+ "utf-8",
720
+ );
721
+ return boundaryRoot;
722
+ }
723
+
724
+ test("emits boundary bundle manifest entries", async () => {
725
+ const boundaryRoot = await createBoundaryFixture("bundler-boundary-");
726
+ try {
727
+ const boundaryResult = await runBuildInSubprocess(boundaryRoot, "client-boundary");
728
+
729
+ if (!boundaryResult.success) {
730
+ console.error("[build.test boundary] errors:", boundaryResult.errors);
731
+ }
732
+ expect(boundaryResult.success).toBe(true);
733
+ expect(boundaryResult.manifest?.boundaries?.["boundary-demo--0"]).toMatchObject({
734
+ route: "boundary-demo",
735
+ module: "src/client/BoundaryWidget.client.tsx",
736
+ exportName: "BoundaryWidget",
737
+ hydrate: "visible",
738
+ });
739
+ expect(boundaryResult.manifest?.boundaries?.["boundary-demo--0"]?.js).toMatch(
740
+ /^\/\.mandu\/client\/boundary-demo--0\.boundary\.js$/,
741
+ );
742
+ expect(boundaryResult.manifest?.bundles?.["boundary-demo"]).toBeUndefined();
743
+
744
+ const refreshGlobal = globalThis as typeof globalThis & {
745
+ $RefreshReg$?: unknown;
746
+ $RefreshSig$?: unknown;
747
+ };
748
+ refreshGlobal.$RefreshReg$ = () => {};
749
+ refreshGlobal.$RefreshSig$ = () => (type: unknown) => type;
750
+ try {
751
+ const boundaryBundle = await import(
752
+ `${pathToFileURL(path.join(boundaryRoot, ".mandu", "client", "boundary-demo--0.boundary.js")).href}?t=${Date.now()}`
753
+ );
754
+ const React = await import("react");
755
+ const { renderToStaticMarkup } = await import("react-dom/server");
756
+
757
+ expect(typeof boundaryBundle.default).toBe("function");
758
+ expect(typeof boundaryBundle.BoundaryWidget).toBe("function");
759
+ expect(renderToStaticMarkup(React.createElement(boundaryBundle.default, { label: "ok" }))).toContain("named:ok");
760
+ expect(renderToStaticMarkup(React.createElement(boundaryBundle.BoundaryWidget, { label: "ok" }))).toContain("named:ok");
761
+ } finally {
762
+ delete refreshGlobal.$RefreshReg$;
763
+ delete refreshGlobal.$RefreshSig$;
764
+ }
765
+ } finally {
766
+ await rm(boundaryRoot, { recursive: true, force: true });
767
+ }
768
+ });
769
+
770
+ test("snapshots route and bundle boundary metadata", async () => {
771
+ const boundaryRoot = await createBoundaryFixture("bundler-boundary-snapshot-");
772
+ try {
773
+ const boundaryResult = await runBuildInSubprocess(boundaryRoot, "client-boundary");
774
+ expect(boundaryResult.success).toBe(true);
775
+
776
+ toMatchSnapshot(
777
+ {
778
+ routes: boundaryResult.manifest?.routes?.map((route) => ({
779
+ id: route.id,
780
+ module: route.module,
781
+ componentModule: route.componentModule,
782
+ boundaries: route.boundaries,
783
+ })),
784
+ bundleBoundaries: boundaryResult.manifest?.boundaries,
785
+ },
786
+ {
787
+ testFile: path.join(import.meta.dir, "build.test.ts"),
788
+ name: "client boundary manifest metadata",
789
+ },
790
+ );
791
+ } finally {
792
+ await rm(boundaryRoot, { recursive: true, force: true });
793
+ }
794
+ });
795
+
796
+ test("updates boundary manifest entries in target-route builds", async () => {
797
+ const boundaryRoot = await createBoundaryFixture("bundler-boundary-target-");
798
+ try {
799
+ const boundaryResult = await runBuildInSubprocess(boundaryRoot, "client-boundary-target");
800
+ expect(boundaryResult.success).toBe(true);
801
+ expect(boundaryResult.manifest?.boundaries?.["boundary-demo--0"]?.js).toBe(
802
+ "/.mandu/client/boundary-demo--0.boundary.js",
803
+ );
804
+ } finally {
805
+ await rm(boundaryRoot, { recursive: true, force: true });
806
+ }
807
+ });
808
+
809
+ test("fails before manifest generation when boundary ids are duplicated", async () => {
810
+ const boundaryRoot = await createBoundaryFixture("bundler-boundary-duplicate-");
811
+ try {
812
+ const boundaryResult = await runBuildInSubprocess(boundaryRoot, "client-boundary-duplicate-id");
813
+
814
+ expect(boundaryResult.success).toBe(false);
815
+ expect(boundaryResult.errors.join("\n")).toContain("MANDU_BOUNDARY_DUPLICATE_ID");
816
+ expect(boundaryResult.errors.join("\n")).toContain("boundary-demo--0");
817
+ } finally {
818
+ await rm(boundaryRoot, { recursive: true, force: true });
819
+ }
820
+ });
821
+
822
+ test("updates boundary manifest entries when framework bundles are skipped", async () => {
823
+ const boundaryRoot = await createBoundaryFixture("bundler-boundary-skip-");
824
+ try {
825
+ const boundaryResult = await runBuildInSubprocess(boundaryRoot, "client-boundary-skip-framework");
826
+ expect(boundaryResult.success).toBe(true);
827
+ expect(boundaryResult.manifest?.boundaries?.["boundary-demo--0"]?.js).toBe(
828
+ "/.mandu/client/boundary-demo--0.boundary.js",
829
+ );
830
+ } finally {
831
+ await rm(boundaryRoot, { recursive: true, force: true });
832
+ }
833
+ });
834
+
835
+ test("builds manifest-generated boundaries from route-owned server wrappers", async () => {
836
+ const boundaryRoot = await mkRepoTempDir("bundler-boundary-generated-wrapper-");
837
+ try {
838
+ await mkdir(path.join(boundaryRoot, "app", "account", "components"), { recursive: true });
839
+ await writeFile(
840
+ path.join(boundaryRoot, "package.json"),
841
+ JSON.stringify({ name: "mandu-boundary-generated-wrapper-test", type: "module" }, null, 2),
842
+ "utf-8",
843
+ );
844
+ await writeFile(
845
+ path.join(boundaryRoot, "app", "account", "page.tsx"),
846
+ `
847
+ import { AccountShell } from "./components/AccountShell";
848
+
849
+ export default function Page() {
850
+ return <main><AccountShell name="Ada" /></main>;
851
+ }
852
+ `,
853
+ "utf-8",
854
+ );
855
+ await writeFile(
856
+ path.join(boundaryRoot, "app", "account", "components", "AccountShell.tsx"),
857
+ `
858
+ import { AccountCard } from "./AccountCard.client";
859
+
860
+ export function AccountShell({ name }) {
861
+ return <AccountCard name={name} />;
862
+ }
863
+ `,
864
+ "utf-8",
865
+ );
866
+ await writeFile(
867
+ path.join(boundaryRoot, "app", "account", "components", "AccountCard.client.tsx"),
868
+ `
869
+ import React from "react";
870
+ export function AccountCard({ name }) {
871
+ return React.createElement("button", null, name);
872
+ }
873
+ `,
874
+ "utf-8",
875
+ );
876
+
877
+ const boundaryResult = await runBuildInSubprocess(boundaryRoot, "client-boundary-generated-transitive");
878
+
879
+ if (!boundaryResult.success) {
880
+ console.error("[build.test generated boundary] errors:", boundaryResult.errors);
881
+ }
882
+ expect(boundaryResult.success).toBe(true);
883
+ expect(boundaryResult.manifest?.boundaries?.["account--0"]).toMatchObject({
884
+ route: "account",
885
+ module: "app/account/components/AccountCard.client.tsx",
886
+ exportName: "AccountCard",
887
+ hydrate: "visible",
888
+ });
889
+ expect(boundaryResult.manifest?.boundaries?.["account--0"]?.js).toBe(
890
+ "/.mandu/client/account--0.boundary.js",
891
+ );
892
+ expect(boundaryResult.manifest?.bundles?.account).toBeUndefined();
893
+ expect(await Bun.file(path.join(boundaryRoot, ".mandu", "client", "account--0.boundary.js")).exists()).toBe(true);
894
+ } finally {
895
+ await rm(boundaryRoot, { recursive: true, force: true });
896
+ }
897
+ });
898
+ });