@uni-helper/vite-plugin-uni-pages 0.4.8 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs DELETED
@@ -1,1399 +0,0 @@
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 write_file_atomic = require("write-file-atomic");
49
- write_file_atomic = __toESM(write_file_atomic, 1);
50
- let node_fs_promises = require("node:fs/promises");
51
- let proper_lockfile = require("proper-lockfile");
52
- proper_lockfile = __toESM(proper_lockfile, 1);
53
- let tinyglobby = require("tinyglobby");
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 */
68
- const MODULE_ID_VIRTUAL = "virtual:uni-pages";
69
- /** Resolved virtual module identifier with \0 prefix to avoid conflicts with other modules */
70
- const RESOLVED_MODULE_ID_VIRTUAL = `\0${MODULE_ID_VIRTUAL}`;
71
- /** Output filename, the uni-app page configuration file */
72
- const OUTPUT_NAME = "pages.json";
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
81
- function slash(str) {
82
- return str.replace(/\\/g, "/");
83
- }
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
- */
94
- function getDeclaration(ctx) {
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 */
102
- /* prettier-ignore */
103
- // @ts-nocheck
104
- // Generated by vite-plugin-uni-pages
105
-
106
- type _LocationUrl =
107
- ${[...ctx.pageMetaData.filter((page) => !tabsPagesPath.includes(page.path)).map((v) => `"/${v.path}"`), ...subPagesPath].join(" |\n ")};
108
-
109
- interface NavigateToOptions {
110
- url: _LocationUrl;
111
- }
112
- interface RedirectToOptions extends NavigateToOptions {}
113
-
114
- interface SwitchTabOptions {
115
- ${tabsPagesPath.length ? `url: ${tabsPagesPath.join(" | ")}` : ""}
116
- }
117
-
118
- type ReLaunchOptions = NavigateToOptions | SwitchTabOptions;
119
-
120
- declare interface Uni {
121
- navigateTo(options: UniNamespace.NavigateToOptions & NavigateToOptions): void;
122
- redirectTo(options: UniNamespace.RedirectToOptions & RedirectToOptions): void;
123
- switchTab(options: UniNamespace.SwitchTabOptions & SwitchTabOptions): void;
124
- reLaunch(options: UniNamespace.ReLaunchOptions & ReLaunchOptions): void;
125
- }
126
-
127
- declare module "virtual:uni-pages" {
128
- export type LocationUrl = _LocationUrl;
129
- }
130
- `;
131
- }
132
- /**
133
- * Write file, automatically create directories
134
- * @param filePath - File path
135
- * @param content - File content
136
- */
137
- async function writeFile(filePath, content) {
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");
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
- */
148
- async function writeDeclaration(ctx, filepath) {
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);
153
- }
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
- */
162
- function invalidatePagesModule(server) {
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
- }
171
- }
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")
194
- };
195
- /**
196
- * Convert file extensions array to glob pattern
197
- * @param extensions - File extensions array
198
- * @returns Glob pattern string
199
- */
200
- function extsToGlob(extensions) {
201
- return extensions.length > 1 ? `{${extensions.join(",")}}` : extensions[0] || "";
202
- }
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);
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
- */
219
- function mergePageMetaDataArray(pageMetaData) {
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;
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
- */
242
- async function parseCode(options) {
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
- }
294
- }
295
- /**
296
- * Async sleep function
297
- * @param ms - Sleep duration in milliseconds
298
- * @returns Promise object
299
- */
300
- function sleep(ms) {
301
- return new Promise((resolve) => setTimeout(resolve, ms));
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
- */
310
- function getDefaultExport(expr) {
311
- return expr.default === void 0 ? expr : expr.default;
312
- }
313
- /** Babel code generator for converting AST back to code */
314
- const babelGenerate = getDefaultExport(_babel_generator.default);
315
- //#endregion
316
- //#region src/files.ts
317
- /**
318
- * Resolves the files that are valid pages for the given context.
319
- */
320
- function getPageFiles(path, options) {
321
- const { exclude } = options;
322
- return (0, tinyglobby.globSync)(`**/*.${extsToGlob(FILE_EXTENSIONS)}`, {
323
- ignore: exclude,
324
- onlyFiles: true,
325
- cwd: path
326
- });
327
- }
328
- /**
329
- * 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
330
- * @param path - File path to check
331
- * @returns boolean - Whether the operation was successful
332
- */
333
- function checkPagesJsonFileSync(path) {
334
- /**
335
- * Create an empty pages.json file
336
- * @param path - File path
337
- * @returns boolean - Whether the creation was successful
338
- */
339
- const createEmptyFile = (path) => {
340
- try {
341
- node_fs.default.writeFileSync(path, JSON.stringify({ pages: [{ path: "" }] }, null, 2), { encoding: "utf-8" });
342
- return true;
343
- } catch {
344
- return false;
345
- }
346
- };
347
- /**
348
- * Delete the file at the specified path
349
- * @param path - File path
350
- * @returns boolean - Whether the deletion was successful
351
- */
352
- const unlinkFile = (path) => {
353
- try {
354
- node_fs.default.unlinkSync(path);
355
- return true;
356
- } catch {
357
- return false;
358
- }
359
- };
360
- try {
361
- try {
362
- node_fs.default.accessSync(path, node_fs.default.constants.F_OK);
363
- } catch {
364
- return createEmptyFile(path);
365
- }
366
- if (!node_fs.default.statSync(path).isFile()) {
367
- if (!unlinkFile(path)) return false;
368
- return createEmptyFile(path);
369
- }
370
- try {
371
- node_fs.default.accessSync(path, node_fs.default.constants.R_OK | node_fs.default.constants.W_OK);
372
- return true;
373
- } catch {
374
- if (!unlinkFile(path)) return false;
375
- return createEmptyFile(path);
376
- }
377
- } catch {
378
- return createEmptyFile(path);
379
- }
380
- }
381
- /**
382
- * Run a task while holding an exclusive file lock.
383
- *
384
- * Unlike {@link writeFileWithLock}, this protects the whole read-modify-write
385
- * critical section. The lock is held from the moment `task` starts until it
386
- * resolves, so concurrent processes cannot observe or overwrite a half-written
387
- * state. This is required by pages.json generation, where the new content
388
- * depends on the current content (other platforms' `#ifdef` blocks).
389
- *
390
- * @param path - File path used as the lock target
391
- * @param task - Async work to run inside the lock; return value is forwarded
392
- * @param retry - Number of retries when lock acquisition fails, defaults to 3
393
- * @returns The value resolved by `task`, or `undefined` if the lock could not be acquired
394
- */
395
- async function withFileLock(path, task, retry = 3) {
396
- if (retry <= 0) {
397
- debug$1.error(`${path} Failed to acquire file lock, task aborted`);
398
- return;
399
- }
400
- let release;
401
- try {
402
- try {
403
- release = await proper_lockfile.default.lock(path, { realpath: false });
404
- } catch {
405
- await sleep(500);
406
- return withFileLock(path, task, retry - 1);
407
- }
408
- return await task();
409
- } finally {
410
- if (release) await release();
411
- }
412
- }
413
- /**
414
- * Safely write file using file lock
415
- * Avoid data corruption caused by concurrent writes through file lock
416
- * Use atomic write to ensure file write integrity
417
- *
418
- * Note: this only makes the *write* atomic. Callers that need to read the
419
- * current content before computing the new one must use {@link withFileLock}
420
- * so the read and write belong to the same critical section.
421
- *
422
- * @param path - File path
423
- * @param content - File content
424
- * @param retry - Number of retries when lock acquisition fails, defaults to 3
425
- */
426
- async function writeFileWithLock(path, content, retry = 3) {
427
- return withFileLock(path, async () => {
428
- await (0, write_file_atomic.default)(path, content);
429
- }, retry);
430
- }
431
- //#endregion
432
- //#region src/options.ts
433
- /**
434
- * Resolve user configuration options
435
- * Merge user-provided configuration with default values and handle path resolution
436
- *
437
- * @param userOptions - User configuration options
438
- * @param viteRoot - Vite project root directory
439
- * @returns Resolved configuration options
440
- */
441
- function resolveOptions(userOptions, viteRoot = node_process.default.cwd()) {
442
- const { dts = true, configSource = "pages.config", homePage = ["pages/index", "pages/index/index"], mergePages = true, dir = "src/pages", subPackages = [], outDir = "src", exclude = [
443
- "node_modules",
444
- ".git",
445
- "**/__*__/**"
446
- ], minify = false, debug = false, onBeforeLoadUserConfig = () => {}, onAfterLoadUserConfig = () => {}, onBeforeScanPages = () => {}, onAfterScanPages = () => {}, onBeforeMergePageMetaData = () => {}, onAfterMergePageMetaData = () => {}, onBeforeWriteFile = () => {}, onAfterWriteFile = () => {} } = userOptions;
447
- const root = viteRoot || slash(node_process.default.env.VITE_ROOT_DIR || node_process.default.cwd());
448
- const resolvedDirs = resolvePageDirs(dir, root, exclude);
449
- const subPackageRootMap = /* @__PURE__ */ new Map();
450
- const resolvedSubDirs = [];
451
- for (const sub of subPackages) if (typeof sub === "string") resolvedSubDirs.push(slash(sub));
452
- else {
453
- const dirPath = slash(sub.dir);
454
- resolvedSubDirs.push(dirPath);
455
- subPackageRootMap.set(dirPath, sub.root);
456
- }
457
- const resolvedHomePage = typeof homePage === "string" ? [homePage] : homePage;
458
- const resolvedConfigSource = typeof configSource === "string" ? [{ files: configSource }] : configSource;
459
- return {
460
- dts: !dts ? false : typeof dts === "string" ? dts : (0, node_path.resolve)(viteRoot, "uni-pages.d.ts"),
461
- configSource: Array.isArray(resolvedConfigSource) ? resolvedConfigSource : [resolvedConfigSource],
462
- homePage: resolvedHomePage,
463
- mergePages,
464
- dirs: resolvedDirs,
465
- subPackages: resolvedSubDirs,
466
- subPackageRootMap,
467
- outDir,
468
- exclude,
469
- root,
470
- minify,
471
- debug,
472
- onBeforeLoadUserConfig,
473
- onAfterLoadUserConfig,
474
- onBeforeScanPages,
475
- onAfterScanPages,
476
- onBeforeMergePageMetaData,
477
- onAfterMergePageMetaData,
478
- onBeforeWriteFile,
479
- onAfterWriteFile
480
- };
481
- }
482
- /**
483
- * Resolves the page dirs for its for its given globs
484
- */
485
- function resolvePageDirs(dir, root, exclude) {
486
- return (0, tinyglobby.globSync)(slash(dir), {
487
- ignore: exclude,
488
- onlyDirectories: true,
489
- expandDirectories: false,
490
- dot: true,
491
- cwd: root
492
- });
493
- }
494
- //#endregion
495
- //#region src/page.ts
496
- /**
497
- * Page class representing a Vue page file
498
- *
499
- * Responsibilities:
500
- * 1. Read page file content
501
- * 2. Parse page metadata defined by definePage macro
502
- * 3. Provide tabBar configuration information
503
- * 4. Track page file change status
504
- */
505
- var Page = class {
506
- /** Page context instance */
507
- ctx;
508
- /** Page path information containing relative and absolute paths */
509
- path;
510
- /** Page URI used for pages.json path field */
511
- uri;
512
- /** Whether the page has changed, used for incremental update judgment */
513
- changed = true;
514
- /** Raw JSON string of page metadata for change detection */
515
- raw = "";
516
- /** Parsed page metadata */
517
- meta;
518
- /**
519
- * Create a page instance
520
- * @param ctx - Page context instance
521
- * @param path - Page path information
522
- */
523
- constructor(ctx, path) {
524
- this.ctx = ctx;
525
- this.path = path;
526
- this.uri = (0, vite.normalizePath)(path.relativePath.replace((0, node_path.extname)(path.relativePath), ""));
527
- }
528
- /**
529
- * Get page metadata
530
- * Parse configuration defined by definePage macro and return metadata for pages.json
531
- *
532
- * @param forceUpdate - Whether to force update, ignoring cache
533
- * @returns Page metadata object
534
- */
535
- async getPageMeta(forceUpdate = false) {
536
- if (forceUpdate || !this.meta) await this.read();
537
- const { path, tabBar: _, ...others } = this.meta || {};
538
- return {
539
- path: path ?? this.uri,
540
- ...others
541
- };
542
- }
543
- /**
544
- * Get page tabBar configuration
545
- * Extract tabBar related configuration from definePage macro
546
- *
547
- * @param forceUpdate - Whether to force update, ignoring cache
548
- * @returns tabBar configuration object, or undefined if page doesn't define tabBar
549
- */
550
- async getTabBar(forceUpdate = false) {
551
- if (forceUpdate || !this.meta) await this.read();
552
- const { tabBar } = this.meta || {};
553
- if (tabBar === void 0) return;
554
- return {
555
- ...tabBar,
556
- pagePath: tabBar.pagePath || this.uri,
557
- index: tabBar.index ?? 0
558
- };
559
- }
560
- /**
561
- * Check if the page has changed
562
- * @returns Whether the page has changed
563
- */
564
- hasChanged() {
565
- return this.changed;
566
- }
567
- /**
568
- * Read page file and parse metadata
569
- * Extract configuration defined by definePage macro from Vue SFC
570
- */
571
- async read() {
572
- let meta;
573
- try {
574
- meta = await this.readPageMetaFromFile();
575
- } catch (err) {
576
- debug$1.error(err);
577
- return;
578
- }
579
- let raw = "";
580
- try {
581
- raw = JSON.stringify(meta);
582
- } catch {}
583
- this.changed = this.raw !== raw;
584
- this.meta = meta;
585
- this.raw = raw;
586
- }
587
- async readPageMetaFromFile() {
588
- try {
589
- const meta = await tryPageMetaFromMacro(parseSFC(await node_fs.default.promises.readFile(this.path.absolutePath, { encoding: "utf-8" }), { filename: this.path.absolutePath }));
590
- if (meta) return meta;
591
- return { type: "page" };
592
- } catch (err) {
593
- throw new Error(`Read page meta fail in ${this.path.relativePath}\n${err.message}`);
594
- }
595
- }
596
- };
597
- /**
598
- * Parse Vue Single File Component (SFC)
599
- * Compatible with different versions of @vue/compiler-sfc
600
- *
601
- * @param code - Vue SFC source code
602
- * @param options - Parse options
603
- * @returns SFC descriptor object
604
- */
605
- function parseSFC(code, options) {
606
- return (0, _vue_compiler_sfc.parse)(code, {
607
- pad: "space",
608
- ...options
609
- }).descriptor || (0, _vue_compiler_sfc.parse)({
610
- source: code,
611
- ...options
612
- });
613
- }
614
- /**
615
- * Try to extract page metadata defined by definePage macro from SFC
616
- * Support using definePage in script setup or regular script
617
- *
618
- * @param sfc - Vue SFC descriptor
619
- * @returns Page metadata object, or undefined if definePage is not found
620
- */
621
- async function tryPageMetaFromMacro(sfc) {
622
- const sfcScript = sfc.scriptSetup || sfc.script;
623
- if (!sfcScript) return;
624
- const ast = (0, ast_kit.babelParse)(sfcScript.content, sfcScript.lang || "js", { plugins: [["importAttributes", { deprecatedAssertSyntax: true }]] });
625
- const macro = findMacro(ast.body, sfc.filename);
626
- if (macro) {
627
- const imports = findImports(ast.body).filter((imp) => !!imp.specifiers.length).map((imp) => babelGenerate(imp).code);
628
- const [macroOption] = macro.arguments;
629
- const code = babelGenerate(macroOption).code;
630
- const parsed = await parseCode({
631
- imports,
632
- code,
633
- filename: sfc.filename
634
- });
635
- return {
636
- type: "page",
637
- ...typeof parsed === "function" ? await Promise.resolve(parsed()) : await Promise.resolve(parsed)
638
- };
639
- }
640
- }
641
- /**
642
- * Find definePage macro call in AST
643
- * Support function expressions, arrow functions and object expressions as arguments
644
- *
645
- * @param stmts - AST statement array
646
- * @param filename - Filename for error reporting
647
- * @returns definePage call expression, or undefined if not found
648
- */
649
- function findMacro(stmts, filename) {
650
- let macro;
651
- for (const stmt of stmts) {
652
- let node = stmt;
653
- if (stmt.type === "ExpressionStatement") node = stmt.expression;
654
- if ((0, ast_kit.isCallOf)(node, "definePage")) {
655
- macro = node;
656
- break;
657
- }
658
- }
659
- if (!macro) return;
660
- const [opt] = macro.arguments;
661
- if (opt && !_babel_types.isFunctionExpression(opt) && !_babel_types.isArrowFunctionExpression(opt) && !_babel_types.isObjectExpression(opt)) {
662
- debug$1.definePage(`definePage() 参数仅支持函数或对象:${filename}`);
663
- return;
664
- }
665
- return macro;
666
- }
667
- /**
668
- * Extract all import declarations from AST
669
- * Used to provide necessary imports when executing definePage arguments
670
- *
671
- * @param stmts - AST statement array
672
- * @returns Import declaration array
673
- */
674
- function findImports(stmts) {
675
- const imports = [];
676
- for (const stmt of stmts) if (_babel_types.isImportDeclaration(stmt)) imports.push(stmt);
677
- return imports;
678
- }
679
- //#endregion
680
- //#region src/context.ts
681
- /**
682
- * Page context class responsible for page scanning, config loading, page metadata merging and pages.json generation
683
- *
684
- * Core responsibilities:
685
- * 1. Scan page directories and collect page files
686
- * 2. Load user configuration files (pages.config.ts, etc.)
687
- * 3. Parse page metadata (definePage macro)
688
- * 4. Merge page configurations and generate pages.json
689
- * 5. Provide virtual module and HMR support
690
- */
691
- var PageContext = class {
692
- _server;
693
- /** Parsed configuration object from user config file (pages.config.ts) */
694
- pagesGlobConfig;
695
- /** Source path list of user configuration files */
696
- pagesConfigSourcePaths = [];
697
- /** Main package page map, key is the absolute path of the page file */
698
- pages = /* @__PURE__ */ new Map();
699
- /** Sub-package page map, key is the sub-package root directory, value is the page map under that sub-package */
700
- subPages = /* @__PURE__ */ new Map();
701
- /** Main package page metadata array for generating pages.json pages field */
702
- pageMetaData = [];
703
- /** Sub-package page metadata array for generating pages.json subPackages field */
704
- subPageMetaData = [];
705
- /** Generated pages.json file path */
706
- resolvedPagesJSONPath = "";
707
- resolvedPagesJSONIndent;
708
- resolvedPagesJSONNewline;
709
- resolvedPagesJSONEofNewline;
710
- /** Original options passed by the user */
711
- rawOptions;
712
- /** Project root directory */
713
- root;
714
- /** Resolved configuration options */
715
- options;
716
- logger;
717
- /** Whether to work with vite-plugin-uni-platform plugin */
718
- withUniPlatform = false;
719
- /** Cached previous pages.json content to avoid redundant writes */
720
- lastPagesJson = "";
721
- /**
722
- * Create a PageContext instance
723
- * @param userOptions - User configuration options
724
- * @param viteRoot - Vite project root directory, defaults to current working directory
725
- */
726
- constructor(userOptions, viteRoot = node_process.default.cwd()) {
727
- this.rawOptions = userOptions;
728
- this.root = slash(viteRoot);
729
- debug$1.options("root", this.root);
730
- this.options = resolveOptions(userOptions, this.root);
731
- const debugOption = this.options.debug;
732
- if (debugOption) {
733
- const prefix = "vite-plugin-uni-pages:";
734
- const suffix = typeof debugOption === "boolean" ? "*" : debugOption;
735
- debug.default.enable(`${prefix}${suffix}`);
736
- }
737
- this.resolvedPagesJSONPath = node_path.default.join(this.root, this.options.outDir, OUTPUT_NAME);
738
- debug$1.options(this.options);
739
- }
740
- /**
741
- * Set the Vite logger
742
- * @param logger - Vite logger instance
743
- */
744
- setLogger(logger) {
745
- this.logger = logger;
746
- }
747
- /**
748
- * Load user page configuration file (e.g. pages.config.ts)
749
- * Uses unconfig to load configuration, supporting multiple config file formats
750
- */
751
- async loadUserPagesConfig() {
752
- const configSource = this.options.configSource;
753
- const { config, sources } = await (0, unconfig.loadConfig)({
754
- cwd: this.root,
755
- sources: configSource,
756
- defaults: {}
757
- });
758
- this.pagesGlobConfig = config.default || config;
759
- this.pagesConfigSourcePaths = sources;
760
- debug$1.options(this.pagesGlobConfig);
761
- }
762
- /**
763
- * Scan main package page directories and collect all page file paths
764
- * Scan corresponding directories based on the configured dirs option
765
- */
766
- async scanPages() {
767
- const paths = this.options.dirs.map((dir) => {
768
- return {
769
- dir,
770
- files: getPagePaths(dir, this.options)
771
- };
772
- }).map((page) => page.files).flat();
773
- debug$1.pages(paths);
774
- const pages = /* @__PURE__ */ new Map();
775
- for (const path of paths) {
776
- const page = this.pages.get(path.absolutePath) || new Page(this, path);
777
- pages.set(path.absolutePath, page);
778
- }
779
- this.pages = pages;
780
- }
781
- /**
782
- * Scan sub-package page directories and collect all sub-package page file paths
783
- * Scan corresponding directories based on the configured subPackages option
784
- */
785
- async scanSubPages() {
786
- const paths = {};
787
- const subPages = /* @__PURE__ */ new Map();
788
- for (const dir of this.options.subPackages) {
789
- const pagePaths = getPagePaths(dir, this.options);
790
- paths[dir] = pagePaths;
791
- const pages = /* @__PURE__ */ new Map();
792
- for (const path of pagePaths) {
793
- const page = this.subPages.get(dir)?.get(path.absolutePath) || new Page(this, path);
794
- pages.set(path.absolutePath, page);
795
- }
796
- subPages.set(dir, pages);
797
- }
798
- debug$1.subPages(JSON.stringify(paths, null, 2));
799
- this.subPages = subPages;
800
- }
801
- /**
802
- * Set up Vite dev server for HMR and file watching
803
- * @param server - Vite dev server instance
804
- */
805
- setupViteServer(server) {
806
- if (this._server === server) return;
807
- this._server = server;
808
- this.setupWatcher(server.watcher);
809
- }
810
- /**
811
- * Set up file watcher to monitor page file and config file changes
812
- * Automatically update pages.json when page files or config files change
813
- * @param watcher - chokidar file watcher instance
814
- */
815
- async setupWatcher(watcher) {
816
- watcher.add(this.pagesConfigSourcePaths);
817
- const targetDirs = [...this.options.dirs, ...this.options.subPackages].map((v) => slash(node_path.default.resolve(this.root, v)));
818
- const isInTargetDirs = (filePath) => targetDirs.some((v) => slash(node_path.default.resolve(this.root, filePath)).startsWith(v));
819
- watcher.on("add", async (path) => {
820
- path = slash(path);
821
- if (!isTargetFile(path)) return;
822
- if (!isInTargetDirs(path)) return;
823
- debug$1.pages(`File added: ${path}`);
824
- if (await this.updatePagesJSON()) this.onUpdate();
825
- });
826
- watcher.on("change", async (path) => {
827
- path = slash(path);
828
- if (!isTargetFile(path)) return;
829
- if (!isInTargetDirs(path)) return;
830
- debug$1.pages(`File changed: ${path}`);
831
- debug$1.pages(targetDirs);
832
- debug$1.pages(isInTargetDirs(path));
833
- if (await this.updatePagesJSON(path)) this.onUpdate();
834
- });
835
- watcher.on("change", async (path) => {
836
- if (this.pagesConfigSourcePaths.includes(path)) {
837
- debug$1.pages(`Config source changed: ${path}`);
838
- if (await this.updatePagesJSON()) this.onUpdate();
839
- }
840
- });
841
- watcher.on("unlink", async (path) => {
842
- path = slash(path);
843
- if (!isTargetFile(path)) return;
844
- if (!isInTargetDirs(path)) return;
845
- debug$1.pages(`File removed: ${path}`);
846
- if (await this.updatePagesJSON()) this.onUpdate();
847
- });
848
- }
849
- /**
850
- * Page update callback, triggered when page files or configuration changes
851
- * Responsible for invalidating virtual modules and notifying the browser to do a full reload
852
- */
853
- onUpdate() {
854
- if (!this._server) return;
855
- invalidatePagesModule(this._server);
856
- debug$1.hmr("Reload generated pages.");
857
- this._server.ws.send({ type: "full-reload" });
858
- }
859
- /**
860
- * parse pages rules && set page type
861
- * @param pages page path array
862
- * @param type page type
863
- * @param overrides custom page config
864
- * @returns pages rules
865
- */
866
- async parsePages(pages, type, overrides) {
867
- const jobs = [];
868
- for (const [_, page] of pages) jobs.push(page.getPageMeta());
869
- const generatedPageMetaData = await Promise.all(jobs);
870
- const customPageMetaData = overrides || [];
871
- const result = customPageMetaData.length ? mergePageMetaDataArray(generatedPageMetaData.concat(customPageMetaData)) : generatedPageMetaData;
872
- const parseMeta = Array.from(result.reduce((map, page) => {
873
- map.set(page.path, page);
874
- return map;
875
- }, /* @__PURE__ */ new Map()).values());
876
- return type === "main" ? this.setHomePage(parseMeta) : parseMeta;
877
- }
878
- /**
879
- * set home page
880
- * @param result pages rules array
881
- * @returns pages rules
882
- */
883
- setHomePage(result) {
884
- if (!result.some(({ type }) => type === "home")) {
885
- const basePath = slash(node_path.default.join(this.options.root, this.options.outDir));
886
- const resolvedHomePages = this.options.homePage.map((v) => {
887
- return slash(node_path.default.relative(basePath, slash(node_path.default.resolve(basePath, v))));
888
- });
889
- const matchHomePage = (itemPath, configPath) => {
890
- if (itemPath === configPath) return true;
891
- const normalizedItem = itemPath.replace(/\\/g, "/");
892
- const normalizedConfig = configPath.replace(/\\/g, "/");
893
- return normalizedItem.endsWith(`/${normalizedConfig}`);
894
- };
895
- if (!result.some((item) => {
896
- const isFound = resolvedHomePages.some((expectedPath) => matchHomePage(item.path, expectedPath));
897
- if (isFound) item.type = "home";
898
- return isFound;
899
- })) 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 });
900
- }
901
- result.sort((page) => page.type === "home" ? -1 : 0);
902
- return result;
903
- }
904
- /**
905
- * Merge main package page metadata
906
- * Filter out pages belonging to sub-packages, then parse page metadata and merge user configuration
907
- */
908
- async mergePageMetaData() {
909
- const subPageAbsolutePaths = Array.from(this.subPages.values()).flatMap((v) => Array.from(v.keys()));
910
- for (const subPageAbsolutePath of subPageAbsolutePaths) this.pages.delete(subPageAbsolutePath);
911
- const pageMetaData = await this.parsePages(this.pages, "main", this.pagesGlobConfig?.pages);
912
- this.pageMetaData = pageMetaData;
913
- debug$1.pages(this.pageMetaData);
914
- }
915
- /**
916
- * Merge sub-package page metadata
917
- * Parse page metadata for each sub-package and handle sub-package configuration inheritance
918
- * Preserves sub-package level properties like plugins from user config
919
- */
920
- async mergeSubPageMetaData() {
921
- const subPageMaps = {};
922
- const subPlugins = {};
923
- const subPackages = this.pagesGlobConfig?.subPackages || [];
924
- for (const [dir, pages] of this.subPages) {
925
- const basePath = slash(node_path.default.join(this.options.root, this.options.outDir));
926
- const root = this.options.subPackageRootMap.get(dir) ?? slash(node_path.default.relative(basePath, node_path.default.join(this.options.root, dir)));
927
- const globPackage = subPackages?.find((v) => v.root === root);
928
- subPageMaps[root] = await this.parsePages(pages, "sub", globPackage?.pages);
929
- subPageMaps[root] = subPageMaps[root].map((page) => ({
930
- ...page,
931
- path: slash(node_path.default.relative(root, page.path))
932
- }));
933
- if (globPackage?.plugins) subPlugins[root] = globPackage.plugins;
934
- }
935
- for (const { root, pages, plugins } of subPackages) if (root && !subPageMaps[root]) {
936
- subPageMaps[root] = pages || [];
937
- if (plugins) subPlugins[root] = plugins;
938
- }
939
- const subPageMetaData = Object.keys(subPageMaps).map((root) => ({
940
- root,
941
- pages: subPageMaps[root],
942
- ...subPlugins[root] && { plugins: subPlugins[root] }
943
- })).filter((meta) => meta.pages.length > 0);
944
- this.subPageMetaData = subPageMetaData;
945
- debug$1.subPages(this.subPageMetaData);
946
- }
947
- /**
948
- * Update pages.json file
949
- * This is the core method responsible for coordinating the entire page configuration generation flow:
950
- * 1. Check file changes (if filepath is specified)
951
- * 2. Load user configuration
952
- * 3. Scan page files
953
- * 4. Merge page metadata
954
- * 5. Generate and write pages.json
955
- * @param filepath - Changed file path for incremental update judgment
956
- * @returns Whether pages.json was successfully updated
957
- */
958
- async updatePagesJSON(filepath) {
959
- if (filepath) {
960
- let page = this.pages.get(filepath);
961
- if (!page) {
962
- let subPage;
963
- for (const [_, pages] of this.subPages) {
964
- subPage = pages.get(filepath);
965
- if (subPage) break;
966
- }
967
- page = subPage;
968
- }
969
- if (page) {
970
- await page.read();
971
- if (!page.hasChanged()) {
972
- debug$1.cache(`The page meta on page ${filepath} did not send any changes, skipping`);
973
- return false;
974
- }
975
- }
976
- }
977
- checkPagesJsonFileSync(this.resolvedPagesJSONPath);
978
- this.options.onBeforeLoadUserConfig(this);
979
- await this.loadUserPagesConfig();
980
- this.options.onAfterLoadUserConfig(this);
981
- if (this.options.mergePages) {
982
- this.options.onBeforeScanPages(this);
983
- await this.scanPages();
984
- await this.scanSubPages();
985
- this.options.onAfterScanPages(this);
986
- }
987
- this.options.onBeforeMergePageMetaData(this);
988
- await this.mergePageMetaData();
989
- await this.mergeSubPageMetaData();
990
- this.options.onAfterMergePageMetaData(this);
991
- const pagesMap = /* @__PURE__ */ new Map();
992
- (this.withUniPlatform ? this.pageMetaData.filter((v) => !/\..*$/.test(v.path) || v.path.includes(_uni_helper_uni_env.platform)).map((v) => {
993
- v.path = v.path.replace(/\..*$/, "");
994
- return v;
995
- }) : this.pageMetaData).forEach((v) => pagesMap.set(v.path, v));
996
- this.pageMetaData = [...pagesMap.values()];
997
- this.options.onBeforeWriteFile(this);
998
- const updated = await withFileLock(this.resolvedPagesJSONPath, async () => {
999
- const pagesJson = (0, comment_json.stringify)(await this.genratePagesJSON(), null, this.options.minify ? void 0 : await this.getIndent()) + (await this.getEndOfLine() ? await this.getNewline() : "");
1000
- if (this.lastPagesJson === pagesJson) {
1001
- debug$1.pages("PagesJson Not have change");
1002
- return false;
1003
- }
1004
- await (0, write_file_atomic.default)(this.resolvedPagesJSONPath, pagesJson);
1005
- this.lastPagesJson = pagesJson;
1006
- return true;
1007
- });
1008
- this.generateDeclaration();
1009
- if (updated) this.options.onAfterWriteFile(this);
1010
- return updated ?? false;
1011
- }
1012
- /**
1013
- * Generate virtual module content
1014
- * Returns JavaScript code containing pages and subPackages exports
1015
- * @returns Virtual module code string
1016
- */
1017
- virtualModule() {
1018
- return [`export const pages = ${this.resolveRoutes()};`, `export const subPackages = ${this.resolveSubRoutes()};`].join("\n");
1019
- }
1020
- /**
1021
- * Resolve main package route data to JSON string
1022
- * @returns JSON string of main package page metadata
1023
- */
1024
- resolveRoutes() {
1025
- return (0, comment_json.stringify)(this.pageMetaData, null, 2);
1026
- }
1027
- /**
1028
- * Resolve sub-package route data to JSON string
1029
- * @returns JSON string of sub-package page metadata
1030
- */
1031
- resolveSubRoutes() {
1032
- return (0, comment_json.stringify)(this.subPageMetaData, null, 2);
1033
- }
1034
- /**
1035
- * Resolve tabBar configuration
1036
- * Merges page-defined tabBar items with config-defined tabBar
1037
- * @returns Merged tabBar configuration object, or undefined if no tabBar exists
1038
- */
1039
- async resolveTabBar() {
1040
- const tabBarItems = [];
1041
- for (const [_, page] of this.pages) {
1042
- const tabbar = await page.getTabBar();
1043
- if (tabbar) tabBarItems.push(tabbar);
1044
- }
1045
- if (tabBarItems.length === 0) return this.pagesGlobConfig?.tabBar;
1046
- const tabBar = {
1047
- ...this.pagesGlobConfig?.tabBar,
1048
- list: this.pagesGlobConfig?.tabBar?.list || []
1049
- };
1050
- const pagePaths = /* @__PURE__ */ new Map();
1051
- for (const item of tabBar.list) pagePaths.set(item.pagePath, true);
1052
- tabBarItems.sort((a, b) => a.index - b.index);
1053
- for (const item of tabBarItems) if (!pagePaths.has(item.pagePath)) {
1054
- const { index: _, ...tabbar } = item;
1055
- tabBar.list.push(tabbar);
1056
- }
1057
- return tabBar;
1058
- }
1059
- /**
1060
- * Generate TypeScript declaration file
1061
- * Generate type definitions for page paths to provide type hints during navigation
1062
- */
1063
- generateDeclaration() {
1064
- if (!this.options.dts) return;
1065
- debug$1.declaration("generating");
1066
- return writeDeclaration(this, this.options.dts);
1067
- }
1068
- async genratePagesJSON() {
1069
- const { pages: oldPages, subPackages: oldSubPackages, tabBar: oldTabBar } = (0, comment_json.parse)(await node_fs.default.promises.readFile(this.resolvedPagesJSONPath, { encoding: "utf-8" }).catch(() => "") || "{}");
1070
- const { pages: _pages, subPackages: _subPackages, tabBar: _tabBar, ...pageJson } = this.pagesGlobConfig || {};
1071
- const currentPlatform = _uni_helper_uni_env.platform.toUpperCase();
1072
- pageJson.pages = mergePlatformItems(oldPages, currentPlatform, this.pageMetaData, "path");
1073
- if (pageJson.pages && pageJson.pages.length > 0) {
1074
- const pagesArray = pageJson.pages;
1075
- const homeIndex = pagesArray.findIndex((page) => page.type === "home");
1076
- if (homeIndex > 0) {
1077
- const [homePage] = pagesArray.splice(homeIndex, 1);
1078
- pagesArray.unshift(homePage);
1079
- }
1080
- }
1081
- pageJson.subPackages = oldSubPackages || new comment_json.CommentArray();
1082
- const newSubPackages = /* @__PURE__ */ new Map();
1083
- for (const item of this.subPageMetaData) newSubPackages.set(item.root, item);
1084
- for (const existing of pageJson.subPackages) {
1085
- const sub = newSubPackages.get(existing.root);
1086
- if (sub) {
1087
- existing.pages = mergePlatformItems(existing.pages, currentPlatform, sub.pages, "path");
1088
- if (sub.plugins) existing.plugins = sub.plugins;
1089
- newSubPackages.delete(existing.root);
1090
- }
1091
- }
1092
- for (const [_, newSub] of newSubPackages) {
1093
- const subPackage = {
1094
- root: newSub.root,
1095
- pages: mergePlatformItems(void 0, currentPlatform, newSub.pages, "path")
1096
- };
1097
- if (newSub.plugins) subPackage.plugins = newSub.plugins;
1098
- pageJson.subPackages.push(subPackage);
1099
- }
1100
- const { list, ...tabBarOthers } = await this.resolveTabBar() || {};
1101
- if (list) {
1102
- const { list: oldList } = oldTabBar || {};
1103
- const newList = mergePlatformItems(oldList, currentPlatform, list, "pagePath");
1104
- pageJson.tabBar = {
1105
- ...tabBarOthers,
1106
- list: newList
1107
- };
1108
- } else pageJson.tabBar = void 0;
1109
- return pageJson;
1110
- }
1111
- async readInfoFromPagesJSON() {
1112
- const resolvedPagesJSONContent = await node_fs.default.promises.readFile(this.resolvedPagesJSONPath, { encoding: "utf-8" }).catch(() => "");
1113
- this.resolvedPagesJSONIndent = (0, detect_indent.default)(resolvedPagesJSONContent).indent || " ";
1114
- this.resolvedPagesJSONNewline = (0, detect_newline.default)(resolvedPagesJSONContent) || "\n";
1115
- this.resolvedPagesJSONEofNewline = (resolvedPagesJSONContent.at(-1) ?? "\n") === this.resolvedPagesJSONNewline;
1116
- }
1117
- async getIndent() {
1118
- if (!this.resolvedPagesJSONIndent) await this.readInfoFromPagesJSON();
1119
- return this.resolvedPagesJSONIndent;
1120
- }
1121
- async getNewline() {
1122
- if (!this.resolvedPagesJSONNewline) await this.readInfoFromPagesJSON();
1123
- return this.resolvedPagesJSONNewline;
1124
- }
1125
- async getEndOfLine() {
1126
- if (!this.resolvedPagesJSONEofNewline) await this.readInfoFromPagesJSON();
1127
- return this.resolvedPagesJSONEofNewline;
1128
- }
1129
- };
1130
- /**
1131
- * Get all page paths in the specified directory
1132
- * @param dir - Page directory path
1133
- * @param options - Resolved configuration options
1134
- * @returns Page path array containing relative and absolute paths
1135
- */
1136
- function getPagePaths(dir, options) {
1137
- const pagesDirPath = slash(node_path.default.resolve(options.root, dir));
1138
- const basePath = slash(node_path.default.join(options.root, options.outDir));
1139
- const files = getPageFiles(pagesDirPath, options);
1140
- debug$1.pages(dir, files);
1141
- return files.map((file) => slash(file)).map((file) => ({
1142
- relativePath: node_path.default.relative(basePath, slash(node_path.default.resolve(pagesDirPath, file))),
1143
- absolutePath: slash(node_path.default.resolve(pagesDirPath, file))
1144
- }));
1145
- }
1146
- /**
1147
- * Merge multi-platform page configuration items
1148
- * Handle conditional compilation comments (#ifdef / #endif), merge configuration items from different platforms into one array
1149
- * Same configuration items will automatically merge platform identifiers, different configuration items will keep conditional compilation comments
1150
- *
1151
- * @param source - Existing configuration item array (from pages.json)
1152
- * @param currentPlatform - Current platform identifier (e.g. H5, MP-WEIXIN)
1153
- * @param items - New configuration item array
1154
- * @param uniqueKeyName - Field name used to identify configuration item uniqueness (e.g. 'path' or 'pagePath')
1155
- * @returns Merged configuration item array with conditional compilation comments
1156
- */
1157
- function mergePlatformItems(source, currentPlatform, items, uniqueKeyName) {
1158
- const src = source || new comment_json.CommentArray();
1159
- currentPlatform = currentPlatform.toUpperCase();
1160
- let lastPlatforms = [];
1161
- for (const comment of src[Symbol.for("before:0")] || []) {
1162
- const trimed = comment.value.trim();
1163
- if (trimed.startsWith("GENERATED BY UNI-PAGES, PLATFORM:")) lastPlatforms = trimed.split(":")[1].split("||").map((s) => s.trim()).filter((s) => s !== currentPlatform).sort();
1164
- }
1165
- const stringifyForCompare = (val) => {
1166
- if (val && typeof val === "object" && "type" in val) {
1167
- const { type: _type, ...rest } = val;
1168
- return JSON.stringify(rest);
1169
- }
1170
- return JSON.stringify(val);
1171
- };
1172
- const tmpMap = /* @__PURE__ */ new Map();
1173
- for (let i = 0; i < src.length; i++) {
1174
- const item = src[i];
1175
- const uniqueKey = item[uniqueKeyName];
1176
- if (!uniqueKey) continue;
1177
- const ifdefComment = src[Symbol.for(`before:${i}`)]?.find((c) => c.value.trim().startsWith("#ifdef"));
1178
- let platforms = [...lastPlatforms];
1179
- if (ifdefComment) {
1180
- const match = ifdefComment.value.match(/#ifdef\s+(.+)/);
1181
- if (match) platforms = match[1].split("||").map((p) => p.trim()).filter((s) => s !== currentPlatform).sort();
1182
- }
1183
- if (platforms.length === 0) continue;
1184
- const existing = tmpMap.get(uniqueKey) || [];
1185
- existing.push({
1186
- item,
1187
- itemStr: stringifyForCompare(item),
1188
- platforms,
1189
- platformStr: platforms.join(" || ")
1190
- });
1191
- tmpMap.set(uniqueKey, existing);
1192
- }
1193
- for (const item of items) {
1194
- const newItem = item;
1195
- const uniqueKey = item[uniqueKeyName];
1196
- if (!uniqueKey) continue;
1197
- if (!tmpMap.has(uniqueKey)) {
1198
- tmpMap.set(uniqueKey, [{
1199
- item: newItem,
1200
- itemStr: stringifyForCompare(newItem),
1201
- platforms: [currentPlatform],
1202
- platformStr: currentPlatform
1203
- }]);
1204
- continue;
1205
- }
1206
- const existing = tmpMap.get(uniqueKey);
1207
- const newItemStr = stringifyForCompare(newItem);
1208
- const equalObj = existing.find((val) => val.itemStr === newItemStr);
1209
- if (equalObj) {
1210
- equalObj.platforms.push(currentPlatform);
1211
- equalObj.platforms.sort();
1212
- equalObj.platformStr = equalObj.platforms.join(" || ");
1213
- } else existing.push({
1214
- item: newItem,
1215
- itemStr: stringifyForCompare(newItem),
1216
- platforms: [currentPlatform],
1217
- platformStr: currentPlatform
1218
- });
1219
- }
1220
- const result = new comment_json.CommentArray();
1221
- const platformUsage = {};
1222
- tmpMap.forEach((val) => {
1223
- Object.values(val).forEach((v) => {
1224
- platformUsage[v.platformStr] = (platformUsage[v.platformStr] || 0) + 1;
1225
- });
1226
- });
1227
- const usageKeys = Object.keys(platformUsage);
1228
- const defaultPlatformStr = usageKeys.length ? usageKeys.reduce((a, b) => platformUsage[a] > platformUsage[b] ? a : b) : currentPlatform;
1229
- result[Symbol.for("before:0")] = [{
1230
- type: "LineComment",
1231
- value: ` GENERATED BY UNI-PAGES, PLATFORM: ${defaultPlatformStr}`,
1232
- inline: false,
1233
- loc: {
1234
- start: {
1235
- line: 0,
1236
- column: 0
1237
- },
1238
- end: {
1239
- line: 0,
1240
- column: 0
1241
- }
1242
- }
1243
- }];
1244
- for (const [_, list] of tmpMap) for (const { item, platformStr } of list) {
1245
- result.push(item);
1246
- if (platformStr !== defaultPlatformStr) {
1247
- result[Symbol.for(`before:${result.length - 1}`)] = [{
1248
- type: "LineComment",
1249
- value: ` #ifdef ${platformStr}`,
1250
- inline: false,
1251
- loc: {
1252
- start: {
1253
- line: 0,
1254
- column: 0
1255
- },
1256
- end: {
1257
- line: 0,
1258
- column: 0
1259
- }
1260
- }
1261
- }];
1262
- result[Symbol.for(`after:${result.length - 1}`)] = [{
1263
- type: "LineComment",
1264
- value: " #endif",
1265
- inline: false,
1266
- loc: {
1267
- start: {
1268
- line: 0,
1269
- column: 0
1270
- },
1271
- end: {
1272
- line: 0,
1273
- column: 0
1274
- }
1275
- }
1276
- }];
1277
- }
1278
- }
1279
- return result;
1280
- }
1281
- //#endregion
1282
- //#region src/config/index.ts
1283
- /**
1284
- * Define uni-pages configuration
1285
- * Used in pages.config.ts configuration file to provide type hints and validation
1286
- *
1287
- * @param config - Page configuration object
1288
- * @returns Configuration object
1289
- */
1290
- function defineUniPages(config) {
1291
- return config;
1292
- }
1293
- //#endregion
1294
- //#region src/index.ts
1295
- /**
1296
- * vite-plugin-uni-pages plugin main entry
1297
- *
1298
- * Automatically scan page directories and generate pages.json configuration file
1299
- * Support definePage macro for defining page metadata
1300
- * Support multi-platform conditional compilation
1301
- * Support sub-package configuration
1302
- * Support TypeScript declaration file generation
1303
- *
1304
- * @param userOptions - User configuration options
1305
- * @returns Vite plugin instance
1306
- */
1307
- function VitePluginUniPages(userOptions = {}) {
1308
- let ctx;
1309
- checkPagesJsonFileSync(node_path.default.join(node_process.default.env.VITE_ROOT_DIR || node_process.default.cwd(), userOptions.outDir ?? "src", OUTPUT_NAME));
1310
- return {
1311
- name: "vite-plugin-uni-pages",
1312
- enforce: "pre",
1313
- /**
1314
- * Vite configResolved hook
1315
- * Initialize PageContext, set logger, generate initial pages.json
1316
- */
1317
- async configResolved(config) {
1318
- ctx = new PageContext(userOptions, config.root);
1319
- if (config.plugins.some((v) => v.name === "vite-plugin-uni-platform")) ctx.withUniPlatform = true;
1320
- const logger = (0, vite.createLogger)(void 0, { prefix: "[vite-plugin-uni-pages]" });
1321
- ctx.setLogger(logger);
1322
- await ctx.updatePagesJSON();
1323
- if (config.command === "build") {
1324
- if (config.build.watch) ctx.setupWatcher(chokidar.default.watch([...ctx.options.dirs, ...ctx.options.subPackages]));
1325
- }
1326
- },
1327
- /**
1328
- * Code transform hook
1329
- * Remove definePage macro calls from Vue SFC to avoid runtime errors
1330
- */
1331
- async transform(code, id) {
1332
- if (!FILE_EXTENSIONS.some((ext) => id.endsWith(ext))) return null;
1333
- const sfc = parseSFC(code, { filename: id });
1334
- let macro;
1335
- if (sfc.scriptSetup) macro = findMacro((0, ast_kit.babelParse)(sfc.scriptSetup.content, sfc.scriptSetup.lang || "js").body, sfc.filename);
1336
- if (!macro && sfc.script) macro = findMacro((0, ast_kit.babelParse)(sfc.script.content, sfc.script.lang || "js").body, sfc.filename);
1337
- if (!macro) return null;
1338
- const s = new magic_string.default(code);
1339
- s.remove(macro.start, macro.end);
1340
- if (s.hasChanged()) return {
1341
- code: s.toString(),
1342
- map: s.generateMap({
1343
- source: id,
1344
- includeContent: true,
1345
- file: `${id}.map`
1346
- })
1347
- };
1348
- },
1349
- /**
1350
- * Configure server hook
1351
- * Set up file watching and HMR support
1352
- */
1353
- configureServer(server) {
1354
- ctx.setupViteServer(server);
1355
- },
1356
- /**
1357
- * Module resolution hook
1358
- * Resolve virtual module identifier to internal path
1359
- */
1360
- resolveId(id) {
1361
- if (id === "virtual:uni-pages") return RESOLVED_MODULE_ID_VIRTUAL;
1362
- },
1363
- /**
1364
- * Module load hook
1365
- * Return the code content of the virtual module
1366
- */
1367
- load(id) {
1368
- if (id === RESOLVED_MODULE_ID_VIRTUAL) return ctx.virtualModule();
1369
- }
1370
- };
1371
- }
1372
- //#endregion
1373
- exports.FILE_EXTENSIONS = FILE_EXTENSIONS;
1374
- exports.MODULE_ID_VIRTUAL = MODULE_ID_VIRTUAL;
1375
- exports.OUTPUT_NAME = OUTPUT_NAME;
1376
- exports.Page = Page;
1377
- exports.PageContext = PageContext;
1378
- exports.RESOLVED_MODULE_ID_VIRTUAL = RESOLVED_MODULE_ID_VIRTUAL;
1379
- exports.VitePluginUniPages = VitePluginUniPages;
1380
- exports.default = VitePluginUniPages;
1381
- exports.babelGenerate = babelGenerate;
1382
- exports.checkPagesJsonFileSync = checkPagesJsonFileSync;
1383
- exports.debug = debug$1;
1384
- exports.defineUniPages = defineUniPages;
1385
- exports.extsToGlob = extsToGlob;
1386
- exports.findImports = findImports;
1387
- exports.findMacro = findMacro;
1388
- exports.getPageFiles = getPageFiles;
1389
- exports.invalidatePagesModule = invalidatePagesModule;
1390
- exports.isTargetFile = isTargetFile;
1391
- exports.mergePageMetaDataArray = mergePageMetaDataArray;
1392
- exports.parseCode = parseCode;
1393
- exports.parseSFC = parseSFC;
1394
- exports.resolveOptions = resolveOptions;
1395
- exports.resolvePageDirs = resolvePageDirs;
1396
- exports.sleep = sleep;
1397
- exports.tryPageMetaFromMacro = tryPageMetaFromMacro;
1398
- exports.withFileLock = withFileLock;
1399
- exports.writeFileWithLock = writeFileWithLock;