weapp-vite 7.3.0 → 7.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/README.md +154 -6
  2. package/bin/bootstrap.js +14 -1
  3. package/dist/adapters-CcHrsYaj.mjs +1 -0
  4. package/dist/analyze-ZJUvEdaY.mjs +248 -0
  5. package/dist/auto-import-components/resolvers.mjs +1 -2
  6. package/dist/auto-import-presets/wevu-router.mjs +1 -2
  7. package/dist/auto-import-presets/wevu.mjs +1 -2
  8. package/dist/auto-routes.mjs +2 -1
  9. package/dist/budget-BD7VqLCl.d.mts +178 -0
  10. package/dist/chunkStrategy-DRA5WpB-.mjs +1436 -0
  11. package/dist/cli-acceptance.d.mts +1 -0
  12. package/dist/cli-acceptance.mjs +21 -0
  13. package/dist/cli.mjs +1918 -2089
  14. package/dist/compatibility.mjs +1 -2
  15. package/dist/{config-1J4rToMR.d.mts → config-V0L-IAJf.d.mts} +419 -39
  16. package/dist/config.d.mts +2 -2
  17. package/dist/config.mjs +1 -1
  18. package/dist/constants-DEZdcsMn.mjs +85 -0
  19. package/dist/{createContext-cqr9Y4EV.mjs → createCompilerContextInstance-DJH_P_nZ.mjs} +17602 -15886
  20. package/dist/createContext-BqYzHhY9.mjs +12 -0
  21. package/dist/dashboard/analyze.d.mts +48 -0
  22. package/dist/dashboard/analyze.mjs +1 -0
  23. package/dist/dashboard/vite.d.mts +9 -0
  24. package/dist/dashboard/vite.mjs +44 -0
  25. package/dist/dashboard-DvqF3Key.mjs +1842 -0
  26. package/dist/dashboard.d.mts +3 -0
  27. package/dist/dashboard.mjs +1 -0
  28. package/dist/dashboardViteBridge-Dy3nAD4m.mjs +299 -0
  29. package/dist/dev-fR5GiJRO.mjs +63 -0
  30. package/dist/devProvider-BGBkw28J.mjs +1050 -0
  31. package/dist/docs/README.md +154 -6
  32. package/dist/docs/ai-workflows.md +4 -0
  33. package/dist/docs/doctor.md +38 -0
  34. package/dist/docs/getting-started.md +52 -1
  35. package/dist/docs/index.md +6 -2
  36. package/dist/docs/mcp.md +94 -1
  37. package/dist/docs/testing.md +29 -2
  38. package/dist/docs/troubleshooting.md +8 -0
  39. package/dist/docs/uni-app-component-libraries.md +8 -7
  40. package/dist/docs/upload.md +226 -0
  41. package/dist/docs/vite-plugin.md +171 -0
  42. package/dist/docs/vue-sfc.md +19 -0
  43. package/dist/docs/weapp-config.md +374 -2
  44. package/dist/docs/wevu-authoring.md +10 -0
  45. package/dist/doctor-worker.d.mts +1 -0
  46. package/dist/doctor-worker.mjs +59 -0
  47. package/dist/doctor.d.mts +144 -0
  48. package/dist/doctor.mjs +848 -0
  49. package/dist/eslint.mjs +1 -2
  50. package/dist/file-DRb4eWqw.mjs +1 -0
  51. package/dist/{file-CKB0Tn8Z.mjs → file-sC3jD7Fh.mjs} +16 -93
  52. package/dist/files-BqxFIPRp.mjs +45 -0
  53. package/dist/getInstance-DiGSzBNI.mjs +28 -0
  54. package/dist/getInstance-SiE6WZRh.mjs +1 -0
  55. package/dist/index-C9HjUX5c.d.mts +741 -0
  56. package/dist/index.d.mts +10 -8
  57. package/dist/index.mjs +3 -2
  58. package/dist/json.d.mts +1 -1
  59. package/dist/json.mjs +1 -2
  60. package/dist/lifecycle-BROTlwSL.mjs +320 -0
  61. package/dist/loadConfig-C3BQhz7F.mjs +59 -0
  62. package/dist/loadConfig-VGtBF4qm.mjs +1 -0
  63. package/dist/logger-DGn5iEVN.mjs +1 -0
  64. package/dist/{mcp-BG6TliEg.mjs → mcp-Cj8Maqo6.mjs} +16 -7
  65. package/dist/mcp-D3Yh24Cj.mjs +529 -0
  66. package/dist/mcp.d.mts +6 -3
  67. package/dist/mcp.mjs +1 -2
  68. package/dist/package-7swhyLmf.mjs +91 -0
  69. package/dist/path-doV773b7.mjs +103 -0
  70. package/dist/platform-CnkySBKz.mjs +175 -0
  71. package/dist/processCleanup-B6KA30Zc.mjs +77 -0
  72. package/dist/protocol-vg8HGJ4n.mjs +138 -0
  73. package/dist/{resolvers-icNxkpcy.mjs → resolvers-Dod-euqX.mjs} +4 -1
  74. package/dist/resolvers.mjs +1 -2
  75. package/dist/runtime.mjs +1 -2
  76. package/dist/session-PskhD-nZ.mjs +390 -0
  77. package/dist/test.d.mts +1 -0
  78. package/dist/test.mjs +201 -44
  79. package/dist/types.d.mts +2 -2
  80. package/dist/upload-D4msblBf.mjs +562 -0
  81. package/dist/upload-worker.d.mts +1 -0
  82. package/dist/upload-worker.mjs +161 -0
  83. package/dist/utils-CJSCgEj6.mjs +1094 -0
  84. package/dist/vite.d.mts +9 -0
  85. package/dist/vite.mjs +270 -0
  86. package/dist/volar.d.mts +2 -2
  87. package/dist/web-apis.mjs +1 -2
  88. package/package.json +85 -37
  89. package/dist/file-CvgkbGIx.mjs +0 -2
  90. package/dist/getInstance-CZ1s63zd.mjs +0 -2
  91. package/dist/logger-mt4mSTqV.mjs +0 -2
