@mpcore/simulator 0.0.0 → 0.0.2

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.mjs CHANGED
@@ -1,15 +1,417 @@
1
+ import { dirname, join, normalize, posix } from "pathe";
2
+ import { parseDocument } from "htmlparser2";
3
+ import { Buffer } from "node:buffer";
1
4
  import fs from "node:fs";
2
5
  import path from "node:path";
3
- import { normalize } from "pathe";
4
6
  import process from "node:process";
5
7
  import vm from "node:vm";
6
- import { parseDocument } from "htmlparser2";
8
+ //#region src/host/globals.ts
9
+ function createDuplicateRegistrationError(kind, id) {
10
+ return /* @__PURE__ */ new Error(`Duplicate ${kind} registration in headless runtime: ${id}`);
11
+ }
12
+ function createHostRegistries() {
13
+ return {
14
+ appDefinition: null,
15
+ components: /* @__PURE__ */ new Map(),
16
+ currentLoadContext: null,
17
+ pages: /* @__PURE__ */ new Map()
18
+ };
19
+ }
20
+ function registerAppDefinition(registries, definition) {
21
+ if (registries.appDefinition) throw createDuplicateRegistrationError("app", "app");
22
+ registries.appDefinition = definition;
23
+ return definition;
24
+ }
25
+ function registerPageDefinition(registries, definition) {
26
+ const route = registries.currentLoadContext?.route;
27
+ if (!route) throw new Error("Cannot register Page() without an active page load context in headless runtime.");
28
+ if (registries.pages.has(route)) throw createDuplicateRegistrationError("page", route);
29
+ registries.pages.set(route, definition);
30
+ return definition;
31
+ }
32
+ function registerComponentDefinition(registries, definition) {
33
+ const id = registries.currentLoadContext?.route ?? `anonymous:${registries.components.size}`;
34
+ if (registries.components.has(id)) throw createDuplicateRegistrationError("component", id);
35
+ registries.components.set(id, definition);
36
+ return definition;
37
+ }
38
+ //#endregion
39
+ //#region src/host/wx.ts
40
+ function invokeWxApi(operation, option) {
41
+ try {
42
+ const result = operation();
43
+ option?.success?.(result);
44
+ option?.complete?.(result);
45
+ return result;
46
+ } catch (error) {
47
+ option?.fail?.(error);
48
+ option?.complete?.();
49
+ return;
50
+ }
51
+ }
52
+ function resolveCapabilityValue(source, schema) {
53
+ const segments = schema.split(".").map((segment) => segment.trim()).filter(Boolean);
54
+ let current = source;
55
+ for (const segment of segments) {
56
+ if (current == null || !(segment in current)) return;
57
+ current = current[segment];
58
+ }
59
+ return current;
60
+ }
61
+ function createHeadlessWx(driver) {
62
+ const capabilityTree = {
63
+ canIUse: true,
64
+ clearStorage: true,
65
+ clearStorageSync: true,
66
+ getAppBaseInfo: { return: {
67
+ SDKVersion: true,
68
+ enableDebug: true,
69
+ host: { env: true },
70
+ language: true,
71
+ platform: true,
72
+ version: true
73
+ } },
74
+ getAppBaseInfoSync: { return: {
75
+ SDKVersion: true,
76
+ enableDebug: true,
77
+ host: { env: true },
78
+ language: true,
79
+ platform: true,
80
+ version: true
81
+ } },
82
+ getEnterOptionsSync: { return: {
83
+ path: true,
84
+ query: true,
85
+ referrerInfo: {
86
+ appId: true,
87
+ extraData: true
88
+ },
89
+ scene: true
90
+ } },
91
+ getLaunchOptionsSync: { return: {
92
+ path: true,
93
+ query: true,
94
+ referrerInfo: {
95
+ appId: true,
96
+ extraData: true
97
+ },
98
+ scene: true
99
+ } },
100
+ getMenuButtonBoundingClientRect: { return: {
101
+ bottom: true,
102
+ height: true,
103
+ left: true,
104
+ right: true,
105
+ top: true,
106
+ width: true
107
+ } },
108
+ getNetworkType: { return: { networkType: true } },
109
+ getStorage: true,
110
+ getStorageInfo: { return: {
111
+ currentSize: true,
112
+ keys: true,
113
+ limitSize: true
114
+ } },
115
+ getStorageInfoSync: { return: {
116
+ currentSize: true,
117
+ keys: true,
118
+ limitSize: true
119
+ } },
120
+ getStorageSync: true,
121
+ getSystemInfo: { return: {
122
+ SDKVersion: true,
123
+ brand: true,
124
+ language: true,
125
+ model: true,
126
+ pixelRatio: true,
127
+ platform: true,
128
+ screenHeight: true,
129
+ screenWidth: true,
130
+ system: true,
131
+ version: true,
132
+ windowHeight: true,
133
+ windowWidth: true
134
+ } },
135
+ getSystemInfoSync: { return: {
136
+ SDKVersion: true,
137
+ brand: true,
138
+ language: true,
139
+ model: true,
140
+ pixelRatio: true,
141
+ platform: true,
142
+ screenHeight: true,
143
+ screenWidth: true,
144
+ system: true,
145
+ version: true,
146
+ windowHeight: true,
147
+ windowWidth: true
148
+ } },
149
+ getWindowInfo: { return: {
150
+ pixelRatio: true,
151
+ screenHeight: true,
152
+ screenWidth: true,
153
+ statusBarHeight: true,
154
+ windowHeight: true,
155
+ windowWidth: true
156
+ } },
157
+ getWindowInfoSync: { return: {
158
+ pixelRatio: true,
159
+ screenHeight: true,
160
+ screenWidth: true,
161
+ statusBarHeight: true,
162
+ windowHeight: true,
163
+ windowWidth: true
164
+ } },
165
+ hideLoading: true,
166
+ hideToast: true,
167
+ navigateBack: true,
168
+ navigateTo: true,
169
+ nextTick: true,
170
+ offNetworkStatusChange: true,
171
+ onNetworkStatusChange: true,
172
+ pageScrollTo: true,
173
+ reLaunch: true,
174
+ redirectTo: true,
175
+ removeStorage: true,
176
+ removeStorageSync: true,
177
+ request: true,
178
+ setBackgroundColor: true,
179
+ setBackgroundTextStyle: true,
180
+ setStorage: true,
181
+ setStorageSync: true,
182
+ setNavigationBarColor: true,
183
+ setNavigationBarTitle: true,
184
+ hideShareMenu: true,
185
+ hideNavigationBarLoading: true,
186
+ hideTabBar: true,
187
+ hideTabBarRedDot: true,
188
+ showShareMenu: true,
189
+ showNavigationBarLoading: true,
190
+ showTabBar: true,
191
+ showTabBarRedDot: true,
192
+ showActionSheet: true,
193
+ showLoading: true,
194
+ showModal: true,
195
+ showToast: true,
196
+ stopPullDownRefresh: true,
197
+ switchTab: true,
198
+ removeTabBarBadge: true,
199
+ setTabBarBadge: true,
200
+ updateShareMenu: true
201
+ };
202
+ return {
203
+ canIUse: (schema) => typeof schema === "string" && schema.trim() !== "" && resolveCapabilityValue(capabilityTree, schema.trim()) != null,
204
+ clearStorage: (option) => invokeWxApi(() => {
205
+ driver.clearStorageSync();
206
+ return { errMsg: "clearStorage:ok" };
207
+ }, option),
208
+ clearStorageSync: () => driver.clearStorageSync(),
209
+ getEnterOptionsSync: () => driver.getEnterOptionsSync(),
210
+ getAppBaseInfo: (option) => invokeWxApi(() => driver.getAppBaseInfoSync(), option),
211
+ getAppBaseInfoSync: () => driver.getAppBaseInfoSync(),
212
+ getLaunchOptionsSync: () => driver.getLaunchOptionsSync(),
213
+ getMenuButtonBoundingClientRect: () => driver.getMenuButtonBoundingClientRect(),
214
+ getNetworkType: (option) => invokeWxApi(() => driver.getNetworkType(), option),
215
+ getStorageInfo: (option) => invokeWxApi(() => driver.getStorageInfoSync(), option),
216
+ getStorageInfoSync: () => driver.getStorageInfoSync(),
217
+ getStorage: (option) => invokeWxApi(() => ({
218
+ data: driver.getStorageSync(option.key),
219
+ errMsg: "getStorage:ok"
220
+ }), option),
221
+ getStorageSync: (key) => driver.getStorageSync(key),
222
+ getSystemInfo: (option) => invokeWxApi(() => driver.getSystemInfoSync(), option),
223
+ getSystemInfoSync: () => driver.getSystemInfoSync(),
224
+ getWindowInfo: (option) => invokeWxApi(() => driver.getWindowInfoSync(), option),
225
+ getWindowInfoSync: () => driver.getWindowInfoSync(),
226
+ hideLoading: (option) => invokeWxApi(() => driver.hideLoading(), option),
227
+ hideToast: () => driver.hideToast(),
228
+ navigateBack: (option) => invokeWxApi(() => {
229
+ driver.navigateBack(option);
230
+ }, option),
231
+ navigateTo: (option) => invokeWxApi(() => {
232
+ driver.navigateTo(option);
233
+ }, option),
234
+ nextTick: (callback) => driver.nextTick(callback),
235
+ offNetworkStatusChange: (callback) => driver.offNetworkStatusChange(callback),
236
+ onNetworkStatusChange: (callback) => driver.onNetworkStatusChange(callback),
237
+ pageScrollTo: (option) => invokeWxApi(() => {
238
+ driver.pageScrollTo(option);
239
+ }, option),
240
+ reLaunch: (option) => invokeWxApi(() => {
241
+ driver.reLaunch(option);
242
+ }, option),
243
+ redirectTo: (option) => invokeWxApi(() => {
244
+ driver.redirectTo(option);
245
+ }, option),
246
+ removeStorage: (option) => invokeWxApi(() => {
247
+ driver.removeStorageSync(option.key);
248
+ return { errMsg: "removeStorage:ok" };
249
+ }, option),
250
+ removeStorageSync: (key) => driver.removeStorageSync(key),
251
+ request: (option) => driver.request(option),
252
+ setBackgroundColor: (option) => invokeWxApi(() => driver.setBackgroundColor(option), option),
253
+ setBackgroundTextStyle: (option) => invokeWxApi(() => driver.setBackgroundTextStyle(option), option),
254
+ setStorage: (option) => invokeWxApi(() => {
255
+ driver.setStorageSync(option.key, option.data);
256
+ return { errMsg: "setStorage:ok" };
257
+ }, option),
258
+ setStorageSync: (key, value) => driver.setStorageSync(key, value),
259
+ setNavigationBarColor: (option) => invokeWxApi(() => driver.setNavigationBarColor(option), option),
260
+ setNavigationBarTitle: (option) => invokeWxApi(() => driver.setNavigationBarTitle(option), option),
261
+ hideShareMenu: (option) => invokeWxApi(() => driver.hideShareMenu(), option),
262
+ hideNavigationBarLoading: (option) => invokeWxApi(() => driver.hideNavigationBarLoading(), option),
263
+ hideTabBar: (option) => invokeWxApi(() => driver.hideTabBar(), option),
264
+ hideTabBarRedDot: (option) => invokeWxApi(() => driver.hideTabBarRedDot(option), option),
265
+ showShareMenu: (option) => invokeWxApi(() => driver.showShareMenu(option ?? {}), option),
266
+ showNavigationBarLoading: (option) => invokeWxApi(() => driver.showNavigationBarLoading(), option),
267
+ showTabBar: (option) => invokeWxApi(() => driver.showTabBar(), option),
268
+ showTabBarRedDot: (option) => invokeWxApi(() => driver.showTabBarRedDot(option), option),
269
+ showActionSheet: (option) => invokeWxApi(() => driver.showActionSheet(option), option),
270
+ showLoading: (option) => invokeWxApi(() => driver.showLoading(option), option),
271
+ showModal: (option) => invokeWxApi(() => driver.showModal(option), option),
272
+ showToast: (option) => invokeWxApi(() => driver.showToast(option), option),
273
+ stopPullDownRefresh: () => driver.stopPullDownRefresh(),
274
+ switchTab: (option) => invokeWxApi(() => {
275
+ driver.switchTab(option);
276
+ }, option),
277
+ removeTabBarBadge: (option) => invokeWxApi(() => driver.removeTabBarBadge(option), option),
278
+ setTabBarBadge: (option) => invokeWxApi(() => driver.setTabBarBadge(option), option),
279
+ updateShareMenu: (option) => invokeWxApi(() => driver.updateShareMenu(option ?? {}), option)
280
+ };
281
+ }
282
+ //#endregion
283
+ //#region src/browser/virtualFiles.ts
284
+ function normalizeBrowserFilePath(filePath) {
285
+ return normalize(filePath).replace(/^\/+/, "").replace(/^\.\//, "");
286
+ }
287
+ function createBrowserVirtualFiles(entries) {
288
+ const files = /* @__PURE__ */ new Map();
289
+ for (const [filePath, content] of entries) files.set(normalizeBrowserFilePath(filePath), content);
290
+ return files;
291
+ }
292
+ async function createBrowserVirtualFilesFromDirectory(files) {
293
+ return createBrowserVirtualFiles(await Promise.all(files.map(async (file) => {
294
+ return [file.webkitRelativePath?.trim() || file.name, await file.text()];
295
+ })));
296
+ }
297
+ function readBrowserVirtualFile(files, filePath) {
298
+ return files.get(normalizeBrowserFilePath(filePath));
299
+ }
300
+ function hasBrowserVirtualFile(files, filePath) {
301
+ return files.has(normalizeBrowserFilePath(filePath));
302
+ }
303
+ //#endregion
304
+ //#region src/browser/moduleLoader.ts
305
+ function createRequireNotFoundError$1(request, importer) {
306
+ return /* @__PURE__ */ new Error(`Cannot resolve require("${request}") from ${normalize(importer)} in browser simulator runtime.`);
307
+ }
308
+ function resolveRequiredModulePath$1(files, importer, request) {
309
+ if (!request.startsWith(".")) throw createRequireNotFoundError$1(request, importer);
310
+ const basePath = normalize(join(dirname(importer), request));
311
+ const candidates = [
312
+ basePath,
313
+ `${basePath}.js`,
314
+ `${basePath}.json`,
315
+ join(basePath, "index.js")
316
+ ];
317
+ for (const candidate of candidates) if (hasBrowserVirtualFile(files, candidate)) return candidate;
318
+ throw createRequireNotFoundError$1(request, importer);
319
+ }
320
+ function createExecutionContext$1(registries, getCurrentPages, getApp, wxDriver) {
321
+ const wx = createHeadlessWx(wxDriver);
322
+ return {
323
+ App(definition) {
324
+ return registerAppDefinition(registries, definition);
325
+ },
326
+ Behavior(definition) {
327
+ return {
328
+ ...definition,
329
+ __isHeadlessBehavior__: true
330
+ };
331
+ },
332
+ Component(definition) {
333
+ return registerComponentDefinition(registries, definition);
334
+ },
335
+ Page(definition) {
336
+ return registerPageDefinition(registries, definition);
337
+ },
338
+ URLSearchParams,
339
+ clearInterval,
340
+ clearTimeout,
341
+ console,
342
+ getApp,
343
+ getCurrentPages,
344
+ globalThis: void 0,
345
+ require: void 0,
346
+ setInterval,
347
+ setTimeout,
348
+ wx
349
+ };
350
+ }
351
+ function createBrowserModuleLoader(files, registries, getCurrentPages, getApp, wxDriver) {
352
+ const moduleCache = /* @__PURE__ */ new Map();
353
+ const executionContext = createExecutionContext$1(registries, getCurrentPages, getApp, wxDriver);
354
+ executionContext.globalThis = executionContext;
355
+ function executeModule(filePath, loadContext) {
356
+ const resolvedPath = normalize(filePath);
357
+ const cached = moduleCache.get(resolvedPath);
358
+ if (cached) return cached.exports;
359
+ const source = readBrowserVirtualFile(files, resolvedPath);
360
+ if (typeof source !== "string") throw new Error(`Missing virtual module in browser simulator runtime: ${resolvedPath}`);
361
+ const module = { exports: {} };
362
+ moduleCache.set(resolvedPath, module);
363
+ const previousLoadContext = registries.currentLoadContext;
364
+ registries.currentLoadContext = loadContext;
365
+ const localRequire = (request) => {
366
+ const requiredPath = resolveRequiredModulePath$1(files, resolvedPath, request);
367
+ if (requiredPath.endsWith(".json")) {
368
+ const content = readBrowserVirtualFile(files, requiredPath);
369
+ if (typeof content !== "string") throw new Error(`Missing virtual json module in browser simulator runtime: ${requiredPath}`);
370
+ return JSON.parse(content);
371
+ }
372
+ return executeModule(requiredPath, null);
373
+ };
374
+ try {
375
+ const contextEntries = Object.entries(executionContext);
376
+ new Function(...contextEntries.map(([key]) => key), "exports", "module", "require", "__filename", "__dirname", source)(...contextEntries.map(([, value]) => value), module.exports, module, localRequire, resolvedPath, dirname(resolvedPath));
377
+ return module.exports;
378
+ } finally {
379
+ registries.currentLoadContext = previousLoadContext;
380
+ }
381
+ }
382
+ return {
383
+ executeAppModule(filePath) {
384
+ executeModule(filePath, { kind: "app" });
385
+ if (!registries.appDefinition) throw new Error(`App() was not registered while executing ${normalize(filePath)} in browser simulator runtime.`);
386
+ return registries.appDefinition;
387
+ },
388
+ executePageModule(filePath, route) {
389
+ executeModule(filePath, {
390
+ kind: "page",
391
+ route
392
+ });
393
+ const definition = registries.pages.get(route);
394
+ if (!definition) throw new Error(`Page() was not registered for route "${route}" while executing ${normalize(filePath)}.`);
395
+ return definition;
396
+ },
397
+ executeComponentModule(filePath, id) {
398
+ executeModule(filePath, {
399
+ kind: "component",
400
+ route: id
401
+ });
402
+ const definition = registries.components.get(id);
403
+ if (!definition) throw new Error(`Component() was not registered for id "${id}" while executing ${normalize(filePath)}.`);
404
+ return definition;
405
+ }
406
+ };
407
+ }
408
+ //#endregion
7
409
  //#region src/project/resolveRoutes.ts
8
- const LEADING_SLASH_RE$2 = /^\/+/;
410
+ const LEADING_SLASH_RE$5 = /^\/+/;
9
411
  const TRAILING_SLASH_RE = /\/+$/;
10
412
  const DUPLICATE_SLASH_RE = /\/{2,}/g;
11
413
  function normalizeSegment(value) {
12
- return value.replace(LEADING_SLASH_RE$2, "").replace(TRAILING_SLASH_RE, "");
414
+ return value.replace(LEADING_SLASH_RE$5, "").replace(TRAILING_SLASH_RE, "");
13
415
  }
14
416
  function pushRoute(records, seen, record) {
15
417
  if (!record.route || seen.has(record.route)) return;
@@ -49,184 +451,2055 @@ function resolveRoutesFromAppConfig(config) {
49
451
  return records;
50
452
  }
51
453
  //#endregion
52
- //#region src/project/loadProject.ts
53
- function readJsonObject(filePath) {
454
+ //#region src/project/createProjectDescriptor.ts
455
+ function createProjectDescriptor(options) {
456
+ return {
457
+ appConfig: options.appConfig,
458
+ appConfigPath: options.appConfigPath,
459
+ miniprogramRoot: options.miniprogramRoot,
460
+ miniprogramRootPath: options.miniprogramRootPath,
461
+ projectPath: options.projectPath,
462
+ projectConfigFiles: options.projectConfigFiles ?? [],
463
+ routes: resolveRoutesFromAppConfig(options.appConfig)
464
+ };
465
+ }
466
+ //#endregion
467
+ //#region src/browser/project.ts
468
+ function readJsonObject$3(files, filePath) {
469
+ const content = readBrowserVirtualFile(files, filePath);
470
+ if (!content) return;
54
471
  try {
55
- const content = fs.readFileSync(filePath, "utf8");
56
472
  const value = JSON.parse(content);
57
473
  return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
58
474
  } catch {
59
475
  return;
60
476
  }
61
477
  }
62
- function resolveProjectConfigFiles(projectPath) {
63
- const entries = [];
64
- for (const fileName of ["project.config.json", "project.private.config.json"]) {
65
- const filePath = path.resolve(projectPath, fileName);
66
- const value = readJsonObject(filePath);
67
- if (!value) continue;
68
- entries.push({
69
- filePath,
70
- value
71
- });
478
+ function createBrowserProject(files, options = {}) {
479
+ const appConfigPath = options.appConfigPath ?? "app.json";
480
+ if (!hasBrowserVirtualFile(files, appConfigPath)) throw new Error(`Missing built app.json for browser simulator project: ${appConfigPath}`);
481
+ const appConfig = readJsonObject$3(files, appConfigPath);
482
+ if (!appConfig) throw new Error(`Failed to read built app.json for browser simulator project: ${appConfigPath}`);
483
+ return createProjectDescriptor({
484
+ appConfig,
485
+ appConfigPath,
486
+ miniprogramRoot: options.miniprogramRoot ?? ".",
487
+ miniprogramRootPath: options.miniprogramRootPath ?? "/",
488
+ projectPath: options.projectPath ?? "browser://simulator",
489
+ projectConfigFiles: []
490
+ });
491
+ }
492
+ //#endregion
493
+ //#region src/runtime/componentInstance.ts
494
+ function bindFunction$2(target, key, value) {
495
+ if (typeof value !== "function") {
496
+ target[key] = value;
497
+ return;
72
498
  }
73
- return entries;
499
+ target[key] = (...args) => value.apply(target, args);
74
500
  }
75
- function resolveMiniprogramRoot(projectPath, configFiles) {
76
- for (const configFile of [...configFiles].reverse()) {
77
- const rawRoot = configFile.value.miniprogramRoot;
78
- if (typeof rawRoot !== "string" || !rawRoot.trim()) continue;
79
- return rawRoot.trim();
501
+ function cloneObject$1(value) {
502
+ return JSON.parse(JSON.stringify(value));
503
+ }
504
+ function cloneValue(value) {
505
+ if (Array.isArray(value)) return JSON.parse(JSON.stringify(value));
506
+ if (value && typeof value === "object") return cloneObject$1(value);
507
+ return value;
508
+ }
509
+ function parseDataPath$1(path) {
510
+ return path.replace(/\[(\d+)\]/g, ".$1").split(".").map((segment) => segment.trim()).filter(Boolean);
511
+ }
512
+ function isArrayIndexSegment$1(segment) {
513
+ return /^\d+$/.test(segment);
514
+ }
515
+ function createContainerByNextSegment$1(nextSegment) {
516
+ return isArrayIndexSegment$1(nextSegment ?? "") ? [] : {};
517
+ }
518
+ function assignByPath$1(target, path, value) {
519
+ const segments = parseDataPath$1(path);
520
+ if (segments.length === 0) return;
521
+ let current = target;
522
+ for (let index = 0; index < segments.length - 1; index += 1) {
523
+ const segment = segments[index];
524
+ const nextSegment = segments[index + 1];
525
+ const normalizedSegment = isArrayIndexSegment$1(segment) ? Number(segment) : segment;
526
+ const next = current?.[normalizedSegment];
527
+ if (!next || typeof next !== "object") current[normalizedSegment] = createContainerByNextSegment$1(nextSegment);
528
+ current = current[normalizedSegment];
80
529
  }
81
- throw new Error(`Failed to resolve miniprogramRoot for headless runtime project: ${projectPath}. Expected project.config.json or project.private.config.json to define miniprogramRoot.`);
530
+ const leafSegment = segments[segments.length - 1];
531
+ const normalizedLeafSegment = isArrayIndexSegment$1(leafSegment) ? Number(leafSegment) : leafSegment;
532
+ current[normalizedLeafSegment] = value;
82
533
  }
83
- function ensureFileExists(filePath, label) {
84
- if (fs.existsSync(filePath)) return;
85
- throw new Error(`Missing ${label} for headless runtime project: ${normalize(filePath)}`);
534
+ function resolveInitialData$2(definition) {
535
+ const rawData = definition.data;
536
+ if (typeof rawData === "function") {
537
+ const next = rawData.call(definition);
538
+ return next && typeof next === "object" && !Array.isArray(next) ? cloneObject$1(next) : {};
539
+ }
540
+ return rawData && typeof rawData === "object" && !Array.isArray(rawData) ? cloneObject$1(rawData) : {};
86
541
  }
87
- function loadAppConfig(appConfigPath) {
88
- const appConfig = readJsonObject(appConfigPath);
89
- if (!appConfig) throw new Error(`Failed to read built app.json for headless runtime project: ${normalize(appConfigPath)}`);
90
- return appConfig;
542
+ function isBehaviorDefinition(value) {
543
+ return !!value && typeof value === "object" && !Array.isArray(value) && value.__isHeadlessBehavior__ === true;
91
544
  }
92
- function loadProject(projectPath) {
93
- const normalizedProjectPath = path.resolve(projectPath);
94
- const projectConfigFiles = resolveProjectConfigFiles(normalizedProjectPath);
95
- if (projectConfigFiles.length === 0) throw new Error(`Missing project config for headless runtime project: ${normalizedProjectPath}. Expected project.config.json or project.private.config.json.`);
96
- const miniprogramRoot = resolveMiniprogramRoot(normalizedProjectPath, projectConfigFiles);
97
- const miniprogramRootPath = path.resolve(normalizedProjectPath, miniprogramRoot);
98
- ensureFileExists(miniprogramRootPath, "miniprogramRoot directory");
99
- const appConfigPath = path.resolve(miniprogramRootPath, "app.json");
100
- ensureFileExists(appConfigPath, "built app.json");
101
- const appConfig = loadAppConfig(appConfigPath);
102
- return {
103
- appConfig,
104
- appConfigPath,
105
- miniprogramRoot,
106
- miniprogramRootPath,
107
- projectPath: normalizedProjectPath,
108
- projectConfigFiles,
109
- routes: resolveRoutesFromAppConfig(appConfig)
110
- };
545
+ function flattenBehaviors(definition) {
546
+ const flattened = [];
547
+ const queue = Array.isArray(definition.behaviors) ? definition.behaviors : [];
548
+ for (const item of queue) {
549
+ if (!isBehaviorDefinition(item)) continue;
550
+ flattened.push(...flattenBehaviors(item));
551
+ flattened.push(item);
552
+ }
553
+ return flattened;
111
554
  }
112
- //#endregion
113
- //#region src/host/globals.ts
114
- function createDuplicateRegistrationError(kind, id) {
115
- return /* @__PURE__ */ new Error(`Duplicate ${kind} registration in headless runtime: ${id}`);
555
+ function mergeRecord(...records) {
556
+ return Object.assign({}, ...records.filter(Boolean));
116
557
  }
117
- function createHostRegistries() {
118
- return {
119
- appDefinition: null,
120
- components: /* @__PURE__ */ new Map(),
121
- currentLoadContext: null,
122
- pages: /* @__PURE__ */ new Map()
558
+ function normalizeComponentDefinition(definition) {
559
+ const behaviors = flattenBehaviors(definition);
560
+ if (behaviors.length === 0) return definition;
561
+ const mergedDataEntries = behaviors.map((item) => item.data).filter(Boolean);
562
+ const mergedDefinition = {
563
+ ...mergeRecord(...behaviors, definition),
564
+ methods: mergeRecord(...behaviors.map((item) => item.methods), definition.methods),
565
+ observers: mergeRecord(...behaviors.map((item) => item.observers), definition.observers),
566
+ pageLifetimes: mergeRecord(...behaviors.map((item) => item.pageLifetimes), definition.pageLifetimes),
567
+ properties: mergeRecord(...behaviors.map((item) => item.properties), definition.properties),
568
+ lifetimes: mergeRecord(...behaviors.map((item) => item.lifetimes), definition.lifetimes)
569
+ };
570
+ if (mergedDataEntries.length > 0 || definition.data) mergedDefinition.data = function mergedComponentData() {
571
+ return mergeRecord(mergeRecord(...mergedDataEntries.map((entry) => {
572
+ if (typeof entry === "function") return entry.call(this);
573
+ return entry;
574
+ })), typeof definition.data === "function" ? definition.data.call(this) : definition.data);
123
575
  };
576
+ return mergedDefinition;
124
577
  }
125
- function registerAppDefinition(registries, definition) {
126
- if (registries.appDefinition) throw createDuplicateRegistrationError("app", "app");
127
- registries.appDefinition = definition;
128
- return definition;
578
+ function normalizePropertyType(option) {
579
+ if (option === null) return null;
580
+ if (option === String || option === Number || option === Boolean || option === Array || option === Object) return option;
581
+ if (!option || typeof option !== "object" || Array.isArray(option)) return;
582
+ return option.type;
129
583
  }
130
- function registerPageDefinition(registries, definition) {
131
- const route = registries.currentLoadContext?.route;
132
- if (!route) throw new Error("Cannot register Page() without an active page load context in headless runtime.");
133
- if (registries.pages.has(route)) throw createDuplicateRegistrationError("page", route);
134
- registries.pages.set(route, definition);
135
- return definition;
584
+ function resolvePropertyTypeCandidates(option) {
585
+ const candidates = [];
586
+ const primaryType = normalizePropertyType(option);
587
+ if (primaryType) candidates.push(primaryType);
588
+ if (option && typeof option === "object" && !Array.isArray(option)) {
589
+ const optionalTypes = option.optionalTypes;
590
+ if (Array.isArray(optionalTypes)) candidates.push(...optionalTypes);
591
+ }
592
+ return candidates;
136
593
  }
137
- function registerComponentDefinition(registries, definition) {
138
- const id = registries.currentLoadContext?.route ?? `anonymous:${registries.components.size}`;
139
- if (registries.components.has(id)) throw createDuplicateRegistrationError("component", id);
140
- registries.components.set(id, definition);
141
- return definition;
594
+ function resolveDefaultValueByType(type) {
595
+ if (type === Number) return 0;
596
+ if (type === Boolean) return false;
597
+ if (type === String) return "";
598
+ if (type === Array) return [];
599
+ if (type === Object) return {};
600
+ if (type === null) return null;
142
601
  }
143
- //#endregion
144
- //#region src/host/wx.ts
145
- function createUnsupportedWxApi(name) {
146
- return () => {
147
- throw new Error(`wx.${name} is not implemented in headless runtime yet.`);
148
- };
602
+ function matchesRuntimeType(rawValue, type) {
603
+ if (type === null) return true;
604
+ if (type === Number) return typeof rawValue === "number";
605
+ if (type === Boolean) return typeof rawValue === "boolean";
606
+ if (type === String) return typeof rawValue === "string";
607
+ if (type === Array) return Array.isArray(rawValue);
608
+ if (type === Object) return !!rawValue && typeof rawValue === "object" && !Array.isArray(rawValue);
609
+ return false;
149
610
  }
150
- function createHeadlessWx() {
151
- return {
152
- navigateBack: createUnsupportedWxApi("navigateBack"),
153
- navigateTo: createUnsupportedWxApi("navigateTo"),
154
- pageScrollTo: createUnsupportedWxApi("pageScrollTo"),
155
- reLaunch: createUnsupportedWxApi("reLaunch"),
156
- redirectTo: createUnsupportedWxApi("redirectTo"),
157
- switchTab: createUnsupportedWxApi("switchTab")
611
+ function coerceComponentPropertyValue(rawValue, option) {
612
+ const candidates = resolvePropertyTypeCandidates(option);
613
+ const primaryType = candidates[0];
614
+ if (primaryType && matchesRuntimeType(rawValue, primaryType)) return rawValue;
615
+ const fallbackCandidates = primaryType ? candidates.slice(1) : candidates;
616
+ for (const type of fallbackCandidates) {
617
+ if (type === Number) {
618
+ const nextValue = typeof rawValue === "number" ? rawValue : Number(rawValue);
619
+ if (!Number.isNaN(nextValue)) return nextValue;
620
+ continue;
621
+ }
622
+ if (type === Boolean) {
623
+ if (typeof rawValue === "boolean") return rawValue;
624
+ if (rawValue === "" || rawValue === "true") return true;
625
+ if (rawValue === "false") return false;
626
+ continue;
627
+ }
628
+ if (type === String) return rawValue == null ? "" : String(rawValue);
629
+ if (type === Array && Array.isArray(rawValue)) return rawValue;
630
+ if (type === Object && rawValue && typeof rawValue === "object" && !Array.isArray(rawValue)) return rawValue;
631
+ if (type === null) return rawValue;
632
+ }
633
+ if (primaryType === Number) {
634
+ const nextValue = typeof rawValue === "number" ? rawValue : Number(rawValue);
635
+ return Number.isNaN(nextValue) ? rawValue : nextValue;
636
+ }
637
+ if (primaryType === Boolean) {
638
+ if (typeof rawValue === "boolean") return rawValue;
639
+ if (rawValue === "" || rawValue === "true") return true;
640
+ if (rawValue === "false") return false;
641
+ return Boolean(rawValue);
642
+ }
643
+ if (primaryType === String) return rawValue == null ? "" : String(rawValue);
644
+ return rawValue;
645
+ }
646
+ function resolveInitialProperties(definition, properties) {
647
+ const resolved = {};
648
+ const propOptions = definition.properties;
649
+ if (propOptions && typeof propOptions === "object" && !Array.isArray(propOptions)) for (const [key, option] of Object.entries(propOptions)) {
650
+ if (Object.prototype.hasOwnProperty.call(properties, key)) {
651
+ resolved[key] = coerceComponentPropertyValue(properties[key], option);
652
+ continue;
653
+ }
654
+ if (option && typeof option === "object" && !Array.isArray(option) && "value" in option) resolved[key] = cloneValue(typeof option.value === "function" ? option.value.call(definition) : option.value);
655
+ else resolved[key] = cloneValue(resolveDefaultValueByType(normalizePropertyType(option)));
656
+ }
657
+ for (const [key, value] of Object.entries(properties)) if (!(key in resolved)) resolved[key] = value;
658
+ return resolved;
659
+ }
660
+ function resolvePropertyDefaultValue(option) {
661
+ if (!option || typeof option !== "object" || Array.isArray(option) || !("value" in option)) return;
662
+ return cloneValue(option.value);
663
+ }
664
+ function runPropertyObservers(definition, instance, changedKeys, previousProperties) {
665
+ const propOptions = definition.properties;
666
+ if (!propOptions || typeof propOptions !== "object" || Array.isArray(propOptions)) return;
667
+ for (const changedKey of changedKeys) {
668
+ const option = propOptions[changedKey];
669
+ if (!option || typeof option !== "object" || Array.isArray(option)) continue;
670
+ const observer = option.observer;
671
+ if (typeof observer !== "function") continue;
672
+ observer.call(instance, instance.properties[changedKey], previousProperties[changedKey]);
673
+ }
674
+ }
675
+ function normalizeObserverPattern(pattern) {
676
+ return pattern.split(",").map((item) => item.trim()).filter(Boolean);
677
+ }
678
+ function resolveObservedValue(instance, pattern) {
679
+ if (pattern === "**") return {
680
+ ...instance.properties,
681
+ ...instance.data
158
682
  };
683
+ const segments = parseDataPath$1(pattern);
684
+ if (segments.length === 0) return;
685
+ const [rootSegment, ...restSegments] = segments;
686
+ let current = (Object.prototype.hasOwnProperty.call(instance.properties, rootSegment) ? instance.properties : instance.data)?.[rootSegment];
687
+ for (const segment of restSegments) {
688
+ const normalizedSegment = isArrayIndexSegment$1(segment) ? Number(segment) : segment;
689
+ current = current?.[normalizedSegment];
690
+ }
691
+ return current;
159
692
  }
160
- //#endregion
161
- //#region src/runtime/appInstance.ts
162
- function bindFunction$1(target, key, value) {
163
- if (typeof value !== "function") {
164
- target[key] = value;
165
- return;
693
+ function matchObserverPattern(pattern, changedKeys) {
694
+ if (pattern === "**") return changedKeys.length > 0;
695
+ const patterns = normalizeObserverPattern(pattern);
696
+ return changedKeys.some((changedKey) => {
697
+ return patterns.some((item) => {
698
+ if (item === "**") return true;
699
+ if (changedKey === item) return true;
700
+ return changedKey.startsWith(`${item}.`) || changedKey.startsWith(`${item}[`);
701
+ });
702
+ });
703
+ }
704
+ function runComponentObservers(definition, instance, changedKeys, previousProperties = {}) {
705
+ if (changedKeys.length === 0) return;
706
+ runPropertyObservers(definition, instance, changedKeys, previousProperties);
707
+ const observers = definition.observers;
708
+ if (observers && typeof observers === "object" && !Array.isArray(observers)) for (const [pattern, handler] of Object.entries(observers)) {
709
+ if (typeof handler !== "function" || !matchObserverPattern(pattern, changedKeys)) continue;
710
+ const args = normalizeObserverPattern(pattern).map((item) => resolveObservedValue(instance, item));
711
+ handler.call(instance, ...args);
166
712
  }
167
- target[key] = (...args) => value.apply(target, args);
168
713
  }
169
- function resolveInitialData$1(definition) {
170
- const rawData = definition.data;
171
- if (typeof rawData === "function") {
172
- const next = rawData.call(definition);
714
+ function normalizeComponentPropertyValue(definition, key, rawValue) {
715
+ const option = definition.properties?.[key];
716
+ if (rawValue == null) return resolvePropertyDefaultValue(option);
717
+ return coerceComponentPropertyValue(rawValue, option);
718
+ }
719
+ function createComponentInstance(options) {
720
+ const definition = normalizeComponentDefinition(options.definition);
721
+ const instance = {
722
+ __definition__: definition,
723
+ data: resolveInitialData$2(definition),
724
+ __propertySnapshots__: {},
725
+ properties: resolveInitialProperties(definition, options.properties ?? {}),
726
+ setData(patch, callback) {
727
+ const changedKeys = Object.keys(patch);
728
+ for (const [key, value] of Object.entries(patch)) assignByPath$1(instance.data, key, value);
729
+ runComponentObservers(definition, instance, changedKeys);
730
+ callback?.();
731
+ },
732
+ triggerEvent(eventName, detail, triggerOptions) {
733
+ options.triggerEvent?.(instance, eventName, detail, triggerOptions);
734
+ }
735
+ };
736
+ for (const [key, value] of Object.entries(definition)) {
737
+ if (key === "data" || key === "methods" || key === "properties" || key === "observers" || key === "lifetimes") continue;
738
+ bindFunction$2(instance, key, value);
739
+ }
740
+ for (const [key, value] of Object.entries(definition.methods ?? {})) bindFunction$2(instance, key, value);
741
+ return instance;
742
+ }
743
+ function runComponentLifecycle(instance, lifecycleName) {
744
+ const definition = instance.__definition__;
745
+ const fromLifetimes = definition?.lifetimes?.[lifecycleName];
746
+ if (typeof fromLifetimes === "function") {
747
+ fromLifetimes.call(instance);
748
+ return;
749
+ }
750
+ const topLevel = definition?.[lifecycleName];
751
+ if (typeof topLevel === "function") topLevel.call(instance);
752
+ }
753
+ function runComponentPageLifetime(instance, lifetimeName, payload) {
754
+ const handler = (instance.__definition__?.pageLifetimes)?.[lifetimeName];
755
+ if (typeof handler !== "function") return;
756
+ handler.call(instance, payload);
757
+ }
758
+ //#endregion
759
+ //#region src/browser/render.ts
760
+ const LEADING_SLASH_RE$4 = /^\/+/;
761
+ const TEMPLATE_INTERPOLATION_RE$1 = /\{\{([^{}]+)\}\}/g;
762
+ const EVENT_BINDING_ATTRS = [
763
+ "bindtap",
764
+ "bind:tap",
765
+ "catchtap",
766
+ "catch:tap"
767
+ ];
768
+ const COMPONENT_EVENT_PREFIXES = [
769
+ "bind:",
770
+ "bind",
771
+ "catch:",
772
+ "catch"
773
+ ];
774
+ const STRUCTURAL_ATTRS = [
775
+ "wx:if",
776
+ "wx:elif",
777
+ "wx:else",
778
+ "wx:for",
779
+ "wx:for-item",
780
+ "wx:for-index",
781
+ "wx:key"
782
+ ];
783
+ const WX_ELSE_ATTRS = new Set(["wx:elif", "wx:else"]);
784
+ const DATASET_NAME_RE$1 = /-([a-z])/g;
785
+ const BRACKET_INDEX_RE = /\[(\d+)\]/g;
786
+ const CLASS_SPLIT_RE = /\s+/;
787
+ const JS_FILE_RE = /\.js$/;
788
+ function isMustacheOnly(value) {
789
+ const trimmed = value.trim();
790
+ return trimmed.startsWith("{{") && trimmed.endsWith("}}") && !trimmed.includes("{{", 2);
791
+ }
792
+ function toDatasetKey$1(attributeName) {
793
+ return attributeName.slice(5).replace(DATASET_NAME_RE$1, (_match, char) => char.toUpperCase());
794
+ }
795
+ function collectDataset$1(node) {
796
+ const dataset = {};
797
+ for (const [key, value] of Object.entries(node.attribs ?? {})) {
798
+ if (!key.startsWith("data-") || key === "data-sim-scope" || key === "data-sim-tap" || key === "data-sim-component") continue;
799
+ dataset[toDatasetKey$1(key)] = String(value);
800
+ }
801
+ return dataset;
802
+ }
803
+ function escapeText$2(text) {
804
+ return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
805
+ }
806
+ function escapeAttribute$2(value) {
807
+ return escapeText$2(value).replaceAll("\"", "&quot;");
808
+ }
809
+ function cloneNode(node) {
810
+ return {
811
+ ...node,
812
+ attribs: node.attribs ? { ...node.attribs } : void 0,
813
+ children: node.children?.map((child) => cloneNode(child))
814
+ };
815
+ }
816
+ function parseExpressionSegments(expression) {
817
+ return expression.replace(BRACKET_INDEX_RE, ".$1").split(".").map((segment) => segment.trim()).filter(Boolean);
818
+ }
819
+ function unwrapMustacheExpression(expression) {
820
+ const normalized = expression.trim();
821
+ if (isMustacheOnly(normalized)) return normalized.slice(2, -2).trim();
822
+ return normalized;
823
+ }
824
+ function resolveLiteralValue(expression) {
825
+ if (expression === "true") return true;
826
+ if (expression === "false") return false;
827
+ if (expression === "null") return null;
828
+ if (expression === "undefined") return;
829
+ if (expression.startsWith("\"") && expression.endsWith("\"") || expression.startsWith("'") && expression.endsWith("'")) return expression.slice(1, -1);
830
+ const numericValue = Number(expression);
831
+ if (!Number.isNaN(numericValue) && expression !== "") return numericValue;
832
+ }
833
+ function resolveValueByExpression(source, expression) {
834
+ const normalized = unwrapMustacheExpression(expression);
835
+ if (!normalized) return;
836
+ if (normalized.startsWith("!")) return !resolveValueByExpression(source, normalized.slice(1));
837
+ const literalValue = resolveLiteralValue(normalized);
838
+ if (literalValue !== void 0 || normalized === "undefined") return literalValue;
839
+ const segments = parseExpressionSegments(normalized);
840
+ let current = source;
841
+ for (const segment of segments) current = current?.[segment];
842
+ return current;
843
+ }
844
+ function resolveValueByPath$1(source, expression) {
845
+ return resolveValueByExpression(source, expression) ?? "";
846
+ }
847
+ function resolveRawValueByPath(source, expression) {
848
+ return resolveValueByExpression(source, expression);
849
+ }
850
+ function interpolateTemplate$1(input, data) {
851
+ return input.replace(TEMPLATE_INTERPOLATION_RE$1, (_match, expression) => {
852
+ const value = resolveValueByPath$1(data, expression);
853
+ return typeof value === "string" ? value : String(value);
854
+ });
855
+ }
856
+ function readTemplateSource(files, filePath) {
857
+ const templateSource = readBrowserVirtualFile(files, filePath);
858
+ if (typeof templateSource !== "string") throw new TypeError(`Missing template in browser simulator runtime: ${filePath}`);
859
+ return templateSource;
860
+ }
861
+ function parseTemplateDocument(templateSource) {
862
+ return parseDocument(`<page>${templateSource}</page>`, {
863
+ xmlMode: false,
864
+ decodeEntities: false,
865
+ recognizeSelfClosing: true
866
+ });
867
+ }
868
+ function serializeDomNode$1(node) {
869
+ if (node.type === "text") return escapeText$2(node.data ?? "");
870
+ if (node.type === "root") return (node.children ?? []).map(serializeDomNode$1).join("");
871
+ const tagName = node.name ?? "";
872
+ if (!tagName) return (node.children ?? []).map(serializeDomNode$1).join("");
873
+ return `<${tagName}${Object.entries(node.attribs ?? {}).map(([key, value]) => ` ${key}="${escapeAttribute$2(value)}"`).join("")}>${(node.children ?? []).map(serializeDomNode$1).join("")}</${tagName}>`;
874
+ }
875
+ function isTagNode(node) {
876
+ return node.type === "tag" && typeof node.name === "string";
877
+ }
878
+ function isIgnorableTextNode(node) {
879
+ return node.type === "text" && typeof node.data === "string" && node.data.trim() === "";
880
+ }
881
+ function resolveAttributeValue(value, scope) {
882
+ if (isMustacheOnly(value)) {
883
+ const expression = value.trim().slice(2, -2);
884
+ return resolveValueByPath$1(scope.data, expression);
885
+ }
886
+ return interpolateTemplate$1(value, scope.data);
887
+ }
888
+ function resolveComponentAttributeValue(value, scope) {
889
+ if (isMustacheOnly(value)) {
890
+ const expression = value.trim().slice(2, -2);
891
+ return resolveRawValueByPath(scope.data, expression);
892
+ }
893
+ return interpolateTemplate$1(value, scope.data);
894
+ }
895
+ function resolveUsingComponents(files, ownerJsonPath, ownerFilePath) {
896
+ const ownerJson = readBrowserVirtualFile(files, ownerJsonPath);
897
+ if (typeof ownerJson !== "string") return /* @__PURE__ */ new Map();
898
+ try {
899
+ const usingComponents = JSON.parse(ownerJson).usingComponents;
900
+ if (!usingComponents || typeof usingComponents !== "object" || Array.isArray(usingComponents)) return /* @__PURE__ */ new Map();
901
+ const resolved = /* @__PURE__ */ new Map();
902
+ for (const [alias, rawPath] of Object.entries(usingComponents)) {
903
+ if (typeof rawPath !== "string") continue;
904
+ const basePath = rawPath.startsWith("/") ? rawPath.replace(LEADING_SLASH_RE$4, "") : normalize(join(dirname(ownerFilePath), rawPath));
905
+ resolved.set(alias, basePath.replace(LEADING_SLASH_RE$4, ""));
906
+ }
907
+ return resolved;
908
+ } catch {
909
+ return /* @__PURE__ */ new Map();
910
+ }
911
+ }
912
+ function resolveComponentRegistryEntry(context, ownerJsonPath, ownerFilePath, alias) {
913
+ const componentBasePath = resolveUsingComponents(context.files, ownerJsonPath, ownerFilePath).get(alias);
914
+ if (!componentBasePath) return null;
915
+ const filePath = `${componentBasePath}.js`;
916
+ const templatePath = `${componentBasePath}.wxml`;
917
+ return {
918
+ definition: context.moduleLoader.executeComponentModule(filePath, componentBasePath),
919
+ filePath,
920
+ templatePath
921
+ };
922
+ }
923
+ function collectComponentEventBindings(hostNode) {
924
+ const eventBindings = /* @__PURE__ */ new Map();
925
+ for (const [key, value] of Object.entries(hostNode.attribs ?? {})) {
926
+ const matchedPrefix = COMPONENT_EVENT_PREFIXES.find((prefix) => key.startsWith(prefix));
927
+ if (!matchedPrefix) continue;
928
+ const eventName = key.slice(matchedPrefix.length);
929
+ if (!eventName) continue;
930
+ eventBindings.set(eventName, {
931
+ method: value,
932
+ stopAfter: matchedPrefix.startsWith("catch")
933
+ });
934
+ }
935
+ return eventBindings;
936
+ }
937
+ function buildComponentTrigger(componentScopeId, context, hostNode) {
938
+ const hostDataset = collectDataset$1(hostNode);
939
+ const hostId = hostNode.attribs?.id ?? "";
940
+ return (instance, eventName, detail, triggerOptions) => {
941
+ const interactionTarget = instance.__lastInteractionEvent__?.target;
942
+ const interactionCurrentTarget = instance.__lastInteractionEvent__?.currentTarget;
943
+ const target = {
944
+ dataset: interactionTarget?.dataset ?? hostDataset,
945
+ id: interactionTarget?.id ?? hostId
946
+ };
947
+ let currentScopeId = componentScopeId;
948
+ while (currentScopeId) {
949
+ const currentScope = context.componentScopes.get(currentScopeId);
950
+ const binding = currentScope?.eventBindings?.get(eventName);
951
+ const listenerScope = currentScope?.listenerScopeId ? context.componentScopes.get(currentScope.listenerScopeId) : null;
952
+ const handler = binding && listenerScope ? listenerScope.getMethod(binding.method) : void 0;
953
+ if (handler) handler({
954
+ bubbles: triggerOptions?.bubbles ?? false,
955
+ capturePhase: false,
956
+ composed: triggerOptions?.composed ?? false,
957
+ detail,
958
+ mark: void 0,
959
+ target,
960
+ type: eventName,
961
+ currentTarget: {
962
+ dataset: currentScope?.dataset ?? interactionCurrentTarget?.dataset ?? hostDataset,
963
+ id: currentScope?.hostId ?? interactionCurrentTarget?.id ?? hostId
964
+ }
965
+ });
966
+ if (binding?.stopAfter) break;
967
+ if (!triggerOptions?.bubbles || !triggerOptions?.composed) break;
968
+ currentScopeId = currentScope?.ownerScopeId;
969
+ }
970
+ };
971
+ }
972
+ function applyNodeBindings(node, scope) {
973
+ if (!isTagNode(node)) {
974
+ if (node.type === "text" && typeof node.data === "string") node.data = interpolateTemplate$1(node.data, scope.data);
975
+ return;
976
+ }
977
+ node.attribs ??= {};
978
+ node.attribs["data-sim-scope"] = scope.getScopeId();
979
+ for (const key of STRUCTURAL_ATTRS) delete node.attribs[key];
980
+ for (const [key, value] of Object.entries({ ...node.attribs })) {
981
+ if (EVENT_BINDING_ATTRS.includes(key)) {
982
+ node.attribs["data-sim-tap"] = value;
983
+ continue;
984
+ }
985
+ node.attribs[key] = typeof value === "string" ? String(resolveAttributeValue(value, scope)) : String(value);
986
+ }
987
+ }
988
+ function syncComponentProperties(instance, definition, nextProperties, bindingExpressions, changedPageKeys) {
989
+ const changedRootKeys = [];
990
+ const previousProperties = {};
991
+ for (const [key, value] of Object.entries(nextProperties)) {
992
+ const nextValue = normalizeComponentPropertyValue(definition, key, value);
993
+ const bindingExpression = bindingExpressions[key];
994
+ const bindingAffected = !!bindingExpression && changedPageKeys.some((changedKey) => {
995
+ return changedKey === bindingExpression || changedKey.startsWith(`${bindingExpression}.`) || changedKey.startsWith(`${bindingExpression}[`);
996
+ });
997
+ const previousSnapshot = instance.__propertySnapshots?.[key];
998
+ const deepChanged = bindingAffected && JSON.stringify(previousSnapshot) !== JSON.stringify(nextValue);
999
+ if (instance.properties[key] !== nextValue || deepChanged) {
1000
+ previousProperties[key] = instance.properties[key];
1001
+ instance.properties[key] = nextValue;
1002
+ changedRootKeys.push(key);
1003
+ }
1004
+ instance.__propertySnapshots ??= {};
1005
+ instance.__propertySnapshots[key] = cloneValue(nextValue);
1006
+ }
1007
+ if (changedRootKeys.length === 0) return;
1008
+ runComponentObservers(definition, instance, changedRootKeys, previousProperties);
1009
+ }
1010
+ function createMergedScopeData(pageData, componentProperties, componentData) {
1011
+ return {
1012
+ ...pageData,
1013
+ ...componentProperties,
1014
+ ...componentData
1015
+ };
1016
+ }
1017
+ function isTruthy(value) {
1018
+ return Boolean(value);
1019
+ }
1020
+ function createLoopScope(scope, itemName, indexName, item, index) {
1021
+ return {
1022
+ ...scope,
1023
+ data: {
1024
+ ...scope.data,
1025
+ [indexName]: index,
1026
+ [itemName]: item
1027
+ }
1028
+ };
1029
+ }
1030
+ function evaluateConditionalBranch(node, scope) {
1031
+ const condition = node.attribs?.["wx:if"] ?? node.attribs?.["wx:elif"];
1032
+ if (condition == null) return true;
1033
+ return isTruthy(resolveRawValueByPath(scope.data, condition));
1034
+ }
1035
+ function expandNodeByFor(node, scope) {
1036
+ const forExpression = node.attribs?.["wx:for"];
1037
+ if (!forExpression) return [{
1038
+ node,
1039
+ scope,
1040
+ instanceSuffix: ""
1041
+ }];
1042
+ const list = resolveRawValueByPath(scope.data, forExpression);
1043
+ const items = Array.isArray(list) ? list : [];
1044
+ const itemName = node.attribs?.["wx:for-item"]?.trim() || "item";
1045
+ const indexName = node.attribs?.["wx:for-index"]?.trim() || "index";
1046
+ return items.map((item, index) => ({
1047
+ node: cloneNode(node),
1048
+ scope: createLoopScope(scope, itemName, indexName, item, index),
1049
+ instanceSuffix: `:for-${index}`
1050
+ }));
1051
+ }
1052
+ function renderNodeVariants(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes) {
1053
+ return expandNodeByFor(node, scope).map(({ node: expandedNode, scope: expandedScope, instanceSuffix }) => renderNodeTree(expandedNode, expandedScope, context, ownerJsonPath, ownerFilePath, `${instancePath}${instanceSuffix}`, seenComponentScopes));
1054
+ }
1055
+ function renderChildren(children, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes) {
1056
+ const renderedChildren = [];
1057
+ for (let index = 0; index < children.length; index += 1) {
1058
+ const child = children[index];
1059
+ if (!isTagNode(child)) {
1060
+ renderedChildren.push(...renderNodeVariants(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes));
1061
+ continue;
1062
+ }
1063
+ const hasConditional = child.attribs?.["wx:if"] != null;
1064
+ const isElseBranch = child.attribs?.["wx:elif"] != null || child.attribs?.["wx:else"] != null;
1065
+ if (hasConditional) {
1066
+ let branchMatched = false;
1067
+ let cursor = index;
1068
+ while (cursor < children.length) {
1069
+ const branch = children[cursor];
1070
+ if (cursor !== index && isIgnorableTextNode(branch)) {
1071
+ cursor += 1;
1072
+ continue;
1073
+ }
1074
+ if (!isTagNode(branch)) break;
1075
+ if (cursor !== index && !WX_ELSE_ATTRS.has(Object.keys(branch.attribs ?? {}).find((key) => key.startsWith("wx:")) ?? "")) break;
1076
+ if (branch.attribs?.["wx:else"] != null ? !branchMatched : !branchMatched && evaluateConditionalBranch(branch, scope)) {
1077
+ renderedChildren.push(...renderNodeVariants(branch, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${cursor}`, seenComponentScopes));
1078
+ branchMatched = true;
1079
+ }
1080
+ let nextBranchIndex = cursor + 1;
1081
+ while (nextBranchIndex < children.length && isIgnorableTextNode(children[nextBranchIndex])) nextBranchIndex += 1;
1082
+ const nextBranch = children[nextBranchIndex];
1083
+ if (!(!!nextBranch && isTagNode(nextBranch) && (nextBranch.attribs?.["wx:elif"] != null || nextBranch.attribs?.["wx:else"] != null))) break;
1084
+ cursor = nextBranchIndex;
1085
+ }
1086
+ index = cursor;
1087
+ continue;
1088
+ }
1089
+ if (isElseBranch) continue;
1090
+ renderedChildren.push(...renderNodeVariants(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes));
1091
+ }
1092
+ return renderedChildren;
1093
+ }
1094
+ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes) {
1095
+ const clonedNode = cloneNode(node);
1096
+ if (!isTagNode(clonedNode)) {
1097
+ applyNodeBindings(clonedNode, scope);
1098
+ return clonedNode;
1099
+ }
1100
+ const componentEntry = resolveComponentRegistryEntry(context, ownerJsonPath, ownerFilePath, clonedNode.name);
1101
+ if (componentEntry) {
1102
+ const componentScopeId = `${instancePath}/${clonedNode.name}`;
1103
+ const ownerScopeId = scope.getScopeId().includes("/") ? scope.getScopeId() : void 0;
1104
+ const nextProperties = {};
1105
+ const bindingExpressions = {};
1106
+ for (const [key, value] of Object.entries(clonedNode.attribs ?? {})) {
1107
+ if (key.startsWith("bind")) continue;
1108
+ if (isMustacheOnly(String(value))) bindingExpressions[key] = String(value).trim().slice(2, -2).trim();
1109
+ nextProperties[key] = resolveComponentAttributeValue(String(value), scope);
1110
+ }
1111
+ let componentInstance = context.componentCache.get(componentScopeId);
1112
+ if (!componentInstance) {
1113
+ componentInstance = createComponentInstance({
1114
+ definition: componentEntry.definition,
1115
+ properties: nextProperties,
1116
+ triggerEvent: buildComponentTrigger(componentScopeId, context, clonedNode)
1117
+ });
1118
+ componentInstance.selectComponent = (selector) => context.session.selectComponentWithin(componentScopeId, selector);
1119
+ componentInstance.selectAllComponents = (selector) => context.session.selectAllComponentsWithin(componentScopeId, selector);
1120
+ componentInstance.selectOwnerComponent = () => ownerScopeId ? context.session.selectOwnerComponent(componentScopeId) : null;
1121
+ runComponentLifecycle(componentInstance, "created");
1122
+ runComponentObservers(componentInstance.__definition__ ?? componentEntry.definition, componentInstance, Object.keys(nextProperties), {});
1123
+ componentInstance.__propertySnapshots = Object.fromEntries(Object.entries(componentInstance.properties).map(([key, propertyValue]) => [key, cloneValue(propertyValue)]));
1124
+ runComponentLifecycle(componentInstance, "attached");
1125
+ runComponentPageLifetime(componentInstance, "show");
1126
+ context.componentCache.set(componentScopeId, componentInstance);
1127
+ } else syncComponentProperties(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, nextProperties, bindingExpressions, context.changedPageKeys);
1128
+ seenComponentScopes.add(componentScopeId);
1129
+ const componentScope = {
1130
+ alias: clonedNode.name,
1131
+ classList: String(clonedNode.attribs?.class ?? "").split(CLASS_SPLIT_RE).map((item) => item.trim()).filter(Boolean),
1132
+ data: createMergedScopeData(scope.data, componentInstance.properties, componentInstance.data),
1133
+ dataset: collectDataset$1(clonedNode),
1134
+ eventBindings: collectComponentEventBindings(clonedNode),
1135
+ getMethod: (methodName) => {
1136
+ const method = componentInstance?.[methodName];
1137
+ return typeof method === "function" ? method : void 0;
1138
+ },
1139
+ getScopeId: () => componentScopeId,
1140
+ hostId: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
1141
+ id: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
1142
+ listenerScopeId: scope.getScopeId(),
1143
+ ownerScopeId
1144
+ };
1145
+ context.componentScopes.set(componentScopeId, componentScope);
1146
+ const componentDocument = parseTemplateDocument(readTemplateSource(context.files, componentEntry.templatePath));
1147
+ const renderedComponentRoot = renderNodeTree((componentDocument.children ?? [])[0] ?? componentDocument, componentScope, context, `${componentEntry.filePath.replace(JS_FILE_RE, "")}.json`, componentEntry.filePath, componentScopeId, seenComponentScopes);
1148
+ if (renderedComponentRoot.attribs) renderedComponentRoot.attribs["data-sim-component"] = clonedNode.name;
1149
+ if (!componentInstance.__ready__) {
1150
+ runComponentLifecycle(componentInstance, "ready");
1151
+ componentInstance.__ready__ = true;
1152
+ }
1153
+ return renderedComponentRoot;
1154
+ }
1155
+ applyNodeBindings(clonedNode, scope);
1156
+ clonedNode.children = renderChildren(clonedNode.children ?? [], scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/${clonedNode.name}`, seenComponentScopes);
1157
+ return clonedNode;
1158
+ }
1159
+ function renderBrowserPageTree(context, page) {
1160
+ const route = page.route.replace(LEADING_SLASH_RE$4, "");
1161
+ const templatePath = join(context.project.miniprogramRootPath, `${route}.wxml`);
1162
+ const document = parseTemplateDocument(readTemplateSource(context.files, templatePath));
1163
+ const pageScopeId = `page:${route}`;
1164
+ const pageScope = {
1165
+ data: page.data,
1166
+ getMethod: (methodName) => {
1167
+ const method = page[methodName];
1168
+ return typeof method === "function" ? method : void 0;
1169
+ },
1170
+ getScopeId: () => pageScopeId,
1171
+ id: "page-root"
1172
+ };
1173
+ context.componentScopes.clear();
1174
+ context.componentScopes.set(pageScopeId, pageScope);
1175
+ const seenComponentScopes = /* @__PURE__ */ new Set();
1176
+ const renderedRoot = renderNodeTree((document.children ?? [])[0] ?? document, pageScope, context, `${route}.json`, `${route}.js`, pageScopeId, seenComponentScopes);
1177
+ for (const [scopeId, instance] of [...context.componentCache.entries()]) if (!seenComponentScopes.has(scopeId)) {
1178
+ runComponentLifecycle(instance, "detached");
1179
+ context.componentCache.delete(scopeId);
1180
+ context.componentScopes.delete(scopeId);
1181
+ }
1182
+ return {
1183
+ root: renderedRoot,
1184
+ wxml: serializeDomNode$1(renderedRoot)
1185
+ };
1186
+ }
1187
+ //#endregion
1188
+ //#region src/project/pageConfig.ts
1189
+ const DEFAULT_NAVIGATION_BAR_BACKGROUND_COLOR = "#ffffff";
1190
+ const DEFAULT_NAVIGATION_BAR_FRONT_COLOR = "#000000";
1191
+ const DEFAULT_NAVIGATION_BAR_FRONT_COLOR_WHITE = "#ffffff";
1192
+ const DEFAULT_BACKGROUND_TEXT_STYLE = "dark";
1193
+ const DEFAULT_BACKGROUND_COLOR = "#ffffff";
1194
+ function resolveNavigationBarTitle(appConfig, pageConfig) {
1195
+ if (typeof pageConfig?.navigationBarTitleText === "string") return pageConfig.navigationBarTitleText;
1196
+ if (typeof appConfig.window?.navigationBarTitleText === "string") return appConfig.window.navigationBarTitleText;
1197
+ return "";
1198
+ }
1199
+ function resolveNavigationBarBackgroundColor(appConfig, pageConfig) {
1200
+ if (typeof pageConfig?.navigationBarBackgroundColor === "string") return pageConfig.navigationBarBackgroundColor;
1201
+ if (typeof appConfig.window?.navigationBarBackgroundColor === "string") return appConfig.window.navigationBarBackgroundColor;
1202
+ return DEFAULT_NAVIGATION_BAR_BACKGROUND_COLOR;
1203
+ }
1204
+ function resolveNavigationBarFrontColor(appConfig, pageConfig) {
1205
+ if ((typeof pageConfig?.navigationBarTextStyle === "string" ? pageConfig.navigationBarTextStyle : typeof appConfig.window?.navigationBarTextStyle === "string" ? appConfig.window.navigationBarTextStyle : void 0) === "white") return DEFAULT_NAVIGATION_BAR_FRONT_COLOR_WHITE;
1206
+ return DEFAULT_NAVIGATION_BAR_FRONT_COLOR;
1207
+ }
1208
+ function cloneNavigationBarSnapshot(snapshot) {
1209
+ return {
1210
+ animation: snapshot.animation ? { ...snapshot.animation } : null,
1211
+ backgroundColor: snapshot.backgroundColor,
1212
+ frontColor: snapshot.frontColor,
1213
+ loading: snapshot.loading,
1214
+ title: snapshot.title
1215
+ };
1216
+ }
1217
+ function resolveNavigationBarSnapshot(appConfig, pageConfig) {
1218
+ return {
1219
+ animation: null,
1220
+ backgroundColor: resolveNavigationBarBackgroundColor(appConfig, pageConfig),
1221
+ frontColor: resolveNavigationBarFrontColor(appConfig, pageConfig),
1222
+ loading: false,
1223
+ title: resolveNavigationBarTitle(appConfig, pageConfig)
1224
+ };
1225
+ }
1226
+ function resolveBackgroundTextStyle(appConfig, pageConfig) {
1227
+ return (typeof pageConfig?.backgroundTextStyle === "string" ? pageConfig.backgroundTextStyle : typeof appConfig.window?.backgroundTextStyle === "string" ? appConfig.window.backgroundTextStyle : void 0) === "light" ? "light" : DEFAULT_BACKGROUND_TEXT_STYLE;
1228
+ }
1229
+ function resolveBackgroundColorValue(appConfig, pageConfig, key) {
1230
+ if (typeof pageConfig?.[key] === "string") return pageConfig[key];
1231
+ if (typeof appConfig.window?.[key] === "string") return appConfig.window[key];
1232
+ return DEFAULT_BACKGROUND_COLOR;
1233
+ }
1234
+ function cloneBackgroundSnapshot(snapshot) {
1235
+ return {
1236
+ backgroundColor: snapshot.backgroundColor,
1237
+ backgroundColorBottom: snapshot.backgroundColorBottom,
1238
+ backgroundColorTop: snapshot.backgroundColorTop,
1239
+ textStyle: snapshot.textStyle
1240
+ };
1241
+ }
1242
+ function resolveBackgroundSnapshot(appConfig, pageConfig) {
1243
+ return {
1244
+ backgroundColor: resolveBackgroundColorValue(appConfig, pageConfig, "backgroundColor"),
1245
+ backgroundColorBottom: resolveBackgroundColorValue(appConfig, pageConfig, "backgroundColorBottom"),
1246
+ backgroundColorTop: resolveBackgroundColorValue(appConfig, pageConfig, "backgroundColorTop"),
1247
+ textStyle: resolveBackgroundTextStyle(appConfig, pageConfig)
1248
+ };
1249
+ }
1250
+ //#endregion
1251
+ //#region src/runtime/appInstance.ts
1252
+ function bindFunction$1(target, key, value) {
1253
+ if (typeof value !== "function") {
1254
+ target[key] = value;
1255
+ return;
1256
+ }
1257
+ target[key] = (...args) => value.apply(target, args);
1258
+ }
1259
+ function resolveInitialData$1(definition) {
1260
+ const rawData = definition.globalData ?? definition.data;
1261
+ if (typeof rawData === "function") {
1262
+ const next = rawData.call(definition);
173
1263
  return next && typeof next === "object" && !Array.isArray(next) ? { ...next } : {};
174
1264
  }
175
- return rawData && typeof rawData === "object" && !Array.isArray(rawData) ? { ...rawData } : {};
176
- }
177
- function createAppInstance(definition) {
178
- const instance = { globalData: resolveInitialData$1(definition) };
179
- for (const [key, value] of Object.entries(definition)) {
180
- if (key === "data") continue;
181
- bindFunction$1(instance, key, value);
1265
+ return rawData && typeof rawData === "object" && !Array.isArray(rawData) ? { ...rawData } : {};
1266
+ }
1267
+ function createAppInstance(definition) {
1268
+ const instance = { globalData: resolveInitialData$1(definition) };
1269
+ for (const [key, value] of Object.entries(definition)) {
1270
+ if (key === "data") continue;
1271
+ bindFunction$1(instance, key, value);
1272
+ }
1273
+ return instance;
1274
+ }
1275
+ //#endregion
1276
+ //#region src/runtime/pageInstance.ts
1277
+ const ARRAY_INDEX_PATH_RE = /\[(\d+)\]/g;
1278
+ const ARRAY_INDEX_SEGMENT_RE = /^\d+$/;
1279
+ const LEADING_ROUTE_SLASH_RE = /^\/+/;
1280
+ function bindFunction(target, key, value) {
1281
+ if (typeof value !== "function") {
1282
+ target[key] = value;
1283
+ return;
1284
+ }
1285
+ target[key] = (...args) => value.apply(target, args);
1286
+ }
1287
+ function cloneObject(value) {
1288
+ return JSON.parse(JSON.stringify(value));
1289
+ }
1290
+ function resolveInitialData(definition) {
1291
+ const rawData = definition.data;
1292
+ if (typeof rawData === "function") {
1293
+ const next = rawData.call(definition);
1294
+ return next && typeof next === "object" && !Array.isArray(next) ? cloneObject(next) : {};
1295
+ }
1296
+ return rawData && typeof rawData === "object" && !Array.isArray(rawData) ? cloneObject(rawData) : {};
1297
+ }
1298
+ function parseDataPath(path) {
1299
+ return path.replace(ARRAY_INDEX_PATH_RE, ".$1").split(".").map((segment) => segment.trim()).filter(Boolean);
1300
+ }
1301
+ function isArrayIndexSegment(segment) {
1302
+ return ARRAY_INDEX_SEGMENT_RE.test(segment);
1303
+ }
1304
+ function createContainerByNextSegment(nextSegment) {
1305
+ return isArrayIndexSegment(nextSegment ?? "") ? [] : {};
1306
+ }
1307
+ function assignByPath(target, path, value) {
1308
+ const segments = parseDataPath(path);
1309
+ if (segments.length === 0) return;
1310
+ let current = target;
1311
+ for (let index = 0; index < segments.length - 1; index += 1) {
1312
+ const segment = segments[index];
1313
+ const nextSegment = segments[index + 1];
1314
+ const normalizedSegment = isArrayIndexSegment(segment) ? Number(segment) : segment;
1315
+ const next = current?.[normalizedSegment];
1316
+ if (!next || typeof next !== "object") current[normalizedSegment] = createContainerByNextSegment(nextSegment);
1317
+ current = current[normalizedSegment];
1318
+ }
1319
+ const leafSegment = segments.at(-1);
1320
+ const normalizedLeafSegment = isArrayIndexSegment(leafSegment) ? Number(leafSegment) : leafSegment;
1321
+ current[normalizedLeafSegment] = value;
1322
+ }
1323
+ function normalizeRoute$1(route) {
1324
+ return route.replace(LEADING_ROUTE_SLASH_RE, "");
1325
+ }
1326
+ function createPageInstance(route, definition, options = {}, pageState = {}) {
1327
+ const normalizedRoute = normalizeRoute$1(route);
1328
+ const instance = {
1329
+ __background__: pageState.background ? cloneBackgroundSnapshot(pageState.background) : void 0,
1330
+ __backgroundTextStyle__: pageState.background?.textStyle ?? pageState.backgroundTextStyle,
1331
+ __route__: normalizedRoute,
1332
+ __navigationBar__: pageState.navigationBar ? cloneNavigationBarSnapshot(pageState.navigationBar) : void 0,
1333
+ __navigationBarTitle__: pageState.navigationBar?.title,
1334
+ data: resolveInitialData(definition),
1335
+ options: { ...options },
1336
+ route: normalizedRoute,
1337
+ setData(patch, callback) {
1338
+ instance.__lastChangedKeys__ = Object.keys(patch);
1339
+ for (const [key, value] of Object.entries(patch)) assignByPath(instance.data, key, value);
1340
+ callback?.();
1341
+ }
1342
+ };
1343
+ for (const [key, value] of Object.entries(definition)) {
1344
+ if (key === "data") continue;
1345
+ bindFunction(instance, key, value);
1346
+ }
1347
+ return instance;
1348
+ }
1349
+ //#endregion
1350
+ //#region src/runtime/systemInfo.ts
1351
+ function createDefaultSystemInfo() {
1352
+ return {
1353
+ SDKVersion: "0.0.0",
1354
+ brand: "devtools",
1355
+ language: "zh_CN",
1356
+ model: "headless-simulator",
1357
+ pixelRatio: 2,
1358
+ platform: "devtools",
1359
+ screenHeight: 667,
1360
+ screenWidth: 375,
1361
+ system: "iOS 0.0.0",
1362
+ version: "0.0.0",
1363
+ windowHeight: 667,
1364
+ windowWidth: 375
1365
+ };
1366
+ }
1367
+ function applyResizeToSystemInfo(systemInfo, options) {
1368
+ const size = options?.size;
1369
+ const nextWindowWidth = Number(size?.windowWidth);
1370
+ const nextWindowHeight = Number(size?.windowHeight);
1371
+ if (Number.isFinite(nextWindowWidth) && nextWindowWidth > 0) {
1372
+ systemInfo.windowWidth = nextWindowWidth;
1373
+ systemInfo.screenWidth = nextWindowWidth;
1374
+ }
1375
+ if (Number.isFinite(nextWindowHeight) && nextWindowHeight > 0) {
1376
+ systemInfo.windowHeight = nextWindowHeight;
1377
+ systemInfo.screenHeight = nextWindowHeight;
1378
+ }
1379
+ return systemInfo;
1380
+ }
1381
+ function deriveWindowInfo(systemInfo) {
1382
+ return {
1383
+ pixelRatio: systemInfo.pixelRatio,
1384
+ screenHeight: systemInfo.screenHeight,
1385
+ screenWidth: systemInfo.screenWidth,
1386
+ statusBarHeight: 20,
1387
+ windowHeight: systemInfo.windowHeight,
1388
+ windowWidth: systemInfo.windowWidth
1389
+ };
1390
+ }
1391
+ function deriveAppBaseInfo(systemInfo) {
1392
+ return {
1393
+ SDKVersion: systemInfo.SDKVersion,
1394
+ enableDebug: false,
1395
+ host: { env: systemInfo.platform },
1396
+ language: systemInfo.language,
1397
+ platform: systemInfo.platform,
1398
+ version: systemInfo.version
1399
+ };
1400
+ }
1401
+ function deriveMenuButtonBoundingClientRect(systemInfo) {
1402
+ const width = 87;
1403
+ const height = 32;
1404
+ const top = 32;
1405
+ const right = Math.max(systemInfo.windowWidth - 12, width);
1406
+ const left = Math.max(0, right - width);
1407
+ return {
1408
+ bottom: top + height,
1409
+ height,
1410
+ left,
1411
+ right,
1412
+ top,
1413
+ width
1414
+ };
1415
+ }
1416
+ //#endregion
1417
+ //#region src/runtime/wxState.ts
1418
+ const STORAGE_LIMIT_SIZE = 10 * 1024;
1419
+ const DEFAULT_MODAL_CANCEL_COLOR = "#000000";
1420
+ const DEFAULT_MODAL_CANCEL_TEXT = "取消";
1421
+ const DEFAULT_MODAL_CONFIRM_COLOR = "#576B95";
1422
+ const DEFAULT_MODAL_CONFIRM_TEXT = "确定";
1423
+ function cloneShareMenuSnapshot(snapshot) {
1424
+ return {
1425
+ isUpdatableMessage: snapshot.isUpdatableMessage,
1426
+ menus: [...snapshot.menus],
1427
+ visible: snapshot.visible,
1428
+ withShareTicket: snapshot.withShareTicket
1429
+ };
1430
+ }
1431
+ function createNetworkSnapshot(networkType) {
1432
+ return {
1433
+ isConnected: networkType !== "none",
1434
+ networkType
1435
+ };
1436
+ }
1437
+ function cloneValue$1(value) {
1438
+ if (value == null || typeof value !== "object") return value;
1439
+ return JSON.parse(JSON.stringify(value));
1440
+ }
1441
+ function normalizeMethod(method) {
1442
+ return (method || "GET").trim().toUpperCase();
1443
+ }
1444
+ function isRequestSuccessResult(value) {
1445
+ return !!value && typeof value === "object" && "data" in value;
1446
+ }
1447
+ function matchesRequestMock(mock, option) {
1448
+ const requestMethod = normalizeMethod(option.method);
1449
+ const mockMethod = normalizeMethod(mock.method);
1450
+ if (mock.method && requestMethod !== mockMethod) return false;
1451
+ if (typeof mock.url === "string") return mock.url === option.url;
1452
+ mock.url.lastIndex = 0;
1453
+ return mock.url.test(option.url);
1454
+ }
1455
+ function resolveRequestResponse(mock, option) {
1456
+ const rawResponse = typeof mock.response === "function" ? mock.response(option) : mock.response;
1457
+ if (isRequestSuccessResult(rawResponse)) return {
1458
+ cookies: Array.isArray(rawResponse.cookies) ? [...rawResponse.cookies] : [],
1459
+ data: cloneValue$1(rawResponse.data),
1460
+ errMsg: rawResponse.errMsg ?? "request:ok",
1461
+ header: { ...rawResponse.header },
1462
+ statusCode: rawResponse.statusCode ?? mock.statusCode ?? 200
1463
+ };
1464
+ return {
1465
+ cookies: [],
1466
+ data: cloneValue$1(rawResponse),
1467
+ errMsg: "request:ok",
1468
+ header: { ...mock.header ?? {} },
1469
+ statusCode: mock.statusCode ?? 200
1470
+ };
1471
+ }
1472
+ function createHeadlessWxState() {
1473
+ const actionSheetLogs = [];
1474
+ const actionSheetMocks = [];
1475
+ const modalLogs = [];
1476
+ const networkStatusChangeCallbacks = /* @__PURE__ */ new Set();
1477
+ const modalMocks = [];
1478
+ const requestLogs = [];
1479
+ const requestMocks = [];
1480
+ const storage = /* @__PURE__ */ new Map();
1481
+ let loading = null;
1482
+ let networkType = "wifi";
1483
+ let shareMenu = {
1484
+ isUpdatableMessage: false,
1485
+ menus: [],
1486
+ visible: false,
1487
+ withShareTicket: false
1488
+ };
1489
+ let toast = null;
1490
+ return {
1491
+ clearStorageSync() {
1492
+ storage.clear();
1493
+ },
1494
+ getActionSheetLogs() {
1495
+ return actionSheetLogs.map((entry) => ({
1496
+ ...entry,
1497
+ itemList: [...entry.itemList],
1498
+ result: entry.result ? { ...entry.result } : void 0
1499
+ }));
1500
+ },
1501
+ getNetworkType() {
1502
+ return {
1503
+ errMsg: "getNetworkType:ok",
1504
+ networkType
1505
+ };
1506
+ },
1507
+ getModalLogs() {
1508
+ return modalLogs.map((entry) => ({
1509
+ ...entry,
1510
+ result: { ...entry.result }
1511
+ }));
1512
+ },
1513
+ getRequestLogs() {
1514
+ return requestLogs.map((entry) => ({
1515
+ ...entry,
1516
+ data: cloneValue$1(entry.data),
1517
+ header: { ...entry.header },
1518
+ response: entry.response ? {
1519
+ ...entry.response,
1520
+ cookies: [...entry.response.cookies],
1521
+ data: cloneValue$1(entry.response.data),
1522
+ header: { ...entry.response.header }
1523
+ } : void 0
1524
+ }));
1525
+ },
1526
+ getStorageInfoSync() {
1527
+ const keys = Array.from(storage.keys()).sort((a, b) => a.localeCompare(b));
1528
+ const totalBytes = Array.from(storage.entries()).reduce((sum, [key, value]) => {
1529
+ return sum + Buffer.byteLength(JSON.stringify([key, value]));
1530
+ }, 0);
1531
+ return {
1532
+ currentSize: Math.ceil(totalBytes / 1024),
1533
+ errMsg: "getStorageInfo:ok",
1534
+ keys,
1535
+ limitSize: STORAGE_LIMIT_SIZE
1536
+ };
1537
+ },
1538
+ getStorageSnapshot() {
1539
+ return Object.fromEntries(Array.from(storage.entries(), ([key, value]) => [key, cloneValue$1(value)]));
1540
+ },
1541
+ getStorageSync(key) {
1542
+ return cloneValue$1(storage.get(key));
1543
+ },
1544
+ getShareMenu() {
1545
+ return cloneShareMenuSnapshot(shareMenu);
1546
+ },
1547
+ getLoading() {
1548
+ return loading ? { ...loading } : null;
1549
+ },
1550
+ hideShareMenu() {
1551
+ shareMenu = {
1552
+ ...shareMenu,
1553
+ visible: false
1554
+ };
1555
+ return { errMsg: "hideShareMenu:ok" };
1556
+ },
1557
+ getToast() {
1558
+ return toast ? { ...toast } : null;
1559
+ },
1560
+ hideLoading() {
1561
+ loading = null;
1562
+ return { errMsg: "hideLoading:ok" };
1563
+ },
1564
+ hideToast() {
1565
+ toast = null;
1566
+ return { errMsg: "hideToast:ok" };
1567
+ },
1568
+ offNetworkStatusChange(callback) {
1569
+ if (!callback) {
1570
+ networkStatusChangeCallbacks.clear();
1571
+ return;
1572
+ }
1573
+ networkStatusChangeCallbacks.delete(callback);
1574
+ },
1575
+ mockRequest(definition) {
1576
+ requestMocks.push({
1577
+ ...definition,
1578
+ delay: definition.delay,
1579
+ header: definition.header ? { ...definition.header } : void 0
1580
+ });
1581
+ },
1582
+ mockModal(definition = {}) {
1583
+ modalMocks.push({
1584
+ cancel: definition.cancel,
1585
+ confirm: definition.confirm
1586
+ });
1587
+ },
1588
+ mockActionSheet(definition = {}) {
1589
+ actionSheetMocks.push({
1590
+ cancel: definition.cancel,
1591
+ tapIndex: definition.tapIndex
1592
+ });
1593
+ },
1594
+ onNetworkStatusChange(callback) {
1595
+ networkStatusChangeCallbacks.add(callback);
1596
+ },
1597
+ removeStorageSync(key) {
1598
+ storage.delete(key);
1599
+ },
1600
+ request(option) {
1601
+ const matchedMock = requestMocks.find((mock) => matchesRequestMock(mock, option));
1602
+ if (!matchedMock) {
1603
+ const logEntry = {
1604
+ data: cloneValue$1(option.data),
1605
+ header: { ...option.header ?? {} },
1606
+ matched: false,
1607
+ method: normalizeMethod(option.method),
1608
+ url: option.url
1609
+ };
1610
+ requestLogs.push(logEntry);
1611
+ const error = /* @__PURE__ */ new Error(`No request mock matched in headless runtime: ${normalizeMethod(option.method)} ${option.url}`);
1612
+ option.fail?.(error);
1613
+ option.complete?.();
1614
+ return { abort() {} };
1615
+ }
1616
+ const response = resolveRequestResponse(matchedMock, option);
1617
+ const requestLogEntry = {
1618
+ data: cloneValue$1(option.data),
1619
+ header: { ...option.header ?? {} },
1620
+ matched: true,
1621
+ method: normalizeMethod(option.method),
1622
+ response,
1623
+ url: option.url
1624
+ };
1625
+ const delay = Number.isFinite(matchedMock.delay) ? Math.max(0, Math.trunc(matchedMock.delay ?? 0)) : 0;
1626
+ if (delay <= 0) {
1627
+ requestLogs.push(requestLogEntry);
1628
+ option.success?.(response);
1629
+ option.complete?.(response);
1630
+ return { abort() {} };
1631
+ }
1632
+ let completed = false;
1633
+ const timer = setTimeout(() => {
1634
+ if (completed) return;
1635
+ completed = true;
1636
+ requestLogs.push(requestLogEntry);
1637
+ option.success?.(response);
1638
+ option.complete?.(response);
1639
+ }, delay);
1640
+ return { abort() {
1641
+ if (completed) return;
1642
+ completed = true;
1643
+ clearTimeout(timer);
1644
+ const error = /* @__PURE__ */ new Error("request:fail abort");
1645
+ option.fail?.(error);
1646
+ option.complete?.();
1647
+ } };
1648
+ },
1649
+ setStorageSync(key, value) {
1650
+ storage.set(key, cloneValue$1(value));
1651
+ },
1652
+ setNetworkType(nextNetworkType) {
1653
+ networkType = nextNetworkType;
1654
+ const snapshot = createNetworkSnapshot(networkType);
1655
+ networkStatusChangeCallbacks.forEach((callback) => callback({ ...snapshot }));
1656
+ return {
1657
+ errMsg: "getNetworkType:ok",
1658
+ networkType
1659
+ };
1660
+ },
1661
+ showActionSheet(option) {
1662
+ const itemList = Array.isArray(option.itemList) ? option.itemList.filter((item) => typeof item === "string") : [];
1663
+ if (itemList.length === 0) throw new Error("showActionSheet:fail invalid itemList");
1664
+ const nextMock = actionSheetMocks.shift();
1665
+ if (nextMock?.cancel) {
1666
+ actionSheetLogs.push({ itemList: [...itemList] });
1667
+ throw new Error("showActionSheet:fail cancel");
1668
+ }
1669
+ const tapIndex = Number.isInteger(nextMock?.tapIndex) ? Number(nextMock?.tapIndex) : 0;
1670
+ if (tapIndex < 0 || tapIndex >= itemList.length) throw new Error("showActionSheet:fail invalid tapIndex");
1671
+ const result = {
1672
+ errMsg: "showActionSheet:ok",
1673
+ tapIndex
1674
+ };
1675
+ actionSheetLogs.push({
1676
+ itemList: [...itemList],
1677
+ result: { ...result }
1678
+ });
1679
+ return result;
1680
+ },
1681
+ showShareMenu(option = {}) {
1682
+ shareMenu = {
1683
+ isUpdatableMessage: Boolean(option.isUpdatableMessage),
1684
+ menus: Array.isArray(option.menus) ? option.menus.filter((item) => typeof item === "string") : shareMenu.menus,
1685
+ visible: true,
1686
+ withShareTicket: Boolean(option.withShareTicket)
1687
+ };
1688
+ return { errMsg: "showShareMenu:ok" };
1689
+ },
1690
+ showLoading(option) {
1691
+ loading = {
1692
+ mask: Boolean(option.mask),
1693
+ title: option.title
1694
+ };
1695
+ return { errMsg: "showLoading:ok" };
1696
+ },
1697
+ showModal(option) {
1698
+ const showCancel = option.showCancel !== false;
1699
+ const nextMock = modalMocks.shift();
1700
+ let confirm = nextMock?.confirm ?? true;
1701
+ let cancel = nextMock?.cancel ?? !confirm;
1702
+ if (!showCancel) {
1703
+ confirm = true;
1704
+ cancel = false;
1705
+ } else if (confirm) cancel = false;
1706
+ else cancel = true;
1707
+ const result = {
1708
+ cancel,
1709
+ confirm,
1710
+ errMsg: "showModal:ok"
1711
+ };
1712
+ modalLogs.push({
1713
+ cancelColor: option.cancelColor ?? DEFAULT_MODAL_CANCEL_COLOR,
1714
+ cancelText: option.cancelText ?? DEFAULT_MODAL_CANCEL_TEXT,
1715
+ confirmColor: option.confirmColor ?? DEFAULT_MODAL_CONFIRM_COLOR,
1716
+ confirmText: option.confirmText ?? DEFAULT_MODAL_CONFIRM_TEXT,
1717
+ content: option.content,
1718
+ result: { ...result },
1719
+ showCancel,
1720
+ title: option.title ?? ""
1721
+ });
1722
+ return result;
1723
+ },
1724
+ showToast(option) {
1725
+ toast = {
1726
+ duration: Number(option.duration ?? 1500),
1727
+ icon: option.icon ?? "success",
1728
+ mask: Boolean(option.mask),
1729
+ title: option.title
1730
+ };
1731
+ return { errMsg: "showToast:ok" };
1732
+ },
1733
+ updateShareMenu(option = {}) {
1734
+ shareMenu = {
1735
+ isUpdatableMessage: option.isUpdatableMessage == null ? shareMenu.isUpdatableMessage : Boolean(option.isUpdatableMessage),
1736
+ menus: Array.isArray(option.menus) ? option.menus.filter((item) => typeof item === "string") : shareMenu.menus,
1737
+ visible: true,
1738
+ withShareTicket: option.withShareTicket == null ? shareMenu.withShareTicket : Boolean(option.withShareTicket)
1739
+ };
1740
+ return { errMsg: "updateShareMenu:ok" };
1741
+ }
1742
+ };
1743
+ }
1744
+ //#endregion
1745
+ //#region src/browser/session.ts
1746
+ const LEADING_SLASH_RE$3 = /^\/+/;
1747
+ const PAGE_STACK_LIMIT$1 = 10;
1748
+ const DATA_ATTR_SELECTOR_RE$1 = /^\[data-([^=\]]+)="([^"]*)"\]$/;
1749
+ const DATASET_KEY_RE = /-([a-z])/g;
1750
+ function stripLeadingSlash$1(route) {
1751
+ return route.replace(LEADING_SLASH_RE$3, "");
1752
+ }
1753
+ function normalizeQuery$1(queryString) {
1754
+ const query = new URLSearchParams(queryString);
1755
+ const result = {};
1756
+ for (const [key, value] of query.entries()) result[key] = value;
1757
+ return result;
1758
+ }
1759
+ function parseNavigationUrl$1(url) {
1760
+ const trimmedUrl = url.trim();
1761
+ if (!trimmedUrl) throw new Error("Navigation url must be a non-empty string in browser simulator runtime.");
1762
+ const [pathWithHash, queryString = ""] = trimmedUrl.split("?");
1763
+ const [pathname] = pathWithHash.split("#");
1764
+ return {
1765
+ pathname: pathname || "",
1766
+ query: normalizeQuery$1(queryString)
1767
+ };
1768
+ }
1769
+ function createAppLaunchOptions$1(pathname, query) {
1770
+ return {
1771
+ path: stripLeadingSlash$1(pathname),
1772
+ query: { ...query },
1773
+ referrerInfo: {
1774
+ appId: "",
1775
+ extraData: {}
1776
+ },
1777
+ scene: 1001
1778
+ };
1779
+ }
1780
+ function readJsonObject$2(files, filePath) {
1781
+ const content = readBrowserVirtualFile(files, filePath);
1782
+ if (!content) return;
1783
+ try {
1784
+ const value = JSON.parse(content);
1785
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
1786
+ } catch {
1787
+ return;
1788
+ }
1789
+ }
1790
+ function resolveNavigationPath$1(targetPath, baseRoute) {
1791
+ if (!targetPath) throw new Error("Navigation url must include a pathname in browser simulator runtime.");
1792
+ if (targetPath.startsWith("/")) return posix.normalize(targetPath).replace(LEADING_SLASH_RE$3, "");
1793
+ if (!baseRoute) throw new Error(`Cannot resolve relative navigation url "${targetPath}" without an active page.`);
1794
+ return posix.resolve(`/${posix.dirname(baseRoute)}`, targetPath).replace(LEADING_SLASH_RE$3, "");
1795
+ }
1796
+ var BrowserHeadlessSession = class {
1797
+ files;
1798
+ project;
1799
+ appDefinition = null;
1800
+ appInstance = null;
1801
+ moduleLoader;
1802
+ registries;
1803
+ currentPageInstance = null;
1804
+ pages = [];
1805
+ componentCache = /* @__PURE__ */ new Map();
1806
+ componentScopes = /* @__PURE__ */ new Map();
1807
+ tabBarRoutes;
1808
+ tabPages = /* @__PURE__ */ new Map();
1809
+ tabBarItems = /* @__PURE__ */ new Map();
1810
+ tabBarState = /* @__PURE__ */ new Map();
1811
+ tabBarVisible = false;
1812
+ systemInfo = createDefaultSystemInfo();
1813
+ enterOptions = createAppLaunchOptions$1("", {});
1814
+ launchOptions = createAppLaunchOptions$1("", {});
1815
+ wxState = createHeadlessWxState();
1816
+ constructor(options) {
1817
+ this.files = options.files;
1818
+ this.project = options.project ?? createBrowserProject(options.files);
1819
+ this.registries = createHostRegistries();
1820
+ const rawTabBarList = Array.isArray(this.project.appConfig.tabBar?.list) ? this.project.appConfig.tabBar.list : [];
1821
+ this.tabBarRoutes = /* @__PURE__ */ new Set();
1822
+ rawTabBarList.forEach((item, index) => {
1823
+ if (typeof item?.pagePath !== "string") return;
1824
+ const pagePath = stripLeadingSlash$1(item.pagePath);
1825
+ if (!pagePath) return;
1826
+ this.tabBarRoutes.add(pagePath);
1827
+ this.tabBarItems.set(pagePath, {
1828
+ index,
1829
+ pagePath,
1830
+ text: typeof item.text === "string" ? item.text : void 0
1831
+ });
1832
+ this.tabBarState.set(index, {
1833
+ badge: null,
1834
+ index,
1835
+ pagePath,
1836
+ redDot: false,
1837
+ text: typeof item.text === "string" ? item.text : void 0
1838
+ });
1839
+ });
1840
+ this.tabBarVisible = this.tabBarRoutes.size > 0;
1841
+ this.moduleLoader = createBrowserModuleLoader(this.files, this.registries, () => this.pages.slice(), () => this.getApp(), {
1842
+ getEnterOptionsSync: () => ({
1843
+ ...this.enterOptions,
1844
+ query: { ...this.enterOptions.query },
1845
+ referrerInfo: {
1846
+ ...this.enterOptions.referrerInfo,
1847
+ extraData: { ...this.enterOptions.referrerInfo.extraData }
1848
+ }
1849
+ }),
1850
+ getAppBaseInfoSync: () => deriveAppBaseInfo(this.systemInfo),
1851
+ getLaunchOptionsSync: () => ({
1852
+ ...this.launchOptions,
1853
+ query: { ...this.launchOptions.query },
1854
+ referrerInfo: {
1855
+ ...this.launchOptions.referrerInfo,
1856
+ extraData: { ...this.launchOptions.referrerInfo.extraData }
1857
+ }
1858
+ }),
1859
+ getMenuButtonBoundingClientRect: () => deriveMenuButtonBoundingClientRect(this.systemInfo),
1860
+ getNetworkType: () => this.wxState.getNetworkType(),
1861
+ navigateBack: (option) => this.navigateBack(option?.delta),
1862
+ navigateTo: (option) => this.navigateTo(option.url),
1863
+ pageScrollTo: (option) => this.pageScrollTo(option),
1864
+ clearStorageSync: () => this.wxState.clearStorageSync(),
1865
+ getStorageInfoSync: () => this.wxState.getStorageInfoSync(),
1866
+ getStorageSync: (key) => this.wxState.getStorageSync(key),
1867
+ getSystemInfoSync: () => ({ ...this.systemInfo }),
1868
+ getWindowInfoSync: () => deriveWindowInfo(this.systemInfo),
1869
+ hideLoading: () => this.wxState.hideLoading(),
1870
+ hideToast: () => this.wxState.hideToast(),
1871
+ reLaunch: (option) => this.reLaunch(option.url),
1872
+ redirectTo: (option) => this.redirectTo(option.url),
1873
+ nextTick: (callback) => queueMicrotask(() => callback?.()),
1874
+ offNetworkStatusChange: (callback) => this.wxState.offNetworkStatusChange(callback),
1875
+ onNetworkStatusChange: (callback) => this.wxState.onNetworkStatusChange(callback),
1876
+ removeStorageSync: (key) => this.wxState.removeStorageSync(key),
1877
+ request: (option) => this.wxState.request(option),
1878
+ setBackgroundColor: (option) => this.setBackgroundColor(option),
1879
+ setBackgroundTextStyle: (option) => this.setBackgroundTextStyle(option.textStyle),
1880
+ setStorageSync: (key, value) => this.wxState.setStorageSync(key, value),
1881
+ setNavigationBarColor: (option) => this.setNavigationBarColor(option),
1882
+ setNavigationBarTitle: (option) => this.setNavigationBarTitle(option.title),
1883
+ hideShareMenu: () => this.wxState.hideShareMenu(),
1884
+ hideNavigationBarLoading: () => this.hideNavigationBarLoading(),
1885
+ hideTabBar: () => this.hideTabBar(),
1886
+ hideTabBarRedDot: (option) => this.hideTabBarRedDot(option.index),
1887
+ showShareMenu: (option) => this.wxState.showShareMenu(option),
1888
+ showNavigationBarLoading: () => this.showNavigationBarLoading(),
1889
+ showTabBar: () => this.showTabBar(),
1890
+ showTabBarRedDot: (option) => this.showTabBarRedDot(option.index),
1891
+ showActionSheet: (option) => this.wxState.showActionSheet(option),
1892
+ showLoading: (option) => this.wxState.showLoading(option),
1893
+ showModal: (option) => this.wxState.showModal(option),
1894
+ showToast: (option) => this.wxState.showToast(option),
1895
+ stopPullDownRefresh: () => this.stopPullDownRefresh(),
1896
+ switchTab: (option) => this.switchTab(option.url),
1897
+ removeTabBarBadge: (option) => this.removeTabBarBadge(option.index),
1898
+ setTabBarBadge: (option) => this.setTabBarBadge(option.index, option.text),
1899
+ updateShareMenu: (option) => this.wxState.updateShareMenu(option)
1900
+ });
1901
+ }
1902
+ getApp() {
1903
+ return this.appInstance;
1904
+ }
1905
+ getCurrentPages() {
1906
+ return this.pages.slice();
1907
+ }
1908
+ getCurrentPageNavigationBarTitle() {
1909
+ return this.currentPageInstance?.__navigationBarTitle__ ?? null;
1910
+ }
1911
+ getCurrentPageNavigationBar() {
1912
+ const snapshot = this.currentPageInstance?.__navigationBar__;
1913
+ return snapshot ? cloneNavigationBarSnapshot(snapshot) : null;
1914
+ }
1915
+ getCurrentPageBackground() {
1916
+ const snapshot = this.currentPageInstance?.__background__;
1917
+ return snapshot ? cloneBackgroundSnapshot(snapshot) : null;
1918
+ }
1919
+ getActionSheetLogs() {
1920
+ return this.wxState.getActionSheetLogs();
1921
+ }
1922
+ getRequestLogs() {
1923
+ return this.wxState.getRequestLogs();
1924
+ }
1925
+ getStorageSnapshot() {
1926
+ return this.wxState.getStorageSnapshot();
1927
+ }
1928
+ getShareMenu() {
1929
+ return this.wxState.getShareMenu();
1930
+ }
1931
+ getTabBar() {
1932
+ return { visible: this.tabBarVisible };
1933
+ }
1934
+ getTabBarSnapshot() {
1935
+ return {
1936
+ items: Array.from(this.tabBarState.values(), (item) => ({
1937
+ badge: item.badge,
1938
+ index: item.index,
1939
+ pagePath: item.pagePath,
1940
+ redDot: item.redDot,
1941
+ text: item.text
1942
+ })),
1943
+ visible: this.tabBarVisible
1944
+ };
1945
+ }
1946
+ getStorageInfo() {
1947
+ return this.wxState.getStorageInfoSync();
1948
+ }
1949
+ getSystemInfo() {
1950
+ return { ...this.systemInfo };
1951
+ }
1952
+ getWindowInfo() {
1953
+ return deriveWindowInfo(this.systemInfo);
1954
+ }
1955
+ getAppBaseInfo() {
1956
+ return deriveAppBaseInfo(this.systemInfo);
1957
+ }
1958
+ getLaunchOptions() {
1959
+ return {
1960
+ ...this.launchOptions,
1961
+ query: { ...this.launchOptions.query },
1962
+ referrerInfo: {
1963
+ ...this.launchOptions.referrerInfo,
1964
+ extraData: { ...this.launchOptions.referrerInfo.extraData }
1965
+ }
1966
+ };
1967
+ }
1968
+ getEnterOptions() {
1969
+ return {
1970
+ ...this.enterOptions,
1971
+ query: { ...this.enterOptions.query },
1972
+ referrerInfo: {
1973
+ ...this.enterOptions.referrerInfo,
1974
+ extraData: { ...this.enterOptions.referrerInfo.extraData }
1975
+ }
1976
+ };
1977
+ }
1978
+ getMenuButtonBoundingClientRect() {
1979
+ return deriveMenuButtonBoundingClientRect(this.systemInfo);
1980
+ }
1981
+ getNetworkType() {
1982
+ return this.wxState.getNetworkType();
1983
+ }
1984
+ getLoading() {
1985
+ return this.wxState.getLoading();
1986
+ }
1987
+ getModalLogs() {
1988
+ return this.wxState.getModalLogs();
1989
+ }
1990
+ getToast() {
1991
+ return this.wxState.getToast();
1992
+ }
1993
+ mockModal(definition = {}) {
1994
+ this.wxState.mockModal(definition);
1995
+ }
1996
+ mockActionSheet(definition = {}) {
1997
+ this.wxState.mockActionSheet(definition);
1998
+ }
1999
+ mockRequest(definition) {
2000
+ this.wxState.mockRequest(definition);
2001
+ }
2002
+ setNetworkType(networkType) {
2003
+ return this.wxState.setNetworkType(networkType);
2004
+ }
2005
+ setBackgroundTextStyle(textStyle) {
2006
+ if (textStyle !== "dark" && textStyle !== "light") throw new Error("setBackgroundTextStyle:fail invalid textStyle");
2007
+ const current = this.requireCurrentPage("wx.setBackgroundTextStyle()");
2008
+ current.__background__ ??= {
2009
+ backgroundColor: "#ffffff",
2010
+ backgroundColorBottom: "#ffffff",
2011
+ backgroundColorTop: "#ffffff",
2012
+ textStyle: "dark"
2013
+ };
2014
+ current.__background__.textStyle = textStyle;
2015
+ current.__backgroundTextStyle__ = textStyle;
2016
+ return { errMsg: "setBackgroundTextStyle:ok" };
2017
+ }
2018
+ setBackgroundColor(option) {
2019
+ const current = this.requireCurrentPage("wx.setBackgroundColor()");
2020
+ current.__background__ ??= {
2021
+ backgroundColor: "#ffffff",
2022
+ backgroundColorBottom: "#ffffff",
2023
+ backgroundColorTop: "#ffffff",
2024
+ textStyle: current.__backgroundTextStyle__ ?? "dark"
2025
+ };
2026
+ if (typeof option.backgroundColor === "string") current.__background__.backgroundColor = option.backgroundColor;
2027
+ if (typeof option.backgroundColorTop === "string") current.__background__.backgroundColorTop = option.backgroundColorTop;
2028
+ if (typeof option.backgroundColorBottom === "string") current.__background__.backgroundColorBottom = option.backgroundColorBottom;
2029
+ return { errMsg: "setBackgroundColor:ok" };
2030
+ }
2031
+ setNavigationBarTitle(title) {
2032
+ const current = this.requireCurrentPage("wx.setNavigationBarTitle()");
2033
+ current.__navigationBar__ ??= {
2034
+ animation: null,
2035
+ backgroundColor: "#ffffff",
2036
+ frontColor: "#000000",
2037
+ loading: false,
2038
+ title: ""
2039
+ };
2040
+ current.__navigationBar__.title = title;
2041
+ current.__navigationBarTitle__ = title;
2042
+ return { errMsg: "setNavigationBarTitle:ok" };
2043
+ }
2044
+ setNavigationBarColor(option) {
2045
+ const current = this.requireCurrentPage("wx.setNavigationBarColor()");
2046
+ current.__navigationBar__ ??= {
2047
+ animation: null,
2048
+ backgroundColor: "#ffffff",
2049
+ frontColor: "#000000",
2050
+ loading: false,
2051
+ title: current.__navigationBarTitle__ ?? ""
2052
+ };
2053
+ if (typeof option.backgroundColor === "string") current.__navigationBar__.backgroundColor = option.backgroundColor;
2054
+ if (typeof option.frontColor === "string") current.__navigationBar__.frontColor = option.frontColor;
2055
+ current.__navigationBar__.animation = option.animation ? {
2056
+ duration: option.animation.duration,
2057
+ timingFunction: option.animation.timingFunction
2058
+ } : null;
2059
+ return { errMsg: "setNavigationBarColor:ok" };
2060
+ }
2061
+ showNavigationBarLoading() {
2062
+ const current = this.requireCurrentPage("wx.showNavigationBarLoading()");
2063
+ current.__navigationBar__ ??= {
2064
+ animation: null,
2065
+ backgroundColor: "#ffffff",
2066
+ frontColor: "#000000",
2067
+ loading: false,
2068
+ title: current.__navigationBarTitle__ ?? ""
2069
+ };
2070
+ current.__navigationBar__.loading = true;
2071
+ return { errMsg: "showNavigationBarLoading:ok" };
2072
+ }
2073
+ hideNavigationBarLoading() {
2074
+ const current = this.requireCurrentPage("wx.hideNavigationBarLoading()");
2075
+ current.__navigationBar__ ??= {
2076
+ animation: null,
2077
+ backgroundColor: "#ffffff",
2078
+ frontColor: "#000000",
2079
+ loading: false,
2080
+ title: current.__navigationBarTitle__ ?? ""
2081
+ };
2082
+ current.__navigationBar__.loading = false;
2083
+ return { errMsg: "hideNavigationBarLoading:ok" };
2084
+ }
2085
+ hideTabBar() {
2086
+ this.tabBarVisible = false;
2087
+ return { errMsg: "hideTabBar:ok" };
2088
+ }
2089
+ hideTabBarRedDot(index) {
2090
+ const item = this.requireTabBarItem(index, "wx.hideTabBarRedDot()");
2091
+ item.redDot = false;
2092
+ return { errMsg: "hideTabBarRedDot:ok" };
2093
+ }
2094
+ showTabBar() {
2095
+ this.tabBarVisible = this.tabBarRoutes.size > 0;
2096
+ return { errMsg: "showTabBar:ok" };
2097
+ }
2098
+ showTabBarRedDot(index) {
2099
+ const item = this.requireTabBarItem(index, "wx.showTabBarRedDot()");
2100
+ item.badge = null;
2101
+ item.redDot = true;
2102
+ return { errMsg: "showTabBarRedDot:ok" };
2103
+ }
2104
+ removeTabBarBadge(index) {
2105
+ const item = this.requireTabBarItem(index, "wx.removeTabBarBadge()");
2106
+ item.badge = null;
2107
+ return { errMsg: "removeTabBarBadge:ok" };
2108
+ }
2109
+ setTabBarBadge(index, text) {
2110
+ const item = this.requireTabBarItem(index, "wx.setTabBarBadge()");
2111
+ item.badge = text;
2112
+ item.redDot = false;
2113
+ return { errMsg: "setTabBarBadge:ok" };
2114
+ }
2115
+ getScopeSnapshot(scopeId) {
2116
+ const scope = this.componentScopes.get(scopeId);
2117
+ if (!scope) return null;
2118
+ const instance = this.componentCache.get(scopeId);
2119
+ if (instance) return {
2120
+ data: instance.data ?? {},
2121
+ methods: Object.keys(instance).filter((key) => typeof instance[key] === "function").sort((a, b) => a.localeCompare(b)),
2122
+ properties: instance.properties ?? {},
2123
+ scopeId,
2124
+ type: "component"
2125
+ };
2126
+ const currentPage = this.currentPageInstance;
2127
+ if (currentPage && scopeId === `page:${currentPage.route}`) return {
2128
+ data: currentPage.data ?? {},
2129
+ methods: Object.keys(currentPage).filter((key) => typeof currentPage[key] === "function").sort((a, b) => a.localeCompare(b)),
2130
+ properties: currentPage.options ?? {},
2131
+ scopeId,
2132
+ type: "page"
2133
+ };
2134
+ return {
2135
+ data: scope.data ?? {},
2136
+ methods: [],
2137
+ properties: {},
2138
+ scopeId,
2139
+ type: "scope"
2140
+ };
2141
+ }
2142
+ selectComponent(selector) {
2143
+ return this.selectComponentsWithin(null, selector)[0] ?? null;
2144
+ }
2145
+ selectAllComponents(selector) {
2146
+ return this.selectComponentsWithin(null, selector);
2147
+ }
2148
+ selectComponentWithin(scopeId, selector) {
2149
+ return this.selectComponentsWithin(scopeId, selector)[0] ?? null;
2150
+ }
2151
+ selectAllComponentsWithin(scopeId, selector) {
2152
+ return this.selectComponentsWithin(scopeId, selector);
2153
+ }
2154
+ selectOwnerComponent(scopeId) {
2155
+ const scope = this.componentScopes.get(scopeId);
2156
+ if (!scope?.ownerScopeId) return null;
2157
+ return this.componentCache.get(scope.ownerScopeId) ?? null;
2158
+ }
2159
+ selectComponentsWithin(rootScopeId, selector) {
2160
+ const normalizedSelector = selector.trim();
2161
+ if (!normalizedSelector) return [];
2162
+ return [...this.componentScopes.entries()].filter(([candidateScopeId, scope]) => {
2163
+ if (!candidateScopeId.includes("/")) return false;
2164
+ if (rootScopeId && candidateScopeId === rootScopeId) return false;
2165
+ if (rootScopeId && !candidateScopeId.startsWith(`${rootScopeId}/`)) return false;
2166
+ if (normalizedSelector.startsWith("#")) return scope.id === normalizedSelector.slice(1);
2167
+ if (normalizedSelector.startsWith(".")) return scope.classList?.includes(normalizedSelector.slice(1)) ?? false;
2168
+ const dataAttrMatch = normalizedSelector.match(DATA_ATTR_SELECTOR_RE$1);
2169
+ if (dataAttrMatch) {
2170
+ const [, key, value] = dataAttrMatch;
2171
+ const datasetKey = key.replace(DATASET_KEY_RE, (_match, char) => char.toUpperCase());
2172
+ return scope.dataset?.[datasetKey] === value;
2173
+ }
2174
+ return scope.alias === normalizedSelector;
2175
+ }).map(([candidateScopeId]) => this.componentCache.get(candidateScopeId)).filter(Boolean);
2176
+ }
2177
+ renderCurrentPage() {
2178
+ const current = this.requireCurrentPage("renderCurrentPage()");
2179
+ const rendered = renderBrowserPageTree({
2180
+ changedPageKeys: current.__lastChangedKeys__ ?? [],
2181
+ componentCache: this.componentCache,
2182
+ componentScopes: this.componentScopes,
2183
+ files: this.files,
2184
+ moduleLoader: this.moduleLoader,
2185
+ project: this.project,
2186
+ session: {
2187
+ selectAllComponentsWithin: (scopeId, selector) => this.selectAllComponentsWithin(scopeId, selector),
2188
+ selectComponentWithin: (scopeId, selector) => this.selectComponentWithin(scopeId, selector),
2189
+ selectOwnerComponent: (scopeId) => this.selectOwnerComponent(scopeId)
2190
+ }
2191
+ }, current);
2192
+ current.__lastChangedKeys__ = [];
2193
+ return rendered;
2194
+ }
2195
+ callTapBinding(scopeId, methodName) {
2196
+ const scope = this.componentScopes.get(scopeId);
2197
+ if (!scope) throw new Error(`Unknown scope "${scopeId}" in browser simulator runtime.`);
2198
+ const method = scope.getMethod(methodName);
2199
+ if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on scope "${scopeId}" in browser simulator runtime.`);
2200
+ return method();
2201
+ }
2202
+ callTapBindingWithEvent(scopeId, methodName, event = {}) {
2203
+ const scope = this.componentScopes.get(scopeId);
2204
+ if (!scope) throw new Error(`Unknown scope "${scopeId}" in browser simulator runtime.`);
2205
+ const method = scope.getMethod(methodName);
2206
+ if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on scope "${scopeId}" in browser simulator runtime.`);
2207
+ const instance = this.componentCache.get(scopeId);
2208
+ if (instance) instance.__lastInteractionEvent__ = {
2209
+ currentTarget: {
2210
+ dataset: event.currentTarget?.dataset ?? event.dataset ?? {},
2211
+ id: event.currentTarget?.id ?? event.id ?? ""
2212
+ },
2213
+ target: {
2214
+ dataset: event.target?.dataset ?? event.dataset ?? {},
2215
+ id: event.target?.id ?? event.id ?? ""
2216
+ }
2217
+ };
2218
+ return method({
2219
+ bubbles: false,
2220
+ capturePhase: false,
2221
+ composed: false,
2222
+ currentTarget: {
2223
+ dataset: event.currentTarget?.dataset ?? event.dataset ?? {},
2224
+ id: event.currentTarget?.id ?? event.id ?? ""
2225
+ },
2226
+ detail: void 0,
2227
+ mark: void 0,
2228
+ target: {
2229
+ dataset: event.target?.dataset ?? event.dataset ?? {},
2230
+ id: event.target?.id ?? event.id ?? ""
2231
+ },
2232
+ type: "tap"
2233
+ });
2234
+ }
2235
+ bootstrap(launchOptions = createAppLaunchOptions$1("", {})) {
2236
+ if (this.appInstance) return this.appInstance;
2237
+ this.launchOptions = createAppLaunchOptions$1(launchOptions.path, launchOptions.query);
2238
+ this.enterOptions = createAppLaunchOptions$1(launchOptions.path, launchOptions.query);
2239
+ const appModulePath = join(this.project.miniprogramRootPath, "app.js");
2240
+ this.appDefinition = this.moduleLoader.executeAppModule(appModulePath);
2241
+ this.appInstance = createAppInstance(this.appDefinition);
2242
+ this.appInstance.onLaunch?.(launchOptions);
2243
+ this.appInstance.onShow?.(launchOptions);
2244
+ return this.appInstance;
2245
+ }
2246
+ reLaunch(url) {
2247
+ const target = this.resolveNavigationTarget(url);
2248
+ this.bootstrap(createAppLaunchOptions$1(target.normalizedRoute, target.query));
2249
+ this.unloadAllPages();
2250
+ const pageInstance = this.createFreshPage(target);
2251
+ this.pages.push(pageInstance);
2252
+ this.currentPageInstance = pageInstance;
2253
+ return pageInstance;
2254
+ }
2255
+ navigateTo(url) {
2256
+ const target = this.resolveNavigationTarget(url);
2257
+ this.bootstrap(createAppLaunchOptions$1(target.normalizedRoute, target.query));
2258
+ if (this.pages.length >= PAGE_STACK_LIMIT$1) throw new Error(`Cannot navigateTo() beyond a ${PAGE_STACK_LIMIT$1}-page stack in browser simulator runtime.`);
2259
+ if (this.isTabBarRoute(target.routeRecord.route)) throw new Error(`wx.navigateTo() cannot open a tabBar page in browser simulator runtime: ${url}`);
2260
+ this.currentPageInstance?.onHide?.();
2261
+ if (this.currentPageInstance) this.runPageComponentLifetime(this.currentPageInstance.route, "hide");
2262
+ const pageInstance = this.createFreshPage(target);
2263
+ this.pages.push(pageInstance);
2264
+ this.currentPageInstance = pageInstance;
2265
+ return pageInstance;
2266
+ }
2267
+ redirectTo(url) {
2268
+ const target = this.resolveNavigationTarget(url);
2269
+ this.bootstrap(createAppLaunchOptions$1(target.normalizedRoute, target.query));
2270
+ if (this.isTabBarRoute(target.routeRecord.route)) throw new Error(`wx.redirectTo() cannot open a tabBar page in browser simulator runtime: ${url}`);
2271
+ const current = this.currentPageInstance;
2272
+ if (current) {
2273
+ this.pages.pop();
2274
+ this.unloadPage(current);
2275
+ }
2276
+ const pageInstance = this.createFreshPage(target);
2277
+ this.pages.push(pageInstance);
2278
+ this.currentPageInstance = pageInstance;
2279
+ return pageInstance;
2280
+ }
2281
+ navigateBack(delta = 1) {
2282
+ this.bootstrap();
2283
+ if (this.pages.length <= 1) return this.currentPageInstance;
2284
+ const removableCount = Math.min(Number.isFinite(delta) ? Math.max(1, Math.trunc(delta)) : 1, this.pages.length - 1);
2285
+ const removedPages = this.pages.splice(this.pages.length - removableCount, removableCount);
2286
+ for (const page of removedPages.reverse()) this.unloadPage(page);
2287
+ const nextPage = this.pages.at(-1) ?? null;
2288
+ this.currentPageInstance = nextPage;
2289
+ nextPage?.onShow?.();
2290
+ if (nextPage) this.runPageComponentLifetime(nextPage.route, "show");
2291
+ return nextPage;
2292
+ }
2293
+ switchTab(url) {
2294
+ const target = this.resolveNavigationTarget(url);
2295
+ this.bootstrap(createAppLaunchOptions$1(target.normalizedRoute, target.query));
2296
+ if (Object.keys(target.query).length > 0) throw new Error(`wx.switchTab() url cannot contain query in browser simulator runtime: ${url}`);
2297
+ if (!this.isTabBarRoute(target.routeRecord.route)) throw new Error(`wx.switchTab() can only open a tabBar page in browser simulator runtime: ${url}`);
2298
+ const current = this.currentPageInstance;
2299
+ const cachedTarget = this.tabPages.get(target.routeRecord.route) ?? null;
2300
+ const tabItem = this.resolveTabBarItem(target.routeRecord.route);
2301
+ if (current === cachedTarget && current) {
2302
+ current.onTabItemTap?.(tabItem);
2303
+ return current;
2304
+ }
2305
+ if (current && current !== cachedTarget) {
2306
+ current.onHide?.();
2307
+ this.runPageComponentLifetime(current.route, "hide");
2308
+ }
2309
+ for (const page of [...this.pages].reverse()) {
2310
+ if (this.isTabBarRoute(stripLeadingSlash$1(page.route))) continue;
2311
+ this.removePageInstance(page);
2312
+ this.unloadPage(page);
2313
+ }
2314
+ let nextPage = cachedTarget;
2315
+ if (!nextPage) {
2316
+ nextPage = this.createFreshPage(target);
2317
+ this.tabPages.set(target.routeRecord.route, nextPage);
2318
+ } else if (current !== nextPage) {
2319
+ nextPage.onShow?.();
2320
+ this.runPageComponentLifetime(nextPage.route, "show");
2321
+ }
2322
+ nextPage.onTabItemTap?.(tabItem);
2323
+ this.pages.length = 0;
2324
+ this.pages.push(nextPage);
2325
+ this.currentPageInstance = nextPage;
2326
+ return nextPage;
2327
+ }
2328
+ pageScrollTo(option) {
2329
+ this.requireCurrentPage("wx.pageScrollTo()").onPageScroll?.({ scrollTop: Number(option.scrollTop ?? 0) });
2330
+ }
2331
+ triggerPullDownRefresh() {
2332
+ const current = this.requireCurrentPage("triggerPullDownRefresh()");
2333
+ current.onPullDownRefresh?.();
2334
+ return current;
2335
+ }
2336
+ triggerReachBottom() {
2337
+ const current = this.requireCurrentPage("triggerReachBottom()");
2338
+ current.onReachBottom?.();
2339
+ return current;
2340
+ }
2341
+ triggerResize(options) {
2342
+ const current = this.requireCurrentPage("triggerResize()");
2343
+ applyResizeToSystemInfo(this.systemInfo, options);
2344
+ current.onResize?.(options);
2345
+ this.runPageComponentLifetime(current.route, "resize", options);
2346
+ return current;
2347
+ }
2348
+ triggerRouteDone(options = {}) {
2349
+ const current = this.requireCurrentPage("triggerRouteDone()");
2350
+ current.onRouteDone?.(options);
2351
+ return current;
2352
+ }
2353
+ stopPullDownRefresh() {}
2354
+ createFreshPage(target) {
2355
+ const pageModulePath = join(this.project.miniprogramRootPath, `${target.routeRecord.route}.js`);
2356
+ const pageConfigPath = join(this.project.miniprogramRootPath, `${target.routeRecord.route}.json`);
2357
+ const pageDefinition = this.moduleLoader.executePageModule(pageModulePath, target.routeRecord.route);
2358
+ const pageConfig = readJsonObject$2(this.files, pageConfigPath);
2359
+ const pageInstance = createPageInstance(target.routeRecord.route, pageDefinition, target.query, {
2360
+ background: resolveBackgroundSnapshot(this.project.appConfig, pageConfig),
2361
+ navigationBar: resolveNavigationBarSnapshot(this.project.appConfig, pageConfig)
2362
+ });
2363
+ pageInstance.selectComponent = (selector) => this.selectComponent(selector);
2364
+ pageInstance.selectAllComponents = (selector) => this.selectAllComponents(selector);
2365
+ pageInstance.onLoad?.(target.query);
2366
+ pageInstance.onShow?.();
2367
+ pageInstance.onReady?.();
2368
+ if (this.isTabBarRoute(target.routeRecord.route)) this.tabPages.set(target.routeRecord.route, pageInstance);
2369
+ return pageInstance;
2370
+ }
2371
+ isTabBarRoute(route) {
2372
+ return this.tabBarRoutes.has(stripLeadingSlash$1(route));
2373
+ }
2374
+ removePageInstance(page) {
2375
+ const index = this.pages.indexOf(page);
2376
+ if (index >= 0) this.pages.splice(index, 1);
2377
+ }
2378
+ resolveNavigationTarget(url) {
2379
+ const { pathname, query } = parseNavigationUrl$1(url);
2380
+ const normalizedRoute = resolveNavigationPath$1(pathname, this.currentPageInstance ? stripLeadingSlash$1(this.currentPageInstance.route) : void 0);
2381
+ const routeRecord = this.project.routes.find((item) => item.route === normalizedRoute);
2382
+ if (!routeRecord) {
2383
+ this.bootstrap(createAppLaunchOptions$1(normalizedRoute, query));
2384
+ this.appInstance?.onPageNotFound?.(createAppLaunchOptions$1(normalizedRoute, query));
2385
+ throw new Error(`Unknown route for browser simulator navigation: ${url}`);
2386
+ }
2387
+ return {
2388
+ normalizedRoute,
2389
+ query,
2390
+ routeRecord
2391
+ };
2392
+ }
2393
+ resolveTabBarItem(route) {
2394
+ const pagePath = stripLeadingSlash$1(route);
2395
+ const item = this.tabBarItems.get(pagePath);
2396
+ if (!item) throw new Error(`Missing tabBar metadata for route "${route}" in browser simulator runtime.`);
2397
+ return { ...item };
2398
+ }
2399
+ requireTabBarItem(index, action) {
2400
+ const normalizedIndex = Number.isFinite(index) ? Math.trunc(index) : NaN;
2401
+ const item = this.tabBarState.get(normalizedIndex);
2402
+ if (!item) throw new Error(`Cannot call ${action} with unknown tabBar index ${index} in browser simulator runtime.`);
2403
+ return item;
2404
+ }
2405
+ unloadAllPages() {
2406
+ const pagesToUnload = new Set([...this.pages, ...this.tabPages.values()]);
2407
+ for (const page of [...pagesToUnload].reverse()) this.unloadPage(page);
2408
+ this.pages.length = 0;
2409
+ this.tabPages.clear();
2410
+ this.componentCache.clear();
2411
+ this.componentScopes.clear();
2412
+ this.currentPageInstance = null;
2413
+ }
2414
+ unloadPage(page) {
2415
+ page.onUnload?.();
2416
+ this.detachPageComponents(page.route);
2417
+ this.tabPages.delete(stripLeadingSlash$1(page.route));
2418
+ }
2419
+ requireCurrentPage(action) {
2420
+ this.bootstrap();
2421
+ const current = this.currentPageInstance;
2422
+ if (!current) throw new Error(`Cannot call ${action} without an active page in browser simulator runtime.`);
2423
+ return current;
2424
+ }
2425
+ detachPageComponents(route) {
2426
+ const prefix = `page:${stripLeadingSlash$1(route)}`;
2427
+ for (const [scopeId, instance] of [...this.componentCache.entries()]) {
2428
+ if (!scopeId.startsWith(prefix)) continue;
2429
+ instance.__definition__?.lifetimes?.detached?.call(instance);
2430
+ this.componentCache.delete(scopeId);
2431
+ this.componentScopes.delete(scopeId);
2432
+ }
182
2433
  }
183
- return instance;
2434
+ runPageComponentLifetime(route, lifetimeName, payload) {
2435
+ const prefix = `page:${stripLeadingSlash$1(route)}`;
2436
+ for (const [scopeId, instance] of this.componentCache.entries()) {
2437
+ if (!scopeId.startsWith(prefix)) continue;
2438
+ runComponentPageLifetime(instance, lifetimeName, payload);
2439
+ }
2440
+ }
2441
+ };
2442
+ function createBrowserHeadlessSession(options) {
2443
+ return new BrowserHeadlessSession(options);
184
2444
  }
185
2445
  //#endregion
186
- //#region src/runtime/pageInstance.ts
187
- function bindFunction(target, key, value) {
188
- if (typeof value !== "function") {
189
- target[key] = value;
2446
+ //#region src/project/loadProject.ts
2447
+ function readJsonObject$1(filePath) {
2448
+ try {
2449
+ const content = fs.readFileSync(filePath, "utf8");
2450
+ const value = JSON.parse(content);
2451
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
2452
+ } catch {
190
2453
  return;
191
2454
  }
192
- target[key] = (...args) => value.apply(target, args);
193
- }
194
- function cloneObject(value) {
195
- return JSON.parse(JSON.stringify(value));
196
2455
  }
197
- function resolveInitialData(definition) {
198
- const rawData = definition.data;
199
- if (typeof rawData === "function") {
200
- const next = rawData.call(definition);
201
- return next && typeof next === "object" && !Array.isArray(next) ? cloneObject(next) : {};
2456
+ function resolveProjectConfigFiles(projectPath) {
2457
+ const entries = [];
2458
+ for (const fileName of ["project.config.json", "project.private.config.json"]) {
2459
+ const filePath = path.resolve(projectPath, fileName);
2460
+ const value = readJsonObject$1(filePath);
2461
+ if (!value) continue;
2462
+ entries.push({
2463
+ filePath,
2464
+ value
2465
+ });
202
2466
  }
203
- return rawData && typeof rawData === "object" && !Array.isArray(rawData) ? cloneObject(rawData) : {};
2467
+ return entries;
204
2468
  }
205
- function assignByPath(target, path, value) {
206
- const segments = path.split(".").filter(Boolean);
207
- if (segments.length === 0) return;
208
- let current = target;
209
- for (let index = 0; index < segments.length - 1; index += 1) {
210
- const segment = segments[index];
211
- const next = current[segment];
212
- if (!next || typeof next !== "object" || Array.isArray(next)) current[segment] = {};
213
- current = current[segment];
2469
+ function resolveMiniprogramRoot(projectPath, configFiles) {
2470
+ for (const configFile of [...configFiles].reverse()) {
2471
+ const rawRoot = configFile.value.miniprogramRoot;
2472
+ if (typeof rawRoot !== "string" || !rawRoot.trim()) continue;
2473
+ return rawRoot.trim();
214
2474
  }
215
- current[segments[segments.length - 1]] = value;
2475
+ throw new Error(`Failed to resolve miniprogramRoot for headless runtime project: ${projectPath}. Expected project.config.json or project.private.config.json to define miniprogramRoot.`);
216
2476
  }
217
- function createPageInstance(route, definition) {
218
- const instance = {
219
- data: resolveInitialData(definition),
220
- route,
221
- setData(patch) {
222
- for (const [key, value] of Object.entries(patch)) assignByPath(instance.data, key, value);
223
- }
224
- };
225
- for (const [key, value] of Object.entries(definition)) {
226
- if (key === "data") continue;
227
- bindFunction(instance, key, value);
228
- }
229
- return instance;
2477
+ function ensureFileExists(filePath, label) {
2478
+ if (fs.existsSync(filePath)) return;
2479
+ throw new Error(`Missing ${label} for headless runtime project: ${normalize(filePath)}`);
2480
+ }
2481
+ function loadAppConfig(appConfigPath) {
2482
+ const appConfig = readJsonObject$1(appConfigPath);
2483
+ if (!appConfig) throw new Error(`Failed to read built app.json for headless runtime project: ${normalize(appConfigPath)}`);
2484
+ return appConfig;
2485
+ }
2486
+ function loadProject(projectPath) {
2487
+ const normalizedProjectPath = path.resolve(projectPath);
2488
+ const projectConfigFiles = resolveProjectConfigFiles(normalizedProjectPath);
2489
+ if (projectConfigFiles.length === 0) throw new Error(`Missing project config for headless runtime project: ${normalizedProjectPath}. Expected project.config.json or project.private.config.json.`);
2490
+ const miniprogramRoot = resolveMiniprogramRoot(normalizedProjectPath, projectConfigFiles);
2491
+ const miniprogramRootPath = path.resolve(normalizedProjectPath, miniprogramRoot);
2492
+ ensureFileExists(miniprogramRootPath, "miniprogramRoot directory");
2493
+ const appConfigPath = path.resolve(miniprogramRootPath, "app.json");
2494
+ ensureFileExists(appConfigPath, "built app.json");
2495
+ return createProjectDescriptor({
2496
+ appConfig: loadAppConfig(appConfigPath),
2497
+ appConfigPath,
2498
+ miniprogramRoot,
2499
+ miniprogramRootPath,
2500
+ projectPath: normalizedProjectPath,
2501
+ projectConfigFiles
2502
+ });
230
2503
  }
231
2504
  //#endregion
232
2505
  //#region src/runtime/moduleLoader.ts
@@ -245,12 +2518,18 @@ function resolveRequiredModulePath(importer, request) {
245
2518
  for (const candidate of candidates) if (fs.existsSync(candidate)) return candidate;
246
2519
  throw createRequireNotFoundError(request, importer);
247
2520
  }
248
- function createExecutionContext(registries, getCurrentPages, getApp) {
249
- const wx = createHeadlessWx();
2521
+ function createExecutionContext(registries, getCurrentPages, getApp, wxDriver) {
2522
+ const wx = createHeadlessWx(wxDriver);
250
2523
  return {
251
2524
  App(definition) {
252
2525
  return registerAppDefinition(registries, definition);
253
2526
  },
2527
+ Behavior(definition) {
2528
+ return {
2529
+ ...definition,
2530
+ __isHeadlessBehavior__: true
2531
+ };
2532
+ },
254
2533
  Component(definition) {
255
2534
  return registerComponentDefinition(registries, definition);
256
2535
  },
@@ -269,9 +2548,9 @@ function createExecutionContext(registries, getCurrentPages, getApp) {
269
2548
  wx
270
2549
  };
271
2550
  }
272
- function createModuleLoader(registries, getCurrentPages, getApp) {
2551
+ function createModuleLoader(registries, getCurrentPages, getApp, wxDriver) {
273
2552
  const moduleCache = /* @__PURE__ */ new Map();
274
- const executionContext = createExecutionContext(registries, getCurrentPages, getApp);
2553
+ const executionContext = createExecutionContext(registries, getCurrentPages, getApp, wxDriver);
275
2554
  executionContext.globalThis = executionContext;
276
2555
  function executeModule(filePath, loadContext) {
277
2556
  const resolvedPath = path.resolve(filePath);
@@ -316,7 +2595,52 @@ function createModuleLoader(registries, getCurrentPages, getApp) {
316
2595
  }
317
2596
  //#endregion
318
2597
  //#region src/runtime/session.ts
319
- const LEADING_SLASH_RE$1 = /^\/+/;
2598
+ const LEADING_SLASH_RE$2 = /^\/+/;
2599
+ const PAGE_STACK_LIMIT = 10;
2600
+ function stripLeadingSlash(route) {
2601
+ return route.replace(LEADING_SLASH_RE$2, "");
2602
+ }
2603
+ function normalizeQuery(queryString) {
2604
+ const query = new URLSearchParams(queryString);
2605
+ const result = {};
2606
+ for (const [key, value] of query.entries()) result[key] = value;
2607
+ return result;
2608
+ }
2609
+ function parseNavigationUrl(url) {
2610
+ const trimmedUrl = url.trim();
2611
+ if (!trimmedUrl) throw new Error("Navigation url must be a non-empty string in headless runtime.");
2612
+ const [pathWithHash, queryString = ""] = trimmedUrl.split("?");
2613
+ const [pathname] = pathWithHash.split("#");
2614
+ return {
2615
+ pathname: pathname || "",
2616
+ query: normalizeQuery(queryString)
2617
+ };
2618
+ }
2619
+ function createAppLaunchOptions(pathname, query) {
2620
+ return {
2621
+ path: stripLeadingSlash(pathname),
2622
+ query: { ...query },
2623
+ referrerInfo: {
2624
+ appId: "",
2625
+ extraData: {}
2626
+ },
2627
+ scene: 1001
2628
+ };
2629
+ }
2630
+ function readJsonObject(filePath) {
2631
+ try {
2632
+ const value = JSON.parse(fs.readFileSync(filePath, "utf8"));
2633
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
2634
+ } catch {
2635
+ return;
2636
+ }
2637
+ }
2638
+ function resolveNavigationPath(targetPath, baseRoute) {
2639
+ if (!targetPath) throw new Error("Navigation url must include a pathname in headless runtime.");
2640
+ if (targetPath.startsWith("/")) return path.posix.normalize(targetPath).replace(LEADING_SLASH_RE$2, "");
2641
+ if (!baseRoute) throw new Error(`Cannot resolve relative navigation url "${targetPath}" without an active page.`);
2642
+ return path.posix.resolve(`/${path.posix.dirname(baseRoute)}`, targetPath).replace(LEADING_SLASH_RE$2, "");
2643
+ }
320
2644
  var HeadlessSession = class {
321
2645
  project;
322
2646
  appDefinition = null;
@@ -325,10 +2649,99 @@ var HeadlessSession = class {
325
2649
  registries;
326
2650
  currentPageInstance = null;
327
2651
  pages = [];
2652
+ tabBarRoutes;
2653
+ tabPages = /* @__PURE__ */ new Map();
2654
+ tabBarItems = /* @__PURE__ */ new Map();
2655
+ tabBarState = /* @__PURE__ */ new Map();
2656
+ tabBarVisible = false;
2657
+ systemInfo = createDefaultSystemInfo();
2658
+ enterOptions = createAppLaunchOptions("", {});
2659
+ launchOptions = createAppLaunchOptions("", {});
2660
+ wxState = createHeadlessWxState();
328
2661
  constructor(options) {
329
2662
  this.project = loadProject(options.projectPath);
330
2663
  this.registries = createHostRegistries();
331
- this.moduleLoader = createModuleLoader(this.registries, () => this.pages.slice(), () => this.getApp());
2664
+ const rawTabBarList = Array.isArray(this.project.appConfig.tabBar?.list) ? this.project.appConfig.tabBar.list : [];
2665
+ this.tabBarRoutes = /* @__PURE__ */ new Set();
2666
+ rawTabBarList.forEach((item, index) => {
2667
+ if (typeof item?.pagePath !== "string") return;
2668
+ const pagePath = stripLeadingSlash(item.pagePath);
2669
+ if (!pagePath) return;
2670
+ this.tabBarRoutes.add(pagePath);
2671
+ this.tabBarItems.set(pagePath, {
2672
+ index,
2673
+ pagePath,
2674
+ text: typeof item.text === "string" ? item.text : void 0
2675
+ });
2676
+ this.tabBarState.set(index, {
2677
+ badge: null,
2678
+ index,
2679
+ pagePath,
2680
+ redDot: false,
2681
+ text: typeof item.text === "string" ? item.text : void 0
2682
+ });
2683
+ });
2684
+ this.tabBarVisible = this.tabBarRoutes.size > 0;
2685
+ this.moduleLoader = createModuleLoader(this.registries, () => this.pages.slice(), () => this.getApp(), {
2686
+ getEnterOptionsSync: () => ({
2687
+ ...this.enterOptions,
2688
+ query: { ...this.enterOptions.query },
2689
+ referrerInfo: {
2690
+ ...this.enterOptions.referrerInfo,
2691
+ extraData: { ...this.enterOptions.referrerInfo.extraData }
2692
+ }
2693
+ }),
2694
+ getAppBaseInfoSync: () => deriveAppBaseInfo(this.systemInfo),
2695
+ getLaunchOptionsSync: () => ({
2696
+ ...this.launchOptions,
2697
+ query: { ...this.launchOptions.query },
2698
+ referrerInfo: {
2699
+ ...this.launchOptions.referrerInfo,
2700
+ extraData: { ...this.launchOptions.referrerInfo.extraData }
2701
+ }
2702
+ }),
2703
+ getMenuButtonBoundingClientRect: () => deriveMenuButtonBoundingClientRect(this.systemInfo),
2704
+ getNetworkType: () => this.wxState.getNetworkType(),
2705
+ navigateBack: (option) => this.navigateBack(option?.delta),
2706
+ navigateTo: (option) => this.navigateTo(option.url),
2707
+ pageScrollTo: (option) => this.pageScrollTo(option),
2708
+ clearStorageSync: () => this.wxState.clearStorageSync(),
2709
+ getStorageInfoSync: () => this.wxState.getStorageInfoSync(),
2710
+ getStorageSync: (key) => this.wxState.getStorageSync(key),
2711
+ getSystemInfoSync: () => ({ ...this.systemInfo }),
2712
+ getWindowInfoSync: () => deriveWindowInfo(this.systemInfo),
2713
+ hideLoading: () => this.wxState.hideLoading(),
2714
+ hideToast: () => this.wxState.hideToast(),
2715
+ reLaunch: (option) => this.reLaunch(option.url),
2716
+ redirectTo: (option) => this.redirectTo(option.url),
2717
+ nextTick: (callback) => queueMicrotask(() => callback?.()),
2718
+ offNetworkStatusChange: (callback) => this.wxState.offNetworkStatusChange(callback),
2719
+ onNetworkStatusChange: (callback) => this.wxState.onNetworkStatusChange(callback),
2720
+ removeStorageSync: (key) => this.wxState.removeStorageSync(key),
2721
+ request: (option) => this.wxState.request(option),
2722
+ setBackgroundColor: (option) => this.setBackgroundColor(option),
2723
+ setBackgroundTextStyle: (option) => this.setBackgroundTextStyle(option.textStyle),
2724
+ setStorageSync: (key, value) => this.wxState.setStorageSync(key, value),
2725
+ setNavigationBarColor: (option) => this.setNavigationBarColor(option),
2726
+ setNavigationBarTitle: (option) => this.setNavigationBarTitle(option.title),
2727
+ hideShareMenu: () => this.wxState.hideShareMenu(),
2728
+ hideNavigationBarLoading: () => this.hideNavigationBarLoading(),
2729
+ hideTabBar: () => this.hideTabBar(),
2730
+ hideTabBarRedDot: (option) => this.hideTabBarRedDot(option.index),
2731
+ showShareMenu: (option) => this.wxState.showShareMenu(option),
2732
+ showNavigationBarLoading: () => this.showNavigationBarLoading(),
2733
+ showTabBar: () => this.showTabBar(),
2734
+ showTabBarRedDot: (option) => this.showTabBarRedDot(option.index),
2735
+ showActionSheet: (option) => this.wxState.showActionSheet(option),
2736
+ showLoading: (option) => this.wxState.showLoading(option),
2737
+ showModal: (option) => this.wxState.showModal(option),
2738
+ showToast: (option) => this.wxState.showToast(option),
2739
+ stopPullDownRefresh: () => this.stopPullDownRefresh(),
2740
+ switchTab: (option) => this.switchTab(option.url),
2741
+ removeTabBarBadge: (option) => this.removeTabBarBadge(option.index),
2742
+ setTabBarBadge: (option) => this.setTabBarBadge(option.index, option.text),
2743
+ updateShareMenu: (option) => this.wxState.updateShareMenu(option)
2744
+ });
332
2745
  }
333
2746
  getApp() {
334
2747
  return this.appInstance;
@@ -336,36 +2749,389 @@ var HeadlessSession = class {
336
2749
  getCurrentPages() {
337
2750
  return this.pages.slice();
338
2751
  }
339
- bootstrap() {
2752
+ getCurrentPageNavigationBarTitle() {
2753
+ return this.currentPageInstance?.__navigationBarTitle__ ?? null;
2754
+ }
2755
+ getCurrentPageNavigationBar() {
2756
+ const snapshot = this.currentPageInstance?.__navigationBar__;
2757
+ return snapshot ? cloneNavigationBarSnapshot(snapshot) : null;
2758
+ }
2759
+ getCurrentPageBackground() {
2760
+ const snapshot = this.currentPageInstance?.__background__;
2761
+ return snapshot ? cloneBackgroundSnapshot(snapshot) : null;
2762
+ }
2763
+ getActionSheetLogs() {
2764
+ return this.wxState.getActionSheetLogs();
2765
+ }
2766
+ getRequestLogs() {
2767
+ return this.wxState.getRequestLogs();
2768
+ }
2769
+ getStorageSnapshot() {
2770
+ return this.wxState.getStorageSnapshot();
2771
+ }
2772
+ getShareMenu() {
2773
+ return this.wxState.getShareMenu();
2774
+ }
2775
+ getTabBar() {
2776
+ return { visible: this.tabBarVisible };
2777
+ }
2778
+ getTabBarSnapshot() {
2779
+ return {
2780
+ items: Array.from(this.tabBarState.values(), (item) => ({
2781
+ badge: item.badge,
2782
+ index: item.index,
2783
+ pagePath: item.pagePath,
2784
+ redDot: item.redDot,
2785
+ text: item.text
2786
+ })),
2787
+ visible: this.tabBarVisible
2788
+ };
2789
+ }
2790
+ getStorageInfo() {
2791
+ return this.wxState.getStorageInfoSync();
2792
+ }
2793
+ getSystemInfo() {
2794
+ return { ...this.systemInfo };
2795
+ }
2796
+ getWindowInfo() {
2797
+ return deriveWindowInfo(this.systemInfo);
2798
+ }
2799
+ getAppBaseInfo() {
2800
+ return deriveAppBaseInfo(this.systemInfo);
2801
+ }
2802
+ getLaunchOptions() {
2803
+ return {
2804
+ ...this.launchOptions,
2805
+ query: { ...this.launchOptions.query },
2806
+ referrerInfo: {
2807
+ ...this.launchOptions.referrerInfo,
2808
+ extraData: { ...this.launchOptions.referrerInfo.extraData }
2809
+ }
2810
+ };
2811
+ }
2812
+ getEnterOptions() {
2813
+ return {
2814
+ ...this.enterOptions,
2815
+ query: { ...this.enterOptions.query },
2816
+ referrerInfo: {
2817
+ ...this.enterOptions.referrerInfo,
2818
+ extraData: { ...this.enterOptions.referrerInfo.extraData }
2819
+ }
2820
+ };
2821
+ }
2822
+ getMenuButtonBoundingClientRect() {
2823
+ return deriveMenuButtonBoundingClientRect(this.systemInfo);
2824
+ }
2825
+ getNetworkType() {
2826
+ return this.wxState.getNetworkType();
2827
+ }
2828
+ getLoading() {
2829
+ return this.wxState.getLoading();
2830
+ }
2831
+ getModalLogs() {
2832
+ return this.wxState.getModalLogs();
2833
+ }
2834
+ getToast() {
2835
+ return this.wxState.getToast();
2836
+ }
2837
+ mockModal(definition = {}) {
2838
+ this.wxState.mockModal(definition);
2839
+ }
2840
+ mockActionSheet(definition = {}) {
2841
+ this.wxState.mockActionSheet(definition);
2842
+ }
2843
+ mockRequest(definition) {
2844
+ this.wxState.mockRequest(definition);
2845
+ }
2846
+ setNetworkType(networkType) {
2847
+ return this.wxState.setNetworkType(networkType);
2848
+ }
2849
+ setBackgroundTextStyle(textStyle) {
2850
+ if (textStyle !== "dark" && textStyle !== "light") throw new Error("setBackgroundTextStyle:fail invalid textStyle");
2851
+ const current = this.requireCurrentPage("wx.setBackgroundTextStyle()");
2852
+ current.__background__ ??= {
2853
+ backgroundColor: "#ffffff",
2854
+ backgroundColorBottom: "#ffffff",
2855
+ backgroundColorTop: "#ffffff",
2856
+ textStyle: "dark"
2857
+ };
2858
+ current.__background__.textStyle = textStyle;
2859
+ current.__backgroundTextStyle__ = textStyle;
2860
+ return { errMsg: "setBackgroundTextStyle:ok" };
2861
+ }
2862
+ setBackgroundColor(option) {
2863
+ const current = this.requireCurrentPage("wx.setBackgroundColor()");
2864
+ current.__background__ ??= {
2865
+ backgroundColor: "#ffffff",
2866
+ backgroundColorBottom: "#ffffff",
2867
+ backgroundColorTop: "#ffffff",
2868
+ textStyle: current.__backgroundTextStyle__ ?? "dark"
2869
+ };
2870
+ if (typeof option.backgroundColor === "string") current.__background__.backgroundColor = option.backgroundColor;
2871
+ if (typeof option.backgroundColorTop === "string") current.__background__.backgroundColorTop = option.backgroundColorTop;
2872
+ if (typeof option.backgroundColorBottom === "string") current.__background__.backgroundColorBottom = option.backgroundColorBottom;
2873
+ return { errMsg: "setBackgroundColor:ok" };
2874
+ }
2875
+ setNavigationBarTitle(title) {
2876
+ const current = this.requireCurrentPage("wx.setNavigationBarTitle()");
2877
+ current.__navigationBar__ ??= {
2878
+ animation: null,
2879
+ backgroundColor: "#ffffff",
2880
+ frontColor: "#000000",
2881
+ loading: false,
2882
+ title: ""
2883
+ };
2884
+ current.__navigationBar__.title = title;
2885
+ current.__navigationBarTitle__ = title;
2886
+ return { errMsg: "setNavigationBarTitle:ok" };
2887
+ }
2888
+ setNavigationBarColor(option) {
2889
+ const current = this.requireCurrentPage("wx.setNavigationBarColor()");
2890
+ current.__navigationBar__ ??= {
2891
+ animation: null,
2892
+ backgroundColor: "#ffffff",
2893
+ frontColor: "#000000",
2894
+ loading: false,
2895
+ title: current.__navigationBarTitle__ ?? ""
2896
+ };
2897
+ if (typeof option.backgroundColor === "string") current.__navigationBar__.backgroundColor = option.backgroundColor;
2898
+ if (typeof option.frontColor === "string") current.__navigationBar__.frontColor = option.frontColor;
2899
+ current.__navigationBar__.animation = option.animation ? {
2900
+ duration: option.animation.duration,
2901
+ timingFunction: option.animation.timingFunction
2902
+ } : null;
2903
+ return { errMsg: "setNavigationBarColor:ok" };
2904
+ }
2905
+ showNavigationBarLoading() {
2906
+ const current = this.requireCurrentPage("wx.showNavigationBarLoading()");
2907
+ current.__navigationBar__ ??= {
2908
+ animation: null,
2909
+ backgroundColor: "#ffffff",
2910
+ frontColor: "#000000",
2911
+ loading: false,
2912
+ title: current.__navigationBarTitle__ ?? ""
2913
+ };
2914
+ current.__navigationBar__.loading = true;
2915
+ return { errMsg: "showNavigationBarLoading:ok" };
2916
+ }
2917
+ hideNavigationBarLoading() {
2918
+ const current = this.requireCurrentPage("wx.hideNavigationBarLoading()");
2919
+ current.__navigationBar__ ??= {
2920
+ animation: null,
2921
+ backgroundColor: "#ffffff",
2922
+ frontColor: "#000000",
2923
+ loading: false,
2924
+ title: current.__navigationBarTitle__ ?? ""
2925
+ };
2926
+ current.__navigationBar__.loading = false;
2927
+ return { errMsg: "hideNavigationBarLoading:ok" };
2928
+ }
2929
+ hideTabBar() {
2930
+ this.tabBarVisible = false;
2931
+ return { errMsg: "hideTabBar:ok" };
2932
+ }
2933
+ hideTabBarRedDot(index) {
2934
+ const item = this.requireTabBarItem(index, "wx.hideTabBarRedDot()");
2935
+ item.redDot = false;
2936
+ return { errMsg: "hideTabBarRedDot:ok" };
2937
+ }
2938
+ showTabBar() {
2939
+ this.tabBarVisible = this.tabBarRoutes.size > 0;
2940
+ return { errMsg: "showTabBar:ok" };
2941
+ }
2942
+ showTabBarRedDot(index) {
2943
+ const item = this.requireTabBarItem(index, "wx.showTabBarRedDot()");
2944
+ item.badge = null;
2945
+ item.redDot = true;
2946
+ return { errMsg: "showTabBarRedDot:ok" };
2947
+ }
2948
+ removeTabBarBadge(index) {
2949
+ const item = this.requireTabBarItem(index, "wx.removeTabBarBadge()");
2950
+ item.badge = null;
2951
+ return { errMsg: "removeTabBarBadge:ok" };
2952
+ }
2953
+ setTabBarBadge(index, text) {
2954
+ const item = this.requireTabBarItem(index, "wx.setTabBarBadge()");
2955
+ item.badge = text;
2956
+ item.redDot = false;
2957
+ return { errMsg: "setTabBarBadge:ok" };
2958
+ }
2959
+ bootstrap(launchOptions = createAppLaunchOptions("", {})) {
340
2960
  if (this.appInstance) return this.appInstance;
2961
+ this.launchOptions = createAppLaunchOptions(launchOptions.path, launchOptions.query);
2962
+ this.enterOptions = createAppLaunchOptions(launchOptions.path, launchOptions.query);
341
2963
  const appModulePath = path.resolve(this.project.miniprogramRootPath, "app.js");
342
2964
  this.appDefinition = this.moduleLoader.executeAppModule(appModulePath);
343
2965
  this.appInstance = createAppInstance(this.appDefinition);
344
- this.appInstance.onLaunch?.();
345
- this.appInstance.onShow?.();
2966
+ this.appInstance.onLaunch?.(launchOptions);
2967
+ this.appInstance.onShow?.(launchOptions);
346
2968
  return this.appInstance;
347
2969
  }
348
- reLaunch(route) {
349
- this.bootstrap();
350
- const normalizedRoute = route.replace(LEADING_SLASH_RE$1, "");
351
- const routeRecord = this.project.routes.find((item) => item.route === normalizedRoute);
352
- if (!routeRecord) throw new Error(`Unknown route for headless runtime reLaunch(): ${route}`);
353
- if (this.currentPageInstance) {
354
- this.currentPageInstance.onHide?.();
355
- this.currentPageInstance.onUnload?.();
356
- this.pages.length = 0;
357
- this.currentPageInstance = null;
358
- }
359
- const pageModulePath = path.resolve(this.project.miniprogramRootPath, `${routeRecord.route}.js`);
360
- const pageDefinition = this.moduleLoader.executePageModule(pageModulePath, routeRecord.route);
361
- const pageInstance = createPageInstance(`/${routeRecord.route}`, pageDefinition);
2970
+ reLaunch(url) {
2971
+ const target = this.resolveNavigationTarget(url);
2972
+ this.bootstrap(createAppLaunchOptions(target.normalizedRoute, target.query));
2973
+ this.unloadAllPages();
2974
+ const pageInstance = this.createFreshPage(target);
2975
+ this.pages.push(pageInstance);
2976
+ this.currentPageInstance = pageInstance;
2977
+ return pageInstance;
2978
+ }
2979
+ navigateTo(url) {
2980
+ const target = this.resolveNavigationTarget(url);
2981
+ this.bootstrap(createAppLaunchOptions(target.normalizedRoute, target.query));
2982
+ if (this.pages.length >= PAGE_STACK_LIMIT) throw new Error(`Cannot navigateTo() beyond a ${PAGE_STACK_LIMIT}-page stack in headless runtime.`);
2983
+ if (this.isTabBarRoute(target.routeRecord.route)) throw new Error(`wx.navigateTo() cannot open a tabBar page in headless runtime: ${url}`);
2984
+ this.currentPageInstance?.onHide?.();
2985
+ const pageInstance = this.createFreshPage(target);
2986
+ this.pages.push(pageInstance);
2987
+ this.currentPageInstance = pageInstance;
2988
+ return pageInstance;
2989
+ }
2990
+ redirectTo(url) {
2991
+ const target = this.resolveNavigationTarget(url);
2992
+ this.bootstrap(createAppLaunchOptions(target.normalizedRoute, target.query));
2993
+ if (this.isTabBarRoute(target.routeRecord.route)) throw new Error(`wx.redirectTo() cannot open a tabBar page in headless runtime: ${url}`);
2994
+ const current = this.currentPageInstance;
2995
+ if (current) {
2996
+ this.pages.pop();
2997
+ this.unloadPage(current);
2998
+ }
2999
+ const pageInstance = this.createFreshPage(target);
362
3000
  this.pages.push(pageInstance);
363
3001
  this.currentPageInstance = pageInstance;
364
- pageInstance.onLoad?.();
3002
+ return pageInstance;
3003
+ }
3004
+ navigateBack(delta = 1) {
3005
+ this.bootstrap();
3006
+ if (this.pages.length <= 1) return this.currentPageInstance;
3007
+ const removableCount = Math.min(Number.isFinite(delta) ? Math.max(1, Math.trunc(delta)) : 1, this.pages.length - 1);
3008
+ const removedPages = this.pages.splice(this.pages.length - removableCount, removableCount);
3009
+ for (const page of removedPages.reverse()) this.unloadPage(page);
3010
+ const nextPage = this.pages.at(-1) ?? null;
3011
+ this.currentPageInstance = nextPage;
3012
+ nextPage?.onShow?.();
3013
+ return nextPage;
3014
+ }
3015
+ switchTab(url) {
3016
+ const target = this.resolveNavigationTarget(url);
3017
+ this.bootstrap(createAppLaunchOptions(target.normalizedRoute, target.query));
3018
+ if (Object.keys(target.query).length > 0) throw new Error(`wx.switchTab() url cannot contain query in headless runtime: ${url}`);
3019
+ if (!this.isTabBarRoute(target.routeRecord.route)) throw new Error(`wx.switchTab() can only open a tabBar page in headless runtime: ${url}`);
3020
+ const current = this.currentPageInstance;
3021
+ const cachedTarget = this.tabPages.get(target.routeRecord.route) ?? null;
3022
+ const tabItem = this.resolveTabBarItem(target.routeRecord.route);
3023
+ if (current === cachedTarget && current) {
3024
+ current.onTabItemTap?.(tabItem);
3025
+ return current;
3026
+ }
3027
+ if (current && current !== cachedTarget) current.onHide?.();
3028
+ for (const page of [...this.pages].reverse()) {
3029
+ if (this.isTabBarRoute(stripLeadingSlash(page.route))) continue;
3030
+ this.removePageInstance(page);
3031
+ this.unloadPage(page);
3032
+ }
3033
+ let nextPage = cachedTarget;
3034
+ if (!nextPage) {
3035
+ nextPage = this.createFreshPage(target);
3036
+ this.tabPages.set(target.routeRecord.route, nextPage);
3037
+ } else if (current !== nextPage) nextPage.onShow?.();
3038
+ nextPage.onTabItemTap?.(tabItem);
3039
+ this.pages.length = 0;
3040
+ this.pages.push(nextPage);
3041
+ this.currentPageInstance = nextPage;
3042
+ return nextPage;
3043
+ }
3044
+ pageScrollTo(option) {
3045
+ this.requireCurrentPage("wx.pageScrollTo()").onPageScroll?.({ scrollTop: Number(option.scrollTop ?? 0) });
3046
+ }
3047
+ triggerPullDownRefresh() {
3048
+ const current = this.requireCurrentPage("triggerPullDownRefresh()");
3049
+ current.onPullDownRefresh?.();
3050
+ return current;
3051
+ }
3052
+ triggerReachBottom() {
3053
+ const current = this.requireCurrentPage("triggerReachBottom()");
3054
+ current.onReachBottom?.();
3055
+ return current;
3056
+ }
3057
+ triggerResize(options) {
3058
+ const current = this.requireCurrentPage("triggerResize()");
3059
+ applyResizeToSystemInfo(this.systemInfo, options);
3060
+ current.onResize?.(options);
3061
+ return current;
3062
+ }
3063
+ triggerRouteDone(options = {}) {
3064
+ const current = this.requireCurrentPage("triggerRouteDone()");
3065
+ current.onRouteDone?.(options);
3066
+ return current;
3067
+ }
3068
+ stopPullDownRefresh() {}
3069
+ createFreshPage(target) {
3070
+ const pageModulePath = path.resolve(this.project.miniprogramRootPath, `${target.routeRecord.route}.js`);
3071
+ const pageConfigPath = path.resolve(this.project.miniprogramRootPath, `${target.routeRecord.route}.json`);
3072
+ const pageDefinition = this.moduleLoader.executePageModule(pageModulePath, target.routeRecord.route);
3073
+ const pageConfig = readJsonObject(pageConfigPath);
3074
+ const pageInstance = createPageInstance(`/${target.routeRecord.route}`, pageDefinition, target.query, {
3075
+ background: resolveBackgroundSnapshot(this.project.appConfig, pageConfig),
3076
+ navigationBar: resolveNavigationBarSnapshot(this.project.appConfig, pageConfig)
3077
+ });
3078
+ pageInstance.onLoad?.(target.query);
365
3079
  pageInstance.onShow?.();
366
3080
  pageInstance.onReady?.();
3081
+ if (this.isTabBarRoute(target.routeRecord.route)) this.tabPages.set(target.routeRecord.route, pageInstance);
367
3082
  return pageInstance;
368
3083
  }
3084
+ isTabBarRoute(route) {
3085
+ return this.tabBarRoutes.has(stripLeadingSlash(route));
3086
+ }
3087
+ resolveTabBarItem(route) {
3088
+ const pagePath = stripLeadingSlash(route);
3089
+ const item = this.tabBarItems.get(pagePath);
3090
+ if (!item) throw new Error(`Missing tabBar metadata for route "${route}" in headless runtime.`);
3091
+ return { ...item };
3092
+ }
3093
+ requireTabBarItem(index, action) {
3094
+ const normalizedIndex = Number.isFinite(index) ? Math.trunc(index) : NaN;
3095
+ const item = this.tabBarState.get(normalizedIndex);
3096
+ if (!item) throw new Error(`Cannot call ${action} with unknown tabBar index ${index} in headless runtime.`);
3097
+ return item;
3098
+ }
3099
+ removePageInstance(page) {
3100
+ const index = this.pages.indexOf(page);
3101
+ if (index >= 0) this.pages.splice(index, 1);
3102
+ }
3103
+ resolveNavigationTarget(url) {
3104
+ const { pathname, query } = parseNavigationUrl(url);
3105
+ const normalizedRoute = resolveNavigationPath(pathname, this.currentPageInstance ? stripLeadingSlash(this.currentPageInstance.route) : void 0);
3106
+ const routeRecord = this.project.routes.find((item) => item.route === normalizedRoute);
3107
+ if (!routeRecord) {
3108
+ this.bootstrap(createAppLaunchOptions(normalizedRoute, query));
3109
+ this.appInstance?.onPageNotFound?.(createAppLaunchOptions(normalizedRoute, query));
3110
+ throw new Error(`Unknown route for headless runtime navigation: ${url}`);
3111
+ }
3112
+ return {
3113
+ normalizedRoute,
3114
+ query,
3115
+ routeRecord
3116
+ };
3117
+ }
3118
+ unloadAllPages() {
3119
+ const pagesToUnload = new Set([...this.pages, ...this.tabPages.values()]);
3120
+ for (const page of [...pagesToUnload].reverse()) this.unloadPage(page);
3121
+ this.pages.length = 0;
3122
+ this.tabPages.clear();
3123
+ this.currentPageInstance = null;
3124
+ }
3125
+ unloadPage(page) {
3126
+ page.onUnload?.();
3127
+ this.tabPages.delete(stripLeadingSlash(page.route));
3128
+ }
3129
+ requireCurrentPage(action) {
3130
+ this.bootstrap();
3131
+ const current = this.currentPageInstance;
3132
+ if (!current) throw new Error(`Cannot call ${action} without an active page in headless runtime.`);
3133
+ return current;
3134
+ }
369
3135
  };
370
3136
  function createHeadlessSession(options) {
371
3137
  return new HeadlessSession(options);
@@ -413,9 +3179,62 @@ function querySelectorAll(root, selector) {
413
3179
  }
414
3180
  //#endregion
415
3181
  //#region src/view/nodeHandle.ts
3182
+ const DATASET_NAME_RE = /-([a-z])/g;
416
3183
  function escapeText$1(text) {
417
3184
  return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
418
3185
  }
3186
+ function toDatasetKey(attributeName) {
3187
+ return attributeName.slice(5).replace(DATASET_NAME_RE, (_match, char) => char.toUpperCase());
3188
+ }
3189
+ function collectDataset(node) {
3190
+ const dataset = {};
3191
+ for (const [key, value] of Object.entries(node.attribs ?? {})) {
3192
+ if (!key.startsWith("data-")) continue;
3193
+ dataset[toDatasetKey(key)] = value;
3194
+ }
3195
+ return dataset;
3196
+ }
3197
+ function resolveEventBinding(node, eventName) {
3198
+ const normalizedEventName = eventName.trim();
3199
+ if (!normalizedEventName) return null;
3200
+ const bindingAttrs = [
3201
+ `bind${normalizedEventName}`,
3202
+ `bind:${normalizedEventName}`,
3203
+ `catch${normalizedEventName}`,
3204
+ `catch:${normalizedEventName}`
3205
+ ];
3206
+ for (const attributeName of bindingAttrs) {
3207
+ const methodName = node.attribs?.[attributeName]?.trim();
3208
+ if (methodName) return methodName;
3209
+ }
3210
+ return null;
3211
+ }
3212
+ function createEventPayload(node, eventName, event) {
3213
+ const dataset = collectDataset(node);
3214
+ const nodeId = node.attribs?.id ?? "";
3215
+ return {
3216
+ bubbles: false,
3217
+ capturePhase: false,
3218
+ composed: false,
3219
+ currentTarget: {
3220
+ dataset: event.currentTarget?.dataset ?? event.dataset ?? dataset,
3221
+ id: event.currentTarget?.id ?? event.id ?? nodeId
3222
+ },
3223
+ detail: event.detail,
3224
+ mark: event.mark,
3225
+ target: {
3226
+ dataset: event.target?.dataset ?? event.dataset ?? dataset,
3227
+ id: event.target?.id ?? event.id ?? nodeId
3228
+ },
3229
+ type: eventName
3230
+ };
3231
+ }
3232
+ function createValueEventDetail(value, detail) {
3233
+ return {
3234
+ value,
3235
+ ...detail ?? {}
3236
+ };
3237
+ }
419
3238
  function escapeAttribute$1(value) {
420
3239
  return escapeText$1(value).replaceAll("\"", "&quot;");
421
3240
  }
@@ -432,34 +3251,62 @@ function collectText(node) {
432
3251
  return (node.children ?? []).map(collectText).join("");
433
3252
  }
434
3253
  var HeadlessTestingNodeHandle = class HeadlessTestingNodeHandle {
435
- constructor(node) {
3254
+ constructor(node, interactions) {
436
3255
  this.node = node;
3256
+ this.interactions = interactions;
437
3257
  }
438
3258
  async $(selector) {
439
3259
  const match = querySelectorAll(this.node, selector)[0];
440
- return match ? new HeadlessTestingNodeHandle(match) : null;
3260
+ return match ? new HeadlessTestingNodeHandle(match, this.interactions) : null;
441
3261
  }
442
3262
  async $$(selector) {
443
- return querySelectorAll(this.node, selector).map((node) => new HeadlessTestingNodeHandle(node));
3263
+ return querySelectorAll(this.node, selector).map((node) => new HeadlessTestingNodeHandle(node, this.interactions));
444
3264
  }
445
3265
  async attr(name) {
446
3266
  return this.node.attribs?.[name];
447
3267
  }
448
3268
  async dataset() {
449
- const dataset = {};
450
- for (const [key, value] of Object.entries(this.node.attribs ?? {})) if (key.startsWith("data-")) dataset[key.slice(5)] = value;
451
- return dataset;
3269
+ return collectDataset(this.node);
452
3270
  }
453
3271
  async text() {
454
3272
  return collectText(this.node);
455
3273
  }
3274
+ async trigger(eventName, event = {}) {
3275
+ if (!this.interactions) throw new Error("Node interactions are not available for this headless testing node.");
3276
+ const normalizedEventName = eventName.trim();
3277
+ if (!normalizedEventName) throw new Error("Event name must be a non-empty string in headless testing runtime.");
3278
+ const methodName = resolveEventBinding(this.node, normalizedEventName);
3279
+ if (!methodName) throw new Error(`No ${normalizedEventName} binding was found on <${this.node.name ?? "unknown"}> in headless testing runtime.`);
3280
+ return await this.interactions.callMethod(methodName, createEventPayload(this.node, normalizedEventName, event));
3281
+ }
3282
+ async tap(event = {}) {
3283
+ return await this.trigger("tap", event);
3284
+ }
3285
+ async input(value, event = {}) {
3286
+ return await this.trigger("input", {
3287
+ ...event,
3288
+ detail: createValueEventDetail(value, event.detail)
3289
+ });
3290
+ }
3291
+ async change(value, event = {}) {
3292
+ return await this.trigger("change", {
3293
+ ...event,
3294
+ detail: createValueEventDetail(value, event.detail)
3295
+ });
3296
+ }
3297
+ async blur(value, event = {}) {
3298
+ return await this.trigger("blur", {
3299
+ ...event,
3300
+ detail: value == null ? event.detail : createValueEventDetail(value, event.detail)
3301
+ });
3302
+ }
456
3303
  async wxml() {
457
3304
  return serializeNode(this.node);
458
3305
  }
459
3306
  };
460
3307
  //#endregion
461
3308
  //#region src/view/render.ts
462
- const LEADING_SLASH_RE = /^\/+/;
3309
+ const LEADING_SLASH_RE$1 = /^\/+/;
463
3310
  const TEMPLATE_INTERPOLATION_RE = /\{\{([^{}]+)\}\}/g;
464
3311
  function resolveValueByPath(source, expression) {
465
3312
  const normalized = expression.trim();
@@ -499,7 +3346,7 @@ function serializeDomNode(node) {
499
3346
  return `<${tagName}${Object.entries(node.attribs ?? {}).map(([key, value]) => ` ${key}="${escapeAttribute(value)}"`).join("")}>${(node.children ?? []).map(serializeDomNode).join("")}</${tagName}>`;
500
3347
  }
501
3348
  function renderPageTree(project, page) {
502
- const route = page.route.replace(LEADING_SLASH_RE, "");
3349
+ const route = page.route.replace(LEADING_SLASH_RE$1, "");
503
3350
  const templatePath = path.resolve(project.miniprogramRootPath, `${route}.wxml`);
504
3351
  const document = parseDocument(`<page>${fs.readFileSync(templatePath, "utf8")}</page>`, {
505
3352
  xmlMode: false,
@@ -514,30 +3361,46 @@ function renderPageTree(project, page) {
514
3361
  }
515
3362
  //#endregion
516
3363
  //#region src/testing/pageHandle.ts
3364
+ const DEFAULT_WAIT_TIMEOUT$1 = 1e3;
3365
+ const DEFAULT_WAIT_INTERVAL$1 = 10;
517
3366
  var HeadlessTestingPageHandle = class {
518
3367
  constructor(project, page) {
519
3368
  this.project = project;
520
3369
  this.page = page;
521
3370
  }
522
- async callMethod(methodName, ...args) {
523
- const method = this.page[methodName];
524
- if (typeof method !== "function") throw new Error(`Method "${methodName}" does not exist on headless page ${this.page.route}.`);
525
- return await method.apply(this.page, args);
526
- }
527
- async data(path) {
3371
+ resolveDataByPath(path) {
528
3372
  if (!path) return this.page.data;
529
3373
  const segments = path.split(".").filter(Boolean);
530
3374
  let current = this.page.data;
531
3375
  for (const segment of segments) current = current?.[segment];
532
3376
  return current;
533
3377
  }
3378
+ async pollUntil(check, errorMessage, options = {}) {
3379
+ const timeout = Number.isFinite(options.timeout) ? Math.max(0, Math.trunc(options.timeout ?? DEFAULT_WAIT_TIMEOUT$1)) : DEFAULT_WAIT_TIMEOUT$1;
3380
+ const interval = Number.isFinite(options.interval) ? Math.max(1, Math.trunc(options.interval ?? DEFAULT_WAIT_INTERVAL$1)) : DEFAULT_WAIT_INTERVAL$1;
3381
+ const deadline = Date.now() + timeout;
3382
+ while (true) {
3383
+ const result = await check();
3384
+ if (result != null) return result;
3385
+ if (Date.now() >= deadline) throw new Error(errorMessage);
3386
+ await this.waitFor(interval);
3387
+ }
3388
+ }
3389
+ async callMethod(methodName, ...args) {
3390
+ const method = this.page[methodName];
3391
+ if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on headless page ${this.page.route}.`);
3392
+ return await method.apply(this.page, args);
3393
+ }
3394
+ async data(path) {
3395
+ return this.resolveDataByPath(path);
3396
+ }
534
3397
  async waitFor(ms = 0) {
535
3398
  if (ms <= 0) return;
536
3399
  await new Promise((resolve) => setTimeout(resolve, ms));
537
3400
  }
538
3401
  async $(selector) {
539
3402
  const tree = renderPageTree(this.project, this.page);
540
- const root = new HeadlessTestingNodeHandle(tree.root.children?.[0] ?? tree.root);
3403
+ const root = new HeadlessTestingNodeHandle(tree.root.children?.[0] ?? tree.root, { callMethod: (methodName, event) => this.callMethod(methodName, event) });
541
3404
  if (selector === "page") return root;
542
3405
  return await root.$(selector);
543
3406
  }
@@ -547,17 +3410,72 @@ var HeadlessTestingPageHandle = class {
547
3410
  if (selector === "page") return [root];
548
3411
  return await root.$$(selector);
549
3412
  }
3413
+ async waitForSelector(selector, options = {}) {
3414
+ const normalizedSelector = selector.trim();
3415
+ if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
3416
+ if ((options.state ?? "attached") === "detached") {
3417
+ await this.pollUntil(async () => await this.$(normalizedSelector) ? null : true, `Timed out waiting for selector "${normalizedSelector}" to become detached in headless testing runtime.`, options);
3418
+ return null;
3419
+ }
3420
+ return await this.pollUntil(async () => await this.$(normalizedSelector), `Timed out waiting for selector "${normalizedSelector}" to appear in headless testing runtime.`, options);
3421
+ }
3422
+ async waitForText(text, options = {}) {
3423
+ const normalizedText = text.trim();
3424
+ if (!normalizedText) throw new Error("Text must be a non-empty string in headless testing runtime.");
3425
+ return await this.pollUntil(async () => {
3426
+ return (await this.wxml()).includes(normalizedText) ? normalizedText : null;
3427
+ }, `Timed out waiting for text "${normalizedText}" in headless testing runtime.`, options);
3428
+ }
3429
+ async waitForTextGone(text, options = {}) {
3430
+ const normalizedText = text.trim();
3431
+ if (!normalizedText) throw new Error("Text must be a non-empty string in headless testing runtime.");
3432
+ await this.pollUntil(async () => {
3433
+ return (await this.wxml()).includes(normalizedText) ? null : true;
3434
+ }, `Timed out waiting for text "${normalizedText}" to disappear in headless testing runtime.`, options);
3435
+ }
3436
+ async waitForData(path, matcher, options = {}) {
3437
+ const normalizedPath = path.trim();
3438
+ if (!normalizedPath) throw new Error("Data path must be a non-empty string in headless testing runtime.");
3439
+ const hasMatcher = arguments.length >= 2;
3440
+ return await this.pollUntil(async () => {
3441
+ const value = this.resolveDataByPath(normalizedPath);
3442
+ if (typeof matcher === "function") return matcher(value) ? value : null;
3443
+ if (hasMatcher) return Object.is(value, matcher) ? value : null;
3444
+ return value === void 0 ? null : value;
3445
+ }, `Timed out waiting for data "${normalizedPath}" in headless testing runtime.`, options);
3446
+ }
550
3447
  async wxml() {
551
3448
  return renderPageTree(this.project, this.page).wxml;
552
3449
  }
553
3450
  };
554
3451
  //#endregion
555
3452
  //#region src/testing/sessionHandle.ts
3453
+ const LEADING_SLASH_RE = /^\/+/;
3454
+ const DEFAULT_WAIT_TIMEOUT = 1e3;
3455
+ const DEFAULT_WAIT_INTERVAL = 10;
3456
+ function normalizeRoute(route) {
3457
+ return route.replace(LEADING_SLASH_RE, "");
3458
+ }
556
3459
  var HeadlessTestingSessionHandle = class {
557
3460
  constructor(project, session) {
558
3461
  this.project = project;
559
3462
  this.session = session;
560
3463
  }
3464
+ async waitFor(ms = 0) {
3465
+ if (ms <= 0) return;
3466
+ await new Promise((resolve) => setTimeout(resolve, ms));
3467
+ }
3468
+ async pollUntil(check, errorMessage, options = {}) {
3469
+ const timeout = Number.isFinite(options.timeout) ? Math.max(0, Math.trunc(options.timeout ?? DEFAULT_WAIT_TIMEOUT)) : DEFAULT_WAIT_TIMEOUT;
3470
+ const interval = Number.isFinite(options.interval) ? Math.max(1, Math.trunc(options.interval ?? DEFAULT_WAIT_INTERVAL)) : DEFAULT_WAIT_INTERVAL;
3471
+ const deadline = Date.now() + timeout;
3472
+ while (true) {
3473
+ const result = await check();
3474
+ if (result != null) return result;
3475
+ if (Date.now() >= deadline) throw new Error(errorMessage);
3476
+ await this.waitFor(interval);
3477
+ }
3478
+ }
561
3479
  async close() {}
562
3480
  async currentPage() {
563
3481
  const current = this.session.getCurrentPages().at(-1);
@@ -570,6 +3488,33 @@ var HeadlessTestingSessionHandle = class {
570
3488
  const page = this.session.reLaunch(route);
571
3489
  return new HeadlessTestingPageHandle(this.project, page);
572
3490
  }
3491
+ async waitForCurrentPage(route, options = {}) {
3492
+ const normalizedRoute = route?.trim();
3493
+ if (normalizedRoute != null && !normalizedRoute) throw new Error("Route must be a non-empty string in headless testing runtime.");
3494
+ return await this.pollUntil(async () => {
3495
+ const currentPageInstance = this.session.getCurrentPages().at(-1);
3496
+ if (!currentPageInstance) return null;
3497
+ const current = new HeadlessTestingPageHandle(this.project, currentPageInstance);
3498
+ if (!normalizedRoute) return current;
3499
+ if (normalizeRoute(currentPageInstance.route) === normalizeRoute(normalizedRoute)) return current;
3500
+ return null;
3501
+ }, normalizedRoute ? `Timed out waiting for current page "${normalizeRoute(normalizedRoute)}" in headless testing runtime.` : "Timed out waiting for a current page in headless testing runtime.", options);
3502
+ }
3503
+ async pageScrollTo(scrollTop) {
3504
+ this.session.pageScrollTo({ scrollTop });
3505
+ }
3506
+ async triggerPullDownRefresh() {
3507
+ this.session.triggerPullDownRefresh();
3508
+ }
3509
+ async triggerReachBottom() {
3510
+ this.session.triggerReachBottom();
3511
+ }
3512
+ async triggerResize(options) {
3513
+ this.session.triggerResize(options);
3514
+ }
3515
+ async triggerRouteDone(options) {
3516
+ this.session.triggerRouteDone(options);
3517
+ }
573
3518
  };
574
3519
  //#endregion
575
3520
  //#region src/testing/launch.ts
@@ -579,4 +3524,4 @@ async function launch(options) {
579
3524
  return new HeadlessTestingSessionHandle(session.project, session);
580
3525
  }
581
3526
  //#endregion
582
- export { HeadlessSession, HeadlessTestingNodeHandle, HeadlessTestingPageHandle, HeadlessTestingSessionHandle, createAppInstance, createHeadlessSession, createHeadlessWx, createHostRegistries, createPageInstance, launch, loadProject, querySelectorAll, registerAppDefinition, registerComponentDefinition, registerPageDefinition, renderPageTree, resolveRoutesFromAppConfig };
3527
+ export { BrowserHeadlessSession, HeadlessSession, HeadlessTestingNodeHandle, HeadlessTestingPageHandle, HeadlessTestingSessionHandle, cloneValue, coerceComponentPropertyValue, createAppInstance, createBrowserHeadlessSession, createBrowserModuleLoader, createBrowserProject, createBrowserVirtualFiles, createBrowserVirtualFilesFromDirectory, createComponentInstance, createHeadlessSession, createHeadlessWx, createHeadlessWxState, createHostRegistries, createPageInstance, createProjectDescriptor, hasBrowserVirtualFile, launch, loadProject, normalizeBrowserFilePath, normalizeComponentPropertyValue, querySelectorAll, readBrowserVirtualFile, registerAppDefinition, registerComponentDefinition, registerPageDefinition, renderBrowserPageTree, renderPageTree, resolveRoutesFromAppConfig, runComponentLifecycle, runComponentObservers, runComponentPageLifetime };