@uni-helper/vite-plugin-uni-pages 0.3.24 → 0.4.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.
package/dist/index.cjs CHANGED
@@ -1,91 +1,110 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- const path = require('node:path');
6
- const process = require('node:process');
7
- const astKit = require('ast-kit');
8
- const chokidar = require('chokidar');
9
- const kolorist = require('kolorist');
10
- const MagicString = require('magic-string');
11
- const vite = require('vite');
12
- const fs = require('node:fs');
13
- const uniEnv = require('@uni-helper/uni-env');
14
- const commentJson = require('comment-json');
15
- const Debug = require('debug');
16
- const detectIndent = require('detect-indent');
17
- const detectNewline = require('detect-newline');
18
- const unconfig = require('unconfig');
19
- const promises = require('node:fs/promises');
20
- const fg = require('fast-glob');
21
- const lockfile = require('proper-lockfile');
22
- const writeFileAtomic = require('write-file-atomic');
23
- const node_module = require('node:module');
24
- const vm = require('node:vm');
25
- const babelGenerator = require('@babel/generator');
26
- const groupBy = require('lodash.groupby');
27
- const ts = require('typescript');
28
- const t = require('@babel/types');
29
- const compilerSfc = require('@vue/compiler-sfc');
30
- const JSON5 = require('json5');
31
- const yaml = require('yaml');
32
-
33
- function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
34
-
35
- function _interopNamespaceCompat(e) {
36
- if (e && typeof e === 'object' && 'default' in e) return e;
37
- const n = Object.create(null);
38
- if (e) {
39
- for (const k in e) {
40
- n[k] = e[k];
41
- }
42
- }
43
- n.default = e;
44
- return n;
45
- }
46
-
47
- const path__default = /*#__PURE__*/_interopDefaultCompat(path);
48
- const process__default = /*#__PURE__*/_interopDefaultCompat(process);
49
- const chokidar__default = /*#__PURE__*/_interopDefaultCompat(chokidar);
50
- const MagicString__default = /*#__PURE__*/_interopDefaultCompat(MagicString);
51
- const fs__default = /*#__PURE__*/_interopDefaultCompat(fs);
52
- const Debug__default = /*#__PURE__*/_interopDefaultCompat(Debug);
53
- const detectIndent__default = /*#__PURE__*/_interopDefaultCompat(detectIndent);
54
- const detectNewline__default = /*#__PURE__*/_interopDefaultCompat(detectNewline);
55
- const fg__default = /*#__PURE__*/_interopDefaultCompat(fg);
56
- const lockfile__default = /*#__PURE__*/_interopDefaultCompat(lockfile);
57
- const writeFileAtomic__default = /*#__PURE__*/_interopDefaultCompat(writeFileAtomic);
58
- const vm__default = /*#__PURE__*/_interopDefaultCompat(vm);
59
- const babelGenerator__default = /*#__PURE__*/_interopDefaultCompat(babelGenerator);
60
- const groupBy__default = /*#__PURE__*/_interopDefaultCompat(groupBy);
61
- const ts__namespace = /*#__PURE__*/_interopNamespaceCompat(ts);
62
- const t__namespace = /*#__PURE__*/_interopNamespaceCompat(t);
63
- const JSON5__default = /*#__PURE__*/_interopDefaultCompat(JSON5);
64
-
1
+ Object.defineProperties(exports, {
2
+ __esModule: { value: true },
3
+ [Symbol.toStringTag]: { value: "Module" }
4
+ });
5
+ //#region \0rolldown/runtime.js
6
+ var __create = Object.create;
7
+ var __defProp = Object.defineProperty;
8
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
9
+ var __getOwnPropNames = Object.getOwnPropertyNames;
10
+ var __getProtoOf = Object.getPrototypeOf;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
14
+ key = keys[i];
15
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
16
+ get: ((k) => from[k]).bind(null, key),
17
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
18
+ });
19
+ }
20
+ return to;
21
+ };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
23
+ value: mod,
24
+ enumerable: true
25
+ }) : target, mod));
26
+ //#endregion
27
+ let node_path = require("node:path");
28
+ node_path = __toESM(node_path, 1);
29
+ let node_process = require("node:process");
30
+ node_process = __toESM(node_process, 1);
31
+ let ast_kit = require("ast-kit");
32
+ let chokidar = require("chokidar");
33
+ chokidar = __toESM(chokidar, 1);
34
+ let magic_string = require("magic-string");
35
+ magic_string = __toESM(magic_string, 1);
36
+ let vite = require("vite");
37
+ let node_fs = require("node:fs");
38
+ node_fs = __toESM(node_fs, 1);
39
+ let _uni_helper_uni_env = require("@uni-helper/uni-env");
40
+ let comment_json = require("comment-json");
41
+ let debug = require("debug");
42
+ debug = __toESM(debug, 1);
43
+ let detect_indent = require("detect-indent");
44
+ detect_indent = __toESM(detect_indent, 1);
45
+ let detect_newline = require("detect-newline");
46
+ detect_newline = __toESM(detect_newline, 1);
47
+ let unconfig = require("unconfig");
48
+ let node_fs_promises = require("node:fs/promises");
49
+ let proper_lockfile = require("proper-lockfile");
50
+ proper_lockfile = __toESM(proper_lockfile, 1);
51
+ let tinyglobby = require("tinyglobby");
52
+ let write_file_atomic = require("write-file-atomic");
53
+ write_file_atomic = __toESM(write_file_atomic, 1);
54
+ let node_module = require("node:module");
55
+ let node_vm = require("node:vm");
56
+ node_vm = __toESM(node_vm, 1);
57
+ let _babel_generator = require("@babel/generator");
58
+ _babel_generator = __toESM(_babel_generator, 1);
59
+ let lodash_groupby = require("lodash.groupby");
60
+ lodash_groupby = __toESM(lodash_groupby, 1);
61
+ let typescript = require("typescript");
62
+ typescript = __toESM(typescript, 1);
63
+ let _babel_types = require("@babel/types");
64
+ _babel_types = __toESM(_babel_types, 1);
65
+ let _vue_compiler_sfc = require("@vue/compiler-sfc");
66
+ //#region src/constant.ts
67
+ /** Virtual module identifier for Vite module resolution */
65
68
  const MODULE_ID_VIRTUAL = "virtual:uni-pages";
69
+ /** Resolved virtual module identifier with \0 prefix to avoid conflicts with other modules */
66
70
  const RESOLVED_MODULE_ID_VIRTUAL = `\0${MODULE_ID_VIRTUAL}`;
71
+ /** Output filename, the uni-app page configuration file */
67
72
  const OUTPUT_NAME = "pages.json";
68
- const FILE_EXTENSIONS = ["vue", "nvue", "uvue"];
69
-
73
+ /** Supported page file extensions */
74
+ const FILE_EXTENSIONS = [
75
+ "vue",
76
+ "nvue",
77
+ "uvue"
78
+ ];
79
+ //#endregion
80
+ //#region ../../node_modules/.pnpm/@antfu+utils@9.3.0/node_modules/@antfu/utils/dist/index.mjs
70
81
  function slash(str) {
71
- return str.replace(/\\/g, "/");
82
+ return str.replace(/\\/g, "/");
72
83
  }