@@ -0,0 +1,1050 @@
1
+ import { a as parseSidecarModuleId, c as resolveRealpath, i as parseLogicalEntryId, l as withRealpathScope, n as createSidecarModuleId, o as parseSidecarSourceRequest, r as createSidecarSourceSpecifier, s as resolveVirtualModuleId } from "./protocol-vg8HGJ4n.mjs";
2
+ import { a as normalizeWatchPath, l as normalizeFsResolvedId, n as normalizePath, s as toPosixPath, t as isPathInside } from "./path-doV773b7.mjs";
3
+ import { a as getPlatformNpmDistDirName, h as resolveMiniPlatformWithDefault } from "./platform-CnkySBKz.mjs";
4
+ import process from "node:process";
5
+ import path from "pathe";
6
+ import { WEAPP_VITE_RUNTIME_VIRTUAL_ID, WEVU_AUTO_ROUTES_MODULE_ID as WEVU_AUTO_ROUTES_MODULE_ID$1, WEVU_AUTO_ROUTES_RESOLVED_MODULE_ID as WEVU_AUTO_ROUTES_RESOLVED_MODULE_ID$1, WEVU_AUTO_ROUTES_VIRTUAL_MODULE_ID as WEVU_AUTO_ROUTES_VIRTUAL_MODULE_ID$1 } from "@weapp-core/constants";
7
+ import picomatch from "picomatch";
8
+ import { readAndParseSfc } from "wevu/compiler";
9
+ import { createLogger, createServer, transformWithOxc } from "vite";
10
+ import { watch } from "chokidar";
11
+ import { getPackageInfoSync } from "local-pkg";
12
+ import { once } from "node:events";
13
+ //#region src/moduleGraph/traversal.ts
14
+ function normalizeSourceId(id) {
15
+ const normalized = normalizeFsResolvedId(id).split("?")[0];
16
+ try {
17
+ return normalizeFsResolvedId(resolveRealpath(normalized));
18
+ } catch {
19
+ return normalized;
20
+ }
21
+ }
22
+ /** 逻辑入口与源码按同一真实路径比较,避免 junction 或原生分隔符制造第二个输出归属。 */
23
+ function isLogicalEntrySource(id, importers = []) {
24
+ let normalizedSource;
25
+ for (const importer of importers) {
26
+ const logicalEntry = parseLogicalEntryId(importer);
27
+ if (!logicalEntry) continue;
28
+ normalizedSource ??= normalizeSourceId(id);
29
+ if (logicalEntry.sourceId === normalizedSource) return true;
30
+ }
31
+ return false;
32
+ }
33
+ function moduleIdMatchesFile(id, file) {
34
+ const sidecarSource = parseSidecarSourceRequest(id);
35
+ if (sidecarSource) return normalizeSourceId(sidecarSource.sourceId) === file;
36
+ const sidecar = parseSidecarModuleId(id);
37
+ if (sidecar) return normalizeSourceId(sidecar.sourceId) === file;
38
+ const logicalEntry = parseLogicalEntryId(id);
39
+ if (logicalEntry) return normalizeSourceId(logicalEntry.sourceId) === file;
40
+ return normalizeSourceId(id) === file;
41
+ }
42
+ /** 存在性查询首次命中即返回,不为布尔结果收集全部模块。 */
43
+ function hasBuildModule(context, file) {
44
+ return withRealpathScope(() => {
45
+ for (const id of context.getModuleIds?.() ?? []) if (moduleIdMatchesFile(id, file)) return true;
46
+ return false;
47
+ });
48
+ }
49
+ /** 优先查询当前文件索引;未命中时仍按完整协议与真实路径查找别名。 */
50
+ function hasDevModule(server, file) {
51
+ return withRealpathScope(() => {
52
+ if (server.moduleGraph.getModulesByFile(file)?.size) return true;
53
+ for (const [id] of server.moduleGraph.idToModuleMap ?? []) if (moduleIdMatchesFile(id, file)) return true;
54
+ return false;
55
+ });
56
+ }
57
+ function collectBuildStartIds(context, file) {
58
+ return withRealpathScope(() => {
59
+ const ids = /* @__PURE__ */ new Set();
60
+ if (typeof context.getModuleIds !== "function") return ids;
61
+ for (const id of context.getModuleIds()) if (moduleIdMatchesFile(id, file)) ids.add(id);
62
+ return ids;
63
+ });
64
+ }
65
+ function collectDevStartNodes(server, file) {
66
+ return withRealpathScope(() => {
67
+ const nodes = new Set(server.moduleGraph.getModulesByFile(file) ?? []);
68
+ for (const [id, node] of server.moduleGraph.idToModuleMap ?? []) if (moduleIdMatchesFile(id, file)) nodes.add(node);
69
+ return nodes;
70
+ });
71
+ }
72
+ //#endregion
73
+ //#region src/utils/regexp.ts
74
+ const CSS_LANGS_RE = /\.(wxss|css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/;
75
+ function isCSSRequest(request) {
76
+ return CSS_LANGS_RE.test(request);
77
+ }
78
+ function isRegexp(value) {
79
+ return Object.prototype.toString.call(value) === "[object RegExp]";
80
+ }
81
+ //#endregion
82
+ //#region src/runtime/autoRoutesPlugin/matcher.ts
83
+ const DEFAULT_AUTO_ROUTE_INCLUDE = ["pages/**"];
84
+ const GLOB_MAGIC_PATTERN = /[*?[\]{}()!]/;
85
+ const RELATIVE_PREFIX_PATTERN = /^\.?\//;
86
+ const LEADING_SLASH_PATTERN = /^\/+/;
87
+ function toArray(include) {
88
+ if (include == null) return [...DEFAULT_AUTO_ROUTE_INCLUDE];
89
+ return Array.isArray(include) ? [...include] : [include];
90
+ }
91
+ function normalizeRuleCandidate(candidate) {
92
+ return toPosixPath(candidate.replace(RELATIVE_PREFIX_PATTERN, "").replace(LEADING_SLASH_PATTERN, ""));
93
+ }
94
+ function createRule(pattern) {
95
+ if (pattern instanceof RegExp) return {
96
+ pattern,
97
+ match(candidate) {
98
+ pattern.lastIndex = 0;
99
+ return pattern.test(candidate);
100
+ }
101
+ };
102
+ return {
103
+ pattern,
104
+ match: picomatch(pattern, { dot: true })
105
+ };
106
+ }
107
+ function isDefaultAutoRouteInclude(include) {
108
+ return include.length === DEFAULT_AUTO_ROUTE_INCLUDE.length && include.every((pattern, index) => pattern === DEFAULT_AUTO_ROUTE_INCLUDE[index]);
109
+ }
110
+ function extractStaticPrefix(pattern) {
111
+ const normalized = normalizeRuleCandidate(pattern);
112
+ if (!normalized) return;
113
+ const segments = normalized.split("/");
114
+ const staticSegments = [];
115
+ for (const segment of segments) {
116
+ if (!segment || GLOB_MAGIC_PATTERN.test(segment)) break;
117
+ staticSegments.push(segment);
118
+ }
119
+ if (staticSegments.length === 0) return;
120
+ return staticSegments.join("/");
121
+ }
122
+ function createAutoRoutesMatcher(include, subPackageRoots = []) {
123
+ const normalizedInclude = toArray(include);
124
+ const rules = normalizedInclude.map(createRule);
125
+ const isDefault = isDefaultAutoRouteInclude(normalizedInclude);
126
+ const normalizedSubPackageRoots = [...subPackageRoots].filter(Boolean).map((root) => normalizeRuleCandidate(root)).filter(Boolean);
127
+ function matches(candidate) {
128
+ const normalizedCandidate = normalizeRuleCandidate(candidate);
129
+ if (!normalizedCandidate) return false;
130
+ if (isDefault) {
131
+ if (normalizedCandidate.startsWith("pages/")) return true;
132
+ return normalizedSubPackageRoots.some((root) => {
133
+ return normalizedCandidate.startsWith(`${root}/`);
134
+ });
135
+ }
136
+ return rules.some((rule) => rule.match(normalizedCandidate));
137
+ }
138
+ function getRoots(absoluteSrcRoot) {
139
+ if (isDefault) {
140
+ const roots = /* @__PURE__ */ new Set([path.join(absoluteSrcRoot, "pages")]);
141
+ for (const root of normalizedSubPackageRoots) roots.add(path.join(absoluteSrcRoot, root));
142
+ return Array.from(roots, (root) => normalizePath(root));
143
+ }
144
+ const roots = /* @__PURE__ */ new Set();
145
+ for (const rule of rules) {
146
+ if (rule.pattern instanceof RegExp) {
147
+ roots.add(absoluteSrcRoot);
148
+ continue;
149
+ }
150
+ const prefix = extractStaticPrefix(rule.pattern);
151
+ if (!prefix) {
152
+ roots.add(absoluteSrcRoot);
153
+ continue;
154
+ }
155
+ roots.add(path.resolve(absoluteSrcRoot, prefix));
156
+ }
157
+ if (roots.size === 0) roots.add(absoluteSrcRoot);
158
+ return Array.from(roots, (root) => normalizePath(root));
159
+ }
160
+ return {
161
+ include: normalizedInclude,
162
+ isDefault,
163
+ matches,
164
+ matchesRelativePath(relativePath) {
165
+ return matches(relativePath);
166
+ },
167
+ getSearchRoots(absoluteSrcRoot) {
168
+ return getRoots(absoluteSrcRoot);
169
+ },
170
+ getWatchRoots(absoluteSrcRoot) {
171
+ return getRoots(absoluteSrcRoot);
172
+ }
173
+ };
174
+ }
175
+ //#endregion
176
+ //#region src/autoRoutesConfig.ts
177
+ function resolveWeappAutoRoutesConfig(config) {
178
+ if (config == null || config === false) return {
179
+ enabled: false,
180
+ typedRouter: false,
181
+ include: [...DEFAULT_AUTO_ROUTE_INCLUDE],
182
+ persistentCache: false,
183
+ watch: false
184
+ };
185
+ const record = typeof config === "object" && config ? config : {};
186
+ return {
187
+ enabled: config === true || record.enabled !== false,
188
+ typedRouter: record.typedRouter !== false,
189
+ include: record.include == null ? [...DEFAULT_AUTO_ROUTE_INCLUDE] : Array.isArray(record.include) ? [...record.include] : [record.include],
190
+ ...record.extensions?.length ? { extensions: [...new Set(record.extensions.map((extension) => extension.replace(/^\./, "")))] } : {},
191
+ persistentCache: typeof record.persistentCache === "string" || record.persistentCache === true,
192
+ persistentCachePath: typeof record.persistentCache === "string" ? record.persistentCache : void 0,
193
+ watch: record.watch !== false
194
+ };
195
+ }
196
+ //#endregion
197
+ //#region src/runtime/autoRoutesPlugin/generatedPaths.ts
198
+ const AUTO_ROUTES_CACHE_FILE = ".weapp-vite/auto-routes.cache.json";
199
+ const TYPED_ROUTER_OUTPUT_FILE = ".weapp-vite/typed-router.d.ts";
200
+ const GENERATED_DIRECTORY_NAMES = /* @__PURE__ */ new Set([
201
+ ".cache",
202
+ ".rolldown-require",
203
+ ".rolldown-require-cache",
204
+ ".tmp",
205
+ ".weapp-vite",
206
+ ".wevu-config",
207
+ "__temp__",
208
+ "coverage",
209
+ "dist",
210
+ "miniprogram_npm",
211
+ "node_modules"
212
+ ]);
213
+ const GENERATED_FILE_NAMES = /* @__PURE__ */ new Set([path.basename(AUTO_ROUTES_CACHE_FILE), path.basename(TYPED_ROUTER_OUTPUT_FILE)]);
214
+ function stripQuery(candidate) {
215
+ return candidate.split("?")[0];
216
+ }
217
+ function resolveGeneratedCandidatePath(candidate, cwd) {
218
+ const pathWithoutQuery = stripQuery(candidate);
219
+ if (!pathWithoutQuery) return;
220
+ return normalizePath(path.isAbsolute(pathWithoutQuery) ? pathWithoutQuery : path.resolve(cwd, pathWithoutQuery));
221
+ }
222
+ function isAutoRoutesGeneratedDirectoryName(name) {
223
+ return GENERATED_DIRECTORY_NAMES.has(name);
224
+ }
225
+ function isAutoRoutesGeneratedFileName(fileName) {
226
+ return GENERATED_FILE_NAMES.has(fileName) || fileName.includes(".auto-routes.") || fileName.includes(".auto-routes-");
227
+ }
228
+ function isAutoRoutesGeneratedRelativePath(relativePath) {
229
+ const segments = toPosixPath(relativePath).split("/").filter(Boolean);
230
+ if (segments.some(isAutoRoutesGeneratedDirectoryName)) return true;
231
+ const fileName = segments[segments.length - 1];
232
+ return Boolean(fileName && isAutoRoutesGeneratedFileName(fileName));
233
+ }
234
+ function resolveAutoRoutesManagedOutputPaths(ctx) {
235
+ const configService = ctx.configService;
236
+ const outputPaths = /* @__PURE__ */ new Set();
237
+ if (!configService) return outputPaths;
238
+ const baseDir = typeof configService.configFilePath === "string" ? path.dirname(configService.configFilePath) : configService.cwd;
239
+ if (!baseDir) return outputPaths;
240
+ outputPaths.add(normalizePath(path.resolve(baseDir, TYPED_ROUTER_OUTPUT_FILE)));
241
+ outputPaths.add(normalizePath(path.resolve(baseDir, AUTO_ROUTES_CACHE_FILE)));
242
+ const autoRoutesConfig = resolveWeappAutoRoutesConfig(configService.weappViteConfig?.autoRoutes);
243
+ if (autoRoutesConfig.persistentCache) outputPaths.add(normalizePath(path.resolve(baseDir, autoRoutesConfig.persistentCachePath ?? AUTO_ROUTES_CACHE_FILE)));
244
+ return outputPaths;
245
+ }
246
+ function isAutoRoutesGeneratedPath(candidate, options) {
247
+ const absolutePath = resolveGeneratedCandidatePath(candidate, options.cwd);
248
+ if (!absolutePath) return false;
249
+ for (const outputPath of options.managedOutputPaths ?? []) if (absolutePath === normalizePath(outputPath)) return true;
250
+ const normalizedSrcRoot = normalizePath(options.absoluteSrcRoot);
251
+ const relativePath = toPosixPath(path.relative(normalizedSrcRoot, absolutePath));
252
+ if (!relativePath || relativePath.startsWith("..") || path.isAbsolute(relativePath)) return false;
253
+ return isAutoRoutesGeneratedRelativePath(relativePath);
254
+ }
255
+ //#endregion
256
+ //#region src/plugins/autoRoutes.shared.ts
257
+ const AUTO_ROUTES_ID = "weapp-vite/auto-routes";
258
+ const VIRTUAL_MODULE_ID = "virtual:weapp-vite-auto-routes";
259
+ const RESOLVED_VIRTUAL_ID = "\0weapp-vite:auto-routes";
260
+ /**
261
+ * 判断当前是否应按 watch 模式为 auto-routes 注册依赖文件。
262
+ */
263
+ function isAutoRoutesWatchMode(configService) {
264
+ return Boolean(configService?.isDev || configService?.inlineConfig?.build?.watch);
265
+ }
266
+ /**
267
+ * 合并 service 与 matcher 提供的监听目录,并去重保留顺序。
268
+ */
269
+ function collectAutoRoutesWatchDirs(watchDirectories, matcherWatchRoots) {
270
+ const watchDirs = /* @__PURE__ */ new Set();
271
+ for (const dir of watchDirectories) watchDirs.add(dir);
272
+ for (const dir of matcherWatchRoots) watchDirs.add(dir);
273
+ return [...watchDirs];
274
+ }
275
+ /**
276
+ * 过滤出真正需要交给 auto-routes watcher 处理的路由源文件。
277
+ * 已知声明依赖不受普通页面发现扩展名限制,其他文件仍沿用发现规则。
278
+ */
279
+ function isAutoRoutesWatchFile(filePath, allowedExtensions, isPagesRelatedPath, isPageDeclarationSource) {
280
+ if (isAutoRoutesGeneratedFileName(path.basename(filePath))) return false;
281
+ if (isPageDeclarationSource(filePath)) return true;
282
+ return allowedExtensions.has(path.extname(filePath)) && isPagesRelatedPath(filePath);
283
+ }
284
+ /**
285
+ * 判断是否满足 auto-routes sidecar watcher 的启动前置条件。
286
+ */
287
+ function shouldStartAutoRoutesWatcher(options) {
288
+ if (options.routeWatcherStarted) return false;
289
+ if (!options.isDev) return false;
290
+ if (!options.autoRoutesEnabled || !options.autoRoutesWatch || !options.serviceEnabled) return false;
291
+ return options.watchDirsLength > 0;
292
+ }
293
+ /**
294
+ * 生成 sidecar watcher map 使用的关闭句柄。
295
+ */
296
+ function createAutoRoutesSidecarWatcher(watcher) {
297
+ return { close: async () => {
298
+ await watcher.close();
299
+ } };
300
+ }
301
+ /**
302
+ * 向插件上下文注册 auto-routes 相关 watch 目标,忽略单个 addWatchFile 失败。
303
+ */
304
+ function addAutoRoutesWatchTargets(pluginCtx, targets) {
305
+ for (const file of targets.files) try {
306
+ pluginCtx.addWatchFile?.(normalizeWatchPath(file));
307
+ } catch {}
308
+ for (const dir of targets.directories) try {
309
+ pluginCtx.addWatchFile?.(normalizeWatchPath(dir));
310
+ } catch {}
311
+ }
312
+ function invalidateAutoRoutesVirtualModules(server, resolvedIds) {
313
+ if (!server) return;
314
+ const seen = /* @__PURE__ */ new Set();
315
+ const invalidateModuleWithImporters = (module) => {
316
+ if (seen.has(module)) return;
317
+ seen.add(module);
318
+ server.moduleGraph.invalidateModule(module);
319
+ for (const importer of module.importers) invalidateModuleWithImporters(importer);
320
+ };
321
+ for (const id of resolvedIds) {
322
+ const virtualModule = server.moduleGraph.getModuleById(id);
323
+ if (virtualModule) invalidateModuleWithImporters(virtualModule);
324
+ }
325
+ }
326
+ /**
327
+ * 统一解析 auto-routes 虚拟模块与 alias 入口的命中关系。
328
+ */
329
+ function resolveAutoRoutesVirtualId(id, aliasTargets) {
330
+ if (id === WEVU_AUTO_ROUTES_MODULE_ID$1 || id === WEVU_AUTO_ROUTES_VIRTUAL_MODULE_ID$1 || id === WEVU_AUTO_ROUTES_RESOLVED_MODULE_ID$1) return WEVU_AUTO_ROUTES_RESOLVED_MODULE_ID$1;
331
+ if (id === "weapp-vite/auto-routes" || id === "virtual:weapp-vite-auto-routes" || id === "\0weapp-vite:auto-routes") return RESOLVED_VIRTUAL_ID;
332
+ return aliasTargets?.has(id) ? RESOLVED_VIRTUAL_ID : null;
333
+ }
334
+ /**
335
+ * 将 create/delete 这类结构性变化映射为 auto-routes 的全量重扫语义。
336
+ */
337
+ function resolveAutoRoutesWatchChangeEvent(event) {
338
+ if (event === "create" || event === "delete") return "rename";
339
+ }
340
+ /**
341
+ * 判断某次热更新是否需要触发 auto-routes 虚拟模块失效。
342
+ */
343
+ function resolveAutoRoutesHotUpdateAction(command, options) {
344
+ if (command === "serve") return options.isRouteFile ? {
345
+ shouldHandle: true,
346
+ shouldUpdateRouteFile: true
347
+ } : {
348
+ shouldHandle: false,
349
+ shouldUpdateRouteFile: false
350
+ };
351
+ if (options.isRouteFile || options.isPagesRelatedPath) return {
352
+ shouldHandle: true,
353
+ shouldUpdateRouteFile: false
354
+ };
355
+ return {
356
+ shouldHandle: false,
357
+ shouldUpdateRouteFile: false
358
+ };
359
+ }
360
+ /**
361
+ * Web 路由表在创建 router 时完成快照,必须越过 SFC 自接受边界重新加载入口。
362
+ * 入口排在前面,避免依赖失效先将生成的入口降为仅更新时间戳的软失效。
363
+ */
364
+ function collectAutoRoutesReloadModules(modules) {
365
+ const pending = [...modules];
366
+ const visited = new Set(pending);
367
+ const reloadModules = /* @__PURE__ */ new Set();
368
+ for (const module of pending) {
369
+ if (module.importers.size === 0) reloadModules.add(module);
370
+ for (const importer of module.importers) if (!visited.has(importer)) {
371
+ visited.add(importer);
372
+ pending.push(importer);
373
+ }
374
+ }
375
+ for (const module of modules) reloadModules.add(module);
376
+ return [...reloadModules];
377
+ }
378
+ //#endregion
379
+ //#region src/runtime/npmPlugin/packageResolution.ts
380
+ /** 保留目录尾斜线,确保当前工程优先,并避免缺失包的目录回退把真实文件当作目录。 */
381
+ function packageSearchOptions(resolveFrom) {
382
+ return resolveFrom ? { paths: [`${path.resolve(resolveFrom).replace(/\/$/, "")}/`] } : void 0;
383
+ }
384
+ //#endregion
385
+ //#region src/runtime/npmPlugin/service/dependencies.ts
386
+ const DEFAULT_NPM_STRATEGY = "explicit";
387
+ function dedupeDependencies(dependencies) {
388
+ return [...new Set(dependencies)];
389
+ }
390
+ function matchDependencyName(patterns, dep) {
391
+ return patterns.some((pattern) => {
392
+ if (typeof pattern === "string") return pattern === dep;
393
+ pattern.lastIndex = 0;
394
+ return pattern.test(dep);
395
+ });
396
+ }
397
+ function createDependencyRecord(dependencies) {
398
+ if (dependencies.length === 0) return;
399
+ return Object.fromEntries(dependencies.map((dep) => [dep, "*"]));
400
+ }
401
+ function resolveNpmStrategy(ctx) {
402
+ return ctx.configService?.weappViteConfig?.npm?.strategy ?? DEFAULT_NPM_STRATEGY;
403
+ }
404
+ function resolveConfiguredDependencyPatterns(ctx) {
405
+ const npmConfig = ctx.configService?.weappViteConfig?.npm;
406
+ const patterns = [...npmConfig?.include ?? []];
407
+ if (ctx.configService?.pluginOnly) {
408
+ if (Array.isArray(npmConfig?.pluginPackage?.dependencies)) patterns.push(...npmConfig.pluginPackage.dependencies);
409
+ return patterns;
410
+ }
411
+ if (Array.isArray(npmConfig?.mainPackage?.dependencies)) patterns.push(...npmConfig.mainPackage.dependencies);
412
+ for (const config of Object.values(npmConfig?.subPackages ?? {})) if (Array.isArray(config?.dependencies)) patterns.push(...config.dependencies);
413
+ return patterns;
414
+ }
415
+ function resolveDeclaredDependencies(pkgJson) {
416
+ return dedupeDependencies([...Object.keys(pkgJson.dependencies ?? {}), ...Object.keys(pkgJson.devDependencies ?? {})]);
417
+ }
418
+ function isMiniprogramPackage(pkg) {
419
+ return Reflect.has(pkg, "miniprogram") && typeof pkg.miniprogram === "string";
420
+ }
421
+ function resolveMiniprogramCandidateDependenciesSync(allDependencies, cwd) {
422
+ return allDependencies.filter((dep) => {
423
+ let packageInfo = null;
424
+ try {
425
+ packageInfo = getPackageInfoSync(dep, packageSearchOptions(cwd));
426
+ } catch {
427
+ packageInfo = null;
428
+ }
429
+ return !!packageInfo && isMiniprogramPackage(packageInfo.packageJson);
430
+ });
431
+ }
432
+ function resolveMainPackageDependencyPatterns(ctx) {
433
+ return ctx.configService?.weappViteConfig?.npm?.mainPackage?.dependencies;
434
+ }
435
+ function resolvePluginPackageDependencyPatterns(ctx) {
436
+ return ctx.configService?.weappViteConfig?.npm?.pluginPackage?.dependencies;
437
+ }
438
+ function resolveTargetDependencies(allDependencies, patterns) {
439
+ if (patterns === false) return [];
440
+ if (!Array.isArray(patterns)) return allDependencies;
441
+ const selected = /* @__PURE__ */ new Set();
442
+ for (const dep of allDependencies) if (matchDependencyName(patterns, dep)) selected.add(dep);
443
+ for (const pattern of patterns) if (typeof pattern === "string") selected.add(pattern);
444
+ return [...selected];
445
+ }
446
+ function resolveNpmBuildCandidateDependenciesSync(ctx, pkgJson, resolveFrom = ctx.configService?.cwd) {
447
+ if (resolveNpmStrategy(ctx) === "legacy") return Object.keys(pkgJson.dependencies ?? {});
448
+ const declaredDependencies = resolveDeclaredDependencies(pkgJson);
449
+ const explicitlyIncludedDependencies = resolveTargetDependencies(declaredDependencies, resolveConfiguredDependencyPatterns(ctx));
450
+ return dedupeDependencies([...resolveMiniprogramCandidateDependenciesSync(declaredDependencies, resolveFrom), ...explicitlyIncludedDependencies]);
451
+ }
452
+ function resolveNpmBuildCandidateDependencyRecordSync(ctx, pkgJson) {
453
+ if (!pkgJson) return;
454
+ return createDependencyRecord(resolveNpmBuildCandidateDependenciesSync(ctx, pkgJson));
455
+ }
456
+ function hasLocalSubPackageNpmConfig(ctx) {
457
+ const npmSubPackages = ctx.configService?.weappViteConfig?.npm?.subPackages;
458
+ if (npmSubPackages && Object.values(npmSubPackages).some((config) => Array.isArray(config?.dependencies) && config.dependencies.length > 0)) return true;
459
+ return false;
460
+ }
461
+ function resolveNpmDistDirName(configService) {
462
+ return getPlatformNpmDistDirName(resolveMiniPlatformWithDefault(configService?.platform), { alipayNpmMode: configService?.weappViteConfig?.npm?.alipayNpmMode });
463
+ }
464
+ function resolveMainBuildDependencyPatterns(ctx) {
465
+ return ctx.configService?.pluginOnly ? resolvePluginPackageDependencyPatterns(ctx) : resolveMainPackageDependencyPatterns(ctx);
466
+ }
467
+ function dedupeNpmDependencies(dependencies) {
468
+ return dedupeDependencies(dependencies);
469
+ }
470
+ function resolveConfiguredNpmDependencyPatterns(ctx) {
471
+ return resolveConfiguredDependencyPatterns(ctx);
472
+ }
473
+ function resolveDeclaredNpmDependencies(pkgJson) {
474
+ return resolveDeclaredDependencies(pkgJson);
475
+ }
476
+ function resolveNpmStrategyMode(ctx) {
477
+ return resolveNpmStrategy(ctx);
478
+ }
479
+ //#endregion
480
+ //#region src/runtime/watch/options.ts
481
+ /**
482
+ * 解析主 watcher 与 sidecar watcher 共享的轮询配置。
483
+ */
484
+ function resolvePollingWatchOptions(configService) {
485
+ const buildWatch = configService.inlineConfig?.build?.watch;
486
+ const chokidar = buildWatch && typeof buildWatch === "object" && "chokidar" in buildWatch ? buildWatch.chokidar : void 0;
487
+ const serverWatch = configService.inlineConfig?.server?.watch;
488
+ const envUsePolling = process.env.CHOKIDAR_USEPOLLING;
489
+ const envInterval = process.env.CHOKIDAR_INTERVAL;
490
+ const envBinaryInterval = process.env.CHOKIDAR_BINARY_INTERVAL;
491
+ const usePollingCandidate = chokidar?.usePolling ?? serverWatch?.usePolling ?? (envUsePolling === "1" || envUsePolling === "true" ? true : envUsePolling === "0" || envUsePolling === "false" ? false : void 0);
492
+ const intervalCandidate = chokidar?.interval ?? serverWatch?.interval ?? (envInterval ? Number(envInterval) : void 0);
493
+ const binaryIntervalCandidate = chokidar?.binaryInterval ?? serverWatch?.binaryInterval ?? (envBinaryInterval ? Number(envBinaryInterval) : void 0);
494
+ return {
495
+ usePolling: typeof usePollingCandidate === "boolean" ? usePollingCandidate : void 0,
496
+ interval: typeof intervalCandidate === "number" && Number.isFinite(intervalCandidate) ? intervalCandidate : void 0,
497
+ binaryInterval: typeof binaryIntervalCandidate === "number" && Number.isFinite(binaryIntervalCandidate) ? binaryIntervalCandidate : void 0
498
+ };
499
+ }
500
+ function createSidecarWatchOptions(configService, input) {
501
+ const polling = resolvePollingWatchOptions(configService);
502
+ return {
503
+ ...input,
504
+ ...polling.usePolling !== void 0 ? { usePolling: polling.usePolling } : {},
505
+ ...typeof polling.interval === "number" ? { interval: polling.interval } : {},
506
+ ...typeof polling.binaryInterval === "number" ? { binaryInterval: polling.binaryInterval } : {}
507
+ };
508
+ }
509
+ /**
510
+ * 合并用户配置并排除 Vite 开发服务器不应监听的构建输出目录。
511
+ */
512
+ function createViteWatchIgnored(root, outDir, ignored) {
513
+ const normalizedRoot = normalizeFsResolvedId(root);
514
+ const normalizedOutDir = normalizeFsResolvedId(path.isAbsolute(outDir) ? outDir : path.resolve(root, outDir));
515
+ return [...ignored === void 0 ? [] : Array.isArray(ignored) ? ignored : [ignored], (id) => {
516
+ const normalizedId = normalizeFsResolvedId(path.isAbsolute(id) ? id : path.resolve(normalizedRoot, id));
517
+ return isPathInside(normalizedOutDir, normalizedId);
518
+ }];
519
+ }
520
+ //#endregion
521
+ //#region src/wxml/processing/registry.ts
522
+ /** 引用计数同时覆盖已发布、在途和失败恢复集合,单次注册不扫描整个工程。 */
523
+ function retainDependency(state, files, file) {
524
+ if (files.has(file)) return;
525
+ files.add(file);
526
+ const count = state.references.get(file) ?? 0;
527
+ state.references.set(file, count + 1);
528
+ if (!count) for (const listener of state.listeners) listener([file]);
529
+ }
530
+ function releaseDependencies(state, templates) {
531
+ for (const files of templates.values()) for (const file of files) {
532
+ const count = state.references.get(file);
533
+ if (count === 1) state.references.delete(file);
534
+ else state.references.set(file, count - 1);
535
+ }
536
+ }
537
+ /** 只释放成功覆盖的模板,局部恢复不能丢失其他失败模板的监听。 */
538
+ function releaseCoveredDependencies(state, templates, covered) {
539
+ if (!covered) {
540
+ releaseDependencies(state, templates);
541
+ templates.clear();
542
+ return;
543
+ }
544
+ for (const name of covered.keys()) {
545
+ const files = templates.get(name);
546
+ if (files) {
547
+ releaseDependencies(state, /* @__PURE__ */ new Map([[name, files]]));
548
+ templates.delete(name);
549
+ }
550
+ }
551
+ }
552
+ //#endregion
553
+ //#region src/wxml/processing/dependencies.ts
554
+ const deferredCommits = /* @__PURE__ */ new WeakMap();
555
+ /** 转换阶段登记的依赖只在本轮输出成功后提交。 */
556
+ function deferWxmlDependencyCommit(ctx, commit) {
557
+ deferredCommits.get(ctx)?.fail();
558
+ if (commit) deferredCommits.set(ctx, commit);
559
+ else deferredCommits.delete(ctx);
560
+ }
561
+ function failWxmlDependencies(ctx) {
562
+ deferredCommits.get(ctx)?.fail();
563
+ deferredCommits.delete(ctx);
564
+ }
565
+ function commitWxmlDependencies(ctx) {
566
+ deferredCommits.get(ctx)?.();
567
+ deferredCommits.delete(ctx);
568
+ }
569
+ const borrowedRegistries = /* @__PURE__ */ new WeakSet();
570
+ /** 隔离快照和独立分包借用开发会话的依赖集合,由拥有者统一释放。 */
571
+ function shareWxmlDependencies(owner, child) {
572
+ child.runtimeState.wxmlProcessing = owner.runtimeState.wxmlProcessing;
573
+ borrowedRegistries.add(child.runtimeState);
574
+ }
575
+ function clearWxmlDependencies(ctx) {
576
+ if (borrowedRegistries.has(ctx.runtimeState)) return;
577
+ ctx.runtimeState.wxmlProcessing?.dependencies.clear();
578
+ ctx.runtimeState.wxmlProcessing?.pending.clear();
579
+ ctx.runtimeState.wxmlProcessing?.failed.clear();
580
+ ctx.runtimeState.wxmlProcessing?.references.clear();
581
+ deferredCommits.delete(ctx);
582
+ ctx.runtimeState.wxmlProcessing?.listeners.clear();
583
+ }
584
+ function getWxmlWatchFiles(ctx) {
585
+ return [...ctx.runtimeState?.wxmlProcessing?.references.keys() ?? []];
586
+ }
587
+ function isWxmlDependency(ctx, file) {
588
+ return ctx.runtimeState?.wxmlProcessing?.references.has(normalizeFsResolvedId(file)) ?? false;
589
+ }
590
+ function observeWxmlDependencies(ctx, listener) {
591
+ const state = ctx.runtimeState?.wxmlProcessing;
592
+ if (!state) return () => {};
593
+ state.listeners.add(listener);
594
+ listener(getWxmlWatchFiles(ctx));
595
+ return () => {
596
+ state.listeners.delete(listener);
597
+ };
598
+ }
599
+ /** 注册立即生效以支持失败恢复,成功后再提交本轮各模板的依赖集合。 */
600
+ function beginWxmlDependencies(ctx, scope, partial, stage = "transform") {
601
+ const state = ctx.runtimeState?.wxmlProcessing;
602
+ const pending = /* @__PURE__ */ new Map();
603
+ const key = `${stage}:${scope}`;
604
+ const token = Symbol(key);
605
+ let completed = false;
606
+ const root = ctx.configService.cwd;
607
+ let output;
608
+ state?.pending.set(token, {
609
+ scope,
610
+ stage,
611
+ templates: pending
612
+ });
613
+ const fail = () => {
614
+ if (!state || completed || !state.pending.has(token)) return;
615
+ completed = true;
616
+ const recovery = state.failed.get(key) ?? /* @__PURE__ */ new Map();
617
+ for (const [name, files] of pending) {
618
+ if (!files.size) continue;
619
+ const retained = recovery.get(name) ?? /* @__PURE__ */ new Set();
620
+ recovery.set(name, retained);
621
+ for (const file of files) retainDependency(state, retained, file);
622
+ }
623
+ if (recovery.size) state.failed.set(key, recovery);
624
+ releaseDependencies(state, pending);
625
+ state.pending.delete(token);
626
+ };
627
+ const commit = () => {
628
+ if (!state || completed || !state.pending.has(token)) return;
629
+ completed = true;
630
+ const next = state.dependencies.get(key) ?? /* @__PURE__ */ new Map();
631
+ releaseCoveredDependencies(state, next, partial ? pending : void 0);
632
+ for (const [name, files] of pending) if (files.size) next.set(name, files);
633
+ if (next.size) state.dependencies.set(key, next);
634
+ else state.dependencies.delete(key);
635
+ const recovery = state.failed.get(key);
636
+ if (recovery) {
637
+ releaseCoveredDependencies(state, recovery, partial ? pending : void 0);
638
+ if (!recovery.size) state.failed.delete(key);
639
+ }
640
+ state.pending.delete(token);
641
+ if (scope === "main" && !partial && ctx.scanService?.independentSubPackageMap) {
642
+ const activeScopes = new Set([...ctx.scanService.independentSubPackageMap.keys()].map((root) => `independent:${root}`));
643
+ for (const groups of [state.dependencies, state.failed]) for (const [registered, templates] of groups) {
644
+ const registeredScope = registered.slice(registered.indexOf(":") + 1);
645
+ if (registeredScope.startsWith("independent:") && !activeScopes.has(registeredScope)) {
646
+ releaseDependencies(state, templates);
647
+ groups.delete(registered);
648
+ }
649
+ }
650
+ }
651
+ };
652
+ return {
653
+ fail,
654
+ commit,
655
+ publish: Object.assign(commit, { fail }),
656
+ template(fileName) {
657
+ const files = pending.get(fileName) ?? /* @__PURE__ */ new Set();
658
+ pending.set(fileName, files);
659
+ return (file) => {
660
+ if (completed || state && !state.pending.has(token)) throw new Error("The template dependency transaction has already completed.");
661
+ if (typeof file !== "string" || !file.trim()) throw new TypeError("addWatchFile expects a nonempty file path.");
662
+ output ??= normalizeFsResolvedId(ctx.configService.outDir);
663
+ const resolved = normalizeFsResolvedId(path.resolve(root, file));
664
+ if (resolved === output || resolved.startsWith(`${output}/`)) throw new Error("addWatchFile cannot watch generated output.");
665
+ if (state) retainDependency(state, files, resolved);
666
+ return resolved;
667
+ };
668
+ }
669
+ };
670
+ }
671
+ //#endregion
672
+ //#region src/wxml/processing/watch.ts
673
+ const externalOwners = /* @__PURE__ */ new WeakMap();
674
+ function ownsExternalWxmlWatch(ctx, file) {
675
+ return externalOwners.get(ctx)?.has(normalizeFsResolvedId(file)) ?? false;
676
+ }
677
+ /** 根外输入按父目录浅层监听,保留删除后的路径身份;根内输入继续由 Vite 监听。 */
678
+ function bindWxmlDependencyWatch(ctx, server, onChange) {
679
+ const root = server.config?.root ?? ctx.configService?.cwd;
680
+ const external = /* @__PURE__ */ new Set();
681
+ const parents = /* @__PURE__ */ new Set();
682
+ let watcher;
683
+ let closed;
684
+ let ready = Promise.resolve();
685
+ externalOwners.set(ctx, external);
686
+ const unobserve = observeWxmlDependencies(ctx, (files) => {
687
+ external.clear();
688
+ const internal = [];
689
+ for (const file of files) {
690
+ const relative = root ? path.relative(root, file) : "";
691
+ if (root && (relative === ".." || relative.startsWith("../") || path.isAbsolute(relative))) external.add(file);
692
+ else internal.push(file);
693
+ }
694
+ server.watcher.add(internal);
695
+ if (!external.size || server.config?.server.watch === null) return;
696
+ const options = server.config?.server.watch ?? {};
697
+ if (!watcher) {
698
+ watcher = watch([], {
699
+ ...options,
700
+ ignoreInitial: true,
701
+ depth: 0,
702
+ ignored: [...Array.isArray(options.ignored) ? options.ignored : options.ignored ? [options.ignored] : [], (file) => !external.has(normalizeFsResolvedId(file)) && !parents.has(normalizeFsResolvedId(file))]
703
+ }).on("all", (event, file) => {
704
+ const normalized = normalizeFsResolvedId(file);
705
+ if (!external.has(normalized)) return;
706
+ if (event === "add" || event === "change" || event === "unlink") onChange({
707
+ event: event === "add" ? "create" : event === "unlink" ? "delete" : "update",
708
+ file: normalized
709
+ });
710
+ }).on("error", (error) => server.config.logger.error(`[weapp-vite] WXML dependency watch failed: ${error instanceof Error ? error.message : String(error)}`));
711
+ ready = once(watcher, "ready");
712
+ }
713
+ for (const file of external) {
714
+ const parent = path.dirname(file);
715
+ if (!parents.has(parent)) {
716
+ parents.add(parent);
717
+ watcher.add(parent);
718
+ }
719
+ }
720
+ });
721
+ const close = () => {
722
+ closed ??= (async () => {
723
+ unobserve();
724
+ if (externalOwners.get(ctx) === external) externalOwners.delete(ctx);
725
+ external.clear();
726
+ await watcher?.close();
727
+ })();
728
+ return closed;
729
+ };
730
+ return Object.assign(close, { ready });
731
+ }
732
+ //#endregion
733
+ //#region src/moduleGraph/host.ts
734
+ const hosts = /* @__PURE__ */ new WeakMap();
735
+ /** 显式借用宿主图;释放借用不会关闭宿主服务器。 */
736
+ function attachDevModuleGraphHost(context, server, onBuild) {
737
+ if (hosts.has(context)) throw new Error("[weapp-vite] 编译上下文已经绑定开发宿主。");
738
+ const host = {
739
+ server,
740
+ onBuild
741
+ };
742
+ hosts.set(context, host);
743
+ return () => {
744
+ if (hosts.get(context) === host) hosts.delete(context);
745
+ };
746
+ }
747
+ function notifyDevModuleGraphHost(context, change) {
748
+ hosts.get(context)?.onChange?.(change);
749
+ }
750
+ function reportDevModuleGraphBuild(context, successful) {
751
+ hosts.get(context)?.onBuild?.(successful);
752
+ }
753
+ function hasDevModuleGraphHost(context) {
754
+ return hosts.has(context);
755
+ }
756
+ function connectDevModuleGraphHost(context, onChange) {
757
+ const host = hosts.get(context);
758
+ if (!host) return;
759
+ host.onChange = onChange;
760
+ const release = context.moduleGraphService.bindDevServer(host.server);
761
+ let closed = false;
762
+ return { async close() {
763
+ if (closed) return;
764
+ closed = true;
765
+ if (host.onChange === onChange) host.onChange = void 0;
766
+ release();
767
+ } };
768
+ }
769
+ //#endregion
770
+ //#region src/moduleGraph/logicalEntry.ts
771
+ function createLogicalEntryModuleCode(entry, dependencies) {
772
+ const source = JSON.stringify(entry.sourceId);
773
+ const isVueLikeEntry = /\.(?:vue|jsx|tsx)$/.test(entry.sourceId);
774
+ const delegatesComponentRegistration = entry.type === "component" && isVueLikeEntry;
775
+ const forwardsDefault = entry.type !== "app" && isVueLikeEntry;
776
+ const imports = delegatesComponentRegistration ? [
777
+ `import { createWevuComponent as __weappViteCreateWevuComponent } from ${JSON.stringify(WEAPP_VITE_RUNTIME_VIRTUAL_ID)};`,
778
+ `import __weappViteComponentOptions from ${source};`,
779
+ `__weappViteCreateWevuComponent(__weappViteComponentOptions);`,
780
+ `export default __weappViteComponentOptions;`
781
+ ] : [forwardsDefault ? `export { default } from ${source};` : `import ${source};`];
782
+ const dependencyIds = /* @__PURE__ */ new Set();
783
+ for (const dependency of dependencies) dependencyIds.add(createSidecarModuleId(entry.sourceId, dependency.sourceId, dependency.kind));
784
+ for (const dependencyId of [...dependencyIds].sort()) imports.push(`import ${JSON.stringify(dependencyId)};`);
785
+ imports.push(`export * from ${source};`);
786
+ return `${imports.join("\n")}\n`;
787
+ }
788
+ function createSidecarModuleCode(ownerId, sourceId, kind) {
789
+ const sourceRequest = createSidecarSourceSpecifier(ownerId, sourceId, kind, kind === "style");
790
+ return `import ${JSON.stringify(sourceRequest)};\nexport default ${JSON.stringify(sourceId)};\n`;
791
+ }
792
+ //#endregion
793
+ //#region src/utils/hmrProfile.ts
794
+ const DEFAULT_HMR_PROFILE_JSONL_RELATIVE_PATH = ".weapp-vite/hmr-profile.jsonl";
795
+ const HMR_PROFILE_JSON_ENV = "WEAPP_VITE_HMR_PROFILE_JSON";
796
+ /**
797
+ * @description 解析 HMR profile JSONL 输出路径。
798
+ */
799
+ function resolveHmrProfileJsonPath(options) {
800
+ const fallbackToDefault = options.fallbackToDefault ?? false;
801
+ if (options.option === true) return path.join(options.cwd, DEFAULT_HMR_PROFILE_JSONL_RELATIVE_PATH);
802
+ if (typeof options.option === "string") {
803
+ const trimmed = options.option.trim();
804
+ if (trimmed) return path.isAbsolute(trimmed) ? trimmed : path.resolve(options.cwd, trimmed);
805
+ }
806
+ if (fallbackToDefault) return path.join(options.cwd, DEFAULT_HMR_PROFILE_JSONL_RELATIVE_PATH);
807
+ }
808
+ /**
809
+ * @description 从环境变量解析 HMR profile JSONL 输出选项。
810
+ */
811
+ function resolveHmrProfileJsonEnvOption(env = process.env) {
812
+ const raw = env[HMR_PROFILE_JSON_ENV]?.trim();
813
+ if (!raw) return;
814
+ if (raw === "1" || raw.toLowerCase() === "true") return true;
815
+ if (raw === "0" || raw.toLowerCase() === "false") return;
816
+ return raw;
817
+ }
818
+ /** 统一写入方与监听边界的 profile 输出选择,保持环境变量优先级一致。 */
819
+ function resolveActiveHmrProfileJsonPath(options, env = process.env) {
820
+ return resolveHmrProfileJsonPath({
821
+ ...options,
822
+ option: resolveHmrProfileJsonEnvOption(env) ?? options.option
823
+ });
824
+ }
825
+ let hmrProfileEventSequence = 0;
826
+ /**
827
+ * @description 创建 HMR profile 事件 id,用于把 watcher 事件、JSONL 样本和外部审计场景稳定关联。
828
+ */
829
+ function createHmrProfileEventId() {
830
+ hmrProfileEventSequence += 1;
831
+ return `${Date.now().toString(36)}-${hmrProfileEventSequence.toString(36)}`;
832
+ }
833
+ /**
834
+ * @description 为 HMR profile 累加阶段耗时。
835
+ */
836
+ function recordHmrProfileDuration(profile, key, durationMs) {
837
+ if (!profile || !Number.isFinite(durationMs) || durationMs < 0) return;
838
+ profile[key] = (profile[key] ?? 0) + durationMs;
839
+ }
840
+ /**
841
+ * @description 为 HMR profile 累加操作次数。
842
+ */
843
+ function recordHmrProfileOperation(profile, key, count = 1) {
844
+ if (!profile || !Number.isFinite(count) || count <= 0) return;
845
+ profile[key] = (profile[key] ?? 0) + count;
846
+ }
847
+ /** 连续记录同一插件内已完成的阶段;停用时不读取时钟,不引入额外异步调度。 */
848
+ function createHmrProfileCheckpoint(profile) {
849
+ let previous = profile ? performance.now() : 0;
850
+ return (key) => {
851
+ if (!profile) return;
852
+ const now = performance.now();
853
+ recordHmrProfileDuration(profile, key, now - previous);
854
+ previous = now;
855
+ };
856
+ }
857
+ //#endregion
858
+ //#region src/moduleGraph/profileOutput.ts
859
+ /** 仅识别当前启用的自身 profile 文件,不屏蔽同目录或同名用户输入。 */
860
+ function createProfileOutputMatcher(configService) {
861
+ return (file) => {
862
+ if (!configService) return false;
863
+ const output = resolveActiveHmrProfileJsonPath({
864
+ cwd: configService.cwd,
865
+ option: configService.weappViteConfig?.hmr?.profileJson
866
+ });
867
+ if (!output) return false;
868
+ const normalize = (value) => {
869
+ const normalized = normalizePath(path.resolve(configService.cwd, normalizePath(value)));
870
+ return process.platform === "win32" ? normalized.toLowerCase() : normalized;
871
+ };
872
+ return normalize(file) === normalize(output);
873
+ };
874
+ }
875
+ //#endregion
876
+ //#region src/moduleGraph/devProvider.ts
877
+ const DEV_EXTERNAL_PREFIX = "\0weapp-vite:module-graph-external:";
878
+ function isInternalPlugin(plugin) {
879
+ if (!plugin || typeof plugin !== "object" || !("name" in plugin)) return false;
880
+ const name = plugin.name;
881
+ return typeof name === "string" && (name.startsWith("weapp-vite:") || name.startsWith("weapp-runtime:"));
882
+ }
883
+ function collectResolverPlugins(config) {
884
+ return (Array.isArray(config.plugins) ? config.plugins : config.plugins ? [config.plugins] : []).filter((plugin) => !isInternalPlugin(plugin));
885
+ }
886
+ async function transformVueSource(code, id, config) {
887
+ const { descriptor, errors } = await readAndParseSfc(id, { source: code });
888
+ if (errors.length) throw errors[0];
889
+ const blocks = [descriptor.script, descriptor.scriptSetup].filter((block) => block?.content || block?.src);
890
+ const source = blocks.map((block) => block.src ? `import ${JSON.stringify(block.src)};` : block.content).join("\n") || "export default {}";
891
+ const lang = blocks.some((block) => block?.lang === "tsx") ? "tsx" : blocks.some((block) => block?.lang === "ts") ? "ts" : "js";
892
+ return await transformWithOxc(source, id, {
893
+ lang,
894
+ sourcemap: false,
895
+ target: "esnext",
896
+ tsconfig: false,
897
+ typescript: { onlyRemoveTypeImports: true }
898
+ }, void 0, config);
899
+ }
900
+ async function isExternalRequest(source, importer, config) {
901
+ const buildOptions = config.build;
902
+ const external = buildOptions?.rolldownOptions?.external ?? buildOptions?.rollupOptions?.external;
903
+ if (typeof external === "function") return await external(source, importer, false);
904
+ return (Array.isArray(external) ? external : external ? [external] : []).some((pattern) => {
905
+ if (typeof pattern === "string") return pattern === source;
906
+ pattern.lastIndex = 0;
907
+ return pattern.test(source);
908
+ });
909
+ }
910
+ function createDevModuleGraphPlugin(ctx, config, onChange) {
911
+ const isProfileOutput = createProfileOutputMatcher(ctx.configService);
912
+ const npmExternalPackages = new Set(ctx.configService?.packageJson ? resolveNpmBuildCandidateDependenciesSync(ctx, ctx.configService.packageJson) : []);
913
+ return {
914
+ name: "weapp-vite:module-graph-provider",
915
+ enforce: "pre",
916
+ config() {
917
+ return {
918
+ server: { watch: { ignored: [isProfileOutput] } },
919
+ resolve: { alias: [{
920
+ find: WEVU_AUTO_ROUTES_MODULE_ID$1,
921
+ replacement: WEVU_AUTO_ROUTES_VIRTUAL_MODULE_ID$1
922
+ }, {
923
+ find: AUTO_ROUTES_ID,
924
+ replacement: VIRTUAL_MODULE_ID
925
+ }] }
926
+ };
927
+ },
928
+ async resolveId(id, importer) {
929
+ const autoRoutesId = resolveAutoRoutesVirtualId(id);
930
+ if (autoRoutesId) return autoRoutesId;
931
+ const virtualId = resolveVirtualModuleId(id);
932
+ if (virtualId) return virtualId;
933
+ if (parseSidecarSourceRequest(id)) return id;
934
+ if (Array.from(npmExternalPackages).some((pkg) => id === pkg || id.startsWith(`${pkg}/`))) return `${DEV_EXTERNAL_PREFIX}${encodeURIComponent(id)}`;
935
+ if (await isExternalRequest(id, importer, config)) return `${DEV_EXTERNAL_PREFIX}${encodeURIComponent(id)}`;
936
+ if (!id.startsWith(".") && !id.startsWith("/") && !id.startsWith("\0") && !/^[a-z]:[\\/]/i.test(id)) {
937
+ const resolved = await this.resolve(id, importer, { skipSelf: true });
938
+ if (!resolved || resolved.external) return `${DEV_EXTERNAL_PREFIX}${encodeURIComponent(id)}`;
939
+ return resolved;
940
+ }
941
+ return null;
942
+ },
943
+ load(id) {
944
+ const autoRoutesId = resolveAutoRoutesVirtualId(id);
945
+ const service = ctx.autoRoutesService;
946
+ if (autoRoutesId && service) return service.ensureFresh().then(() => autoRoutesId === WEVU_AUTO_ROUTES_RESOLVED_MODULE_ID$1 ? service.getNamedModuleCode() : service.getModuleCode());
947
+ if (id.startsWith(DEV_EXTERNAL_PREFIX)) return "export default {}";
948
+ const logicalEntry = parseLogicalEntryId(id);
949
+ if (logicalEntry) return createLogicalEntryModuleCode(logicalEntry, ctx.moduleGraphService.getEntryDependencies(logicalEntry.sourceId));
950
+ const sidecar = parseSidecarModuleId(id);
951
+ if (sidecar) {
952
+ if (sidecar.kind === "style") {
953
+ const source = createSidecarSourceSpecifier(sidecar.ownerId, sidecar.sourceId, "style");
954
+ return `import ${JSON.stringify(source)};\nexport default ${JSON.stringify(sidecar.sourceId)};\n`;
955
+ }
956
+ return createSidecarModuleCode(sidecar.ownerId, sidecar.sourceId, sidecar.kind);
957
+ }
958
+ const sidecarSource = parseSidecarSourceRequest(id);
959
+ if (sidecarSource) {
960
+ if (sidecarSource.kind === "style" && !sidecarSource.dependencyOnly) return null;
961
+ return `export default ${JSON.stringify(sidecarSource.sourceId)};`;
962
+ }
963
+ return null;
964
+ },
965
+ async transform(code, id) {
966
+ if (isCSSRequest(id) && !id.startsWith("\0")) this.addWatchFile(normalizeSourceId(id));
967
+ for (const dependency of ctx.moduleGraphService.getTransformDependencies?.(id) ?? []) this.addWatchFile(dependency);
968
+ if (!id.endsWith(".vue")) return null;
969
+ return await transformVueSource(code, id, this?.environment?.config);
970
+ },
971
+ async hotUpdate({ type, file, read }) {
972
+ if (this.environment.name !== "client" || isProfileOutput(file) || ownsExternalWxmlWatch(ctx, file)) return;
973
+ if (type === "delete") {
974
+ onChange({
975
+ event: type,
976
+ file
977
+ });
978
+ return;
979
+ }
980
+ try {
981
+ await read();
982
+ } catch (error) {
983
+ if (error.code === "ENOENT") return;
984
+ throw error;
985
+ }
986
+ onChange({
987
+ event: type,
988
+ file
989
+ });
990
+ }
991
+ };
992
+ }
993
+ async function createDevModuleGraphProvider(ctx, buildConfig, onChange) {
994
+ const host = connectDevModuleGraphHost(ctx, onChange);
995
+ if (host) return host;
996
+ const configService = ctx.configService;
997
+ const userWatch = buildConfig.server?.watch;
998
+ const pollingWatchOptions = resolvePollingWatchOptions({ inlineConfig: configService?.inlineConfig ?? {} });
999
+ const ignored = configService?.outDir ? createViteWatchIgnored(buildConfig.root ?? configService.cwd, configService.outDir, userWatch?.ignored) : userWatch?.ignored;
1000
+ const server = await createServer({
1001
+ ...buildConfig,
1002
+ root: buildConfig.root ?? configService?.cwd,
1003
+ appType: "custom",
1004
+ configFile: false,
1005
+ customLogger: createLogger("silent"),
1006
+ plugins: [createDevModuleGraphPlugin(ctx, buildConfig, onChange), ...collectResolverPlugins(buildConfig)],
1007
+ server: {
1008
+ ...buildConfig.server ?? {},
1009
+ hmr: true,
1010
+ middlewareMode: true,
1011
+ watch: {
1012
+ ...userWatch ?? {},
1013
+ ...Object.fromEntries(Object.entries(pollingWatchOptions).filter(([, value]) => value !== void 0)),
1014
+ ...ignored !== void 0 ? { ignored } : {}
1015
+ }
1016
+ },
1017
+ build: {
1018
+ ...buildConfig.build ?? {},
1019
+ watch: void 0,
1020
+ write: false
1021
+ }
1022
+ });
1023
+ const releaseServer = ctx.moduleGraphService.bindDevServer(server);
1024
+ const unobserveWxml = bindWxmlDependencyWatch(ctx, server, onChange);
1025
+ try {
1026
+ await unobserveWxml.ready;
1027
+ } catch (error) {
1028
+ await unobserveWxml();
1029
+ try {
1030
+ await server.close();
1031
+ } finally {
1032
+ releaseServer();
1033
+ }
1034
+ throw error;
1035
+ }
1036
+ let closePromise;
1037
+ return { close() {
1038
+ closePromise ??= (async () => {
1039
+ await unobserveWxml();
1040
+ try {
1041
+ await server.close();
1042
+ } finally {
1043
+ releaseServer();
1044
+ }
1045
+ })();
1046
+ return closePromise;
1047
+ } };
1048
+ }
1049
+ //#endregion
1050
+ export { isAutoRoutesGeneratedPath as $, resolveConfiguredNpmDependencyPatterns as A, WEVU_AUTO_ROUTES_RESOLVED_MODULE_ID$1 as B, isWxmlDependency as C, resolvePollingWatchOptions as D, createViteWatchIgnored as E, resolveNpmDistDirName as F, invalidateAutoRoutesVirtualModules as G, collectAutoRoutesReloadModules as H, resolveNpmStrategyMode as I, resolveAutoRoutesHotUpdateAction as J, isAutoRoutesWatchFile as K, resolveTargetDependencies as L, resolveMainBuildDependencyPatterns as M, resolveNpmBuildCandidateDependenciesSync as N, dedupeNpmDependencies as O, resolveNpmBuildCandidateDependencyRecordSync as P, isAutoRoutesGeneratedDirectoryName as Q, packageSearchOptions as R, getWxmlWatchFiles as S, createSidecarWatchOptions as T, collectAutoRoutesWatchDirs as U, addAutoRoutesWatchTargets as V, createAutoRoutesSidecarWatcher as W, resolveAutoRoutesWatchChangeEvent as X, resolveAutoRoutesVirtualId as Y, shouldStartAutoRoutesWatcher as Z, beginWxmlDependencies as _, recordHmrProfileDuration as a, isRegexp as at, deferWxmlDependencyCommit as b, resolveHmrProfileJsonEnvOption as c, hasBuildModule as ct, createSidecarModuleCode as d, normalizeSourceId as dt, isAutoRoutesGeneratedRelativePath as et, attachDevModuleGraphHost as f, bindWxmlDependencyWatch as g, reportDevModuleGraphBuild as h, createHmrProfileEventId as i, isCSSRequest as it, resolveDeclaredNpmDependencies as j, hasLocalSubPackageNpmConfig as k, resolveHmrProfileJsonPath as l, hasDevModule as lt, notifyDevModuleGraphHost as m, createDevModuleGraphProvider as n, resolveWeappAutoRoutesConfig as nt, recordHmrProfileOperation as o, collectBuildStartIds as ot, hasDevModuleGraphHost as p, isAutoRoutesWatchMode as q, createHmrProfileCheckpoint as r, createAutoRoutesMatcher as rt, resolveActiveHmrProfileJsonPath as s, collectDevStartNodes as st, createDevModuleGraphPlugin as t, resolveAutoRoutesManagedOutputPaths as tt, createLogicalEntryModuleCode as u, isLogicalEntrySource as ut, clearWxmlDependencies as v, shareWxmlDependencies as w, failWxmlDependencies as x, commitWxmlDependencies as y, RESOLVED_VIRTUAL_ID as z };