vite-plugin-taro 0.6.2 → 0.6.5

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 (46) hide show
  1. package/README.en.md +8 -3
  2. package/README.md +8 -3
  3. package/dist/node/plugins/wx/dev/dev-host.d.ts +5 -4
  4. package/dist/node/plugins/wx/dev/dev-host.js +19 -43
  5. package/dist/node/plugins/wx/dev/plugins.d.ts +6 -15
  6. package/dist/node/plugins/wx/dev/plugins.js +16 -70
  7. package/dist/node/plugins/wx/dev/react-refresh.d.ts +9 -3
  8. package/dist/node/plugins/wx/dev/react-refresh.js +35 -7
  9. package/dist/node/plugins/wx/dev/wx-dev-options.d.ts +2 -3
  10. package/dist/node/plugins/wx/dev/wx-dev-options.js +6 -7
  11. package/dist/node/plugins/wx/plugins.js +5 -11
  12. package/dist/node/plugins/wx/resolve/resolver.js +4 -4
  13. package/dist/node/plugins/wx/resolve/{specialize-bootstrap.d.ts → specialize-app-capsule.d.ts} +2 -2
  14. package/dist/node/plugins/wx/resolve/{specialize-bootstrap.js → specialize-app-capsule.js} +2 -2
  15. package/dist/node/plugins/wx/styles/plugins.d.ts +141 -3
  16. package/dist/node/plugins/wx/styles/plugins.js +401 -89
  17. package/dist/node/utils/vite.d.ts +4 -14
  18. package/dist/node/utils/vite.js +7 -40
  19. package/dist/runtime/wx/amphibious/bootstrap.d.ts +0 -2
  20. package/dist/runtime/wx/amphibious/bootstrap.js +0 -2
  21. package/dist/runtime/wx/capsule/app.d.ts +2 -2
  22. package/dist/runtime/wx/capsule/app.js +2 -2
  23. package/dist/runtime/wx/dev/dev-runtime.js +55 -79
  24. package/package.json +4 -3
  25. package/src/node/plugins/wx/dev/dev-host.ts +22 -44
  26. package/src/node/plugins/wx/dev/plugins.ts +17 -73
  27. package/src/node/plugins/wx/dev/react-refresh.ts +36 -7
  28. package/src/node/plugins/wx/dev/wx-dev-options.ts +7 -10
  29. package/src/node/plugins/wx/plugins.ts +5 -11
  30. package/src/node/plugins/wx/resolve/resolver.ts +4 -4
  31. package/src/node/plugins/wx/resolve/{specialize-bootstrap.ts → specialize-app-capsule.ts} +2 -2
  32. package/src/node/plugins/wx/styles/plugins.ts +518 -93
  33. package/src/node/utils/vite.ts +13 -58
  34. package/src/runtime/wx/amphibious/bootstrap.ts +0 -5
  35. package/src/runtime/wx/capsule/app.ts +5 -2
  36. package/src/runtime/wx/dev/dev-runtime.ts +71 -120
  37. package/src/runtime/wx/wechat.d.ts +1 -2
  38. package/dist/node/plugins/wx/dev/create-style-capture.d.ts +0 -54
  39. package/dist/node/plugins/wx/dev/create-style-capture.js +0 -173
  40. package/dist/node/plugins/wx/styles/transform-wx-style.d.ts +0 -8
  41. package/dist/node/plugins/wx/styles/transform-wx-style.js +0 -9
  42. package/dist/node/plugins/wx/styles/utils.d.ts +0 -39
  43. package/dist/node/plugins/wx/styles/utils.js +0 -95
  44. package/src/node/plugins/wx/dev/create-style-capture.ts +0 -248
  45. package/src/node/plugins/wx/styles/transform-wx-style.ts +0 -11
  46. package/src/node/plugins/wx/styles/utils.ts +0 -119
@@ -1,7 +1,7 @@
1
1
  // biome-ignore assist/source/organizeImports: Taro must initialize before the App component.
2
2
  import { createReactApp, ReactDOM } from './taro-runtime.js';
3
3
  import React from 'react';
4
- import { appConfig } from '../amphibious/bootstrap.js';
5
4
  // @ts-expect-error: The wx build resolves this private App component.
6
5
  import AppComponent from '\0vpt:app-component';
7
- export default createReactApp(AppComponent, React, ReactDOM, appConfig);
6
+ const config = createReactApp(AppComponent, React, ReactDOM, __VPT_APP_CONFIG__);
7
+ export default config;
@@ -5,16 +5,13 @@
5
5
  // The `DevRuntime` base class is injected into the chunk by Rolldown's dev-mode
6
6
  // transform, so the WX host only extends it.
7
7
  //