73
-
84
+ //#endregion
85
+ //#region src/declaration.ts
86
+ /**
87
+ * Generate TypeScript declaration file content
88
+ * Provide type hints for uni-app navigation APIs (navigateTo, redirectTo, switchTab, reLaunch)
89
+ * Ensure page paths get type checking at compile time
90
+ *
91
+ * @param ctx - Page context instance
92
+ * @returns Declaration file code string
93
+ */
74
94
  function getDeclaration(ctx) {
75
- const subPagesPath = ctx.subPageMetaData.map((sub) => {
76
- return sub.pages.map((v) => `"/${vite.normalizePath(path.join(sub.root, v.path))}"`);
77
- }).flat();
78
- const tabsPagesPath = ctx.pagesGlobConfig?.tabBar?.list?.map((v) => {
79
- return `"/${v.pagePath}"`;
80
- }) ?? [];
81
- const allPagesPath = [...ctx.pageMetaData.filter((page) => !tabsPagesPath.includes(page.path)).map((v) => `"/${v.path}"`), ...subPagesPath];
82
- const code = `/* eslint-disable */
95
+ const subPagesPath = ctx.subPageMetaData.map((sub) => {
96
+ return sub.pages.map((v) => `"/${(0, vite.normalizePath)((0, node_path.join)(sub.root, v.path))}"`);
97
+ }).flat();
98
+ const tabsPagesPath = ctx.pagesGlobConfig?.tabBar?.list?.map((v) => {
99
+ return `"/${v.pagePath}"`;
100
+ }) ?? [];
101
+ return `/* eslint-disable */
83
102
  /* prettier-ignore */
84
103
  // @ts-nocheck
85
104
  // Generated by vite-plugin-uni-pages
86
105
 
87
106
  type _LocationUrl =
88
- ${allPagesPath.join(" |\n ")};
107
+ ${[...ctx.pageMetaData.filter((page) => !tabsPagesPath.includes(page.path)).map((v) => `"/${v.path}"`), ...subPagesPath].join(" |\n ")};
89
108
 
90
109
  interface NavigateToOptions {
91
110
  url: _LocationUrl;
@@ -109,1111 +128,1222 @@ declare module "virtual:uni-pages" {
109
128
  export type LocationUrl = _LocationUrl;
110
129
  }
111
130
  `;
112
- return code;
113
131
  }
132
+ /**
133
+ * Write file, automatically create directories
134
+ * @param filePath - File path
135
+ * @param content - File content
136
+ */
114
137
  async function writeFile(filePath, content) {
115
- await promises.mkdir(path.dirname(filePath), { recursive: true });
116
- return await promises.writeFile(filePath, content, "utf-8");
138
+ await (0, node_fs_promises.mkdir)((0, node_path.dirname)(filePath), { recursive: true });
139
+ return await (0, node_fs_promises.writeFile)(filePath, content, "utf-8");
117
140
  }
141
+ /**
142
+ * Write declaration file to disk
143
+ * Only writes when content changes to avoid unnecessary file operations
144
+ *
145
+ * @param ctx - Page context instance
146
+ * @param filepath - Declaration file output path
147
+ */
118
148
  async function writeDeclaration(ctx, filepath) {
119
- const originalContent = fs.existsSync(filepath) ? await promises.readFile(filepath, "utf-8") : "";
120
- const code = getDeclaration(ctx);
121
- if (!code)
122
- return;
123
- if (code !== originalContent)
124
- await writeFile(filepath, code);
149
+ const originalContent = (0, node_fs.existsSync)(filepath) ? await (0, node_fs_promises.readFile)(filepath, "utf-8") : "";
150
+ const code = getDeclaration(ctx);
151
+ if (!code) return;
152
+ if (code !== originalContent) await writeFile(filepath, code);
125
153
  }
126
-
154
+ //#endregion
155
+ //#region src/utils.ts
156
+ /**
157
+ * Invalidate virtual module to trigger HMR update
158
+ * When page configuration changes, the virtual module needs to be invalidated to regenerate content
159
+ *
160
+ * @param server - Vite dev server instance
161
+ */
127
162
  function invalidatePagesModule(server) {
128
- const { moduleGraph } = server;
129
- const mods = moduleGraph.getModulesByFile(RESOLVED_MODULE_ID_VIRTUAL);
130
- if (mods) {
131
- const seen = /* @__PURE__ */ new Set();
132
- mods.forEach((mod) => {
133
- moduleGraph.invalidateModule(mod, seen);
134
- });
135
- }
163
+ const { moduleGraph } = server;
164
+ const mods = moduleGraph.getModulesByFile(RESOLVED_MODULE_ID_VIRTUAL);
165
+ if (mods) {
166
+ const seen = /* @__PURE__ */ new Set();
167
+ mods.forEach((mod) => {
168
+ moduleGraph.invalidateModule(mod, seen);
169
+ });
170
+ }
136
171
  }
137
- const debug = {
138
- hmr: Debug__default("vite-plugin-uni-pages:hmr"),
139
- routeBlock: Debug__default("vite-plugin-uni-pages:routeBlock"),
140
- options: Debug__default("vite-plugin-uni-pages:options"),
141
- pages: Debug__default("vite-plugin-uni-pages:pages"),
142
- subPages: Debug__default("vite-plugin-uni-pages:subPages"),
143
- error: Debug__default("vite-plugin-uni-pages:error"),
144
- cache: Debug__default("vite-plugin-uni-pages:cache"),
145
- declaration: Debug__default("vite-plugin-uni-pages:declaration"),
146
- definePage: Debug__default("vite-plugin-uni-pages:definePage")
172
+ /**
173
+ * Debug logging utility
174
+ * Uses debug package for leveled log output
175
+ * Enable via environment variable DEBUG=vite-plugin-uni-pages:*
176
+ */
177
+ const debug$1 = {
178
+ /** HMR related logs */
179
+ hmr: (0, debug.default)("vite-plugin-uni-pages:hmr"),
180
+ /** Configuration options related logs */
181
+ options: (0, debug.default)("vite-plugin-uni-pages:options"),
182
+ /** Main package page scanning logs */
183
+ pages: (0, debug.default)("vite-plugin-uni-pages:pages"),
184
+ /** Sub-package page scanning logs */
185
+ subPages: (0, debug.default)("vite-plugin-uni-pages:subPages"),
186
+ /** Error logs */
187
+ error: (0, debug.default)("vite-plugin-uni-pages:error"),
188
+ /** Cache related logs */
189
+ cache: (0, debug.default)("vite-plugin-uni-pages:cache"),
190
+ /** Declaration file generation logs */
191
+ declaration: (0, debug.default)("vite-plugin-uni-pages:declaration"),
192
+ /** definePage macro parsing logs */
193
+ definePage: (0, debug.default)("vite-plugin-uni-pages:definePage")
147
194
  };
195
+ /**
196
+ * Convert file extensions array to glob pattern
197
+ * @param extensions - File extensions array
198
+ * @returns Glob pattern string
199
+ */
148
200
  function extsToGlob(extensions) {
149
- return extensions.length > 1 ? `{${extensions.join(",")}}` : extensions[0] || "";
201
+ return extensions.length > 1 ? `{${extensions.join(",")}}` : extensions[0] || "";
150
202
  }
151
- function isTargetFile(path2) {
152
- const ext = path2.split(".").pop();
153
- return FILE_EXTENSIONS.includes(ext);
203
+ /**
204
+ * Check if file is a target page file
205
+ * Determine if the file extension is in the supported page file types list
206
+ *
207
+ * @param path - File path
208
+ * @returns Whether it's a target file
209
+ */
210
+ function isTargetFile(path) {
211
+ const ext = path.split(".").pop();
212
+ return FILE_EXTENSIONS.includes(ext);
154
213
  }
214
+ /**
215
+ * merge page meta data array by path and assign style
216
+ * @param pageMetaData page meta data array
217
+ * TODO: support merge middleware
218
+ */
155
219
  function mergePageMetaDataArray(pageMetaData) {
156
- const pageMetaDataObj = groupBy__default(pageMetaData, "path");
157
- const result = [];
158
- for (const path2 in pageMetaDataObj) {
159
- const _pageMetaData = pageMetaDataObj[path2];
160
- const options = _pageMetaData[0];
161
- for (const page of _pageMetaData) {
162
- options.style = Object.assign(options.style ?? {}, page.style ?? {});
163
- Object.assign(options, page);
164
- }
165
- result.push(options);
166
- }
167
- return result;
220
+ const pageMetaDataObj = (0, lodash_groupby.default)(pageMetaData, "path");
221
+ const result = [];
222
+ for (const path in pageMetaDataObj) {
223
+ const _pageMetaData = pageMetaDataObj[path];
224
+ const options = _pageMetaData[0];
225
+ for (const page of _pageMetaData) {
226
+ options.style = Object.assign(options.style ?? {}, page.style ?? {});
227
+ Object.assign(options, page);
228
+ }
229
+ result.push(options);
230
+ }
231
+ return result;
168
232
  }
233
+ /**
234
+ * Convert TypeScript / JavaScript script code to object/function
235
+ *
236
+ * @param options - Configuration required for script execution
237
+ * @param options.imports - List of module import statements to include
238
+ * @param options.code - TypeScript code content to execute
239
+ * @param options.filename - Script filename for error location and context
240
+ * @returns Script execution result, if export is a function then execute and return its return value
241
+ */
169
242
  async function parseCode(options) {
170
- const { imports = [], code, filename } = options;
171
- let jsCode = "";
172
- try {
173
- const tmpCode = `${imports.join("\n")}
174
- export default ${code}`;
175
- jsCode = ts__namespace.transpileModule(tmpCode, {
176
- compilerOptions: {
177
- module: ts__namespace.ModuleKind.CommonJS,
178
- // 生成的模块格式为 CommonJS(Node.js 默认格式)
179
- target: ts__namespace.ScriptTarget.ES2022,
180
- // 编译后的 JavaScript 目标版本
181
- noEmit: true,
182
- // 不生成输出文件
183
- strict: false,
184
- // 关闭所有严格类型检查选项
185
- noImplicitAny: false,
186
- // 允许表达式和 any 类型
187
- strictNullChecks: false,
188
- // 关闭严格的 null 和 undefined 检查
189
- strictFunctionTypes: false,
190
- // 关闭函数参数的严格逆变比较
191
- strictBindCallApply: false,
192
- // 关闭对 bind、call 和 apply 方法的严格类型检查
193
- strictPropertyInitialization: false,
194
- // 关闭类属性初始化的严格检查
195
- noImplicitThis: false,
196
- // 允许 this 表达式具有隐式的 any 类型
197
- alwaysStrict: false,
198
- // 不以严格模式解析并为每个源文件生成 "use strict" 指令
199
- allowJs: true,
200
- // 允许编译 JavaScript 文件
201
- checkJs: false,
202
- // 不检查 JavaScript 文件中的类型
203
- skipLibCheck: true,
204
- // 跳过对 TypeScript 声明文件 (*.d.ts) 的类型检查
205
- esModuleInterop: true,
206
- // 启用 ES 模块互操作性,允许使用 import 导入 CommonJS 模块
207
- removeComments: true
208
- // 删除注释
209
- },
210
- jsDocParsingMode: ts__namespace.JSDocParsingMode.ParseNone
211
- // 不解析 JSDoc
212
- }).outputText;
213
- const dir = path__default.dirname(filename);
214
- const vmContext = {
215
- module: {},
216
- exports: {},
217
- __filename: filename,
218
- __dirname: dir,
219
- require: node_module.createRequire(dir),
220
- import: (id) => import(id),
221
- // 定时器相关
222
- setTimeout,
223
- clearTimeout,
224
- setInterval,
225
- clearInterval,
226
- setImmediate,
227
- clearImmediate,
228
- // 控制台相关
229
- console,
230
- // URL 处理
231
- URL,
232
- URLSearchParams,
233
- // 进程和性能相关
234
- performance,
235
- // 全局对象引用
236
- global: globalThis,
237
- globalThis
238
- };
239
- const script = new vm__default.Script(jsCode, { filename });
240
- await script.runInNewContext(vmContext, {
241
- timeout: 1e3
242
- // 设置超时避免长时间运行
243
- });
244
- const result = vmContext.exports.default || vmContext.exports;
245
- return result;
246
- } catch (error) {
247
- throw new Error(`EXEC SCRIPT FAIL IN ${filename}: ${error.message}
248
-
249
- ${jsCode}
250
-
251
- `);
252
- }
243
+ const { imports = [], code, filename } = options;
244
+ let jsCode = "";
245
+ try {
246
+ const tmpCode = `${imports.join("\n")}\n export default ${code}`;
247
+ jsCode = typescript.transpileModule(tmpCode, {
248
+ compilerOptions: {
249
+ module: typescript.ModuleKind.CommonJS,
250
+ target: typescript.ScriptTarget.ES2022,
251
+ noEmit: true,
252
+ strict: false,
253
+ noImplicitAny: false,
254
+ strictNullChecks: false,
255
+ strictFunctionTypes: false,
256
+ strictBindCallApply: false,
257
+ strictPropertyInitialization: false,
258
+ noImplicitThis: false,
259
+ alwaysStrict: false,
260
+ allowJs: true,
261
+ checkJs: false,
262
+ skipLibCheck: true,
263
+ esModuleInterop: true,
264
+ removeComments: true
265
+ },
266
+ jsDocParsingMode: typescript.JSDocParsingMode.ParseNone
267
+ }).outputText;
268
+ const dir = node_path.default.dirname(filename);
269
+ const vmContext = {
270
+ module: {},
271
+ exports: {},
272
+ __filename: filename,
273
+ __dirname: dir,
274
+ require: (0, node_module.createRequire)(dir),
275
+ import: (id) => import(id),
276
+ setTimeout,
277
+ clearTimeout,
278
+ setInterval,
279
+ clearInterval,
280
+ setImmediate,
281
+ clearImmediate,
282
+ console,
283
+ URL,
284
+ URLSearchParams,
285
+ performance,
286
+ global: globalThis,
287
+ globalThis
288
+ };
289
+ await new node_vm.default.Script(jsCode, { filename }).runInNewContext(vmContext, { timeout: 1e3 });
290
+ return vmContext.exports.default || vmContext.exports;
291
+ } catch (error) {
292
+ throw new Error(`EXEC SCRIPT FAIL IN ${filename}: ${error.message} \n\n${jsCode}\n\n`);
293
+ }
253
294
  }
295
+ /**
296
+ * Async sleep function
297
+ * @param ms - Sleep duration in milliseconds
298
+ * @returns Promise object
299
+ */
254
300
  function sleep(ms) {
255
- return new Promise((resolve) => setTimeout(resolve, ms));
301
+ return new Promise((resolve) => setTimeout(resolve, ms));
256
302
  }
303
+ /**
304
+ * Get default export of a module
305
+ * Compatible with CommonJS and ES Module export styles
306
+ *
307
+ * @param expr - Module object
308
+ * @returns Default export value
309
+ */
257
310
  function getDefaultExport(expr) {
258
- return expr.default === void 0 ? expr : expr.default;
311
+ return expr.default === void 0 ? expr : expr.default;
259
312
  }
260
- const babelGenerate = getDefaultExport(babelGenerator__default);
261
-
313
+ /** Babel code generator for converting AST back to code */
314
+ const babelGenerate = getDefaultExport(_babel_generator.default);
315
+ function stripType(item) {
316
+ const { type, ...rest } = item;
317
+ return rest;
318
+ }
319
+ //#endregion
320
+ //#region src/files.ts
321
+ /**
322
+ * Resolves the files that are valid pages for the given context.
323
+ */
262
324
  function getPageFiles(path, options) {
263
- const { exclude } = options;
264
- const ext = extsToGlob(FILE_EXTENSIONS);
265
- const files = fg__default.sync(`**/*.${ext}`, {
266
- ignore: exclude,
267
- onlyFiles: true,
268
- cwd: path
269
- });
270
- return files;
325
+ const { exclude } = options;
326
+ return (0, tinyglobby.globSync)(`**/*.${extsToGlob(FILE_EXTENSIONS)}`, {
327
+ ignore: exclude,
328
+ onlyFiles: true,
329
+ cwd: path
330
+ });
271
331
  }
332
+ /**
333
+ * Check the pages.json file at the specified path, create an empty pages.json file if it doesn't exist or is not a valid file
334
+ * @param path - File path to check
335
+ * @returns boolean - Whether the operation was successful
336
+ */
272
337
  function checkPagesJsonFileSync(path) {
273
- const createEmptyFile = (path2) => {
274
- try {
275
- fs__default.writeFileSync(
276
- path2,
277
- JSON.stringify({ pages: [{ path: "" }] }, null, 2),
278
- { encoding: "utf-8" }
279
- );
280
- return true;
281
- } catch {
282
- return false;
283
- }
284
- };
285
- const unlinkFile = (path2) => {
286
- try {
287
- fs__default.unlinkSync(path2);
288
- return true;
289
- } catch {
290
- return false;
291
- }
292
- };
293
- try {
294
- try {
295
- fs__default.accessSync(path, fs__default.constants.F_OK);
296
- } catch {
297
- return createEmptyFile(path);
298
- }
299
- const stat = fs__default.statSync(path);
300
- if (!stat.isFile()) {
301
- if (!unlinkFile(path)) {
302
- return false;
303
- }
304
- return createEmptyFile(path);
305
- }
306
- try {
307
- fs__default.accessSync(path, fs__default.constants.R_OK | fs__default.constants.W_OK);
308
- return true;
309
- } catch {
310
- if (!unlinkFile(path)) {
311
- return false;
312
- }
313
- return createEmptyFile(path);
314
- }
315
- } catch {
316
- return createEmptyFile(path);
317
- }
338
+ /**
339
+ * Create an empty pages.json file
340
+ * @param path - File path
341
+ * @returns boolean - Whether the creation was successful
342
+ */
343
+ const createEmptyFile = (path) => {
344
+ try {
345
+ node_fs.default.writeFileSync(path, JSON.stringify({ pages: [{ path: "" }] }, null, 2), { encoding: "utf-8" });
346
+ return true;
347
+ } catch {
348
+ return false;
349
+ }
350
+ };
351
+ /**
352
+ * Delete the file at the specified path
353
+ * @param path - File path
354
+ * @returns boolean - Whether the deletion was successful
355
+ */
356
+ const unlinkFile = (path) => {
357
+ try {
358
+ node_fs.default.unlinkSync(path);
359
+ return true;
360
+ } catch {
361
+ return false;
362
+ }
363
+ };
364
+ try {
365
+ try {
366
+ node_fs.default.accessSync(path, node_fs.default.constants.F_OK);
367
+ } catch {
368
+ return createEmptyFile(path);
369
+ }
370
+ if (!node_fs.default.statSync(path).isFile()) {
371
+ if (!unlinkFile(path)) return false;
372
+ return createEmptyFile(path);
373
+ }
374
+ try {
375
+ node_fs.default.accessSync(path, node_fs.default.constants.R_OK | node_fs.default.constants.W_OK);
376
+ return true;
377
+ } catch {
378
+ if (!unlinkFile(path)) return false;
379
+ return createEmptyFile(path);
380
+ }
381
+ } catch {
382
+ return createEmptyFile(path);
383
+ }
318
384
  }
385
+ /**
386
+ * Safely write file using file lock
387
+ * Avoid data corruption caused by concurrent writes through file lock
388
+ * Use atomic write to ensure file write integrity
389
+ *
390
+ * @param path - File path
391
+ * @param content - File content
392
+ * @param retry - Number of retries when lock acquisition fails, defaults to 3
393
+ */
319
394
  async function writeFileWithLock(path, content, retry = 3) {
320
- if (retry <= 0) {
321
- debug.error(`${path} \u83B7\u53D6\u6587\u4EF6\u9501\u5931\u8D25\uFF0C\u5199\u5165\u5931\u8D25`);
322
- return;
323
- }
324
- let release;
325
- try {
326
- try {
327
- release = await lockfile__default.lock(path, { realpath: false });
328
- } catch {
329
- await sleep(500);
330
- return writeFileWithLock(path, content, retry - 1);
331
- }
332
- await writeFileAtomic__default(path, content);
333
- } finally {
334
- if (release) {
335
- await release();
336
- }
337
- }
395
+ if (retry <= 0) {
396
+ debug$1.error(`${path} Failed to acquire file lock, write failed`);
397
+ return;
398
+ }
399
+ let release;
400
+ try {
401
+ try {
402
+ release = await proper_lockfile.default.lock(path, { realpath: false });
403
+ } catch {
404
+ await sleep(500);
405
+ return writeFileWithLock(path, content, retry - 1);
406
+ }
407
+ await (0, write_file_atomic.default)(path, content);
408
+ } finally {
409
+ if (release) await release();
410
+ }
338
411
  }
339
-
340
- function resolveOptions(userOptions, viteRoot = process__default.cwd()) {
341
- const {
342
- dts = true,
343
- configSource = "pages.config",
344
- homePage = ["pages/index", "pages/index/index"],
345
- mergePages = true,
346
- dir = "src/pages",
347
- subPackages = [],
348
- outDir = "src",
349
- exclude = ["node_modules", ".git", "**/__*__/**"],
350
- routeBlockLang = "json5",
351
- minify = false,
352
- debug = false,
353
- onBeforeLoadUserConfig = () => {
354
- },
355
- onAfterLoadUserConfig = () => {
356
- },
357
- onBeforeScanPages = () => {
358
- },
359
- onAfterScanPages = () => {
360
- },
361
- onBeforeMergePageMetaData = () => {
362
- },
363
- onAfterMergePageMetaData = () => {
364
- },
365
- onBeforeWriteFile = () => {
366
- },
367
- onAfterWriteFile = () => {
368
- }
369
- } = userOptions;
370
- const root = viteRoot || slash(process__default.env.VITE_ROOT_DIR || process__default.cwd());
371
- const resolvedDirs = resolvePageDirs(dir, root, exclude);
372
- const resolvedSubDirs = subPackages.map((dir2) => slash(dir2));
373
- const resolvedHomePage = typeof homePage === "string" ? [homePage] : homePage;
374
- const resolvedConfigSource = typeof configSource === "string" ? [{ files: configSource }] : configSource;
375
- const resolvedDts = !dts ? false : typeof dts === "string" ? dts : path.resolve(viteRoot, "uni-pages.d.ts");
376
- const resolvedOptions = {
377
- dts: resolvedDts,
378
- configSource: Array.isArray(resolvedConfigSource) ? resolvedConfigSource : [resolvedConfigSource],
379
- homePage: resolvedHomePage,
380
- mergePages,
381
- dirs: resolvedDirs,
382
- subPackages: resolvedSubDirs,
383
- outDir,
384
- exclude,
385
- routeBlockLang,
386
- root,
387
- minify,
388
- debug,
389
- onBeforeLoadUserConfig,
390
- onAfterLoadUserConfig,
391
- onBeforeScanPages,
392
- onAfterScanPages,
393
- onBeforeMergePageMetaData,
394
- onAfterMergePageMetaData,
395
- onBeforeWriteFile,
396
- onAfterWriteFile
397
- };
398
- return resolvedOptions;
412
+ //#endregion
413
+ //#region src/options.ts
414
+ /**
415
+ * Resolve user configuration options
416
+ * Merge user-provided configuration with default values and handle path resolution
417
+ *
418
+ * @param userOptions - User configuration options
419
+ * @param viteRoot - Vite project root directory
420
+ * @returns Resolved configuration options
421
+ */
422
+ function resolveOptions(userOptions, viteRoot = node_process.default.cwd()) {
423
+ const { dts = true, configSource = "pages.config", homePage = ["pages/index", "pages/index/index"], mergePages = true, dir = "src/pages", subPackages = [], outDir = "src", exclude = [
424
+ "node_modules",
425
+ ".git",
426
+ "**/__*__/**"
427
+ ], minify = false, debug = false, onBeforeLoadUserConfig = () => {}, onAfterLoadUserConfig = () => {}, onBeforeScanPages = () => {}, onAfterScanPages = () => {}, onBeforeMergePageMetaData = () => {}, onAfterMergePageMetaData = () => {}, onBeforeWriteFile = () => {}, onAfterWriteFile = () => {} } = userOptions;
428
+ const root = viteRoot || slash(node_process.default.env.VITE_ROOT_DIR || node_process.default.cwd());
429
+ const resolvedDirs = resolvePageDirs(dir, root, exclude);
430
+ const subPackageRootMap = /* @__PURE__ */ new Map();
431
+ const resolvedSubDirs = [];
432
+ for (const sub of subPackages) if (typeof sub === "string") resolvedSubDirs.push(slash(sub));
433
+ else {
434
+ const dirPath = slash(sub.dir);
435
+ resolvedSubDirs.push(dirPath);
436
+ subPackageRootMap.set(dirPath, sub.root);
437
+ }
438
+ const resolvedHomePage = typeof homePage === "string" ? [homePage] : homePage;
439
+ const resolvedConfigSource = typeof configSource === "string" ? [{ files: configSource }] : configSource;
440
+ return {
441
+ dts: !dts ? false : typeof dts === "string" ? dts : (0, node_path.resolve)(viteRoot, "uni-pages.d.ts"),
442
+ configSource: Array.isArray(resolvedConfigSource) ? resolvedConfigSource : [resolvedConfigSource],
443
+ homePage: resolvedHomePage,
444
+ mergePages,
445
+ dirs: resolvedDirs,
446
+ subPackages: resolvedSubDirs,
447
+ subPackageRootMap,
448
+ outDir,
449
+ exclude,
450
+ root,
451
+ minify,
452
+ debug,
453
+ onBeforeLoadUserConfig,
454
+ onAfterLoadUserConfig,
455
+ onBeforeScanPages,
456
+ onAfterScanPages,
457
+ onBeforeMergePageMetaData,
458
+ onAfterMergePageMetaData,
459
+ onBeforeWriteFile,
460
+ onAfterWriteFile
461
+ };
399
462
  }
463
+ /**
464
+ * Resolves the page dirs for its for its given globs
465
+ */
400
466
  function resolvePageDirs(dir, root, exclude) {
401
- const dirs = fg__default.sync(slash(dir), {
402
- ignore: exclude,
403
- onlyDirectories: true,
404
- dot: true,
405
- unique: true,
406
- cwd: root
407
- });
408
- return dirs;
409
- }
410
-
411
- function parseCustomBlock(block, filePath, routeBlockLang) {
412
- const lang = block.lang ?? routeBlockLang;
413
- const attr = {
414
- type: "page",
415
- ...block.attrs
416
- };
417
- let content;
418
- debug.routeBlock(`use ${lang} parser`);
419
- if (lang === "json5") {
420
- try {
421
- content = JSON5__default.parse(block.content);
422
- } catch (err) {
423
- throw new Error(
424
- `Invalid JSON5 format of <${block.type}> content in ${filePath}
425
- ${err.message}`
426
- );
427
- }
428
- } else if (lang === "jsonc") {
429
- try {
430
- content = commentJson.parse(block.content);
431
- } catch (err) {
432
- throw new Error(
433
- `Invalid JSONC format of <${block.type}> content in ${filePath}
434
- ${err.message}`
435
- );
436
- }
437
- } else if (lang === "json") {
438
- try {
439
- content = JSON.parse(block.content);
440
- } catch (err) {
441
- throw new Error(
442
- `Invalid JSON format of <${block.type}> content in ${filePath}
443
- ${err.message}`
444
- );
445
- }
446
- } else if (lang === "yaml" || lang === "yml") {
447
- try {
448
- content = yaml.parse(block.content);
449
- } catch (err) {
450
- throw new Error(
451
- `Invalid YAML format of <${block.type}> content in ${filePath}
452
- ${err.message}`
453
- );
454
- }
455
- }
456
- return {
457
- attr,
458
- content: content ?? {}
459
- };
460
- }
461
- function getRouteSfcBlock(sfc) {
462
- return sfc?.customBlocks.find((b) => b.type === "route");
467
+ return (0, tinyglobby.globSync)(slash(dir), {
468
+ ignore: exclude,
469
+ onlyDirectories: true,
470
+ expandDirectories: false,
471
+ dot: true,
472
+ cwd: root
473
+ });
463
474
  }
464
- function getRouteBlock(path, blockStr, routeBlockLang) {
465
- if (!blockStr)
466
- return;
467
- return parseCustomBlock(blockStr, path, routeBlockLang);
468
- }
469
-
470
- var __defProp$1 = Object.defineProperty;
471
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
472
- var __publicField$1 = (obj, key, value) => {
473
- __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
474
- return value;
475
+ //#endregion
476
+ //#region src/page.ts
477
+ /**
478
+ * Page class representing a Vue page file
479
+ *
480
+ * Responsibilities:
481
+ * 1. Read page file content
482
+ * 2. Parse page metadata defined by definePage macro
483
+ * 3. Provide tabBar configuration information
484
+ * 4. Track page file change status
485
+ */
486
+ var Page = class {
487
+ /** Page context instance */
488
+ ctx;
489
+ /** Page path information containing relative and absolute paths */
490
+ path;
491
+ /** Page URI used for pages.json path field */
492
+ uri;
493
+ /** Whether the page has changed, used for incremental update judgment */
494
+ changed = true;
495
+ /** Raw JSON string of page metadata for change detection */
496
+ raw = "";
497
+ /** Parsed page metadata */
498
+ meta;
499
+ /**
500
+ * Create a page instance
501
+ * @param ctx - Page context instance
502
+ * @param path - Page path information
503
+ */
504
+ constructor(ctx, path) {
505
+ this.ctx = ctx;
506
+ this.path = path;
507
+ this.uri = (0, vite.normalizePath)(path.relativePath.replace((0, node_path.extname)(path.relativePath), ""));
508
+ }
509
+ /**
510
+ * Get page metadata
511
+ * Parse configuration defined by definePage macro and return metadata for pages.json
512
+ *
513
+ * @param forceUpdate - Whether to force update, ignoring cache
514
+ * @returns Page metadata object
515
+ */
516
+ async getPageMeta(forceUpdate = false) {
517
+ if (forceUpdate || !this.meta) await this.read();
518
+ const { path, tabBar: _, ...others } = this.meta || {};
519
+ return {
520
+ path: path ?? this.uri,
521
+ ...others
522
+ };
523
+ }
524
+ /**
525
+ * Get page tabBar configuration
526
+ * Extract tabBar related configuration from definePage macro
527
+ *
528
+ * @param forceUpdate - Whether to force update, ignoring cache
529
+ * @returns tabBar configuration object, or undefined if page doesn't define tabBar
530
+ */
531
+ async getTabBar(forceUpdate = false) {
532
+ if (forceUpdate || !this.meta) await this.read();
533
+ const { tabBar } = this.meta || {};
534
+ if (tabBar === void 0) return;
535
+ return {
536
+ ...tabBar,
537
+ pagePath: tabBar.pagePath || this.uri,
538
+ index: tabBar.index ?? 0
539
+ };
540
+ }
541
+ /**
542
+ * Check if the page has changed
543
+ * @returns Whether the page has changed
544
+ */
545
+ hasChanged() {
546
+ return this.changed;
547
+ }
548
+ /**
549
+ * Read page file and parse metadata
550
+ * Extract configuration defined by definePage macro from Vue SFC
551
+ */
552
+ async read() {
553
+ let meta;
554
+ try {
555
+ meta = await this.readPageMetaFromFile();
556
+ } catch (err) {
557
+ debug$1.error(err);
558
+ return;
559
+ }
560
+ let raw = "";
561
+ try {
562
+ raw = JSON.stringify(meta);
563
+ } catch {}
564
+ this.changed = this.raw !== raw;
565
+ this.meta = meta;
566
+ this.raw = raw;
567
+ }
568
+ async readPageMetaFromFile() {
569
+ try {
570
+ const meta = await tryPageMetaFromMacro(parseSFC(await node_fs.default.promises.readFile(this.path.absolutePath, { encoding: "utf-8" }), { filename: this.path.absolutePath }));
571
+ if (meta) return meta;
572
+ return { type: "page" };
573
+ } catch (err) {
574
+ throw new Error(`Read page meta fail in ${this.path.relativePath}\n${err.message}`);
575
+ }
576
+ }
475
577
  };
476
- class Page {
477
- constructor(ctx, path$1) {
478
- __publicField$1(this, "ctx");
479
- __publicField$1(this, "path");
480
- __publicField$1(this, "uri");
481
- __publicField$1(this, "changed", true);
482
- __publicField$1(this, "raw", "");
483
- __publicField$1(this, "meta");
484
- this.ctx = ctx;
485
- this.path = path$1;
486
- this.uri = vite.normalizePath(path$1.relativePath.replace(path.extname(path$1.relativePath), ""));
487
- }
488
- async getPageMeta(forceUpdate = false) {
489
- if (forceUpdate || !this.meta) {
490
- await this.read();
491
- }
492
- const { path, tabBar: _, ...others } = this.meta || {};
493
- return {
494
- path: path ?? this.uri,
495
- ...others
496
- };
497
- }
498
- async getTabBar(forceUpdate = false) {
499
- if (forceUpdate || !this.meta) {
500
- await this.read();
501
- }
502
- const { tabBar } = this.meta || {};
503
- if (tabBar === void 0) {
504
- return void 0;
505
- }
506
- return {
507
- ...tabBar,
508
- pagePath: tabBar.pagePath || this.uri,
509
- index: tabBar.index || 0
510
- };
511
- }
512
- hasChanged() {
513
- return this.changed;
514
- }
515
- async read() {
516
- let meta;
517
- try {
518
- meta = await this.readPageMetaFromFile();
519
- } catch (err) {
520
- debug.error(err);
521
- return;
522
- }
523
- let raw = "";
524
- try {
525
- raw = JSON.stringify(meta);
526
- } catch {
527
- }
528
- this.changed = this.raw !== raw;
529
- this.meta = meta;
530
- this.raw = raw;
531
- }
532
- async readPageMetaFromFile() {
533
- try {
534
- const content = await fs__default.promises.readFile(this.path.absolutePath, { encoding: "utf-8" });
535
- const sfc = parseSFC(content, { filename: this.path.absolutePath });
536
- const meta = await tryPageMetaFromMacro(sfc);
537
- if (meta) {
538
- return meta;
539
- }
540
- return tryPageMetaFromCustomBlock(sfc, this.ctx.options.routeBlockLang);
541
- } catch (err) {
542
- throw new Error(`Read page meta fail in ${this.path.relativePath}
543
- ${err.message}`);
544
- }
545
- }
546
- }
578
+ /**
579
+ * Parse Vue Single File Component (SFC)
580
+ * Compatible with different versions of @vue/compiler-sfc
581
+ *
582
+ * @param code - Vue SFC source code
583
+ * @param options - Parse options
584
+ * @returns SFC descriptor object
585
+ */
547
586
  function parseSFC(code, options) {
548
- return compilerSfc.parse(code, {
549
- pad: "space",
550
- ...options
551
- }).descriptor || compilerSfc.parse({
552
- source: code,
553
- ...options
554
- });
587
+ return (0, _vue_compiler_sfc.parse)(code, {
588
+ pad: "space",
589
+ ...options
590
+ }).descriptor || (0, _vue_compiler_sfc.parse)({
591
+ source: code,
592
+ ...options
593
+ });
555
594
  }
595
+ /**
596
+ * Try to extract page metadata defined by definePage macro from SFC
597
+ * Support using definePage in script setup or regular script
598
+ *
599
+ * @param sfc - Vue SFC descriptor
600
+ * @returns Page metadata object, or undefined if definePage is not found
601
+ */
556
602
  async function tryPageMetaFromMacro(sfc) {
557
- const sfcScript = sfc.scriptSetup || sfc.script;
558
- if (!sfcScript) {
559
- return void 0;
560
- }
561
- const ast = astKit.babelParse(sfcScript.content, sfcScript.lang || "js", {
562
- plugins: [["importAttributes", { deprecatedAssertSyntax: true }]]
563
- });
564
- const macro = findMacro(ast.body, sfc.filename);
565
- if (macro) {
566
- const imports = findImports(ast.body).filter((imp) => !!imp.specifiers.length).map((imp) => babelGenerate(imp).code);
567
- const [macroOption] = macro.arguments;
568
- const code = babelGenerate(macroOption).code;
569
- const parsed = await parseCode({
570
- imports,
571
- code,
572
- filename: sfc.filename
573
- });
574
- const res = typeof parsed === "function" ? await Promise.resolve(parsed()) : await Promise.resolve(parsed);
575
- return {
576
- type: "page",
577
- ...res
578
- };
579
- }
580
- return void 0;
581
- }
582
- async function tryPageMetaFromCustomBlock(sfc, routeBlockLang) {
583
- const block = getRouteSfcBlock(sfc);
584
- const routeBlock = getRouteBlock(sfc.filename, block, routeBlockLang);
585
- const pageMeta = {
586
- type: routeBlock?.attr.type ?? "page"
587
- };
588
- if (routeBlock) {
589
- try {
590
- commentJson.assign(pageMeta, routeBlock.content);
591
- } catch {
592
- }
593
- }
594
- return pageMeta;
603
+ const sfcScript = sfc.scriptSetup || sfc.script;
604
+ if (!sfcScript) return;
605
+ const ast = (0, ast_kit.babelParse)(sfcScript.content, sfcScript.lang || "js", { plugins: [["importAttributes", { deprecatedAssertSyntax: true }]] });
606
+ const macro = findMacro(ast.body, sfc.filename);
607
+ if (macro) {
608
+ const imports = findImports(ast.body).filter((imp) => !!imp.specifiers.length).map((imp) => babelGenerate(imp).code);
609
+ const [macroOption] = macro.arguments;
610
+ const code = babelGenerate(macroOption).code;
611
+ const parsed = await parseCode({
612
+ imports,
613
+ code,
614
+ filename: sfc.filename
615
+ });
616
+ return {
617
+ type: "page",
618
+ ...typeof parsed === "function" ? await Promise.resolve(parsed()) : await Promise.resolve(parsed)
619
+ };
620
+ }
595
621
  }
622
+ /**
623
+ * Find definePage macro call in AST
624
+ * Support function expressions, arrow functions and object expressions as arguments
625
+ *
626
+ * @param stmts - AST statement array
627
+ * @param filename - Filename for error reporting
628
+ * @returns definePage call expression, or undefined if not found
629
+ */
596
630
  function findMacro(stmts, filename) {
597
- let macro;
598
- for (const stmt of stmts) {
599
- let node = stmt;
600
- if (stmt.type === "ExpressionStatement")
601
- node = stmt.expression;
602
- if (astKit.isCallOf(node, "definePage")) {
603
- macro = node;
604
- break;
605
- }
606
- }
607
- if (!macro)
608
- return;
609
- const [opt] = macro.arguments;
610
- if (opt && !t__namespace.isFunctionExpression(opt) && !t__namespace.isArrowFunctionExpression(opt) && !t__namespace.isObjectExpression(opt)) {
611
- debug.definePage(`definePage() \u53C2\u6570\u4EC5\u652F\u6301\u51FD\u6570\u6216\u5BF9\u8C61\uFF1A${filename}`);
612
- return;
613
- }
614
- return macro;
631
+ let macro;
632
+ for (const stmt of stmts) {
633
+ let node = stmt;
634
+ if (stmt.type === "ExpressionStatement") node = stmt.expression;
635
+ if ((0, ast_kit.isCallOf)(node, "definePage")) {
636
+ macro = node;
637
+ break;
638
+ }
639
+ }
640
+ if (!macro) return;
641
+ const [opt] = macro.arguments;
642
+ if (opt && !_babel_types.isFunctionExpression(opt) && !_babel_types.isArrowFunctionExpression(opt) && !_babel_types.isObjectExpression(opt)) {
643
+ debug$1.definePage(`definePage() 参数仅支持函数或对象:${filename}`);
644
+ return;
645
+ }
646
+ return macro;
615
647
  }
648
+ /**
649
+ * Extract all import declarations from AST
650
+ * Used to provide necessary imports when executing definePage arguments
651
+ *
652
+ * @param stmts - AST statement array
653
+ * @returns Import declaration array
654
+ */
616
655
  function findImports(stmts) {
617
- const imports = [];
618
- for (const stmt of stmts) {
619
- if (t__namespace.isImportDeclaration(stmt)) {
620
- imports.push(stmt);
621
- }
622
- }
623
- return imports;
656
+ const imports = [];
657
+ for (const stmt of stmts) if (_babel_types.isImportDeclaration(stmt)) imports.push(stmt);
658
+ return imports;
624
659
  }
625
-
626
- var __defProp = Object.defineProperty;
627
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
628
- var __publicField = (obj, key, value) => {
629
- __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
630
- return value;
660
+ //#endregion
661
+ //#region src/context.ts
662
+ /**
663
+ * Page context class responsible for page scanning, config loading, page metadata merging and pages.json generation
664
+ *
665
+ * Core responsibilities:
666
+ * 1. Scan page directories and collect page files
667
+ * 2. Load user configuration files (pages.config.ts, etc.)
668
+ * 3. Parse page metadata (definePage macro)
669
+ * 4. Merge page configurations and generate pages.json
670
+ * 5. Provide virtual module and HMR support
671
+ */
672
+ var PageContext = class {
673
+ _server;
674
+ /** Parsed configuration object from user config file (pages.config.ts) */
675
+ pagesGlobConfig;
676
+ /** Source path list of user configuration files */
677
+ pagesConfigSourcePaths = [];
678
+ /** Main package page map, key is the absolute path of the page file */
679
+ pages = /* @__PURE__ */ new Map();
680
+ /** Sub-package page map, key is the sub-package root directory, value is the page map under that sub-package */
681
+ subPages = /* @__PURE__ */ new Map();
682
+ /** Main package page metadata array for generating pages.json pages field */
683
+ pageMetaData = [];
684
+ /** Sub-package page metadata array for generating pages.json subPackages field */
685
+ subPageMetaData = [];
686
+ /** Generated pages.json file path */
687
+ resolvedPagesJSONPath = "";
688
+ resolvedPagesJSONIndent;
689
+ resolvedPagesJSONNewline;
690
+ resolvedPagesJSONEofNewline;
691
+ /** Original options passed by the user */
692
+ rawOptions;
693
+ /** Project root directory */
694
+ root;
695
+ /** Resolved configuration options */
696
+ options;
697
+ logger;
698
+ /** Whether to work with vite-plugin-uni-platform plugin */
699
+ withUniPlatform = false;
700
+ /** Cached previous pages.json content to avoid redundant writes */
701
+ lastPagesJson = "";
702
+ /**
703
+ * Create a PageContext instance
704
+ * @param userOptions - User configuration options
705
+ * @param viteRoot - Vite project root directory, defaults to current working directory
706
+ */
707
+ constructor(userOptions, viteRoot = node_process.default.cwd()) {
708
+ this.rawOptions = userOptions;
709
+ this.root = slash(viteRoot);
710
+ debug$1.options("root", this.root);
711
+ this.options = resolveOptions(userOptions, this.root);
712
+ const debugOption = this.options.debug;
713
+ if (debugOption) {
714
+ const prefix = "vite-plugin-uni-pages:";
715
+ const suffix = typeof debugOption === "boolean" ? "*" : debugOption;
716
+ debug.default.enable(`${prefix}${suffix}`);
717
+ }
718
+ this.resolvedPagesJSONPath = node_path.default.join(this.root, this.options.outDir, OUTPUT_NAME);
719
+ debug$1.options(this.options);
720
+ }
721
+ /**
722
+ * Set the Vite logger
723
+ * @param logger - Vite logger instance
724
+ */
725
+ setLogger(logger) {
726
+ this.logger = logger;
727
+ }
728
+ /**
729
+ * Load user page configuration file (e.g. pages.config.ts)
730
+ * Uses unconfig to load configuration, supporting multiple config file formats
731
+ */
732
+ async loadUserPagesConfig() {
733
+ const configSource = this.options.configSource;
734
+ const { config, sources } = await (0, unconfig.loadConfig)({
735
+ cwd: this.root,
736
+ sources: configSource,
737
+ defaults: {}
738
+ });
739
+ this.pagesGlobConfig = config.default || config;
740
+ this.pagesConfigSourcePaths = sources;
741
+ debug$1.options(this.pagesGlobConfig);
742
+ }
743
+ /**
744
+ * Scan main package page directories and collect all page file paths
745
+ * Scan corresponding directories based on the configured dirs option
746
+ */
747
+ async scanPages() {
748
+ const paths = this.options.dirs.map((dir) => {
749
+ return {
750
+ dir,
751
+ files: getPagePaths(dir, this.options)
752
+ };
753
+ }).map((page) => page.files).flat();
754
+ debug$1.pages(paths);
755
+ const pages = /* @__PURE__ */ new Map();
756
+ for (const path of paths) {
757
+ const page = this.pages.get(path.absolutePath) || new Page(this, path);
758
+ pages.set(path.absolutePath, page);
759
+ }
760
+ this.pages = pages;
761
+ }
762
+ /**
763
+ * Scan sub-package page directories and collect all sub-package page file paths
764
+ * Scan corresponding directories based on the configured subPackages option
765
+ */
766
+ async scanSubPages() {
767
+ const paths = {};
768
+ const subPages = /* @__PURE__ */ new Map();
769
+ for (const dir of this.options.subPackages) {
770
+ const pagePaths = getPagePaths(dir, this.options);
771
+ paths[dir] = pagePaths;
772
+ const pages = /* @__PURE__ */ new Map();
773
+ for (const path of pagePaths) {
774
+ const page = this.subPages.get(dir)?.get(path.absolutePath) || new Page(this, path);
775
+ pages.set(path.absolutePath, page);
776
+ }
777
+ subPages.set(dir, pages);
778
+ }
779
+ debug$1.subPages(JSON.stringify(paths, null, 2));
780
+ this.subPages = subPages;
781
+ }
782
+ /**
783
+ * Set up Vite dev server for HMR and file watching
784
+ * @param server - Vite dev server instance
785
+ */
786
+ setupViteServer(server) {
787
+ if (this._server === server) return;
788
+ this._server = server;
789
+ this.setupWatcher(server.watcher);
790
+ }
791
+ /**
792
+ * Set up file watcher to monitor page file and config file changes
793
+ * Automatically update pages.json when page files or config files change
794
+ * @param watcher - chokidar file watcher instance
795
+ */
796
+ async setupWatcher(watcher) {
797
+ watcher.add(this.pagesConfigSourcePaths);
798
+ const targetDirs = [...this.options.dirs, ...this.options.subPackages].map((v) => slash(node_path.default.resolve(this.root, v)));
799
+ const isInTargetDirs = (filePath) => targetDirs.some((v) => slash(node_path.default.resolve(this.root, filePath)).startsWith(v));
800
+ watcher.on("add", async (path) => {
801
+ path = slash(path);
802
+ if (!isTargetFile(path)) return;
803
+ if (!isInTargetDirs(path)) return;
804
+ debug$1.pages(`File added: ${path}`);
805
+ if (await this.updatePagesJSON()) this.onUpdate();
806
+ });
807
+ watcher.on("change", async (path) => {
808
+ path = slash(path);
809
+ if (!isTargetFile(path)) return;
810
+ if (!isInTargetDirs(path)) return;
811
+ debug$1.pages(`File changed: ${path}`);
812
+ debug$1.pages(targetDirs);
813
+ debug$1.pages(isInTargetDirs(path));
814
+ if (await this.updatePagesJSON(path)) this.onUpdate();
815
+ });
816
+ watcher.on("change", async (path) => {
817
+ if (this.pagesConfigSourcePaths.includes(path)) {
818
+ debug$1.pages(`Config source changed: ${path}`);
819
+ if (await this.updatePagesJSON()) this.onUpdate();
820
+ }
821
+ });
822
+ watcher.on("unlink", async (path) => {
823
+ path = slash(path);
824
+ if (!isTargetFile(path)) return;
825
+ if (!isInTargetDirs(path)) return;
826
+ debug$1.pages(`File removed: ${path}`);
827
+ if (await this.updatePagesJSON()) this.onUpdate();
828
+ });
829
+ }
830
+ /**
831
+ * Page update callback, triggered when page files or configuration changes
832
+ * Responsible for invalidating virtual modules and notifying the browser to do a full reload
833
+ */
834
+ onUpdate() {
835
+ if (!this._server) return;
836
+ invalidatePagesModule(this._server);
837
+ debug$1.hmr("Reload generated pages.");
838
+ this._server.ws.send({ type: "full-reload" });
839
+ }
840
+ /**
841
+ * parse pages rules && set page type
842
+ * @param pages page path array
843
+ * @param type page type
844
+ * @param overrides custom page config
845
+ * @returns pages rules
846
+ */
847
+ async parsePages(pages, type, overrides) {
848
+ const jobs = [];
849
+ for (const [_, page] of pages) jobs.push(page.getPageMeta());
850
+ const generatedPageMetaData = await Promise.all(jobs);
851
+ const customPageMetaData = overrides || [];
852
+ const result = customPageMetaData.length ? mergePageMetaDataArray(generatedPageMetaData.concat(customPageMetaData)) : generatedPageMetaData;
853
+ const parseMeta = Array.from(result.reduce((map, page) => {
854
+ map.set(page.path, page);
855
+ return map;
856
+ }, /* @__PURE__ */ new Map()).values());
857
+ return type === "main" ? this.setHomePage(parseMeta) : parseMeta;
858
+ }
859
+ /**
860
+ * set home page
861
+ * @param result pages rules array
862
+ * @returns pages rules
863
+ */
864
+ setHomePage(result) {
865
+ if (!result.some(({ type }) => type === "home")) {
866
+ const basePath = slash(node_path.default.join(this.options.root, this.options.outDir));
867
+ const resolvedHomePages = this.options.homePage.map((v) => {
868
+ return slash(node_path.default.relative(basePath, slash(node_path.default.resolve(basePath, v))));
869
+ });
870
+ const matchHomePage = (itemPath, configPath) => {
871
+ if (itemPath === configPath) return true;
872
+ const normalizedItem = itemPath.replace(/\\/g, "/");
873
+ const normalizedConfig = configPath.replace(/\\/g, "/");
874
+ return normalizedItem.endsWith(`/${normalizedConfig}`);
875
+ };
876
+ if (!result.some((item) => {
877
+ const isFound = resolvedHomePages.some((expectedPath) => matchHomePage(item.path, expectedPath));
878
+ if (isFound) item.type = "home";
879
+ return isFound;
880
+ })) this.logger?.warn("No home page found, check the configuration of pages.config.ts, or add the `homePage` option to UniPages in vite.config.js, or add `definePage({ type: \"home\" })` in your vue page.", { timestamp: true });
881
+ }
882
+ result.sort((page) => page.type === "home" ? -1 : 0);
883
+ return result;
884
+ }
885
+ /**
886
+ * Merge main package page metadata
887
+ * Filter out pages belonging to sub-packages, then parse page metadata and merge user configuration
888
+ */
889
+ async mergePageMetaData() {
890
+ const subPageAbsolutePaths = Array.from(this.subPages.values()).flatMap((v) => Array.from(v.keys()));
891
+ for (const subPageAbsolutePath of subPageAbsolutePaths) this.pages.delete(subPageAbsolutePath);
892
+ const pageMetaData = await this.parsePages(this.pages, "main", this.pagesGlobConfig?.pages);
893
+ this.pageMetaData = pageMetaData;
894
+ debug$1.pages(this.pageMetaData);
895
+ }
896
+ /**
897
+ * Merge sub-package page metadata
898
+ * Parse page metadata for each sub-package and handle sub-package configuration inheritance
899
+ * Preserves sub-package level properties like plugins from user config
900
+ */
901
+ async mergeSubPageMetaData() {
902
+ const subPageMaps = {};
903
+ const subPlugins = {};
904
+ const subPackages = this.pagesGlobConfig?.subPackages || [];
905
+ for (const [dir, pages] of this.subPages) {
906
+ const basePath = slash(node_path.default.join(this.options.root, this.options.outDir));
907
+ const root = this.options.subPackageRootMap.get(dir) ?? slash(node_path.default.relative(basePath, node_path.default.join(this.options.root, dir)));
908
+ const globPackage = subPackages?.find((v) => v.root === root);
909
+ subPageMaps[root] = await this.parsePages(pages, "sub", globPackage?.pages);
910
+ subPageMaps[root] = subPageMaps[root].map((page) => ({
911
+ ...page,
912
+ path: slash(node_path.default.relative(root, page.path))
913
+ }));
914
+ if (globPackage?.plugins) subPlugins[root] = globPackage.plugins;
915
+ }
916
+ for (const { root, pages, plugins } of subPackages) if (root && !subPageMaps[root]) {
917
+ subPageMaps[root] = pages || [];
918
+ if (plugins) subPlugins[root] = plugins;
919
+ }
920
+ const subPageMetaData = Object.keys(subPageMaps).map((root) => ({
921
+ root,
922
+ pages: subPageMaps[root],
923
+ ...subPlugins[root] && { plugins: subPlugins[root] }
924
+ })).filter((meta) => meta.pages.length > 0);
925
+ this.subPageMetaData = subPageMetaData;
926
+ debug$1.subPages(this.subPageMetaData);
927
+ }
928
+ /**
929
+ * Update pages.json file
930
+ * This is the core method responsible for coordinating the entire page configuration generation flow:
931
+ * 1. Check file changes (if filepath is specified)
932
+ * 2. Load user configuration
933
+ * 3. Scan page files
934
+ * 4. Merge page metadata
935
+ * 5. Generate and write pages.json
936
+ * @param filepath - Changed file path for incremental update judgment
937
+ * @returns Whether pages.json was successfully updated
938
+ */
939
+ async updatePagesJSON(filepath) {
940
+ if (filepath) {
941
+ let page = this.pages.get(filepath);
942
+ if (!page) {
943
+ let subPage;
944
+ for (const [_, pages] of this.subPages) {
945
+ subPage = pages.get(filepath);
946
+ if (subPage) break;
947
+ }
948
+ page = subPage;
949
+ }
950
+ if (page) {
951
+ await page.read();
952
+ if (!page.hasChanged()) {
953
+ debug$1.cache(`The page meta on page ${filepath} did not send any changes, skipping`);
954
+ return false;
955
+ }
956
+ }
957
+ }
958
+ checkPagesJsonFileSync(this.resolvedPagesJSONPath);
959
+ this.options.onBeforeLoadUserConfig(this);
960
+ await this.loadUserPagesConfig();
961
+ this.options.onAfterLoadUserConfig(this);
962
+ if (this.options.mergePages) {
963
+ this.options.onBeforeScanPages(this);
964
+ await this.scanPages();
965
+ await this.scanSubPages();
966
+ this.options.onAfterScanPages(this);
967
+ }
968
+ this.options.onBeforeMergePageMetaData(this);
969
+ await this.mergePageMetaData();
970
+ await this.mergeSubPageMetaData();
971
+ this.options.onAfterMergePageMetaData(this);
972
+ const pagesMap = /* @__PURE__ */ new Map();
973
+ (this.withUniPlatform ? this.pageMetaData.filter((v) => !/\..*$/.test(v.path) || v.path.includes(_uni_helper_uni_env.platform)).map((v) => {
974
+ v.path = v.path.replace(/\..*$/, "");
975
+ return v;
976
+ }) : this.pageMetaData).forEach((v) => pagesMap.set(v.path, v));
977
+ this.pageMetaData = [...pagesMap.values()];
978
+ this.options.onBeforeWriteFile(this);
979
+ const pagesJson = (0, comment_json.stringify)(await this.genratePagesJSON(), null, this.options.minify ? void 0 : await this.getIndent()) + (await this.getEndOfLine() ? await this.getNewline() : "");
980
+ this.generateDeclaration();
981
+ if (this.lastPagesJson === pagesJson) {
982
+ debug$1.pages("PagesJson Not have change");
983
+ return false;
984
+ }
985
+ await writeFileWithLock(this.resolvedPagesJSONPath, pagesJson);
986
+ this.lastPagesJson = pagesJson;
987
+ this.options.onAfterWriteFile(this);
988
+ return true;
989
+ }
990
+ /**
991
+ * Generate virtual module content
992
+ * Returns JavaScript code containing pages and subPackages exports
993
+ * @returns Virtual module code string
994
+ */
995
+ virtualModule() {
996
+ return [`export const pages = ${this.resolveRoutes()};`, `export const subPackages = ${this.resolveSubRoutes()};`].join("\n");
997
+ }
998
+ /**
999
+ * Resolve main package route data to JSON string
1000
+ * @returns JSON string of main package page metadata
1001
+ */
1002
+ resolveRoutes() {
1003
+ return (0, comment_json.stringify)(this.pageMetaData.map(stripType), null, 2);
1004
+ }
1005
+ /**
1006
+ * Resolve sub-package route data to JSON string
1007
+ * @returns JSON string of sub-package page metadata
1008
+ */
1009
+ resolveSubRoutes() {
1010
+ return (0, comment_json.stringify)(this.subPageMetaData.map(({ pages, ...rest }) => ({
1011
+ ...rest,
1012
+ pages: pages.map(stripType)
1013
+ })), null, 2);
1014
+ }
1015
+ /**
1016
+ * Resolve tabBar configuration
1017
+ * Merges page-defined tabBar items with config-defined tabBar
1018
+ * @returns Merged tabBar configuration object, or undefined if no tabBar exists
1019
+ */
1020
+ async resolveTabBar() {
1021
+ const tabBarItems = [];
1022
+ for (const [_, page] of this.pages) {
1023
+ const tabbar = await page.getTabBar();
1024
+ if (tabbar) tabBarItems.push(tabbar);
1025
+ }
1026
+ if (tabBarItems.length === 0) return this.pagesGlobConfig?.tabBar;
1027
+ const tabBar = {
1028
+ ...this.pagesGlobConfig?.tabBar,
1029
+ list: this.pagesGlobConfig?.tabBar?.list || []
1030
+ };
1031
+ const pagePaths = /* @__PURE__ */ new Map();
1032
+ for (const item of tabBar.list) pagePaths.set(item.pagePath, true);
1033
+ tabBarItems.sort((a, b) => a.index - b.index);
1034
+ for (const item of tabBarItems) if (!pagePaths.has(item.pagePath)) {
1035
+ const { index: _, ...tabbar } = item;
1036
+ tabBar.list.push(tabbar);
1037
+ }
1038
+ return tabBar;
1039
+ }
1040
+ /**
1041
+ * Generate TypeScript declaration file
1042
+ * Generate type definitions for page paths to provide type hints during navigation
1043
+ */
1044
+ generateDeclaration() {
1045
+ if (!this.options.dts) return;
1046
+ debug$1.declaration("generating");
1047
+ return writeDeclaration(this, this.options.dts);
1048
+ }
1049
+ async genratePagesJSON() {
1050
+ const { pages: oldPages, subPackages: oldSubPackages, tabBar: oldTabBar } = (0, comment_json.parse)(await node_fs.default.promises.readFile(this.resolvedPagesJSONPath, { encoding: "utf-8" }).catch(() => "") || "{}");
1051
+ const { pages: _pages, subPackages: _subPackages, tabBar: _tabBar, ...pageJson } = this.pagesGlobConfig || {};
1052
+ const currentPlatform = _uni_helper_uni_env.platform.toUpperCase();
1053
+ pageJson.pages = mergePlatformItems(oldPages, currentPlatform, this.pageMetaData, "path").map(stripType);
1054
+ if (pageJson.pages && pageJson.pages.length > 0) {
1055
+ const pagesArray = pageJson.pages;
1056
+ const homeIndex = pagesArray.findIndex((page) => page.type === "home");
1057
+ if (homeIndex > 0) {
1058
+ const [homePage] = pagesArray.splice(homeIndex, 1);
1059
+ pagesArray.unshift(homePage);
1060
+ }
1061
+ }
1062
+ pageJson.subPackages = oldSubPackages || new comment_json.CommentArray();
1063
+ const newSubPackages = /* @__PURE__ */ new Map();
1064
+ for (const item of this.subPageMetaData) newSubPackages.set(item.root, item);
1065
+ for (const existing of pageJson.subPackages) {
1066
+ const sub = newSubPackages.get(existing.root);
1067
+ if (sub) {
1068
+ existing.pages = mergePlatformItems(existing.pages, currentPlatform, sub.pages, "path").map(stripType);
1069
+ if (sub.plugins) existing.plugins = sub.plugins;
1070
+ newSubPackages.delete(existing.root);
1071
+ }
1072
+ }
1073
+ for (const [_, newSub] of newSubPackages) {
1074
+ const subPackage = {
1075
+ root: newSub.root,
1076
+ pages: mergePlatformItems(void 0, currentPlatform, newSub.pages, "path").map(stripType)
1077
+ };
1078
+ if (newSub.plugins) subPackage.plugins = newSub.plugins;
1079
+ pageJson.subPackages.push(subPackage);
1080
+ }
1081
+ const { list, ...tabBarOthers } = await this.resolveTabBar() || {};
1082
+ if (list) {
1083
+ const { list: oldList } = oldTabBar || {};
1084
+ const newList = mergePlatformItems(oldList, currentPlatform, list, "pagePath");
1085
+ pageJson.tabBar = {
1086
+ ...tabBarOthers,
1087
+ list: newList
1088
+ };
1089
+ } else pageJson.tabBar = void 0;
1090
+ return pageJson;
1091
+ }
1092
+ async readInfoFromPagesJSON() {
1093
+ const resolvedPagesJSONContent = await node_fs.default.promises.readFile(this.resolvedPagesJSONPath, { encoding: "utf-8" }).catch(() => "");
1094
+ this.resolvedPagesJSONIndent = (0, detect_indent.default)(resolvedPagesJSONContent).indent || " ";
1095
+ this.resolvedPagesJSONNewline = (0, detect_newline.default)(resolvedPagesJSONContent) || "\n";
1096
+ this.resolvedPagesJSONEofNewline = (resolvedPagesJSONContent.at(-1) ?? "\n") === this.resolvedPagesJSONNewline;
1097
+ }
1098
+ async getIndent() {
1099
+ if (!this.resolvedPagesJSONIndent) await this.readInfoFromPagesJSON();
1100
+ return this.resolvedPagesJSONIndent;
1101
+ }
1102
+ async getNewline() {
1103
+ if (!this.resolvedPagesJSONNewline) await this.readInfoFromPagesJSON();
1104
+ return this.resolvedPagesJSONNewline;
1105
+ }
1106
+ async getEndOfLine() {
1107
+ if (!this.resolvedPagesJSONEofNewline) await this.readInfoFromPagesJSON();
1108
+ return this.resolvedPagesJSONEofNewline;
1109
+ }
631
1110
  };
632
- class PageContext {
633
- constructor(userOptions, viteRoot = process__default.cwd()) {
634
- __publicField(this, "_server");
635
- __publicField(this, "pagesGlobConfig");
636
- __publicField(this, "pagesConfigSourcePaths", []);
637
- __publicField(this, "pages", /* @__PURE__ */ new Map());
638
- // abs path -> Page
639
- __publicField(this, "subPages", /* @__PURE__ */ new Map());
640
- // root -> abs path -> page
641
- __publicField(this, "pageMetaData", []);
642
- __publicField(this, "subPageMetaData", []);
643
- __publicField(this, "resolvedPagesJSONPath", "");
644
- __publicField(this, "resolvedPagesJSONIndent");
645
- // ' '
646
- __publicField(this, "resolvedPagesJSONNewline");
647
- // '\n'
648
- __publicField(this, "resolvedPagesJSONEofNewline");
649
- // true
650
- __publicField(this, "rawOptions");
651
- __publicField(this, "root");
652
- __publicField(this, "options");
653
- __publicField(this, "logger");
654
- __publicField(this, "withUniPlatform", false);
655
- __publicField(this, "lastPagesJson", "");
656
- this.rawOptions = userOptions;
657
- this.root = slash(viteRoot);
658
- debug.options("root", this.root);
659
- this.options = resolveOptions(userOptions, this.root);
660
- const debugOption = this.options.debug;
661
- if (debugOption) {
662
- const prefix = "vite-plugin-uni-pages:";
663
- const suffix = typeof debugOption === "boolean" ? "*" : debugOption;
664
- Debug__default.enable(`${prefix}${suffix}`);
665
- }
666
- this.resolvedPagesJSONPath = path__default.join(this.root, this.options.outDir, OUTPUT_NAME);
667
- debug.options(this.options);
668
- }
669
- setLogger(logger) {
670
- this.logger = logger;
671
- }
672
- async loadUserPagesConfig() {
673
- const configSource = this.options.configSource;
674
- const { config, sources } = await unconfig.loadConfig({ cwd: this.root, sources: configSource, defaults: {} });
675
- this.pagesGlobConfig = config.default || config;
676
- this.pagesConfigSourcePaths = sources;
677
- debug.options(this.pagesGlobConfig);
678
- }
679
- async scanPages() {
680
- const pageDirFiles = this.options.dirs.map((dir) => {
681
- return { dir, files: getPagePaths(dir, this.options) };
682
- });
683
- const paths = pageDirFiles.map((page) => page.files).flat();
684
- debug.pages(paths);
685
- const pages = /* @__PURE__ */ new Map();
686
- for (const path2 of paths) {
687
- const page = this.pages.get(path2.absolutePath) || new Page(this, path2);
688
- pages.set(path2.absolutePath, page);
689
- }
690
- this.pages = pages;
691
- }
692
- async scanSubPages() {
693
- const paths = {};
694
- const subPages = /* @__PURE__ */ new Map();
695
- for (const dir of this.options.subPackages) {
696
- const pagePaths = getPagePaths(dir, this.options);
697
- paths[dir] = pagePaths;
698
- const pages = /* @__PURE__ */ new Map();
699
- for (const path2 of pagePaths) {
700
- const page = this.subPages.get(dir)?.get(path2.absolutePath) || new Page(this, path2);
701
- pages.set(path2.absolutePath, page);
702
- }
703
- subPages.set(dir, pages);
704
- }
705
- debug.subPages(JSON.stringify(paths, null, 2));
706
- this.subPages = subPages;
707
- }
708
- setupViteServer(server) {
709
- if (this._server === server)
710
- return;
711
- this._server = server;
712
- this.setupWatcher(server.watcher);
713
- }
714
- async setupWatcher(watcher) {
715
- watcher.add(this.pagesConfigSourcePaths);
716
- const targetDirs = [...this.options.dirs, ...this.options.subPackages].map((v) => slash(path__default.resolve(this.root, v)));
717
- const isInTargetDirs = (filePath) => targetDirs.some((v) => slash(path__default.resolve(this.root, filePath)).startsWith(v));
718
- watcher.on("add", async (path2) => {
719
- path2 = slash(path2);
720
- if (!isTargetFile(path2))
721
- return;
722
- if (!isInTargetDirs(path2))
723
- return;
724
- debug.pages(`File added: ${path2}`);
725
- if (await this.updatePagesJSON())
726
- this.onUpdate();
727
- });
728
- watcher.on("change", async (path2) => {
729
- path2 = slash(path2);
730
- if (!isTargetFile(path2))
731
- return;
732
- if (!isInTargetDirs(path2))
733
- return;
734
- debug.pages(`File changed: ${path2}`);
735
- debug.pages(targetDirs);
736
- debug.pages(isInTargetDirs(path2));
737
- if (await this.updatePagesJSON(path2))
738
- this.onUpdate();
739
- });
740
- watcher.on("change", async (path2) => {
741
- if (this.pagesConfigSourcePaths.includes(path2)) {
742
- debug.pages(`Config source changed: ${path2}`);
743
- if (await this.updatePagesJSON())
744
- this.onUpdate();
745
- }
746
- });
747
- watcher.on("unlink", async (path2) => {
748
- path2 = slash(path2);
749
- if (!isTargetFile(path2))
750
- return;
751
- if (!isInTargetDirs(path2))
752
- return;
753
- debug.pages(`File removed: ${path2}`);
754
- if (await this.updatePagesJSON())
755
- this.onUpdate();
756
- });
757
- }
758
- onUpdate() {
759
- if (!this._server)
760
- return;
761
- invalidatePagesModule(this._server);
762
- debug.hmr("Reload generated pages.");
763
- this._server.ws.send({
764
- type: "full-reload"
765
- });
766
- }
767
- /**
768
- * parse pages rules && set page type
769
- * @param pages page path array
770
- * @param type page type
771
- * @param overrides custom page config
772
- * @returns pages rules
773
- */
774
- async parsePages(pages, type, overrides) {
775
- const jobs = [];
776
- for (const [_, page] of pages) {
777
- jobs.push(page.getPageMeta());
778
- }
779
- const generatedPageMetaData = await Promise.all(jobs);
780
- const customPageMetaData = overrides || [];
781
- const result = customPageMetaData.length ? mergePageMetaDataArray(generatedPageMetaData.concat(customPageMetaData)) : generatedPageMetaData;
782
- const parseMeta = Array.from(
783
- result.reduce((map, page) => {
784
- map.set(page.path, page);
785
- return map;
786
- }, /* @__PURE__ */ new Map()).values()
787
- );
788
- return type === "main" ? this.setHomePage(parseMeta) : parseMeta;
789
- }
790
- /**
791
- * set home page
792
- * @param result pages rules array
793
- * @returns pages rules
794
- */
795
- setHomePage(result) {
796
- const hasHome = result.some(({ type }) => type === "home");
797
- if (!hasHome) {
798
- const isFoundHome = result.some((item) => {
799
- const isFound = this.options.homePage.find((v) => v === item.path);
800
- if (isFound)
801
- item.type = "home";
802
- return isFound;
803
- });
804
- if (!isFoundHome) {
805
- this.logger?.warn('No home page found, check the configuration of pages.config.ts, or add the `homePage` option to UniPages in vite.config.js, or add `type="home"` to the routeBlock of your vue page.', {
806
- timestamp: true
807
- });
808
- }
809
- }
810
- result.sort((page) => page.type === "home" ? -1 : 0);
811
- return result;
812
- }
813
- async mergePageMetaData() {
814
- const subPageAbsolutePaths = Array.from(this.subPages.values()).flatMap((v) => Array.from(v.keys()));
815
- for (const subPageAbsolutePath of subPageAbsolutePaths)
816
- this.pages.delete(subPageAbsolutePath);
817
- const pageMetaData = await this.parsePages(this.pages, "main", this.pagesGlobConfig?.pages);
818
- this.pageMetaData = pageMetaData;
819
- debug.pages(this.pageMetaData);
820
- }
821
- async mergeSubPageMetaData() {
822
- const subPageMaps = {};
823
- const subPackages = this.pagesGlobConfig?.subPackages || [];
824
- for (const [dir, pages] of this.subPages) {
825
- const basePath = slash(path__default.join(this.options.root, this.options.outDir));
826
- const root = slash(path__default.relative(basePath, path__default.join(this.options.root, dir)));
827
- const globPackage = subPackages?.find((v) => v.root === root);
828
- subPageMaps[root] = await this.parsePages(pages, "sub", globPackage?.pages);
829
- subPageMaps[root] = subPageMaps[root].map((page) => ({ ...page, path: slash(path__default.relative(root, page.path)) }));
830
- }
831
- for (const { root, pages } of subPackages) {
832
- if (root && !subPageMaps[root])
833
- subPageMaps[root] = pages || [];
834
- }
835
- const subPageMetaData = Object.keys(subPageMaps).map((root) => ({ root, pages: subPageMaps[root] })).filter((meta) => meta.pages.length > 0);
836
- this.subPageMetaData = subPageMetaData;
837
- debug.subPages(this.subPageMetaData);
838
- }
839
- async getTabBarMerged() {
840
- const tabBarItems = [];
841
- for (const [_, page] of this.pages) {
842
- const tabbar = await page.getTabBar();
843
- if (tabbar) {
844
- tabBarItems.push(tabbar);
845
- }
846
- }
847
- if (tabBarItems.length === 0) {
848
- return this.pagesGlobConfig?.tabBar;
849
- }
850
- const tabBar = {
851
- ...this.pagesGlobConfig?.tabBar,
852
- list: this.pagesGlobConfig?.tabBar?.list || []
853
- };
854
- const pagePaths = /* @__PURE__ */ new Map();
855
- for (const item of tabBar.list) {
856
- pagePaths.set(item.pagePath, true);
857
- }
858
- tabBarItems.sort((a, b) => a.index - b.index);
859
- for (const item of tabBarItems) {
860
- if (!pagePaths.has(item.pagePath)) {
861
- const { index: _, ...tabbar } = item;
862
- tabBar.list.push(tabbar);
863
- }
864
- }
865
- return tabBar;
866
- }
867
- async updatePagesJSON(filepath) {
868
- if (filepath) {
869
- let page = this.pages.get(filepath);
870
- if (!page) {
871
- let subPage;
872
- for (const [_, pages2] of this.subPages) {
873
- subPage = pages2.get(filepath);
874
- if (subPage) {
875
- break;
876
- }
877
- }
878
- page = subPage;
879
- }
880
- if (page) {
881
- await page.read();
882
- if (!page.hasChanged()) {
883
- debug.cache(`The route block on page ${filepath} did not send any changes, skipping`);
884
- return false;
885
- }
886
- }
887
- }
888
- checkPagesJsonFileSync(this.resolvedPagesJSONPath);
889
- this.options.onBeforeLoadUserConfig(this);
890
- await this.loadUserPagesConfig();
891
- this.options.onAfterLoadUserConfig(this);
892
- if (this.options.mergePages) {
893
- this.options.onBeforeScanPages(this);
894
- await this.scanPages();
895
- await this.scanSubPages();
896
- this.options.onAfterScanPages(this);
897
- }
898
- this.options.onBeforeMergePageMetaData(this);
899
- await this.mergePageMetaData();
900
- await this.mergeSubPageMetaData();
901
- this.options.onAfterMergePageMetaData(this);
902
- const pagesMap = /* @__PURE__ */ new Map();
903
- const pages = this.withUniPlatform ? this.pageMetaData.filter((v) => !/\..*$/.test(v.path) || v.path.includes(uniEnv.platform)).map((v) => {
904
- v.path = v.path.replace(/\..*$/, "");
905
- return v;
906
- }) : this.pageMetaData;
907
- pages.forEach((v) => pagesMap.set(v.path, v));
908
- this.pageMetaData = [...pagesMap.values()];
909
- this.options.onBeforeWriteFile(this);
910
- const data = await this.genratePagesJSON();
911
- const pagesJson = commentJson.stringify(
912
- data,
913
- null,
914
- this.options.minify ? void 0 : await this.getIndent()
915
- ) + (await this.getEndOfLine() ? await this.getNewline() : "");
916
- this.generateDeclaration();
917
- if (this.lastPagesJson === pagesJson) {
918
- debug.pages("PagesJson Not have change");
919
- return false;
920
- }
921
- await writeFileWithLock(this.resolvedPagesJSONPath, pagesJson);
922
- this.lastPagesJson = pagesJson;
923
- this.options.onAfterWriteFile(this);
924
- return true;
925
- }
926
- virtualModule() {
927
- const pages = `export const pages = ${this.resolveRoutes()};`;
928
- const subPackages = `export const subPackages = ${this.resolveSubRoutes()};`;
929
- return [pages, subPackages].join("\n");
930
- }
931
- resolveRoutes() {
932
- return commentJson.stringify(this.pageMetaData, null, 2);
933
- }
934
- resolveSubRoutes() {
935
- return commentJson.stringify(this.subPageMetaData, null, 2);
936
- }
937
- generateDeclaration() {
938
- if (!this.options.dts)
939
- return;
940
- debug.declaration("generating");
941
- return writeDeclaration(this, this.options.dts);
942
- }
943
- async genratePagesJSON() {
944
- const content = await fs__default.promises.readFile(this.resolvedPagesJSONPath, { encoding: "utf-8" }).catch(() => "");
945
- const { pages: oldPages, subPackages: oldSubPackages, tabBar: oldTabBar } = commentJson.parse(content || "{}");
946
- const { pages: _, subPackages: __, tabBar: ___, ...pageJson } = this.pagesGlobConfig || {};
947
- const currentPlatform = uniEnv.platform.toUpperCase();
948
- pageJson.pages = mergePlatformItems(oldPages, currentPlatform, this.pageMetaData, "path");
949
- pageJson.subPackages = oldSubPackages || new commentJson.CommentArray();
950
- const newSubPackages = /* @__PURE__ */ new Map();
951
- for (const item of this.subPageMetaData) {
952
- newSubPackages.set(item.root, item);
953
- }
954
- for (const existing of pageJson.subPackages) {
955
- const sub = newSubPackages.get(existing.root);
956
- if (sub) {
957
- existing.pages = mergePlatformItems(existing.pages, currentPlatform, sub.pages, "path");
958
- newSubPackages.delete(existing.root);
959
- }
960
- }
961
- for (const [_2, newSub] of newSubPackages) {
962
- pageJson.subPackages.push({
963
- root: newSub.root,
964
- pages: mergePlatformItems(void 0, currentPlatform, newSub.pages, "path")
965
- });
966
- }
967
- const { list, ...tabBarOthers } = await this.getTabBarMerged() || {};
968
- if (list) {
969
- const { list: oldList } = oldTabBar || {};
970
- const newList = mergePlatformItems(oldList, currentPlatform, list, "pagePath");
971
- pageJson.tabBar = {
972
- ...tabBarOthers,
973
- // 每次都直接更新除 list 外的其他属性
974
- list: newList
975
- };
976
- } else {
977
- pageJson.tabBar = void 0;
978
- }
979
- return pageJson;
980
- }
981
- async readInfoFromPagesJSON() {
982
- const resolvedPagesJSONContent = await fs__default.promises.readFile(this.resolvedPagesJSONPath, { encoding: "utf-8" }).catch(() => "");
983
- this.resolvedPagesJSONIndent = detectIndent__default(resolvedPagesJSONContent).indent || " ";
984
- this.resolvedPagesJSONNewline = detectNewline__default(resolvedPagesJSONContent) || "\n";
985
- this.resolvedPagesJSONEofNewline = (resolvedPagesJSONContent.at(-1) ?? "\n") === this.resolvedPagesJSONNewline;
986
- }
987
- async getIndent() {
988
- if (!this.resolvedPagesJSONIndent) {
989
- await this.readInfoFromPagesJSON();
990
- }
991
- return this.resolvedPagesJSONIndent;
992
- }
993
- async getNewline() {
994
- if (!this.resolvedPagesJSONNewline) {
995
- await this.readInfoFromPagesJSON();
996
- }
997
- return this.resolvedPagesJSONNewline;
998
- }
999
- async getEndOfLine() {
1000
- if (!this.resolvedPagesJSONEofNewline) {
1001
- await this.readInfoFromPagesJSON();
1002
- }
1003
- return this.resolvedPagesJSONEofNewline;
1004
- }
1005
- }
1111
+ /**
1112
+ * Get all page paths in the specified directory
1113
+ * @param dir - Page directory path
1114
+ * @param options - Resolved configuration options
1115
+ * @returns Page path array containing relative and absolute paths
1116
+ */
1006
1117
  function getPagePaths(dir, options) {
1007
- const pagesDirPath = slash(path__default.resolve(options.root, dir));
1008
- const basePath = slash(path__default.join(options.root, options.outDir));
1009
- const files = getPageFiles(pagesDirPath, options);
1010
- debug.pages(dir, files);
1011
- const pagePaths = files.map((file) => slash(file)).map((file) => ({
1012
- relativePath: path__default.relative(basePath, slash(path__default.resolve(pagesDirPath, file))),
1013
- absolutePath: slash(path__default.resolve(pagesDirPath, file))
1014
- }));
1015
- return pagePaths;
1118
+ const pagesDirPath = slash(node_path.default.resolve(options.root, dir));
1119
+ const basePath = slash(node_path.default.join(options.root, options.outDir));
1120
+ const files = getPageFiles(pagesDirPath, options);
1121
+ debug$1.pages(dir, files);
1122
+ return files.map((file) => slash(file)).map((file) => ({
1123
+ relativePath: node_path.default.relative(basePath, slash(node_path.default.resolve(pagesDirPath, file))),
1124
+ absolutePath: slash(node_path.default.resolve(pagesDirPath, file))
1125
+ }));
1016
1126
  }