8
- // Every Page explicitly passes the inert hmr/patches.js export here before importing its capsule. The runtime applies that
8
+ // Every Page explicitly passes the inert hmr/patches.js export here before native Page registration. The runtime applies that
9
9
  // cumulative suffix synchronously, reports its successful application frontier, and ignores sequences replayed by other Pages.
10
- /** Forwards a native lifecycle with its original Page receiver. */
11
- function forward(handler, receiver, args) {
10
+ const pageHmrStateKey = Symbol('vpt.pageHmrState');
11
+ /** Calls a native lifecycle with the same Page bound to `this` and the same arguments. */
12
+ function forward(handler, page, args) {
12
13
  if (typeof handler === 'function')
13
- handler.apply(receiver, args);
14
- }
15
- /** Narrows the untyped element returned across the Taro connection boundary. */
16
- function isTaroRoot(value) {
17
- return typeof value === 'object' && value !== null && 'ctx' in value;
14
+ handler.apply(page, args);
18
15
  }
19
16
  /** Shared no-op CSS contract because physical rebuilds replace styles wholesale. */
20
17
  const hotContextInternals = Object.freeze({
@@ -168,92 +165,76 @@ class WxDevRuntime extends DevRuntime {
168
165
  return;
169
166
  this.session = { ...info, appliedSeq: 0 };
170
167
  }
171
- /**
172
- * One-shot bridge to the application's Taro singleton. It cannot be imported into this
173
- * separately bundled global runtime without creating a second Taro identity. Undefined
174
- * only before the serve-only facade connection; route transactions share its lifetime.
175
- */
176
- taro;
177
- /** Connects HMR to the same Taro singleton used by the application module graph. */
178
- connectTaro(current, document, injectPageInstance) {
179
- if (this.taro) {
180
- return;
168
+ /** Tracks the mounted native Page and prepares its static config for HMR re-registration. */
169
+ injectPageHmr(config) {
170
+ const existingState = config[pageHmrStateKey];
171
+ if (existingState) {
172
+ const mountedPage = existingState.mountedPage;
173
+ /*
174
+ * The static config can outlive a native Page instance. Before its first ordinary onLoad, or after a real onUnload,
175
+ * there is no mounted Page or current view-model to carry into another registration. Leave the lifecycle gate
176
+ * unarmed and preserve the config's existing initial data so a future real onLoad still enters Taro normally.
177
+ */
178
+ if (!mountedPage) {
179
+ return config;
180
+ }
181
+ /*
182
+ * Arm the lifecycle wrappers on this exact static config before it is passed back to `Page(config)`. DevTools then
183
+ * triggers an unload/load/show sequence for that native re-registration: unload and load observe `true` and return
184
+ * before entering Taro, preserving the mounted React tree and its original Page connection; show consumes the
185
+ * one-shot gate by restoring `false`. Ordinary navigation never enters this branch, and every Page config owns an
186
+ * independent state object, so no route map, global phase, or Page identity comparison participates in the decision.
187
+ */
188
+ existingState.isReregistering = true;
189
+ /*
190
+ * `Page(config)` reads `config.data` as the initial native view-model for this registration. Supplying the mounted
191
+ * Page's latest data before that call prevents the temporary Page used for re-registration callbacks from starting
192
+ * empty. This is an O(1) reference assignment in vpt: it does not clone the recursive data tree, call `setData`, move
193
+ * React state, or rebind Taro. The ordinary Taro lifecycle remains suppressed until re-registration onShow, so its
194
+ * React tree and output connection stay attached to `mountedPage`; every later registration reads its latest data.
195
+ */
196
+ config.data = mountedPage.data;
197
+ return config;
181
198
  }
182
- this.taro = {
183
- current,
184
- document,
185
- injectPageInstance,
186
- pageReplacements: new Map()
187
- };
188
- }
189
- /** Injects snapshot-preserving behavior into one route-specific Taro Page configuration. */
190
- injectPageHmr(config, route) {
191
199
  const originalOnUnload = config.onUnload;
192
200
  const originalOnLoad = config.onLoad;
193
201
  const originalOnShow = config.onShow;
194
- const runtime = this;
202
+ const state = {
203
+ isReregistering: false,
204
+ mountedPage: undefined
205
+ };
206
+ /*
207
+ * Attach the one mutable HMR state object to this exact static config. The lifecycle wrappers below close over the same
208
+ * object, while a later `injectPageHmr(config)` call finds it through the symbol and knows wrapping is already complete.
209
+ * A symbol cannot collide with WeChat or Taro's string-named Page options, and config-local ownership avoids route maps,
210
+ * a runtime-wide WeakMap, or state shared by two Page configs. The state becomes unreachable together with the config.
211
+ */
212
+ config[pageHmrStateKey] = state;
195
213
  config.onUnload = function (...args) {
196
- const taro = runtime.requireTaro();
197
- if (taro.pageReplacements.has(route)) {
198
- taro.pageReplacements.set(route, {
199
- $taroPath: this.$taroPath,
200
- $taroParams: this.$taroParams,
201
- // WeChat owns this serializable view-model. Keeping its reference is O(1),
202
- // unlike cloning the complete recursive projection before every edit.
203
- data: this.data
204
- });
214
+ if (state.isReregistering) {
205
215
  return;
206
216
  }
207
217
  forward(originalOnUnload, this, args);
218
+ state.mountedPage = undefined;
208
219
  };
209
220
  config.onLoad = function (...args) {
210
- const taro = runtime.requireTaro();
211
- const snapshot = taro.pageReplacements.get(route);
212
- if (snapshot) {
213
- // Replace the transaction before native work so exceptions cannot retain the
214
- // large data snapshot while the route waits for its synthetic onShow.
215
- taro.pageReplacements.set(route, null);
216
- // Snapshot paint is the first bridge operation and removes the empty-page gap.
217
- this.setData(snapshot.data);
218
- this.$taroPath = snapshot.$taroPath;
219
- this.$taroParams = snapshot.$taroParams;
220
- runtime.bindPage(this, snapshot.$taroPath);
221
+ if (state.isReregistering) {
221
222
  return;
222
223
  }
223
224
  forward(originalOnLoad, this, args);
225
+ state.mountedPage = this;
224
226
  };
225
227
  config.onShow = function (...args) {
226
- if (runtime.requireTaro().pageReplacements.delete(route)) {
227
- // Synthetic shows must not repeat requests or reset application state.
228
+ if (state.isReregistering) {
229
+ state.isReregistering = false;
228
230
  return;
229
231
  }
230
232
  forward(originalOnShow, this, args);
231
233
  };
234
+ return config;
232
235
  }
233
- /** Returns the Taro connection or fails at the first incorrectly ordered use. */
234
- requireTaro() {
235
- if (!this.taro)
236
- throw new Error('[vpt] WX HMR used before the Taro runtime was connected');
237
- return this.taro;
238
- }
239
- /** Returns a retained Taro root after normal Page mount has created it. */
240
- findRoot(path) {
241
- const root = this.requireTaro().document.getElementById(path);
242
- return isTaroRoot(root) ? root : undefined;
243
- }
244
- /** Rebinds a retained Taro tree to one replacement native Page without repainting. */
245
- bindPage(instance, path) {
246
- const taro = this.requireTaro();
247
- taro.injectPageInstance(instance, path);
248
- taro.current.page = instance;
249
- const pageElement = this.findRoot(path);
250
- if (!pageElement) {
251
- throw new Error(`[vpt] retained Taro page not found: ${path}`);
252
- }
253
- pageElement.ctx = instance;
254
- }
255
- /** Applies one Page-delivered payload and arms its route for native replacement. */
256
- applyPatches(payload, route) {
236
+ /** Applies one Page-delivered payload before its native shell registers the static route configuration. */
237
+ applyPatches(payload) {
257
238
  // The initial physical dependency exports undefined until the host has a patch range.
258
239
  if (!payload)
259
240
  return;
@@ -262,11 +243,6 @@ class WxDevRuntime extends DevRuntime {
262
243
  console.warn('[vpt] patches for a stale build');
263
244
  return;
264
245
  }
265
- // A replayed payload still causes DevTools to replace this physical Page. Arm the
266
- // route independently of whether this App heap already applied its patch sequence.
267
- if (route) {
268
- this.requireTaro().pageReplacements.set(route, null);
269
- }
270
246
  // Apply synchronously: the page's imports below the require resolve against the
271
247
  // freshly registered modules, so the re-executed Page evaluates with the new code.
272
248
  if (this.applyPatchBatch(session, payload.patches)) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vite-plugin-taro",
3
- "version": "0.6.2",
3
+ "version": "0.6.5",
4
4
  "author": "sep2",
5
5
  "description": "Vite 8 plugin for building one React/Taro codebase for WeChat Mini Program and H5 targets.",
6
6
  "type": "module",
@@ -57,6 +57,7 @@
57
57
  "@oxc-project/types": "0.143.0",
58
58
  "@rolldown/plugin-babel": "^0.2.3",
59
59
  "@tailwindcss-mangle/engine": "0.2.0",
60
+ "@tailwindcss/oxide": "4.3.3",
60
61
  "@tarojs/components": "4.2.0",
61
62
  "@tarojs/helper": "4.2.0",
62
63
  "@tarojs/plugin-platform-h5": "4.2.0",
@@ -75,8 +76,8 @@
75
76
  "rxjs": "^7.8.2",
76
77
  "tailwindcss": "^4.3.3",
77
78
  "weapp-tailwindcss": "^5.2.11",
78
- "@tarojs/plugin-framework-react": "npm:vite-plugin-taro-plugin-framework-react@0.6.2",
79
- "@tarojs/react": "npm:vite-plugin-taro-react@0.6.2"
79
+ "@tarojs/plugin-framework-react": "npm:vite-plugin-taro-plugin-framework-react@0.6.5",
80
+ "@tarojs/react": "npm:vite-plugin-taro-react@0.6.5"
80
81
  },
81
82
  "peerDependencies": {
82
83
  "react": "^19.0.0",
@@ -1,4 +1,3 @@
1
- import { readFile } from 'node:fs/promises'
2
1
  import type { ServerResponse } from 'node:http'
3
2
  import path from 'node:path'
4
3
  import colors from 'picocolors'
@@ -6,10 +5,11 @@ import { type DevEngine, type DevOptions, dev } from 'rolldown/experimental'
6
5
  import { asyncScheduler } from 'rxjs'
7
6
  import type { Connect, ViteDevServer } from 'vite'
8
7
  import type { VptOptions } from '../../../../options.ts'
8
+ import type { WxStylePlugin } from '../styles/plugins.ts'
9
9
  import { createHmrResultsStream } from './create-hmr-results-stream.ts'
10
- import { createStyleCapture, type StyleCaptureAction } from './create-style-capture.ts'
11
10
  import {
12
11
  developmentAppWxssFileName,
12
+ globalWxssFileName,
13
13
  type HmrInfo,
14
14
  hmrControlPath,
15
15
  hmrInfoFileName,
@@ -36,7 +36,6 @@ type DevOutputResult = Parameters<NonNullable<DevOptions['onOutput']>>[0]
36
36
  type OutputAction = Readonly<{ kind: 'output'; result: DevOutputResult }>
37
37
 
38
38
  type HostAction =
39
- | StyleCaptureAction
40
39
  | Readonly<{ kind: 'publish'; result: HmrUpdates }>
41
40
  | Readonly<{ kind: 'error'; error: Error }>
42
41
  | Readonly<{ kind: 'reports'; reports: readonly RuntimeReport[] }>
@@ -52,17 +51,17 @@ const hmrSettleMilliseconds = 16
52
51
  * engine writes directly to the Mini Program output directory instead of serving browser
53
52
  * HMR over HTTP.
54
53
  *
55
- * `applicationEntryIds` is the resolver's immutable cascade policy, not a second graph: it selects the App capsule followed
56
- * by configured Page capsules from Rolldown's larger entry set. Rolldown remains the authority for every live import edge.
54
+ * The shared style plugin carries the resolver's immutable App/Page cascade policy while Rolldown remains authoritative for
55
+ * every live import edge.
57
56
  */
58
57
  export async function createWxDevHost({
59
58
  server,
60
59
  options,
61
- applicationEntryIds
60
+ styles
62
61
  }: {
63
62
  server: ViteDevServer
64
63
  options: VptOptions
65
- applicationEntryIds: readonly string[]
64
+ styles: WxStylePlugin
66
65
  }): Promise<WxDevHost> {
67
66
  const bundledDev = getBundledDev(server)
68
67
 
@@ -71,23 +70,12 @@ export async function createWxDevHost({
71
70
  logWxError(server.config.logger, `wx HMR ${action.kind} failed`, error)
72
71
  )
73
72
 
74
- const styleCapture = createStyleCapture({
75
- applicationEntryIds: applicationEntryIds,
76
- outDir: server.config.build.outDir,
77
- // Capture hooks run only after engine.run, when the host action subscription and all reducer dependencies are ready.
78
- emit: (action) => hostActions.next(action),
79
- transformTailwindRoot: async (rootId, requestId) => {
80
- // The capture contains generated CSS, while the sidecar must re-run from raw Tailwind directives. Vite exposes no
81
- // raw source in its live module graph, so this read is the authoritative source generation rather than a read-back.
82
- return server.environments.client.pluginContainer.transform(await readFile(rootId, 'utf8'), requestId)
83
- }
84
- })
85
73
  const publisher = new PatchPublisher((content) =>
86
74
  writeHmrFile(server.config.build.outDir, hmrPatchesFileName, content)
87
75
  )
88
76
 
89
77
  // Option installation now configures only Rolldown. Build lifecycle results enter through the engine's output action below.
90
- installWxDevOptions({ bundledDev, server, options, hostPlugins: [styleCapture.plugin] })
78
+ installWxDevOptions({ bundledDev, server, options })
91
79
  const engine: DevEngine = await createEngine()
92
80
 
93
81
  const hmrResults = createHmrResultsStream(
@@ -158,12 +146,17 @@ export async function createWxDevHost({
158
146
  hmrResults.complete()
159
147
  runtimeReports.complete()
160
148
  await hostActions.waitForIdle()
161
- // Keep the action edge open until the final generation has admitted all capture and output callbacks.
149
+ // Keep the action edge open until the final generation has admitted every output callback.
162
150
  await engine.ensureCurrentBuildFinish()
163
151
  await hostActions.complete()
164
152
  }
165
153
  }
166
154
 
155
+ /** Atomically materializes the style plugin's prepared global artifact. */
156
+ async function writeGlobalStyle(wxss: string): Promise<void> {
157
+ await writeHmrFile(server.config.build.outDir, globalWxssFileName, wxss)
158
+ }
159
+
167
160
  /** Rotates the build identity and materializes the App metadata for it. */
168
161
  async function rotateBuildSession(): Promise<void> {
169
162
  const port = boundPort(server)
@@ -207,14 +200,6 @@ export async function createWxDevHost({
207
200
  /** Reduces one merged source action through the existing authoritative host state. */
208
201
  function applyHostAction(action: HostAction): void | Promise<void> {
209
202
  switch (action.kind) {
210
- case 'capture-graph':
211
- // The buildStart reader is a live capability; replacing it only here makes the reducer own build rebinding.
212
- styleCapture.captureGraph(action.getModuleInfo)
213
- return
214
- case 'capture-style':
215
- // A failed upstream transform emits no action, intentionally retaining the last valid processed CSS generation.
216
- styleCapture.captureStyle(action.id, action.style)
217
- return
218
203
  case 'publish':
219
204
  return publishUpdates(action.result)
220
205
  case 'error':
@@ -228,21 +213,15 @@ export async function createWxDevHost({
228
213
  logWxError(server.config.logger, 'wx dev build failed', action.result)
229
214
  return
230
215
  }
231
- return reconcileCompleteOutput(action.result.output)
216
+ return publishCompleteStyles()
232
217
  case 'listening':
233
218
  return rotateBuildSession()
234
219
  }
235
220
  }
236
221
 
237
- /**
238
- * Reconciles graph-complete styles before rotating the App-visible build identity.
239
- *
240
- * DevEngine has already written its compiler asset when onOutput fires, but bundled development may have omitted CSS Modules
241
- * from that asset. Awaiting reconciliation inside the serialized reducer guarantees the subsequent app.wxss rotation—the
242
- * event that refreshes DevTools—can only expose a generation whose global WXSS already represents the complete App/Page graph.
243
- */
244
- async function reconcileCompleteOutput(output: Exclude<DevOutputResult, Error>['output']): Promise<void> {
245
- await styleCapture.reconcileComplete(output)
222
+ /** Publishes graph-complete styles before rotating the App-visible build identity. */
223
+ async function publishCompleteStyles(): Promise<void> {
224
+ await styles.finalizeUpdate([], writeGlobalStyle)
246
225
  await rotateBuildSession()
247
226
  }
248
227
 
@@ -329,18 +308,17 @@ export async function createWxDevHost({
329
308
  return
330
309
  }
331
310
 
332
- // `onHmrUpdates` is the transaction boundary after every affected transform has updated graph and candidate state.
333
- // Every non-CSS edit may alter imports or Tailwind classes; rendering broadly and comparing finalized bytes avoids
334
- // source scanning while preventing unrelated JavaScript edits from notifying DevTools through an identical rename.
335
- await styleCapture.publishChanged(patches.flatMap((patch) => patch.changedIds))
311
+ // `onHmrUpdates` runs after every affected transform has updated captured CSS and the live import graph. The style
312
+ // boundary finalizes every factory before atomically publishing their matching WXSS.
313
+ const finalizedPatches = await styles.finalizeUpdate(patches, writeGlobalStyle)
336
314
 
337
315
  // Publish global.wxss before the matching JavaScript patch so DevTools observes a coherent HMR transaction.
338
316
  // The physical file must exist before Rolldown advances: once committed, later patches may be generated relative to
339
317
  // this batch even if DevTools has not observed its file event yet. PatchPublisher keeps the unapplied range cumulative,
340
318
  // so any later file generation still carries every factory needed to bridge the runtime's older application frontier.
341
- await publisher.produce(patches)
319
+ await publisher.produce(finalizedPatches)
342
320
 
343
- await commitPublishedBatch(patches)
321
+ await commitPublishedBatch(finalizedPatches)
344
322
  }
345
323
 
346
324
  /**
@@ -3,13 +3,12 @@ import type { VptOptions } from '../../../../options.ts'
3
3
  import { esTarget } from '../../../utils/constant.ts'
4
4
  import { memoize } from '../../../utils/memoize.ts'
5
5
  import { normalizeModuleId } from '../../../utils/modules.ts'
6
- import { appCapsulePath, pageCapsulePath, rolldownRuntimeId, taroRuntimePath } from '../module/module.ts'
6
+ import { pageShellPath, rolldownRuntimeId } from '../module/module.ts'
7
+ import type { WxStylePlugin } from '../styles/plugins.ts'
7
8
  import { createWxDevHost, type WxDevHost } from './dev-host.ts'
8
9
  import { developmentAppWxssFileName } from './hmr-files.ts'
9
10
  import { createWxReactRefreshTransforms } from './react-refresh.ts'
10
11
 
11
- const taroRuntimeId = '@tarojs/runtime'
12
-
13
12
  /** Selects the sole Vite environment that owns the physical Mini Program development project. */
14
13
  export function isWxClientEnvironment(environment: Readonly<{ name: string }>): boolean {
15
14
  return environment.name === 'client'
@@ -19,10 +18,10 @@ export function isWxClientEnvironment(environment: Readonly<{ name: string }>):
19
18
  * Adds the serve-only bundled-development plugin set for the wx target: the dev adapter,
20
19
  * Page HMR activation, and React Refresh adaptation transforms.
21
20
  *
22
- * The ordered application entries cross this configuration boundary unchanged so the host can compose global CSS without
23
- * reconstructing the resolver's App/Page ownership policy from unrelated Rolldown shell and transport entries.
21
+ * The shared style pipeline already owns the resolver's ordered App/Page cascade policy, so the host does not reconstruct it
22
+ * from unrelated Rolldown shell and transport entries.
24
23
  */
25
- export function createWxDevelopmentPlugin(options: VptOptions, applicationEntryIds: readonly string[]): PluginOption[] {
24
+ export function createWxDevelopmentPlugin(options: VptOptions, styles: WxStylePlugin): PluginOption[] {
26
25
  /*
27
26
  * Vite creates this plugin descriptor before a server or DevEngine exists, then invokes configureServer and closeBundle on
28
27
  * different lifecycle stacks. This mutable handle transfers the one client-owned host between those hooks: configureServer
@@ -32,9 +31,7 @@ export function createWxDevelopmentPlugin(options: VptOptions, applicationEntryI
32
31
  */
33
32
  let host: WxDevHost | null = null
34
33
  // Portable hook filters stay broad; these exact identities exclude similarly named user modules.
35
- const normalizedAppCapsulePath = normalizePath(appCapsulePath)
36
- const normalizedPageCapsulePath = normalizePath(pageCapsulePath)
37
- const normalizedTaroRuntimePath = normalizePath(taroRuntimePath)
34
+ const normalizedPageShellPath = normalizePath(pageShellPath)
38
35
 
39
36
  return [
40
37
  {
@@ -75,7 +72,7 @@ export function createWxDevelopmentPlugin(options: VptOptions, applicationEntryI
75
72
  host = await createWxDevHost({
76
73
  server: server,
77
74
  options: options,
78
- applicationEntryIds: applicationEntryIds
75
+ styles: styles
79
76
  })
80
77
  }
81
78
  },
@@ -116,38 +113,14 @@ export function createWxDevelopmentPlugin(options: VptOptions, applicationEntryI
116
113
  }
117
114
  },
118
115
  {
119
- name: 'vpt:wx-react-refresh-bootstrap',
120
- apply: 'serve',
121
- transform: {
122
- order: 'post',
123
- filter: { id: /\/runtime\/wx\/capsule\/app\.js(?:\?|$)/ },
124
- handler(code, id) {
125
- if (normalizeModuleId(id) !== normalizedAppCapsulePath) return
126
- return injectReactRefreshBootstrap(code)
127
- }
128
- }
129
- },
130
- {
131
- name: 'vpt:wx-page-hmr',
132
- apply: 'serve',
133
- transform: {
134
- order: 'post',
135
- filter: { id: /\/runtime\/wx\/capsule\/page\.js(?:\?|$)/ },
136
- handler(code, id) {
137
- if (normalizeModuleId(id) !== normalizedPageCapsulePath) return
138
- return injectPageHmr(code, getPageRoute(id))
139
- }
140
- }
141
- },
142
- {
143
- name: 'vpt:wx-taro-hmr',
116
+ name: 'vpt:wx-page-shell-hmr',
144
117
  apply: 'serve',
145
118
  transform: {
146
119
  order: 'post',
147
- filter: { id: /\/runtime\/wx\/capsule\/taro-runtime\.js(?:\?|$)/ },
120
+ filter: { id: /\/runtime\/wx\/native\/page\.js(?:\?|$)/ },
148
121
  handler(code, id) {
149
- if (normalizeModuleId(id) !== normalizedTaroRuntimePath) return
150
- return injectTaroConnection(code)
122
+ if (normalizeModuleId(id) !== normalizedPageShellPath) return
123
+ return injectPageShellHmr(code)
151
124
  }
152
125
  }
153
126
  },
@@ -174,48 +147,19 @@ export function removeDevelopmentAppWxss(bundle: Record<string, unknown>): void
174
147
  delete bundle[developmentAppWxssFileName]
175
148
  }
176
149
 
177
- /** Ensures the Refresh hook exists before React's renderer evaluates and injects itself. */
178
- export function injectReactRefreshBootstrap(code: string): { code: string; map: null } {
179
- return {
180
- code: `import ${JSON.stringify('/@react-refresh')};\n${code}`,
181
- map: null
182
- }
183
- }
184
-
185
- /** Connects the shared WX dev runtime to the application graph's Taro runtime instance. */
186
- export function injectTaroConnection(code: string): { code: string; map: null } {
187
- if (!/\bCurrent\b/.test(code) || !/\bdocument\b/.test(code) || !/\binjectPageInstance\b/.test(code)) {
188
- throw new Error('WX Taro runtime must expose Current, document, and injectPageInstance for HMR')
189
- }
190
-
191
- const taroImport = `import { Current as __vptCurrent, document as __vptDocument, injectPageInstance as __vptInjectPageInstance } from ${JSON.stringify(taroRuntimeId)};`
192
-
193
- return {
194
- code: `${code}\n${taroImport}\n__rolldown_runtime__.connectTaro(__vptCurrent, __vptDocument, __vptInjectPageInstance);`,
195
- map: null
196
- }
197
- }
198
-
199
- /** Activates development-only lifecycle handling for one plugin-owned Page capsule. */
200
- export function injectPageHmr(code: string, route: string): { code: string; map: null } {
201
- if (!/\bconst\s+config\s*=/.test(code) || !/\bexport\s+default\s+config\b/.test(code)) {
202
- throw new Error('WX Page capsule must declare and default-export config before HMR injection')
150
+ /** Injects the retained snapshot at the exact native Page registration edge. */
151
+ export function injectPageShellHmr(code: string): { code: string; map: null } {
152
+ const registration = 'Page(pageConfig)'
153
+ if (!code.includes(registration)) {
154
+ throw new Error('WX native Page shell must register pageConfig')
203
155
  }
204
156
 
205
157
  return {
206
- code: `${code}\n__rolldown_runtime__.injectPageHmr(config, ${JSON.stringify(route)});`,
158
+ code: code.replace(registration, 'Page(__rolldown_runtime__.injectPageHmr(pageConfig))'),
207
159
  map: null
208
160
  }
209
161
  }
210
162
 
211
- /** Reads the stable route carried by every specialized Page capsule ID. */
212
- function getPageRoute(id: string): string {
213
- const queryIndex = id.indexOf('?')
214
- const route = queryIndex < 0 ? null : new URLSearchParams(id.slice(queryIndex + 1)).get('route')
215
- if (!route) throw new Error(`WX Page capsule is missing its route: ${id}`)
216
- return route
217
- }
218
-
219
163
  /*
220
164
  * memoize owns a mutable one-entry-by-input cache. The assembled runtime source is byte-identical across complete generations
221
165
  * because both the Rolldown base and injected implementation are immutable for the server lifetime. Reusing its lowered result
@@ -2,7 +2,9 @@ import { isReferenceIdentifier, type WalkerEnter } from 'oxc-walker'
2
2
  import type { RolldownMagicString } from 'rolldown'
3
3
  import type { Plugin } from 'vite'
4
4
  import { memoize } from '../../../utils/memoize.ts'
5
+ import { normalizeModuleId } from '../../../utils/modules.ts'
5
6
  import { transformWithOxcWalker } from '../../../utils/oxc-transform.ts'
7
+ import { reactReconcilerRoot } from '../module/module.ts'
6
8
 
7
9
  /** The React DevTools hook protocol name; free references must target `global` in wx. */
8
10
  const reactDevtoolsHookProtocol = '__REACT_DEVTOOLS_GLOBAL_HOOK__'
@@ -14,7 +16,7 @@ const reactDevtoolsHookProtocol = '__REACT_DEVTOOLS_GLOBAL_HOOK__'
14
16
  * - `__getReactRefreshIgnoredExports` is an optional extension point read while validating a refresh boundary.
15
17
  * Leaving that read on the nonexistent `window` crashes every update validation pass.
16
18
  *
17
- * Keeping this list explicit prevents the adapter from rewriting unrelated browser accesses if the vendored runtime
19
+ * Keeping this list explicit prevents the adapter from rewriting unrelated browser accesses if the refresh runtime
18
20
  * gains new code. Any future React Refresh protocol addition therefore requires a deliberate compatibility decision.
19
21
  */
20
22
  const refreshRuntimeWindowGlobals = ['__registerBeforePerformReactRefresh', '__getReactRefreshIgnoredExports'] as const
@@ -24,8 +26,9 @@ const refreshRuntimeWindowGlobals = ['__registerBeforePerformReactRefresh', '__g
24
26
  *
25
27
  * @vitejs/plugin-react's generated refresh code assumes the web HTML preamble and a browser
26
28
  * global scope; wx has neither. Each transform adapts one piece of that contract:
27
- * - the refresh runtime module (id-filtered): the vendored runtime reads and assigns
29
+ * - the refresh runtime module (id-filtered): the runtime reads and assigns
28
30
  * `window` protocol globals (rewritten to `global`) and must inject itself at evaluation;
31
+ * - React Reconciler: its renderer injection statically depends on the refresh runtime, fixing cold-start order;
29
32
  * - react-family modules (filtered on free references): the DevTools hook is read as a free
30
33
  * variable, which the WeChat runtime scope never resolves against `global` — every free
31
34
  * reference becomes an explicit member access;
@@ -33,8 +36,8 @@ const refreshRuntimeWindowGlobals = ['__registerBeforePerformReactRefresh', '__g
33
36
  * needed because the transform generates local wrappers over the imported refresh
34
37
  * runtime, so the guard that checks for the global is removed.
35
38
  *
36
- * Each transform's filter is its routing: the three domains are disjoint, so a module is
37
- * transformed by at most one of them, and modules outside all three never reach a handler.
39
+ * Filters route every adaptation directly. The Reconciler intentionally receives the renderer dependency first and the
40
+ * global-hook rewrite second; modules outside these explicit domains never reach a handler.
38
41
  */
39
42
  export function createWxReactRefreshTransforms(): Plugin[] {
40
43
  return [
@@ -43,13 +46,26 @@ export function createWxReactRefreshTransforms(): Plugin[] {
43
46
  apply: 'serve',
44
47
  transform: {
45
48
  order: 'post',
46
- // The vendored refresh runtime module; id-filtered, so no code scan.
49
+ // The refresh runtime module is id-filtered, so no code scan is needed.
47
50
  filter: { id: /^\/@react-refresh(?:\?|$)/ },
48
51
  handler(code, id) {
49
52
  return fixRefreshRuntime({ code, id })
50
53
  }
51
54
  }
52
55
  },
56
+ {
57
+ name: 'vpt:wx-react-refresh-renderer-dependency',
58
+ apply: 'serve',
59
+ transform: {
60
+ order: 'post',
61
+ filter: { id: /\/react-reconciler\/cjs\/react-reconciler\.development\.js(?:\?|$)/ },
62
+ handler(code, id) {
63
+ const rendererId = `${reactReconcilerRoot}/cjs/react-reconciler.development.js`
64
+ if (normalizeModuleId(id) !== rendererId) return
65
+ return injectReactRefreshRendererDependency(code)
66
+ }
67
+ }
68
+ },
53
69
  {
54
70
  name: 'vpt:wx-react-devtools-hook',
55
71
  apply: 'serve',
@@ -92,7 +108,8 @@ export function createWxReactRefreshTransforms(): Plugin[] {
92
108
  * The protocol name is unique, but only reference identifiers are rewritten. Declaration
93
109
  * keys and explicit members such as `global.__REACT_DEVTOOLS_GLOBAL_HOOK__` must remain
94
110
  * untouched; rewriting those would either produce invalid syntax or double-prefix the hook.
95
- * The eagerly evaluated refresh runtime creates the hook on `global` before the renderer loads.
111
+ * The Reconciler's injected static dependency orders hook injection before renderer initialization independently of Rolldown's
112
+ * final chunking decision.
96
113
  */
97
114
  function createReactDevtoolsHookVisitor(editor: RolldownMagicString): WalkerEnter {
98
115
  return function enter(node, parent) {
@@ -146,7 +163,7 @@ function createRefreshRuntimeVisitor(editor: RolldownMagicString): WalkerEnter {
146
163
  refreshRuntimeWindowGlobals.some((globalName) => globalName === node.property.name)
147
164
  ) {
148
165
  // `global` is the shared wx App heap used by the dev runtime and hook injection. Only
149
- // replacing the object range preserves the vendored runtime byte-for-byte otherwise
166
+ // replacing the object range preserves the upstream runtime byte-for-byte otherwise
150
167
  // and prevents unrelated `window` expressions from being silently adapted.
151
168
  editor.overwrite(node.object.start, node.object.end, 'global')
152
169
  }
@@ -187,6 +204,18 @@ function createRefreshPreambleGuardVisitor(editor: RolldownMagicString): WalkerE
187
204
  }
188
205
  }
189
206
 
207
+ /** Makes renderer hook injection statically depend on the refresh runtime. */
208
+ export function injectReactRefreshRendererDependency(code: string): { code: string; map: null } {
209
+ if (!/\bhook\.inject\(internals\)/.test(code)) {
210
+ throw new Error('React Reconciler must inject its renderer into the DevTools hook')
211
+ }
212
+
213
+ return {
214
+ code: `import '/@react-refresh'\n${code}`,
215
+ map: null
216
+ }
217
+ }
218
+
190
219
  export function transformRefreshRuntime({ code, id }: { code: string; id: string }) {
191
220
  return transformWithOxcWalker({
192
221
  code,