1127
+ /**
1128
+ * Merge multi-platform page configuration items
1129
+ * Handle conditional compilation comments (#ifdef / #endif), merge configuration items from different platforms into one array
1130
+ * Same configuration items will automatically merge platform identifiers, different configuration items will keep conditional compilation comments
1131
+ *
1132
+ * @param source - Existing configuration item array (from pages.json)
1133
+ * @param currentPlatform - Current platform identifier (e.g. H5, MP-WEIXIN)
1134
+ * @param items - New configuration item array
1135
+ * @param uniqueKeyName - Field name used to identify configuration item uniqueness (e.g. 'path' or 'pagePath')
1136
+ * @returns Merged configuration item array with conditional compilation comments
1137
+ */
1017
1138
  function mergePlatformItems(source, currentPlatform, items, uniqueKeyName) {
1018
- const src = source || new commentJson.CommentArray();
1019
- currentPlatform = currentPlatform.toUpperCase();
1020
- let lastPlatforms = [];
1021
- for (const comment of src[Symbol.for("before:0")] || []) {
1022
- const trimed = comment.value.trim();
1023
- if (trimed.startsWith("GENERATED BY UNI-PAGES, PLATFORM:")) {
1024
- lastPlatforms = trimed.split(":")[1].split("||").map((s) => s.trim()).filter((s) => s !== currentPlatform).sort();
1025
- }
1026
- }
1027
- const tmpMap = /* @__PURE__ */ new Map();
1028
- for (let i = 0; i < src.length; i++) {
1029
- const item = src[i];
1030
- const uniqueKey = item[uniqueKeyName];
1031
- if (!uniqueKey) {
1032
- continue;
1033
- }
1034
- const beforeComments = src[Symbol.for(`before:${i}`)];
1035
- const ifdefComment = beforeComments?.find((c) => c.value.trim().startsWith("#ifdef"));
1036
- let platforms = [...lastPlatforms];
1037
- if (ifdefComment) {
1038
- const match = ifdefComment.value.match(/#ifdef\s+(.+)/);
1039
- if (match) {
1040
- platforms = match[1].split("||").map((p) => p.trim()).filter((s) => s !== currentPlatform).sort();
1041
- }
1042
- }
1043
- if (platforms.length === 0) {
1044
- continue;
1045
- }
1046
- const existing = tmpMap.get(uniqueKey) || [];
1047
- existing.push({ item, itemStr: JSON.stringify(item), platforms, platformStr: platforms.join(" || ") });
1048
- tmpMap.set(uniqueKey, existing);
1049
- }
1050
- for (const item of items) {
1051
- const newItem = item;
1052
- const uniqueKey = item[uniqueKeyName];
1053
- if (!uniqueKey) {
1054
- continue;
1055
- }
1056
- if (!tmpMap.has(uniqueKey)) {
1057
- tmpMap.set(uniqueKey, [{
1058
- item: newItem,
1059
- itemStr: JSON.stringify(newItem),
1060
- platforms: [currentPlatform],
1061
- platformStr: currentPlatform
1062
- }]);
1063
- continue;
1064
- }
1065
- const existing = tmpMap.get(uniqueKey);
1066
- const newItemStr = JSON.stringify(newItem);
1067
- const equalObj = existing.find((val) => val.itemStr === newItemStr);
1068
- if (equalObj) {
1069
- equalObj.platforms.push(currentPlatform);
1070
- equalObj.platforms.sort();
1071
- equalObj.platformStr = equalObj.platforms.join(" || ");
1072
- } else {
1073
- existing.push({
1074
- item: newItem,
1075
- itemStr: newItemStr,
1076
- platforms: [currentPlatform],
1077
- platformStr: currentPlatform
1078
- });
1079
- }
1080
- }
1081
- const result = new commentJson.CommentArray();
1082
- const platformUsage = {};
1083
- tmpMap.forEach((val) => {
1084
- Object.values(val).forEach((v) => {
1085
- platformUsage[v.platformStr] = (platformUsage[v.platformStr] || 0) + 1;
1086
- });
1087
- });
1088
- const usageKeys = Object.keys(platformUsage);
1089
- const defaultPlatformStr = usageKeys.length ? usageKeys.reduce((a, b) => platformUsage[a] > platformUsage[b] ? a : b) : currentPlatform;
1090
- result[Symbol.for("before:0")] = [{
1091
- type: "LineComment",
1092
- value: ` GENERATED BY UNI-PAGES, PLATFORM: ${defaultPlatformStr}`,
1093
- inline: false,
1094
- loc: {
1095
- start: { line: 0, column: 0 },
1096
- end: { line: 0, column: 0 }
1097
- }
1098
- }];
1099
- for (const [_, list] of tmpMap) {
1100
- for (const { item, platformStr } of list) {
1101
- result.push(item);
1102
- if (platformStr !== defaultPlatformStr) {
1103
- result[Symbol.for(`before:${result.length - 1}`)] = [{
1104
- type: "LineComment",
1105
- value: ` #ifdef ${platformStr}`,
1106
- inline: false,
1107
- loc: {
1108
- start: { line: 0, column: 0 },
1109
- end: { line: 0, column: 0 }
1110
- }
1111
- }];
1112
- result[Symbol.for(`after:${result.length - 1}`)] = [{
1113
- type: "LineComment",
1114
- value: " #endif",
1115
- inline: false,
1116
- loc: {
1117
- start: { line: 0, column: 0 },
1118
- end: { line: 0, column: 0 }
1119
- }
1120
- }];
1121
- }
1122
- }
1123
- }
1124
- return result;
1139
+ const src = source || new comment_json.CommentArray();
1140
+ currentPlatform = currentPlatform.toUpperCase();
1141
+ let lastPlatforms = [];
1142
+ for (const comment of src[Symbol.for("before:0")] || []) {
1143
+ const trimed = comment.value.trim();
1144
+ if (trimed.startsWith("GENERATED BY UNI-PAGES, PLATFORM:")) lastPlatforms = trimed.split(":")[1].split("||").map((s) => s.trim()).filter((s) => s !== currentPlatform).sort();
1145
+ }
1146
+ const tmpMap = /* @__PURE__ */ new Map();
1147
+ for (let i = 0; i < src.length; i++) {
1148
+ const item = src[i];
1149
+ const uniqueKey = item[uniqueKeyName];
1150
+ if (!uniqueKey) continue;
1151
+ const ifdefComment = src[Symbol.for(`before:${i}`)]?.find((c) => c.value.trim().startsWith("#ifdef"));
1152
+ let platforms = [...lastPlatforms];
1153
+ if (ifdefComment) {
1154
+ const match = ifdefComment.value.match(/#ifdef\s+(.+)/);
1155
+ if (match) platforms = match[1].split("||").map((p) => p.trim()).filter((s) => s !== currentPlatform).sort();
1156
+ }
1157
+ if (platforms.length === 0) continue;
1158
+ const existing = tmpMap.get(uniqueKey) || [];
1159
+ existing.push({
1160
+ item,
1161
+ itemStr: JSON.stringify(item),
1162
+ platforms,
1163
+ platformStr: platforms.join(" || ")
1164
+ });
1165
+ tmpMap.set(uniqueKey, existing);
1166
+ }
1167
+ for (const item of items) {
1168
+ const newItem = item;
1169
+ const uniqueKey = item[uniqueKeyName];
1170
+ if (!uniqueKey) continue;
1171
+ if (!tmpMap.has(uniqueKey)) {
1172
+ tmpMap.set(uniqueKey, [{
1173
+ item: newItem,
1174
+ itemStr: JSON.stringify(newItem),
1175
+ platforms: [currentPlatform],
1176
+ platformStr: currentPlatform
1177
+ }]);
1178
+ continue;
1179
+ }
1180
+ const existing = tmpMap.get(uniqueKey);
1181
+ const newItemStr = JSON.stringify(newItem);
1182
+ const equalObj = existing.find((val) => val.itemStr === newItemStr);
1183
+ if (equalObj) {
1184
+ equalObj.platforms.push(currentPlatform);
1185
+ equalObj.platforms.sort();
1186
+ equalObj.platformStr = equalObj.platforms.join(" || ");
1187
+ } else existing.push({
1188
+ item: newItem,
1189
+ itemStr: newItemStr,
1190
+ platforms: [currentPlatform],
1191
+ platformStr: currentPlatform
1192
+ });
1193
+ }
1194
+ const result = new comment_json.CommentArray();
1195
+ const platformUsage = {};
1196
+ tmpMap.forEach((val) => {
1197
+ Object.values(val).forEach((v) => {
1198
+ platformUsage[v.platformStr] = (platformUsage[v.platformStr] || 0) + 1;
1199
+ });
1200
+ });
1201
+ const usageKeys = Object.keys(platformUsage);
1202
+ const defaultPlatformStr = usageKeys.length ? usageKeys.reduce((a, b) => platformUsage[a] > platformUsage[b] ? a : b) : currentPlatform;
1203
+ result[Symbol.for("before:0")] = [{
1204
+ type: "LineComment",
1205
+ value: ` GENERATED BY UNI-PAGES, PLATFORM: ${defaultPlatformStr}`,
1206
+ inline: false,
1207
+ loc: {
1208
+ start: {
1209
+ line: 0,
1210
+ column: 0
1211
+ },
1212
+ end: {
1213
+ line: 0,
1214
+ column: 0
1215
+ }
1216
+ }
1217
+ }];
1218
+ for (const [_, list] of tmpMap) for (const { item, platformStr } of list) {
1219
+ result.push(item);
1220
+ if (platformStr !== defaultPlatformStr) {
1221
+ result[Symbol.for(`before:${result.length - 1}`)] = [{
1222
+ type: "LineComment",
1223
+ value: ` #ifdef ${platformStr}`,
1224
+ inline: false,
1225
+ loc: {
1226
+ start: {
1227
+ line: 0,
1228
+ column: 0
1229
+ },
1230
+ end: {
1231
+ line: 0,
1232
+ column: 0
1233
+ }
1234
+ }
1235
+ }];
1236
+ result[Symbol.for(`after:${result.length - 1}`)] = [{
1237
+ type: "LineComment",
1238
+ value: " #endif",
1239
+ inline: false,
1240
+ loc: {
1241
+ start: {
1242
+ line: 0,
1243
+ column: 0
1244
+ },
1245
+ end: {
1246
+ line: 0,
1247
+ column: 0
1248
+ }
1249
+ }
1250
+ }];
1251
+ }
1252
+ }
1253
+ return result;
1125
1254
  }
1126
-
1255
+ //#endregion
1256
+ //#region src/config/index.ts
1257
+ /**
1258
+ * Define uni-pages configuration
1259
+ * Used in pages.config.ts configuration file to provide type hints and validation
1260
+ *
1261
+ * @param config - Page configuration object
1262
+ * @returns Configuration object
1263
+ */
1127
1264
  function defineUniPages(config) {
1128
- return config;
1265
+ return config;
1129
1266
  }
1130
-
1267
+ //#endregion
1268
+ //#region src/index.ts
1269
+ /**
1270
+ * vite-plugin-uni-pages plugin main entry
1271
+ *
1272
+ * Automatically scan page directories and generate pages.json configuration file
1273
+ * Support definePage macro for defining page metadata
1274
+ * Support multi-platform conditional compilation
1275
+ * Support sub-package configuration
1276
+ * Support TypeScript declaration file generation
1277
+ *
1278
+ * @param userOptions - User configuration options
1279
+ * @returns Vite plugin instance
1280
+ */
1131
1281
  function VitePluginUniPages(userOptions = {}) {
1132
- let ctx;
1133
- const resolvedPagesJSONPath = path__default.join(
1134
- process__default.env.VITE_ROOT_DIR || process__default.cwd(),
1135
- userOptions.outDir ?? "src",
1136
- OUTPUT_NAME
1137
- );
1138
- checkPagesJsonFileSync(resolvedPagesJSONPath);
1139
- return {
1140
- name: "vite-plugin-uni-pages",
1141
- enforce: "pre",
1142
- async configResolved(config) {
1143
- ctx = new PageContext(userOptions, config.root);
1144
- if (config.plugins.some((v) => v.name === "vite-plugin-uni-platform"))
1145
- ctx.withUniPlatform = true;
1146
- const logger = vite.createLogger(void 0, {
1147
- prefix: "[vite-plugin-uni-pages]"
1148
- });
1149
- ctx.setLogger(logger);
1150
- await ctx.updatePagesJSON();
1151
- if (config.command === "build") {
1152
- if (config.build.watch)
1153
- ctx.setupWatcher(chokidar__default.watch([...ctx.options.dirs, ...ctx.options.subPackages]));
1154
- }
1155
- },
1156
- // Applet do not support custom route block, so we need to remove the route block here
1157
- async transform(code, id) {
1158
- if (!FILE_EXTENSIONS.find((ext) => id.endsWith(ext))) {
1159
- return null;
1160
- }
1161
- const sfc = parseSFC(code, { filename: id });
1162
- let macro;
1163
- if (sfc.scriptSetup) {
1164
- const ast = astKit.babelParse(sfc.scriptSetup.content, sfc.scriptSetup.lang || "js");
1165
- macro = findMacro(ast.body, sfc.filename);
1166
- }
1167
- if (!macro && sfc.script) {
1168
- const ast = astKit.babelParse(sfc.script.content, sfc.script.lang || "js");
1169
- macro = findMacro(ast.body, sfc.filename);
1170
- }
1171
- const routeBlock = sfc.customBlocks.find((block) => block.type === "route");
1172
- if (!macro && !routeBlock)
1173
- return null;
1174
- if (macro && routeBlock)
1175
- throw new Error(`\u4E0D\u652F\u6301\u6DF7\u5408\u4F7F\u7528 definePage() \u548C <route/> ${id}`);
1176
- const s = new MagicString__default(code);
1177
- if (macro)
1178
- s.remove(macro.start, macro.end);
1179
- if (routeBlock) {
1180
- console.log(kolorist.lightYellow("\u8B66\u544A\uFF1A"), `${kolorist.bold("<route/>")} \u6807\u7B7E\u5DF2\u5E9F\u5F03\uFF0C\u5C06\u5728\u4E0B\u4E00\u4E2A\u7248\u672C\u4E2D\u79FB\u9664\uFF0C\u8BF7\u4F7F\u7528 definePage() \u4EE3\u66FF\uFF1B${kolorist.link("\u67E5\u770B\u8FC1\u79FB\u6307\u5357", "https://uni-helper.js.org/vite-plugin-uni-pages/definePage")}\u3002`);
1181
- console.log(kolorist.dim(id));
1182
- console.log();
1183
- const routeBlockMatches = s.original.matchAll(
1184
- /<route[^>]*>([\s\S]*?)<\/route>/g
1185
- );
1186
- for (const match of routeBlockMatches) {
1187
- const index = match.index;
1188
- const length = match[0].length;
1189
- s.remove(index, index + length);
1190
- }
1191
- }
1192
- if (s.hasChanged()) {
1193
- return {
1194
- code: s.toString(),
1195
- map: s.generateMap({
1196
- source: id,
1197
- includeContent: true,
1198
- file: `${id}.map`
1199
- })
1200
- };
1201
- }
1202
- },
1203
- configureServer(server) {
1204
- ctx.setupViteServer(server);
1205
- },
1206
- resolveId(id) {
1207
- if (id === MODULE_ID_VIRTUAL)
1208
- return RESOLVED_MODULE_ID_VIRTUAL;
1209
- },
1210
- load(id) {
1211
- if (id === RESOLVED_MODULE_ID_VIRTUAL)
1212
- return ctx.virtualModule();
1213
- }
1214
- };
1282
+ let ctx;
1283
+ checkPagesJsonFileSync(node_path.default.join(node_process.default.env.VITE_ROOT_DIR || node_process.default.cwd(), userOptions.outDir ?? "src", OUTPUT_NAME));
1284
+ return {
1285
+ name: "vite-plugin-uni-pages",
1286
+ enforce: "pre",
1287
+ /**
1288
+ * Vite configResolved hook
1289
+ * Initialize PageContext, set logger, generate initial pages.json
1290
+ */
1291
+ async configResolved(config) {
1292
+ ctx = new PageContext(userOptions, config.root);
1293
+ if (config.plugins.some((v) => v.name === "vite-plugin-uni-platform")) ctx.withUniPlatform = true;
1294
+ const logger = (0, vite.createLogger)(void 0, { prefix: "[vite-plugin-uni-pages]" });
1295
+ ctx.setLogger(logger);
1296
+ await ctx.updatePagesJSON();
1297
+ if (config.command === "build") {
1298
+ if (config.build.watch) ctx.setupWatcher(chokidar.default.watch([...ctx.options.dirs, ...ctx.options.subPackages]));
1299
+ }
1300
+ },
1301
+ /**
1302
+ * Code transform hook
1303
+ * Remove definePage macro calls from Vue SFC to avoid runtime errors
1304
+ */
1305
+ async transform(code, id) {
1306
+ if (!FILE_EXTENSIONS.some((ext) => id.endsWith(ext))) return null;
1307
+ const sfc = parseSFC(code, { filename: id });
1308
+ let macro;
1309
+ if (sfc.scriptSetup) macro = findMacro((0, ast_kit.babelParse)(sfc.scriptSetup.content, sfc.scriptSetup.lang || "js").body, sfc.filename);
1310
+ if (!macro && sfc.script) macro = findMacro((0, ast_kit.babelParse)(sfc.script.content, sfc.script.lang || "js").body, sfc.filename);
1311
+ if (!macro) return null;
1312
+ const s = new magic_string.default(code);
1313
+ s.remove(macro.start, macro.end);
1314
+ if (s.hasChanged()) return {
1315
+ code: s.toString(),
1316
+ map: s.generateMap({
1317
+ source: id,
1318
+ includeContent: true,
1319
+ file: `${id}.map`
1320
+ })
1321
+ };
1322
+ },
1323
+ /**
1324
+ * Configure server hook
1325
+ * Set up file watching and HMR support
1326
+ */
1327
+ configureServer(server) {
1328
+ ctx.setupViteServer(server);
1329
+ },
1330
+ /**
1331
+ * Module resolution hook
1332
+ * Resolve virtual module identifier to internal path
1333
+ */
1334
+ resolveId(id) {
1335
+ if (id === "virtual:uni-pages") return RESOLVED_MODULE_ID_VIRTUAL;
1336
+ },
1337
+ /**
1338
+ * Module load hook
1339
+ * Return the code content of the virtual module
1340
+ */
1341
+ load(id) {
1342
+ if (id === RESOLVED_MODULE_ID_VIRTUAL) return ctx.virtualModule();
1343
+ }
1344
+ };
1215
1345
  }
1216
-
1346
+ //#endregion
1217
1347
  exports.FILE_EXTENSIONS = FILE_EXTENSIONS;
1218
1348
  exports.MODULE_ID_VIRTUAL = MODULE_ID_VIRTUAL;
1219
1349
  exports.OUTPUT_NAME = OUTPUT_NAME;
@@ -1221,26 +1351,23 @@ exports.Page = Page;
1221
1351
  exports.PageContext = PageContext;
1222
1352
  exports.RESOLVED_MODULE_ID_VIRTUAL = RESOLVED_MODULE_ID_VIRTUAL;
1223
1353
  exports.VitePluginUniPages = VitePluginUniPages;
1354
+ exports.default = VitePluginUniPages;
1224
1355
  exports.babelGenerate = babelGenerate;
1225
1356
  exports.checkPagesJsonFileSync = checkPagesJsonFileSync;
1226
- exports.debug = debug;
1227
- exports.default = VitePluginUniPages;
1357
+ exports.debug = debug$1;
1228
1358
  exports.defineUniPages = defineUniPages;
1229
1359
  exports.extsToGlob = extsToGlob;
1230
1360
  exports.findImports = findImports;
1231
1361
  exports.findMacro = findMacro;
1232
1362
  exports.getPageFiles = getPageFiles;
1233
- exports.getRouteBlock = getRouteBlock;
1234
- exports.getRouteSfcBlock = getRouteSfcBlock;
1235
1363
  exports.invalidatePagesModule = invalidatePagesModule;
1236
1364
  exports.isTargetFile = isTargetFile;
1237
1365
  exports.mergePageMetaDataArray = mergePageMetaDataArray;
1238
1366
  exports.parseCode = parseCode;
1239
- exports.parseCustomBlock = parseCustomBlock;
1240
1367
  exports.parseSFC = parseSFC;
1241
1368
  exports.resolveOptions = resolveOptions;
1242
1369
  exports.resolvePageDirs = resolvePageDirs;
1243
1370
  exports.sleep = sleep;
1244
- exports.tryPageMetaFromCustomBlock = tryPageMetaFromCustomBlock;
1371
+ exports.stripType = stripType;
1245
1372
  exports.tryPageMetaFromMacro = tryPageMetaFromMacro;
1246
1373
  exports.writeFileWithLock = writeFileWithLock;